echarts.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (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. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. /**
  30. * zrender: 生成唯一id
  31. *
  32. * @author errorrik (errorrik@gmail.com)
  33. */
  34. var idStart = 0x0907;
  35. var guid = function () {
  36. return idStart++;
  37. };
  38. /**
  39. * echarts设备环境识别
  40. *
  41. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  42. * @author firede[firede@firede.us]
  43. * @desc thanks zepto.
  44. */
  45. /* global wx */
  46. var env = {};
  47. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  48. // In Weixin Application
  49. env = {
  50. browser: {},
  51. os: {},
  52. node: false,
  53. wxa: true,
  54. // Weixin Application
  55. canvasSupported: true,
  56. svgSupported: false,
  57. touchEventsSupported: true,
  58. domSupported: false
  59. };
  60. } else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  61. // In worker
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. worker: true,
  67. canvasSupported: true,
  68. domSupported: false
  69. };
  70. } else if (typeof navigator === 'undefined') {
  71. // In node
  72. env = {
  73. browser: {},
  74. os: {},
  75. node: true,
  76. worker: false,
  77. // Assume canvas is supported
  78. canvasSupported: true,
  79. svgSupported: true,
  80. domSupported: false
  81. };
  82. } else {
  83. env = detect(navigator.userAgent);
  84. }
  85. var env$1 = env; // Zepto.js
  86. // (c) 2010-2013 Thomas Fuchs
  87. // Zepto.js may be freely distributed under the MIT license.
  88. function detect(ua) {
  89. var os = {};
  90. var browser = {}; // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  91. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  92. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  93. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  94. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  95. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  96. // var touchpad = webos && ua.match(/TouchPad/);
  97. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  98. // var silk = ua.match(/Silk\/([\d._]+)/);
  99. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  100. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  101. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  102. // var playbook = ua.match(/PlayBook/);
  103. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  104. var firefox = ua.match(/Firefox\/([\d.]+)/); // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  105. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  106. var ie = ua.match(/MSIE\s([\d.]+)/) // IE 11 Trident/7.0; rv:11.0
  107. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  108. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  109. var weChat = /micromessenger/i.test(ua); // Todo: clean this up with a better OS/browser seperation:
  110. // - discern (more) between multiple browsers on android
  111. // - decide if kindle fire in silk mode is android or not
  112. // - Firefox on Android doesn't specify the Android version
  113. // - possibly devide in os, device and browser hashes
  114. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  115. // if (android) os.android = true, os.version = android[2];
  116. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  117. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  118. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  119. // if (webos) os.webos = true, os.version = webos[2];
  120. // if (touchpad) os.touchpad = true;
  121. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  122. // if (bb10) os.bb10 = true, os.version = bb10[2];
  123. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  124. // if (playbook) browser.playbook = true;
  125. // if (kindle) os.kindle = true, os.version = kindle[1];
  126. // if (silk) browser.silk = true, browser.version = silk[1];
  127. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  128. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  129. if (firefox) {
  130. browser.firefox = true;
  131. browser.version = firefox[1];
  132. } // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  133. // if (webview) browser.webview = true;
  134. if (ie) {
  135. browser.ie = true;
  136. browser.version = ie[1];
  137. }
  138. if (edge) {
  139. browser.edge = true;
  140. browser.version = edge[1];
  141. } // It is difficult to detect WeChat in Win Phone precisely, because ua can
  142. // not be set on win phone. So we do not consider Win Phone.
  143. if (weChat) {
  144. browser.weChat = true;
  145. } // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  146. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  147. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  148. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  149. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  150. return {
  151. browser: browser,
  152. os: os,
  153. node: false,
  154. // 原生canvas支持,改极端点了
  155. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  156. canvasSupported: !!document.createElement('canvas').getContext,
  157. svgSupported: typeof SVGRect !== 'undefined',
  158. // works on most browsers
  159. // IE10/11 does not support touch event, and MS Edge supports them but not by
  160. // default, so we dont check navigator.maxTouchPoints for them here.
  161. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  162. // <http://caniuse.com/#search=pointer%20event>.
  163. pointerEventsSupported: // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  164. // events currently. So we dont use that on other browsers unless tested sufficiently.
  165. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  166. // scroll, the `pointermove` event can not be fired any more. That will break some
  167. // features like "pan horizontally to move something and pan vertically to page scroll".
  168. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  169. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  170. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  171. 'onpointerdown' in window && (browser.edge || browser.ie && browser.version >= 11),
  172. // passiveSupported: detectPassiveSupport()
  173. domSupported: typeof document !== 'undefined'
  174. };
  175. } // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  176. // function detectPassiveSupport() {
  177. // // Test via a getter in the options object to see if the passive property is accessed
  178. // var supportsPassive = false;
  179. // try {
  180. // var opts = Object.defineProperty({}, 'passive', {
  181. // get: function() {
  182. // supportsPassive = true;
  183. // }
  184. // });
  185. // window.addEventListener('testPassive', function() {}, opts);
  186. // } catch (e) {
  187. // }
  188. // return supportsPassive;
  189. // }
  190. /**
  191. * @module zrender/core/util
  192. */
  193. // 用于处理merge时无法遍历Date等对象的问题
  194. var BUILTIN_OBJECT = {
  195. '[object Function]': 1,
  196. '[object RegExp]': 1,
  197. '[object Date]': 1,
  198. '[object Error]': 1,
  199. '[object CanvasGradient]': 1,
  200. '[object CanvasPattern]': 1,
  201. // For node-canvas
  202. '[object Image]': 1,
  203. '[object Canvas]': 1
  204. };
  205. var TYPED_ARRAY = {
  206. '[object Int8Array]': 1,
  207. '[object Uint8Array]': 1,
  208. '[object Uint8ClampedArray]': 1,
  209. '[object Int16Array]': 1,
  210. '[object Uint16Array]': 1,
  211. '[object Int32Array]': 1,
  212. '[object Uint32Array]': 1,
  213. '[object Float32Array]': 1,
  214. '[object Float64Array]': 1
  215. };
  216. var objToString = Object.prototype.toString;
  217. var arrayProto = Array.prototype;
  218. var nativeForEach = arrayProto.forEach;
  219. var nativeFilter = arrayProto.filter;
  220. var nativeSlice = arrayProto.slice;
  221. var nativeMap = arrayProto.map;
  222. var nativeReduce = arrayProto.reduce; // Avoid assign to an exported variable, for transforming to cjs.
  223. var methods = {};
  224. function $override(name, fn) {
  225. // Clear ctx instance for different environment
  226. if (name === 'createCanvas') {
  227. _ctx = null;
  228. }
  229. methods[name] = fn;
  230. }
  231. /**
  232. * Those data types can be cloned:
  233. * Plain object, Array, TypedArray, number, string, null, undefined.
  234. * Those data types will be assgined using the orginal data:
  235. * BUILTIN_OBJECT
  236. * Instance of user defined class will be cloned to a plain object, without
  237. * properties in prototype.
  238. * Other data types is not supported (not sure what will happen).
  239. *
  240. * Caution: do not support clone Date, for performance consideration.
  241. * (There might be a large number of date in `series.data`).
  242. * So date should not be modified in and out of echarts.
  243. *
  244. * @param {*} source
  245. * @return {*} new
  246. */
  247. function clone(source) {
  248. if (source == null || typeof source !== 'object') {
  249. return source;
  250. }
  251. var result = source;
  252. var typeStr = objToString.call(source);
  253. if (typeStr === '[object Array]') {
  254. if (!isPrimitive(source)) {
  255. result = [];
  256. for (var i = 0, len = source.length; i < len; i++) {
  257. result[i] = clone(source[i]);
  258. }
  259. }
  260. } else if (TYPED_ARRAY[typeStr]) {
  261. if (!isPrimitive(source)) {
  262. var Ctor = source.constructor;
  263. if (source.constructor.from) {
  264. result = Ctor.from(source);
  265. } else {
  266. result = new Ctor(source.length);
  267. for (var i = 0, len = source.length; i < len; i++) {
  268. result[i] = clone(source[i]);
  269. }
  270. }
  271. }
  272. } else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  273. result = {};
  274. for (var key in source) {
  275. if (source.hasOwnProperty(key)) {
  276. result[key] = clone(source[key]);
  277. }
  278. }
  279. }
  280. return result;
  281. }
  282. /**
  283. * @memberOf module:zrender/core/util
  284. * @param {*} target
  285. * @param {*} source
  286. * @param {boolean} [overwrite=false]
  287. */
  288. function merge(target, source, overwrite) {
  289. // We should escapse that source is string
  290. // and enter for ... in ...
  291. if (!isObject$1(source) || !isObject$1(target)) {
  292. return overwrite ? clone(source) : target;
  293. }
  294. for (var key in source) {
  295. if (source.hasOwnProperty(key)) {
  296. var targetProp = target[key];
  297. var sourceProp = source[key];
  298. if (isObject$1(sourceProp) && isObject$1(targetProp) && !isArray(sourceProp) && !isArray(targetProp) && !isDom(sourceProp) && !isDom(targetProp) && !isBuiltInObject(sourceProp) && !isBuiltInObject(targetProp) && !isPrimitive(sourceProp) && !isPrimitive(targetProp)) {
  299. // 如果需要递归覆盖,就递归调用merge
  300. merge(targetProp, sourceProp, overwrite);
  301. } else if (overwrite || !(key in target)) {
  302. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  303. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  304. target[key] = clone(source[key], true);
  305. }
  306. }
  307. }
  308. return target;
  309. }
  310. /**
  311. * @param {Array} targetAndSources The first item is target, and the rests are source.
  312. * @param {boolean} [overwrite=false]
  313. * @return {*} target
  314. */
  315. function mergeAll(targetAndSources, overwrite) {
  316. var result = targetAndSources[0];
  317. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  318. result = merge(result, targetAndSources[i], overwrite);
  319. }
  320. return result;
  321. }
  322. /**
  323. * @param {*} target
  324. * @param {*} source
  325. * @memberOf module:zrender/core/util
  326. */
  327. function extend(target, source) {
  328. for (var key in source) {
  329. if (source.hasOwnProperty(key)) {
  330. target[key] = source[key];
  331. }
  332. }
  333. return target;
  334. }
  335. /**
  336. * @param {*} target
  337. * @param {*} source
  338. * @param {boolean} [overlay=false]
  339. * @memberOf module:zrender/core/util
  340. */
  341. function defaults(target, source, overlay) {
  342. for (var key in source) {
  343. if (source.hasOwnProperty(key) && (overlay ? source[key] != null : target[key] == null)) {
  344. target[key] = source[key];
  345. }
  346. }
  347. return target;
  348. }
  349. var createCanvas = function () {
  350. return methods.createCanvas();
  351. };
  352. methods.createCanvas = function () {
  353. return document.createElement('canvas');
  354. }; // FIXME
  355. var _ctx;
  356. function getContext() {
  357. if (!_ctx) {
  358. // Use util.createCanvas instead of createCanvas
  359. // because createCanvas may be overwritten in different environment
  360. _ctx = createCanvas().getContext('2d');
  361. }
  362. return _ctx;
  363. }
  364. /**
  365. * 查询数组中元素的index
  366. * @memberOf module:zrender/core/util
  367. */
  368. function indexOf(array, value) {
  369. if (array) {
  370. if (array.indexOf) {
  371. return array.indexOf(value);
  372. }
  373. for (var i = 0, len = array.length; i < len; i++) {
  374. if (array[i] === value) {
  375. return i;
  376. }
  377. }
  378. }
  379. return -1;
  380. }
  381. /**
  382. * 构造类继承关系
  383. *
  384. * @memberOf module:zrender/core/util
  385. * @param {Function} clazz 源类
  386. * @param {Function} baseClazz 基类
  387. */
  388. function inherits(clazz, baseClazz) {
  389. var clazzPrototype = clazz.prototype;
  390. function F() {}
  391. F.prototype = baseClazz.prototype;
  392. clazz.prototype = new F();
  393. for (var prop in clazzPrototype) {
  394. if (clazzPrototype.hasOwnProperty(prop)) {
  395. clazz.prototype[prop] = clazzPrototype[prop];
  396. }
  397. }
  398. clazz.prototype.constructor = clazz;
  399. clazz.superClass = baseClazz;
  400. }
  401. /**
  402. * @memberOf module:zrender/core/util
  403. * @param {Object|Function} target
  404. * @param {Object|Function} sorce
  405. * @param {boolean} overlay
  406. */
  407. function mixin(target, source, overlay) {
  408. target = 'prototype' in target ? target.prototype : target;
  409. source = 'prototype' in source ? source.prototype : source;
  410. defaults(target, source, overlay);
  411. }
  412. /**
  413. * Consider typed array.
  414. * @param {Array|TypedArray} data
  415. */
  416. function isArrayLike(data) {
  417. if (!data) {
  418. return;
  419. }
  420. if (typeof data === 'string') {
  421. return false;
  422. }
  423. return typeof data.length === 'number';
  424. }
  425. /**
  426. * 数组或对象遍历
  427. * @memberOf module:zrender/core/util
  428. * @param {Object|Array} obj
  429. * @param {Function} cb
  430. * @param {*} [context]
  431. */
  432. function each$1(obj, cb, context) {
  433. if (!(obj && cb)) {
  434. return;
  435. }
  436. if (obj.forEach && obj.forEach === nativeForEach) {
  437. obj.forEach(cb, context);
  438. } else if (obj.length === +obj.length) {
  439. for (var i = 0, len = obj.length; i < len; i++) {
  440. cb.call(context, obj[i], i, obj);
  441. }
  442. } else {
  443. for (var key in obj) {
  444. if (obj.hasOwnProperty(key)) {
  445. cb.call(context, obj[key], key, obj);
  446. }
  447. }
  448. }
  449. }
  450. /**
  451. * 数组映射
  452. * @memberOf module:zrender/core/util
  453. * @param {Array} obj
  454. * @param {Function} cb
  455. * @param {*} [context]
  456. * @return {Array}
  457. */
  458. function map(obj, cb, context) {
  459. if (!(obj && cb)) {
  460. return;
  461. }
  462. if (obj.map && obj.map === nativeMap) {
  463. return obj.map(cb, context);
  464. } else {
  465. var result = [];
  466. for (var i = 0, len = obj.length; i < len; i++) {
  467. result.push(cb.call(context, obj[i], i, obj));
  468. }
  469. return result;
  470. }
  471. }
  472. /**
  473. * @memberOf module:zrender/core/util
  474. * @param {Array} obj
  475. * @param {Function} cb
  476. * @param {Object} [memo]
  477. * @param {*} [context]
  478. * @return {Array}
  479. */
  480. function reduce(obj, cb, memo, context) {
  481. if (!(obj && cb)) {
  482. return;
  483. }
  484. if (obj.reduce && obj.reduce === nativeReduce) {
  485. return obj.reduce(cb, memo, context);
  486. } else {
  487. for (var i = 0, len = obj.length; i < len; i++) {
  488. memo = cb.call(context, memo, obj[i], i, obj);
  489. }
  490. return memo;
  491. }
  492. }
  493. /**
  494. * 数组过滤
  495. * @memberOf module:zrender/core/util
  496. * @param {Array} obj
  497. * @param {Function} cb
  498. * @param {*} [context]
  499. * @return {Array}
  500. */
  501. function filter(obj, cb, context) {
  502. if (!(obj && cb)) {
  503. return;
  504. }
  505. if (obj.filter && obj.filter === nativeFilter) {
  506. return obj.filter(cb, context);
  507. } else {
  508. var result = [];
  509. for (var i = 0, len = obj.length; i < len; i++) {
  510. if (cb.call(context, obj[i], i, obj)) {
  511. result.push(obj[i]);
  512. }
  513. }
  514. return result;
  515. }
  516. }
  517. /**
  518. * 数组项查找
  519. * @memberOf module:zrender/core/util
  520. * @param {Array} obj
  521. * @param {Function} cb
  522. * @param {*} [context]
  523. * @return {*}
  524. */
  525. function find(obj, cb, context) {
  526. if (!(obj && cb)) {
  527. return;
  528. }
  529. for (var i = 0, len = obj.length; i < len; i++) {
  530. if (cb.call(context, obj[i], i, obj)) {
  531. return obj[i];
  532. }
  533. }
  534. }
  535. /**
  536. * @memberOf module:zrender/core/util
  537. * @param {Function} func
  538. * @param {*} context
  539. * @return {Function}
  540. */
  541. function bind(func, context) {
  542. var args = nativeSlice.call(arguments, 2);
  543. return function () {
  544. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  545. };
  546. }
  547. /**
  548. * @memberOf module:zrender/core/util
  549. * @param {Function} func
  550. * @return {Function}
  551. */
  552. function curry(func) {
  553. var args = nativeSlice.call(arguments, 1);
  554. return function () {
  555. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  556. };
  557. }
  558. /**
  559. * @memberOf module:zrender/core/util
  560. * @param {*} value
  561. * @return {boolean}
  562. */
  563. function isArray(value) {
  564. return objToString.call(value) === '[object Array]';
  565. }
  566. /**
  567. * @memberOf module:zrender/core/util
  568. * @param {*} value
  569. * @return {boolean}
  570. */
  571. function isFunction$1(value) {
  572. return typeof value === 'function';
  573. }
  574. /**
  575. * @memberOf module:zrender/core/util
  576. * @param {*} value
  577. * @return {boolean}
  578. */
  579. function isString(value) {
  580. return objToString.call(value) === '[object String]';
  581. }
  582. /**
  583. * @memberOf module:zrender/core/util
  584. * @param {*} value
  585. * @return {boolean}
  586. */
  587. function isObject$1(value) {
  588. // Avoid a V8 JIT bug in Chrome 19-20.
  589. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  590. var type = typeof value;
  591. return type === 'function' || !!value && type === 'object';
  592. }
  593. /**
  594. * @memberOf module:zrender/core/util
  595. * @param {*} value
  596. * @return {boolean}
  597. */
  598. function isBuiltInObject(value) {
  599. return !!BUILTIN_OBJECT[objToString.call(value)];
  600. }
  601. /**
  602. * @memberOf module:zrender/core/util
  603. * @param {*} value
  604. * @return {boolean}
  605. */
  606. function isTypedArray(value) {
  607. return !!TYPED_ARRAY[objToString.call(value)];
  608. }
  609. /**
  610. * @memberOf module:zrender/core/util
  611. * @param {*} value
  612. * @return {boolean}
  613. */
  614. function isDom(value) {
  615. return typeof value === 'object' && typeof value.nodeType === 'number' && typeof value.ownerDocument === 'object';
  616. }
  617. /**
  618. * Whether is exactly NaN. Notice isNaN('a') returns true.
  619. * @param {*} value
  620. * @return {boolean}
  621. */
  622. function eqNaN(value) {
  623. /* eslint-disable-next-line no-self-compare */
  624. return value !== value;
  625. }
  626. /**
  627. * If value1 is not null, then return value1, otherwise judget rest of values.
  628. * Low performance.
  629. * @memberOf module:zrender/core/util
  630. * @return {*} Final value
  631. */
  632. function retrieve(values) {
  633. for (var i = 0, len = arguments.length; i < len; i++) {
  634. if (arguments[i] != null) {
  635. return arguments[i];
  636. }
  637. }
  638. }
  639. function retrieve2(value0, value1) {
  640. return value0 != null ? value0 : value1;
  641. }
  642. function retrieve3(value0, value1, value2) {
  643. return value0 != null ? value0 : value1 != null ? value1 : value2;
  644. }
  645. /**
  646. * @memberOf module:zrender/core/util
  647. * @param {Array} arr
  648. * @param {number} startIndex
  649. * @param {number} endIndex
  650. * @return {Array}
  651. */
  652. function slice() {
  653. return Function.call.apply(nativeSlice, arguments);
  654. }
  655. /**
  656. * Normalize css liked array configuration
  657. * e.g.
  658. * 3 => [3, 3, 3, 3]
  659. * [4, 2] => [4, 2, 4, 2]
  660. * [4, 3, 2] => [4, 3, 2, 3]
  661. * @param {number|Array.<number>} val
  662. * @return {Array.<number>}
  663. */
  664. function normalizeCssArray(val) {
  665. if (typeof val === 'number') {
  666. return [val, val, val, val];
  667. }
  668. var len = val.length;
  669. if (len === 2) {
  670. // vertical | horizontal
  671. return [val[0], val[1], val[0], val[1]];
  672. } else if (len === 3) {
  673. // top | horizontal | bottom
  674. return [val[0], val[1], val[2], val[1]];
  675. }
  676. return val;
  677. }
  678. /**
  679. * @memberOf module:zrender/core/util
  680. * @param {boolean} condition
  681. * @param {string} message
  682. */
  683. function assert$1(condition, message) {
  684. if (!condition) {
  685. throw new Error(message);
  686. }
  687. }
  688. /**
  689. * @memberOf module:zrender/core/util
  690. * @param {string} str string to be trimed
  691. * @return {string} trimed string
  692. */
  693. function trim(str) {
  694. if (str == null) {
  695. return null;
  696. } else if (typeof str.trim === 'function') {
  697. return str.trim();
  698. } else {
  699. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  700. }
  701. }
  702. var primitiveKey = '__ec_primitive__';
  703. /**
  704. * Set an object as primitive to be ignored traversing children in clone or merge
  705. */
  706. function setAsPrimitive(obj) {
  707. obj[primitiveKey] = true;
  708. }
  709. function isPrimitive(obj) {
  710. return obj[primitiveKey];
  711. }
  712. /**
  713. * @constructor
  714. * @param {Object} obj Only apply `ownProperty`.
  715. */
  716. function HashMap(obj) {
  717. var isArr = isArray(obj); // Key should not be set on this, otherwise
  718. // methods get/set/... may be overrided.
  719. this.data = {};
  720. var thisMap = this;
  721. obj instanceof HashMap ? obj.each(visit) : obj && each$1(obj, visit);
  722. function visit(value, key) {
  723. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  724. }
  725. }
  726. HashMap.prototype = {
  727. constructor: HashMap,
  728. // Do not provide `has` method to avoid defining what is `has`.
  729. // (We usually treat `null` and `undefined` as the same, different
  730. // from ES6 Map).
  731. get: function (key) {
  732. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  733. },
  734. set: function (key, value) {
  735. // Comparing with invocation chaining, `return value` is more commonly
  736. // used in this case: `var someVal = map.set('a', genVal());`
  737. return this.data[key] = value;
  738. },
  739. // Although util.each can be performed on this hashMap directly, user
  740. // should not use the exposed keys, who are prefixed.
  741. each: function (cb, context) {
  742. context !== void 0 && (cb = bind(cb, context));
  743. /* eslint-disable guard-for-in */
  744. for (var key in this.data) {
  745. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  746. }
  747. /* eslint-enable guard-for-in */
  748. },
  749. // Do not use this method if performance sensitive.
  750. removeKey: function (key) {
  751. delete this.data[key];
  752. }
  753. };
  754. function createHashMap(obj) {
  755. return new HashMap(obj);
  756. }
  757. function concatArray(a, b) {
  758. var newArray = new a.constructor(a.length + b.length);
  759. for (var i = 0; i < a.length; i++) {
  760. newArray[i] = a[i];
  761. }
  762. var offset = a.length;
  763. for (i = 0; i < b.length; i++) {
  764. newArray[i + offset] = b[i];
  765. }
  766. return newArray;
  767. }
  768. function noop() {}
  769. var zrUtil = (Object.freeze || Object)({
  770. $override: $override,
  771. clone: clone,
  772. merge: merge,
  773. mergeAll: mergeAll,
  774. extend: extend,
  775. defaults: defaults,
  776. createCanvas: createCanvas,
  777. getContext: getContext,
  778. indexOf: indexOf,
  779. inherits: inherits,
  780. mixin: mixin,
  781. isArrayLike: isArrayLike,
  782. each: each$1,
  783. map: map,
  784. reduce: reduce,
  785. filter: filter,
  786. find: find,
  787. bind: bind,
  788. curry: curry,
  789. isArray: isArray,
  790. isFunction: isFunction$1,
  791. isString: isString,
  792. isObject: isObject$1,
  793. isBuiltInObject: isBuiltInObject,
  794. isTypedArray: isTypedArray,
  795. isDom: isDom,
  796. eqNaN: eqNaN,
  797. retrieve: retrieve,
  798. retrieve2: retrieve2,
  799. retrieve3: retrieve3,
  800. slice: slice,
  801. normalizeCssArray: normalizeCssArray,
  802. assert: assert$1,
  803. trim: trim,
  804. setAsPrimitive: setAsPrimitive,
  805. isPrimitive: isPrimitive,
  806. createHashMap: createHashMap,
  807. concatArray: concatArray,
  808. noop: noop
  809. });
  810. /* global Float32Array */
  811. var ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array;
  812. /**
  813. * 创建一个向量
  814. * @param {number} [x=0]
  815. * @param {number} [y=0]
  816. * @return {Vector2}
  817. */
  818. function create(x, y) {
  819. var out = new ArrayCtor(2);
  820. if (x == null) {
  821. x = 0;
  822. }
  823. if (y == null) {
  824. y = 0;
  825. }
  826. out[0] = x;
  827. out[1] = y;
  828. return out;
  829. }
  830. /**
  831. * 复制向量数据
  832. * @param {Vector2} out
  833. * @param {Vector2} v
  834. * @return {Vector2}
  835. */
  836. function copy(out, v) {
  837. out[0] = v[0];
  838. out[1] = v[1];
  839. return out;
  840. }
  841. /**
  842. * 克隆一个向量
  843. * @param {Vector2} v
  844. * @return {Vector2}
  845. */
  846. function clone$1(v) {
  847. var out = new ArrayCtor(2);
  848. out[0] = v[0];
  849. out[1] = v[1];
  850. return out;
  851. }
  852. /**
  853. * 设置向量的两个项
  854. * @param {Vector2} out
  855. * @param {number} a
  856. * @param {number} b
  857. * @return {Vector2} 结果
  858. */
  859. function set(out, a, b) {
  860. out[0] = a;
  861. out[1] = b;
  862. return out;
  863. }
  864. /**
  865. * 向量相加
  866. * @param {Vector2} out
  867. * @param {Vector2} v1
  868. * @param {Vector2} v2
  869. */
  870. function add(out, v1, v2) {
  871. out[0] = v1[0] + v2[0];
  872. out[1] = v1[1] + v2[1];
  873. return out;
  874. }
  875. /**
  876. * 向量缩放后相加
  877. * @param {Vector2} out
  878. * @param {Vector2} v1
  879. * @param {Vector2} v2
  880. * @param {number} a
  881. */
  882. function scaleAndAdd(out, v1, v2, a) {
  883. out[0] = v1[0] + v2[0] * a;
  884. out[1] = v1[1] + v2[1] * a;
  885. return out;
  886. }
  887. /**
  888. * 向量相减
  889. * @param {Vector2} out
  890. * @param {Vector2} v1
  891. * @param {Vector2} v2
  892. */
  893. function sub(out, v1, v2) {
  894. out[0] = v1[0] - v2[0];
  895. out[1] = v1[1] - v2[1];
  896. return out;
  897. }
  898. /**
  899. * 向量长度
  900. * @param {Vector2} v
  901. * @return {number}
  902. */
  903. function len(v) {
  904. return Math.sqrt(lenSquare(v));
  905. }
  906. var length = len; // jshint ignore:line
  907. /**
  908. * 向量长度平方
  909. * @param {Vector2} v
  910. * @return {number}
  911. */
  912. function lenSquare(v) {
  913. return v[0] * v[0] + v[1] * v[1];
  914. }
  915. var lengthSquare = lenSquare;
  916. /**
  917. * 向量乘法
  918. * @param {Vector2} out
  919. * @param {Vector2} v1
  920. * @param {Vector2} v2
  921. */
  922. function mul(out, v1, v2) {
  923. out[0] = v1[0] * v2[0];
  924. out[1] = v1[1] * v2[1];
  925. return out;
  926. }
  927. /**
  928. * 向量除法
  929. * @param {Vector2} out
  930. * @param {Vector2} v1
  931. * @param {Vector2} v2
  932. */
  933. function div(out, v1, v2) {
  934. out[0] = v1[0] / v2[0];
  935. out[1] = v1[1] / v2[1];
  936. return out;
  937. }
  938. /**
  939. * 向量点乘
  940. * @param {Vector2} v1
  941. * @param {Vector2} v2
  942. * @return {number}
  943. */
  944. function dot(v1, v2) {
  945. return v1[0] * v2[0] + v1[1] * v2[1];
  946. }
  947. /**
  948. * 向量缩放
  949. * @param {Vector2} out
  950. * @param {Vector2} v
  951. * @param {number} s
  952. */
  953. function scale(out, v, s) {
  954. out[0] = v[0] * s;
  955. out[1] = v[1] * s;
  956. return out;
  957. }
  958. /**
  959. * 向量归一化
  960. * @param {Vector2} out
  961. * @param {Vector2} v
  962. */
  963. function normalize(out, v) {
  964. var d = len(v);
  965. if (d === 0) {
  966. out[0] = 0;
  967. out[1] = 0;
  968. } else {
  969. out[0] = v[0] / d;
  970. out[1] = v[1] / d;
  971. }
  972. return out;
  973. }
  974. /**
  975. * 计算向量间距离
  976. * @param {Vector2} v1
  977. * @param {Vector2} v2
  978. * @return {number}
  979. */
  980. function distance(v1, v2) {
  981. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  982. }
  983. var dist = distance;
  984. /**
  985. * 向量距离平方
  986. * @param {Vector2} v1
  987. * @param {Vector2} v2
  988. * @return {number}
  989. */
  990. function distanceSquare(v1, v2) {
  991. return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  992. }
  993. var distSquare = distanceSquare;
  994. /**
  995. * 求负向量
  996. * @param {Vector2} out
  997. * @param {Vector2} v
  998. */
  999. function negate(out, v) {
  1000. out[0] = -v[0];
  1001. out[1] = -v[1];
  1002. return out;
  1003. }
  1004. /**
  1005. * 插值两个点
  1006. * @param {Vector2} out
  1007. * @param {Vector2} v1
  1008. * @param {Vector2} v2
  1009. * @param {number} t
  1010. */
  1011. function lerp(out, v1, v2, t) {
  1012. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1013. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1014. return out;
  1015. }
  1016. /**
  1017. * 矩阵左乘向量
  1018. * @param {Vector2} out
  1019. * @param {Vector2} v
  1020. * @param {Vector2} m
  1021. */
  1022. function applyTransform(out, v, m) {
  1023. var x = v[0];
  1024. var y = v[1];
  1025. out[0] = m[0] * x + m[2] * y + m[4];
  1026. out[1] = m[1] * x + m[3] * y + m[5];
  1027. return out;
  1028. }
  1029. /**
  1030. * 求两个向量最小值
  1031. * @param {Vector2} out
  1032. * @param {Vector2} v1
  1033. * @param {Vector2} v2
  1034. */
  1035. function min(out, v1, v2) {
  1036. out[0] = Math.min(v1[0], v2[0]);
  1037. out[1] = Math.min(v1[1], v2[1]);
  1038. return out;
  1039. }
  1040. /**
  1041. * 求两个向量最大值
  1042. * @param {Vector2} out
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. */
  1046. function max(out, v1, v2) {
  1047. out[0] = Math.max(v1[0], v2[0]);
  1048. out[1] = Math.max(v1[1], v2[1]);
  1049. return out;
  1050. }
  1051. var vector = (Object.freeze || Object)({
  1052. create: create,
  1053. copy: copy,
  1054. clone: clone$1,
  1055. set: set,
  1056. add: add,
  1057. scaleAndAdd: scaleAndAdd,
  1058. sub: sub,
  1059. len: len,
  1060. length: length,
  1061. lenSquare: lenSquare,
  1062. lengthSquare: lengthSquare,
  1063. mul: mul,
  1064. div: div,
  1065. dot: dot,
  1066. scale: scale,
  1067. normalize: normalize,
  1068. distance: distance,
  1069. dist: dist,
  1070. distanceSquare: distanceSquare,
  1071. distSquare: distSquare,
  1072. negate: negate,
  1073. lerp: lerp,
  1074. applyTransform: applyTransform,
  1075. min: min,
  1076. max: max
  1077. });
  1078. // TODO Draggable for group
  1079. // FIXME Draggable on element which has parent rotation or scale
  1080. function Draggable() {
  1081. this.on('mousedown', this._dragStart, this);
  1082. this.on('mousemove', this._drag, this);
  1083. this.on('mouseup', this._dragEnd, this); // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1084. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1085. // `_dragEnd` when globalout. That would brings better user experience.
  1086. // this.on('globalout', this._dragEnd, this);
  1087. // this._dropTarget = null;
  1088. // this._draggingTarget = null;
  1089. // this._x = 0;
  1090. // this._y = 0;
  1091. }
  1092. Draggable.prototype = {
  1093. constructor: Draggable,
  1094. _dragStart: function (e) {
  1095. var draggingTarget = e.target; // Find if there is draggable in the ancestor
  1096. while (draggingTarget && !draggingTarget.draggable) {
  1097. draggingTarget = draggingTarget.parent;
  1098. }
  1099. if (draggingTarget) {
  1100. this._draggingTarget = draggingTarget;
  1101. draggingTarget.dragging = true;
  1102. this._x = e.offsetX;
  1103. this._y = e.offsetY;
  1104. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1105. }
  1106. },
  1107. _drag: function (e) {
  1108. var draggingTarget = this._draggingTarget;
  1109. if (draggingTarget) {
  1110. var x = e.offsetX;
  1111. var y = e.offsetY;
  1112. var dx = x - this._x;
  1113. var dy = y - this._y;
  1114. this._x = x;
  1115. this._y = y;
  1116. draggingTarget.drift(dx, dy, e);
  1117. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1118. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1119. var lastDropTarget = this._dropTarget;
  1120. this._dropTarget = dropTarget;
  1121. if (draggingTarget !== dropTarget) {
  1122. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1123. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1124. }
  1125. if (dropTarget && dropTarget !== lastDropTarget) {
  1126. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1127. }
  1128. }
  1129. }
  1130. },
  1131. _dragEnd: function (e) {
  1132. var draggingTarget = this._draggingTarget;
  1133. if (draggingTarget) {
  1134. draggingTarget.dragging = false;
  1135. }
  1136. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1137. if (this._dropTarget) {
  1138. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1139. }
  1140. this._draggingTarget = null;
  1141. this._dropTarget = null;
  1142. }
  1143. };
  1144. function param(target, e) {
  1145. return {
  1146. target: target,
  1147. topTarget: e && e.topTarget
  1148. };
  1149. }
  1150. /**
  1151. * Event Mixin
  1152. * @module zrender/mixin/Eventful
  1153. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1154. * pissang (https://www.github.com/pissang)
  1155. */
  1156. var arrySlice = Array.prototype.slice;
  1157. /**
  1158. * Event dispatcher.
  1159. *
  1160. * @alias module:zrender/mixin/Eventful
  1161. * @constructor
  1162. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1163. * `eventProcessor.xxx` called.
  1164. * @param {Function} [eventProcessor.normalizeQuery]
  1165. * param: {string|Object} Raw query.
  1166. * return: {string|Object} Normalized query.
  1167. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1168. * if it returns `true`.
  1169. * param: {string} eventType
  1170. * param: {string|Object} query
  1171. * return: {boolean}
  1172. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1173. * param: {string} eventType
  1174. */
  1175. var Eventful = function (eventProcessor) {
  1176. this._$handlers = {};
  1177. this._$eventProcessor = eventProcessor;
  1178. };
  1179. Eventful.prototype = {
  1180. constructor: Eventful,
  1181. /**
  1182. * The handler can only be triggered once, then removed.
  1183. *
  1184. * @param {string} event The event name.
  1185. * @param {string|Object} [query] Condition used on event filter.
  1186. * @param {Function} handler The event handler.
  1187. * @param {Object} context
  1188. */
  1189. one: function (event, query, handler, context) {
  1190. return on(this, event, query, handler, context, true);
  1191. },
  1192. /**
  1193. * Bind a handler.
  1194. *
  1195. * @param {string} event The event name.
  1196. * @param {string|Object} [query] Condition used on event filter.
  1197. * @param {Function} handler The event handler.
  1198. * @param {Object} [context]
  1199. */
  1200. on: function (event, query, handler, context) {
  1201. return on(this, event, query, handler, context, false);
  1202. },
  1203. /**
  1204. * Whether any handler has bound.
  1205. *
  1206. * @param {string} event
  1207. * @return {boolean}
  1208. */
  1209. isSilent: function (event) {
  1210. var _h = this._$handlers;
  1211. return !_h[event] || !_h[event].length;
  1212. },
  1213. /**
  1214. * Unbind a event.
  1215. *
  1216. * @param {string} [event] The event name.
  1217. * If no `event` input, "off" all listeners.
  1218. * @param {Function} [handler] The event handler.
  1219. * If no `handler` input, "off" all listeners of the `event`.
  1220. */
  1221. off: function (event, handler) {
  1222. var _h = this._$handlers;
  1223. if (!event) {
  1224. this._$handlers = {};
  1225. return this;
  1226. }
  1227. if (handler) {
  1228. if (_h[event]) {
  1229. var newList = [];
  1230. for (var i = 0, l = _h[event].length; i < l; i++) {
  1231. if (_h[event][i].h !== handler) {
  1232. newList.push(_h[event][i]);
  1233. }
  1234. }
  1235. _h[event] = newList;
  1236. }
  1237. if (_h[event] && _h[event].length === 0) {
  1238. delete _h[event];
  1239. }
  1240. } else {
  1241. delete _h[event];
  1242. }
  1243. return this;
  1244. },
  1245. /**
  1246. * Dispatch a event.
  1247. *
  1248. * @param {string} type The event name.
  1249. */
  1250. trigger: function (type) {
  1251. var _h = this._$handlers[type];
  1252. var eventProcessor = this._$eventProcessor;
  1253. if (_h) {
  1254. var args = arguments;
  1255. var argLen = args.length;
  1256. if (argLen > 3) {
  1257. args = arrySlice.call(args, 1);
  1258. }
  1259. var len = _h.length;
  1260. for (var i = 0; i < len;) {
  1261. var hItem = _h[i];
  1262. if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query)) {
  1263. i++;
  1264. continue;
  1265. } // Optimize advise from backbone
  1266. switch (argLen) {
  1267. case 1:
  1268. hItem.h.call(hItem.ctx);
  1269. break;
  1270. case 2:
  1271. hItem.h.call(hItem.ctx, args[1]);
  1272. break;
  1273. case 3:
  1274. hItem.h.call(hItem.ctx, args[1], args[2]);
  1275. break;
  1276. default:
  1277. // have more than 2 given arguments
  1278. hItem.h.apply(hItem.ctx, args);
  1279. break;
  1280. }
  1281. if (hItem.one) {
  1282. _h.splice(i, 1);
  1283. len--;
  1284. } else {
  1285. i++;
  1286. }
  1287. }
  1288. }
  1289. eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type);
  1290. return this;
  1291. },
  1292. /**
  1293. * Dispatch a event with context, which is specified at the last parameter.
  1294. *
  1295. * @param {string} type The event name.
  1296. */
  1297. triggerWithContext: function (type) {
  1298. var _h = this._$handlers[type];
  1299. var eventProcessor = this._$eventProcessor;
  1300. if (_h) {
  1301. var args = arguments;
  1302. var argLen = args.length;
  1303. if (argLen > 4) {
  1304. args = arrySlice.call(args, 1, args.length - 1);
  1305. }
  1306. var ctx = args[args.length - 1];
  1307. var len = _h.length;
  1308. for (var i = 0; i < len;) {
  1309. var hItem = _h[i];
  1310. if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query)) {
  1311. i++;
  1312. continue;
  1313. } // Optimize advise from backbone
  1314. switch (argLen) {
  1315. case 1:
  1316. hItem.h.call(ctx);
  1317. break;
  1318. case 2:
  1319. hItem.h.call(ctx, args[1]);
  1320. break;
  1321. case 3:
  1322. hItem.h.call(ctx, args[1], args[2]);
  1323. break;
  1324. default:
  1325. // have more than 2 given arguments
  1326. hItem.h.apply(ctx, args);
  1327. break;
  1328. }
  1329. if (hItem.one) {
  1330. _h.splice(i, 1);
  1331. len--;
  1332. } else {
  1333. i++;
  1334. }
  1335. }
  1336. }
  1337. eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type);
  1338. return this;
  1339. }
  1340. };
  1341. function normalizeQuery(host, query) {
  1342. var eventProcessor = host._$eventProcessor;
  1343. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1344. query = eventProcessor.normalizeQuery(query);
  1345. }
  1346. return query;
  1347. }
  1348. function on(eventful, event, query, handler, context, isOnce) {
  1349. var _h = eventful._$handlers;
  1350. if (typeof query === 'function') {
  1351. context = handler;
  1352. handler = query;
  1353. query = null;
  1354. }
  1355. if (!handler || !event) {
  1356. return eventful;
  1357. }
  1358. query = normalizeQuery(eventful, query);
  1359. if (!_h[event]) {
  1360. _h[event] = [];
  1361. }
  1362. for (var i = 0; i < _h[event].length; i++) {
  1363. if (_h[event][i].h === handler) {
  1364. return eventful;
  1365. }
  1366. }
  1367. var wrap = {
  1368. h: handler,
  1369. one: isOnce,
  1370. query: query,
  1371. ctx: context || eventful,
  1372. // FIXME
  1373. // Do not publish this feature util it is proved that it makes sense.
  1374. callAtLast: handler.zrEventfulCallAtLast
  1375. };
  1376. var lastIndex = _h[event].length - 1;
  1377. var lastWrap = _h[event][lastIndex];
  1378. lastWrap && lastWrap.callAtLast ? _h[event].splice(lastIndex, 0, wrap) : _h[event].push(wrap);
  1379. return eventful;
  1380. } // ----------------------
  1381. /**
  1382. * The algoritm is learnt from
  1383. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1384. * And we made some optimization for matrix inversion.
  1385. * Other similar approaches:
  1386. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1387. */
  1388. var LN2 = Math.log(2);
  1389. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1390. var cacheKey = rowMask + '-' + colMask;
  1391. var fullRank = rows.length;
  1392. if (detCache.hasOwnProperty(cacheKey)) {
  1393. return detCache[cacheKey];
  1394. }
  1395. if (rank === 1) {
  1396. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1397. var colStart = Math.round(Math.log((1 << fullRank) - 1 & ~colMask) / LN2);
  1398. return rows[rowStart][colStart];
  1399. }
  1400. var subRowMask = rowMask | 1 << rowStart;
  1401. var subRowStart = rowStart + 1;
  1402. while (rowMask & 1 << subRowStart) {
  1403. subRowStart++;
  1404. }
  1405. var sum = 0;
  1406. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1407. var colTag = 1 << j;
  1408. if (!(colTag & colMask)) {
  1409. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j] // det(subMatrix(0, j))
  1410. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1411. colLocalIdx++;
  1412. }
  1413. }
  1414. detCache[cacheKey] = sum;
  1415. return sum;
  1416. }
  1417. /**
  1418. * Usage:
  1419. * ```js
  1420. * var transformer = buildTransformer(
  1421. * [10, 44, 100, 44, 100, 300, 10, 300],
  1422. * [50, 54, 130, 14, 140, 330, 14, 220]
  1423. * );
  1424. * var out = [];
  1425. * transformer && transformer([11, 33], out);
  1426. * ```
  1427. *
  1428. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1429. *
  1430. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1431. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1432. * @return {Function} transformer If fail, return null/undefined.
  1433. */
  1434. function buildTransformer(src, dest) {
  1435. var mA = [[src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]], [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]], [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]], [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]], [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]], [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]], [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]], [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]];
  1436. var detCache = {};
  1437. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1438. if (det === 0) {
  1439. // can not make transformer when and only when
  1440. // any three of the markers are collinear.
  1441. return;
  1442. } // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1443. var vh = [];
  1444. for (var i = 0; i < 8; i++) {
  1445. for (var j = 0; j < 8; j++) {
  1446. vh[j] == null && (vh[j] = 0);
  1447. vh[j] += ((i + j) % 2 ? -1 : 1) * // det(subMatrix(i, j))
  1448. determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache) / det * dest[i];
  1449. }
  1450. }
  1451. return function (out, srcPointX, srcPointY) {
  1452. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1453. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1454. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1455. };
  1456. }
  1457. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1458. var _calcOut$1 = [];
  1459. /**
  1460. * Transform "local coord" from `elFrom` to `elTarget`.
  1461. * "local coord": the coord based on the input `el`. The origin point is at
  1462. * the position of "left: 0; top: 0;" in the `el`.
  1463. *
  1464. * Support when CSS transform is used.
  1465. *
  1466. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1467. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1468. * to locate the element.
  1469. *
  1470. * For example, this code below positions a child of `document.body` on the event
  1471. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1472. * ```js
  1473. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1474. * if (!eqNaN(out[0])) {
  1475. * // Then locate the tip element on the event point.
  1476. * var tipEl = document.createElement('div');
  1477. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1478. * document.body.appendChild(tipEl);
  1479. * }
  1480. * ```
  1481. *
  1482. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1483. *
  1484. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1485. * If can not transform, `out` will not be modified but return `false`.
  1486. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1487. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1488. * @param {number} inX
  1489. * @param {number} inY
  1490. * @return {boolean} Whether transform successfully.
  1491. */
  1492. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1493. return transformCoordWithViewport(_calcOut$1, elFrom, inX, inY, true) && transformCoordWithViewport(out, elTarget, _calcOut$1[0], _calcOut$1[1]);
  1494. }
  1495. /**
  1496. * Transform between a "viewport coord" and a "local coord".
  1497. * "viewport coord": the coord based on the left-top corner of the viewport
  1498. * of the browser.
  1499. * "local coord": the coord based on the input `el`. The origin point is at
  1500. * the position of "left: 0; top: 0;" in the `el`.
  1501. *
  1502. * Support the case when CSS transform is used on el.
  1503. *
  1504. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1505. * it represents "local coord", otherwise "vireport coord".
  1506. * If can not transform, `out` will not be modified but return `false`.
  1507. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1508. * @param {number} inX If `inverse: false`,
  1509. * it represents "vireport coord", otherwise "local coord".
  1510. * @param {number} inY If `inverse: false`,
  1511. * it represents "vireport coord", otherwise "local coord".
  1512. * @param {boolean} [inverse=false]
  1513. * `true`: from "viewport coord" to "local coord".
  1514. * `false`: from "local coord" to "viewport coord".
  1515. * @return {boolean} Whether transform successfully.
  1516. */
  1517. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1518. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1519. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1520. var markers = prepareCoordMarkers(el, saved);
  1521. var transformer = preparePointerTransformer(markers, saved, inverse);
  1522. if (transformer) {
  1523. transformer(out, inX, inY);
  1524. return true;
  1525. }
  1526. }
  1527. return false;
  1528. }
  1529. function prepareCoordMarkers(el, saved) {
  1530. var markers = saved.markers;
  1531. if (markers) {
  1532. return markers;
  1533. }
  1534. markers = saved.markers = [];
  1535. var propLR = ['left', 'right'];
  1536. var propTB = ['top', 'bottom'];
  1537. for (var i = 0; i < 4; i++) {
  1538. var marker = document.createElement('div');
  1539. var stl = marker.style;
  1540. var idxLR = i % 2;
  1541. var idxTB = (i >> 1) % 2;
  1542. stl.cssText = ['position: absolute', 'visibility: hidden', 'padding: 0', 'margin: 0', 'border-width: 0', 'user-select: none', 'width:0', 'height:0', // 'width: 5px',
  1543. // 'height: 5px',
  1544. propLR[idxLR] + ':0', propTB[idxTB] + ':0', propLR[1 - idxLR] + ':auto', propTB[1 - idxTB] + ':auto', ''].join('!important;');
  1545. el.appendChild(marker);
  1546. markers.push(marker);
  1547. }
  1548. return markers;
  1549. }
  1550. function preparePointerTransformer(markers, saved, inverse) {
  1551. var transformerName = inverse ? 'invTrans' : 'trans';
  1552. var transformer = saved[transformerName];
  1553. var oldSrcCoords = saved.srcCoords;
  1554. var oldCoordTheSame = true;
  1555. var srcCoords = [];
  1556. var destCoords = [];
  1557. for (var i = 0; i < 4; i++) {
  1558. var rect = markers[i].getBoundingClientRect();
  1559. var ii = 2 * i;
  1560. var x = rect.left;
  1561. var y = rect.top;
  1562. srcCoords.push(x, y);
  1563. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1564. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1565. } // Cache to avoid time consuming of `buildTransformer`.
  1566. return oldCoordTheSame && transformer ? transformer : (saved.srcCoords = srcCoords, saved[transformerName] = inverse ? buildTransformer(destCoords, srcCoords) : buildTransformer(srcCoords, destCoords));
  1567. }
  1568. function isCanvasEl(el) {
  1569. return el.nodeName.toUpperCase() === 'CANVAS';
  1570. }
  1571. /**
  1572. * Utilities for mouse or touch events.
  1573. */
  1574. var isDomLevel2 = typeof window !== 'undefined' && !!window.addEventListener;
  1575. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1576. var _calcOut = [];
  1577. /**
  1578. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1579. * the input `el`.
  1580. * CSS transform (2D & 3D) is supported.
  1581. *
  1582. * The strategy to fetch the coords:
  1583. * + If `calculate` is not set as `true`, users of this method should
  1584. * ensure that `el` is the same or the same size & location as `e.target`.
  1585. * Otherwise the result coords are probably not expected. Because we
  1586. * firstly try to get coords from e.offsetX/e.offsetY.
  1587. * + If `calculate` is set as `true`, the input `el` can be any element
  1588. * and we force to calculate the coords based on `el`.
  1589. * + The input `el` should be positionable (not position:static).
  1590. *
  1591. * The force `calculate` can be used in case like:
  1592. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1593. *
  1594. * @param {HTMLElement} el DOM element.
  1595. * @param {Event} e Mouse event or touch event.
  1596. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1597. * @param {boolean} [calculate=false] Whether to force calculate
  1598. * the coordinates but not use ones provided by browser.
  1599. */
  1600. function clientToLocal(el, e, out, calculate) {
  1601. out = out || {}; // According to the W3C Working Draft, offsetX and offsetY should be relative
  1602. // to the padding edge of the target element. The only browser using this convention
  1603. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1604. // not support the properties.
  1605. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1606. // In zr painter.dom, padding edge equals to border edge.
  1607. if (calculate || !env$1.canvasSupported) {
  1608. calculateZrXY(el, e, out);
  1609. } // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1610. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1611. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1612. // zoom-factor, overflow / opacity layers, transforms ...)
  1613. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1614. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1615. // BTW3, In ff, offsetX/offsetY is always 0.
  1616. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1617. out.zrX = e.layerX;
  1618. out.zrY = e.layerY;
  1619. } // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1620. else if (e.offsetX != null) {
  1621. out.zrX = e.offsetX;
  1622. out.zrY = e.offsetY;
  1623. } // For some other device, e.g., IOS safari.
  1624. else {
  1625. calculateZrXY(el, e, out);
  1626. }
  1627. return out;
  1628. }
  1629. function calculateZrXY(el, e, out) {
  1630. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1631. if (env$1.domSupported && el.getBoundingClientRect) {
  1632. var ex = e.clientX;
  1633. var ey = e.clientY;
  1634. if (isCanvasEl(el)) {
  1635. // Original approach, which do not support CSS transform.
  1636. // marker can not be locationed in a canvas container
  1637. // (getBoundingClientRect is always 0). We do not support
  1638. // that input a pre-created canvas to zr while using css
  1639. // transform in iOS.
  1640. var box = el.getBoundingClientRect();
  1641. out.zrX = ex - box.left;
  1642. out.zrY = ey - box.top;
  1643. return;
  1644. } else {
  1645. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1646. out.zrX = _calcOut[0];
  1647. out.zrY = _calcOut[1];
  1648. return;
  1649. }
  1650. }
  1651. }
  1652. out.zrX = out.zrY = 0;
  1653. }
  1654. /**
  1655. * Find native event compat for legency IE.
  1656. * Should be called at the begining of a native event listener.
  1657. *
  1658. * @param {Event} [e] Mouse event or touch event or pointer event.
  1659. * For lagency IE, we use `window.event` is used.
  1660. * @return {Event} The native event.
  1661. */
  1662. function getNativeEvent(e) {
  1663. return e || window.event;
  1664. }
  1665. /**
  1666. * Normalize the coordinates of the input event.
  1667. *
  1668. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1669. * the input `el`.
  1670. * Get `e.zrDelta` if using mouse wheel.
  1671. * Get `e.which`, see the comment inside this function.
  1672. *
  1673. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1674. *
  1675. * Notice: see comments in `clientToLocal`. check the relationship
  1676. * between the result coords and the parameters `el` and `calculate`.
  1677. *
  1678. * @param {HTMLElement} el DOM element.
  1679. * @param {Event} [e] See `getNativeEvent`.
  1680. * @param {boolean} [calculate=false] Whether to force calculate
  1681. * the coordinates but not use ones provided by browser.
  1682. * @return {UIEvent} The normalized native UIEvent.
  1683. */
  1684. function normalizeEvent(el, e, calculate) {
  1685. e = getNativeEvent(e);
  1686. if (e.zrX != null) {
  1687. return e;
  1688. }
  1689. var eventType = e.type;
  1690. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1691. if (!isTouch) {
  1692. clientToLocal(el, e, e, calculate);
  1693. e.zrDelta = e.wheelDelta ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1694. } else {
  1695. var touch = eventType !== 'touchend' ? e.targetTouches[0] : e.changedTouches[0];
  1696. touch && clientToLocal(el, touch, e, calculate);
  1697. } // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1698. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1699. // If e.which has been defined, it may be readonly,
  1700. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1701. var button = e.button;
  1702. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1703. e.which = button & 1 ? 1 : button & 2 ? 3 : button & 4 ? 2 : 0;
  1704. } // [Caution]: `e.which` from browser is not always reliable. For example,
  1705. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1706. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1707. // `mousedown (pointerdown)` is the same as Chrome does.
  1708. return e;
  1709. }
  1710. /**
  1711. * @param {HTMLElement} el
  1712. * @param {string} name
  1713. * @param {Function} handler
  1714. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1715. * @param {boolean} [opt.capture=false]
  1716. * @param {boolean} [opt.passive=false]
  1717. */
  1718. function addEventListener(el, name, handler, opt) {
  1719. if (isDomLevel2) {
  1720. // Reproduct the console warning:
  1721. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1722. // Consider marking event handler as 'passive' to make the page more responsive.
  1723. // Just set console log level: verbose in chrome dev tool.
  1724. // then the warning log will be printed when addEventListener called.
  1725. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1726. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1727. // listener delegate all of the upper events of element. Some of those events need
  1728. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1729. // Before passive can be adopted, these issues should be considered:
  1730. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1731. // passive or not.
  1732. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1733. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1734. // compatibility should be handled.
  1735. // var opts = (env.passiveSupported && name === 'mousewheel')
  1736. // ? {passive: true}
  1737. // // By default, the third param of el.addEventListener is `capture: false`.
  1738. // : void 0;
  1739. // el.addEventListener(name, handler /* , opts */);
  1740. el.addEventListener(name, handler, opt);
  1741. } else {
  1742. // For simplicity, do not implement `setCapture` for IE9-.
  1743. el.attachEvent('on' + name, handler);
  1744. }
  1745. }
  1746. /**
  1747. * Parameter are the same as `addEventListener`.
  1748. *
  1749. * Notice that if a listener is registered twice, one with capture and one without,
  1750. * remove each one separately. Removal of a capturing listener does not affect a
  1751. * non-capturing version of the same listener, and vice versa.
  1752. */
  1753. function removeEventListener(el, name, handler, opt) {
  1754. if (isDomLevel2) {
  1755. el.removeEventListener(name, handler, opt);
  1756. } else {
  1757. el.detachEvent('on' + name, handler);
  1758. }
  1759. }
  1760. /**
  1761. * preventDefault and stopPropagation.
  1762. * Notice: do not use this method in zrender. It can only be
  1763. * used by upper applications if necessary.
  1764. *
  1765. * @param {Event} e A mouse or touch event.
  1766. */
  1767. var stop = isDomLevel2 ? function (e) {
  1768. e.preventDefault();
  1769. e.stopPropagation();
  1770. e.cancelBubble = true;
  1771. } : function (e) {
  1772. e.returnValue = false;
  1773. e.cancelBubble = true;
  1774. };
  1775. /**
  1776. * This method only works for mouseup and mousedown. The functionality is restricted
  1777. * for fault tolerance, See the `e.which` compatibility above.
  1778. *
  1779. * @param {MouseEvent} e
  1780. * @return {boolean}
  1781. */
  1782. /**
  1783. * To be removed.
  1784. * @deprecated
  1785. */
  1786. // For backward compatibility
  1787. /**
  1788. * Only implements needed gestures for mobile.
  1789. */
  1790. var GestureMgr = function () {
  1791. /**
  1792. * @private
  1793. * @type {Array.<Object>}
  1794. */
  1795. this._track = [];
  1796. };
  1797. GestureMgr.prototype = {
  1798. constructor: GestureMgr,
  1799. recognize: function (event, target, root) {
  1800. this._doTrack(event, target, root);
  1801. return this._recognize(event);
  1802. },
  1803. clear: function () {
  1804. this._track.length = 0;
  1805. return this;
  1806. },
  1807. _doTrack: function (event, target, root) {
  1808. var touches = event.touches;
  1809. if (!touches) {
  1810. return;
  1811. }
  1812. var trackItem = {
  1813. points: [],
  1814. touches: [],
  1815. target: target,
  1816. event: event
  1817. };
  1818. for (var i = 0, len = touches.length; i < len; i++) {
  1819. var touch = touches[i];
  1820. var pos = clientToLocal(root, touch, {});
  1821. trackItem.points.push([pos.zrX, pos.zrY]);
  1822. trackItem.touches.push(touch);
  1823. }
  1824. this._track.push(trackItem);
  1825. },
  1826. _recognize: function (event) {
  1827. for (var eventName in recognizers) {
  1828. if (recognizers.hasOwnProperty(eventName)) {
  1829. var gestureInfo = recognizers[eventName](this._track, event);
  1830. if (gestureInfo) {
  1831. return gestureInfo;
  1832. }
  1833. }
  1834. }
  1835. }
  1836. };
  1837. function dist$1(pointPair) {
  1838. var dx = pointPair[1][0] - pointPair[0][0];
  1839. var dy = pointPair[1][1] - pointPair[0][1];
  1840. return Math.sqrt(dx * dx + dy * dy);
  1841. }
  1842. function center(pointPair) {
  1843. return [(pointPair[0][0] + pointPair[1][0]) / 2, (pointPair[0][1] + pointPair[1][1]) / 2];
  1844. }
  1845. var recognizers = {
  1846. pinch: function (track, event) {
  1847. var trackLen = track.length;
  1848. if (!trackLen) {
  1849. return;
  1850. }
  1851. var pinchEnd = (track[trackLen - 1] || {}).points;
  1852. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1853. if (pinchPre && pinchPre.length > 1 && pinchEnd && pinchEnd.length > 1) {
  1854. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1855. !isFinite(pinchScale) && (pinchScale = 1);
  1856. event.pinchScale = pinchScale;
  1857. var pinchCenter = center(pinchEnd);
  1858. event.pinchX = pinchCenter[0];
  1859. event.pinchY = pinchCenter[1];
  1860. return {
  1861. type: 'pinch',
  1862. target: track[0].target,
  1863. event: event
  1864. };
  1865. }
  1866. } // Only pinch currently.
  1867. };
  1868. /**
  1869. * [The interface between `Handler` and `HandlerProxy`]:
  1870. *
  1871. * The default `HandlerProxy` only support the common standard web environment
  1872. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1873. * But `HandlerProxy` can be replaced to support more non-standard environment
  1874. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1875. * not provided (like echarts-gl did).
  1876. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1877. * make break changes util inevitable. The interface include the public methods
  1878. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1879. * drives `Handler`.
  1880. */
  1881. /**
  1882. * [Drag outside]:
  1883. *
  1884. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1885. * zrender area when dragging. That is important for the improvement of the user experience
  1886. * when dragging something near the boundary without being terminated unexpectedly.
  1887. *
  1888. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1889. * to resolve this issue. But some drawbacks of it is described in
  1890. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1891. *
  1892. * Instead, we referenced the specifications:
  1893. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1894. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1895. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1896. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1897. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1898. *
  1899. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1900. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1901. * to fire until release the pointer. That is implemented by listen to those event on
  1902. * `document`.
  1903. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1904. * The touch event support this feature by default.
  1905. *
  1906. * Note:
  1907. * There might be some cases that the mouse event can not be
  1908. * received on `document`. For example,
  1909. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1910. * of zr dom throw Error .
  1911. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1912. * zr dom call `stopPropagation`.
  1913. * In these cases, the `mousemove` event might be keep triggered event
  1914. * if the mouse is released. We try to reduce the side-effect in those cases.
  1915. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1916. *
  1917. * Note:
  1918. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1919. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1920. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1921. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1922. * But they are needed to work when the pointer inside the zrender dom.
  1923. */
  1924. var SILENT = 'silent';
  1925. function makeEventPacket(eveType, targetInfo, event) {
  1926. return {
  1927. type: eveType,
  1928. event: event,
  1929. // target can only be an element that is not silent.
  1930. target: targetInfo.target,
  1931. // topTarget can be a silent element.
  1932. topTarget: targetInfo.topTarget,
  1933. cancelBubble: false,
  1934. offsetX: event.zrX,
  1935. offsetY: event.zrY,
  1936. gestureEvent: event.gestureEvent,
  1937. pinchX: event.pinchX,
  1938. pinchY: event.pinchY,
  1939. pinchScale: event.pinchScale,
  1940. wheelDelta: event.zrDelta,
  1941. zrByTouch: event.zrByTouch,
  1942. which: event.which,
  1943. stop: stopEvent
  1944. };
  1945. }
  1946. function stopEvent() {
  1947. stop(this.event);
  1948. }
  1949. function EmptyProxy() {}
  1950. EmptyProxy.prototype.dispose = function () {};
  1951. var handlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  1952. /**
  1953. * @alias module:zrender/Handler
  1954. * @constructor
  1955. * @extends module:zrender/mixin/Eventful
  1956. * @param {module:zrender/Storage} storage Storage instance.
  1957. * @param {module:zrender/Painter} painter Painter instance.
  1958. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1959. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1960. */
  1961. var Handler = function (storage, painter, proxy, painterRoot) {
  1962. Eventful.call(this);
  1963. this.storage = storage;
  1964. this.painter = painter;
  1965. this.painterRoot = painterRoot;
  1966. proxy = proxy || new EmptyProxy();
  1967. /**
  1968. * Proxy of event. can be Dom, WebGLSurface, etc.
  1969. */
  1970. this.proxy = null;
  1971. /**
  1972. * {target, topTarget, x, y}
  1973. * @private
  1974. * @type {Object}
  1975. */
  1976. this._hovered = {};
  1977. /**
  1978. * @private
  1979. * @type {Date}
  1980. */
  1981. this._lastTouchMoment;
  1982. /**
  1983. * @private
  1984. * @type {number}
  1985. */
  1986. this._lastX;
  1987. /**
  1988. * @private
  1989. * @type {number}
  1990. */
  1991. this._lastY;
  1992. /**
  1993. * @private
  1994. * @type {module:zrender/core/GestureMgr}
  1995. */
  1996. this._gestureMgr;
  1997. Draggable.call(this);
  1998. this.setHandlerProxy(proxy);
  1999. };
  2000. Handler.prototype = {
  2001. constructor: Handler,
  2002. setHandlerProxy: function (proxy) {
  2003. if (this.proxy) {
  2004. this.proxy.dispose();
  2005. }
  2006. if (proxy) {
  2007. each$1(handlerNames, function (name) {
  2008. proxy.on && proxy.on(name, this[name], this);
  2009. }, this); // Attach handler
  2010. proxy.handler = this;
  2011. }
  2012. this.proxy = proxy;
  2013. },
  2014. mousemove: function (event) {
  2015. var x = event.zrX;
  2016. var y = event.zrY;
  2017. var isOutside = isOutsideBoundary(this, x, y);
  2018. var lastHovered = this._hovered;
  2019. var lastHoveredTarget = lastHovered.target; // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2020. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2021. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2022. // See #6198.
  2023. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2024. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2025. lastHoveredTarget = lastHovered.target;
  2026. }
  2027. var hovered = this._hovered = isOutside ? {
  2028. x: x,
  2029. y: y
  2030. } : this.findHover(x, y);
  2031. var hoveredTarget = hovered.target;
  2032. var proxy = this.proxy;
  2033. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default'); // Mouse out on previous hovered element
  2034. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2035. this.dispatchToElement(lastHovered, 'mouseout', event);
  2036. } // Mouse moving on one element
  2037. this.dispatchToElement(hovered, 'mousemove', event); // Mouse over on a new element
  2038. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2039. this.dispatchToElement(hovered, 'mouseover', event);
  2040. }
  2041. },
  2042. mouseout: function (event) {
  2043. var eventControl = event.zrEventControl;
  2044. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2045. if (eventControl !== 'only_globalout') {
  2046. this.dispatchToElement(this._hovered, 'mouseout', event);
  2047. }
  2048. if (eventControl !== 'no_globalout') {
  2049. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2050. // the `globalout` should have been triggered. But currently not.
  2051. !zrIsToLocalDOM && this.trigger('globalout', {
  2052. type: 'globalout',
  2053. event: event
  2054. });
  2055. }
  2056. },
  2057. /**
  2058. * Resize
  2059. */
  2060. resize: function (event) {
  2061. this._hovered = {};
  2062. },
  2063. /**
  2064. * Dispatch event
  2065. * @param {string} eventName
  2066. * @param {event=} eventArgs
  2067. */
  2068. dispatch: function (eventName, eventArgs) {
  2069. var handler = this[eventName];
  2070. handler && handler.call(this, eventArgs);
  2071. },
  2072. /**
  2073. * Dispose
  2074. */
  2075. dispose: function () {
  2076. this.proxy.dispose();
  2077. this.storage = this.proxy = this.painter = null;
  2078. },
  2079. /**
  2080. * 设置默认的cursor style
  2081. * @param {string} [cursorStyle='default'] 例如 crosshair
  2082. */
  2083. setCursorStyle: function (cursorStyle) {
  2084. var proxy = this.proxy;
  2085. proxy.setCursor && proxy.setCursor(cursorStyle);
  2086. },
  2087. /**
  2088. * 事件分发代理
  2089. *
  2090. * @private
  2091. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2092. * @param {string} eventName 事件名称
  2093. * @param {Object} event 事件对象
  2094. */
  2095. dispatchToElement: function (targetInfo, eventName, event) {
  2096. targetInfo = targetInfo || {};
  2097. var el = targetInfo.target;
  2098. if (el && el.silent) {
  2099. return;
  2100. }
  2101. var eventHandler = 'on' + eventName;
  2102. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2103. while (el) {
  2104. el[eventHandler] && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2105. el.trigger(eventName, eventPacket);
  2106. el = el.parent;
  2107. if (eventPacket.cancelBubble) {
  2108. break;
  2109. }
  2110. }
  2111. if (!eventPacket.cancelBubble) {
  2112. // 冒泡到顶级 zrender 对象
  2113. this.trigger(eventName, eventPacket); // 分发事件到用户自定义层
  2114. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2115. this.painter && this.painter.eachOtherLayer(function (layer) {
  2116. if (typeof layer[eventHandler] === 'function') {
  2117. layer[eventHandler].call(layer, eventPacket);
  2118. }
  2119. if (layer.trigger) {
  2120. layer.trigger(eventName, eventPacket);
  2121. }
  2122. });
  2123. }
  2124. },
  2125. /**
  2126. * @private
  2127. * @param {number} x
  2128. * @param {number} y
  2129. * @param {module:zrender/graphic/Displayable} exclude
  2130. * @return {model:zrender/Element}
  2131. * @method
  2132. */
  2133. findHover: function (x, y, exclude) {
  2134. var list = this.storage.getDisplayList();
  2135. var out = {
  2136. x: x,
  2137. y: y
  2138. };
  2139. for (var i = list.length - 1; i >= 0; i--) {
  2140. var hoverCheckResult;
  2141. if (list[i] !== exclude // getDisplayList may include ignored item in VML mode
  2142. && !list[i].ignore && (hoverCheckResult = isHover(list[i], x, y))) {
  2143. !out.topTarget && (out.topTarget = list[i]);
  2144. if (hoverCheckResult !== SILENT) {
  2145. out.target = list[i];
  2146. break;
  2147. }
  2148. }
  2149. }
  2150. return out;
  2151. },
  2152. processGesture: function (event, stage) {
  2153. if (!this._gestureMgr) {
  2154. this._gestureMgr = new GestureMgr();
  2155. }
  2156. var gestureMgr = this._gestureMgr;
  2157. stage === 'start' && gestureMgr.clear();
  2158. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2159. stage === 'end' && gestureMgr.clear(); // Do not do any preventDefault here. Upper application do that if necessary.
  2160. if (gestureInfo) {
  2161. var type = gestureInfo.type;
  2162. event.gestureEvent = type;
  2163. this.dispatchToElement({
  2164. target: gestureInfo.target
  2165. }, type, gestureInfo.event);
  2166. }
  2167. }
  2168. }; // Common handlers
  2169. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2170. Handler.prototype[name] = function (event) {
  2171. var x = event.zrX;
  2172. var y = event.zrY;
  2173. var isOutside = isOutsideBoundary(this, x, y);
  2174. var hovered;
  2175. var hoveredTarget;
  2176. if (name !== 'mouseup' || !isOutside) {
  2177. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2178. hovered = this.findHover(x, y);
  2179. hoveredTarget = hovered.target;
  2180. }
  2181. if (name === 'mousedown') {
  2182. this._downEl = hoveredTarget;
  2183. this._downPoint = [event.zrX, event.zrY]; // In case click triggered before mouseup
  2184. this._upEl = hoveredTarget;
  2185. } else if (name === 'mouseup') {
  2186. this._upEl = hoveredTarget;
  2187. } else if (name === 'click') {
  2188. if (this._downEl !== this._upEl // Original click event is triggered on the whole canvas element,
  2189. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2190. // which should be filtered, otherwise it will bring trouble to
  2191. // pan and zoom.
  2192. || !this._downPoint // Arbitrary value
  2193. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2194. return;
  2195. }
  2196. this._downPoint = null;
  2197. }
  2198. this.dispatchToElement(hovered, name, event);
  2199. };
  2200. });
  2201. function isHover(displayable, x, y) {
  2202. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2203. var el = displayable;
  2204. var isSilent;
  2205. while (el) {
  2206. // If clipped by ancestor.
  2207. // FIXME: If clipPath has neither stroke nor fill,
  2208. // el.clipPath.contain(x, y) will always return false.
  2209. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2210. return false;
  2211. }
  2212. if (el.silent) {
  2213. isSilent = true;
  2214. }
  2215. el = el.parent;
  2216. }
  2217. return isSilent ? SILENT : true;
  2218. }
  2219. return false;
  2220. }
  2221. /**
  2222. * See [Drag outside].
  2223. */
  2224. function isOutsideBoundary(handlerInstance, x, y) {
  2225. var painter = handlerInstance.painter;
  2226. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2227. }
  2228. mixin(Handler, Eventful);
  2229. mixin(Handler, Draggable);
  2230. /**
  2231. * 3x2矩阵操作类
  2232. * @exports zrender/tool/matrix
  2233. */
  2234. /* global Float32Array */
  2235. var ArrayCtor$1 = typeof Float32Array === 'undefined' ? Array : Float32Array;
  2236. /**
  2237. * Create a identity matrix.
  2238. * @return {Float32Array|Array.<number>}
  2239. */
  2240. function create$1() {
  2241. var out = new ArrayCtor$1(6);
  2242. identity(out);
  2243. return out;
  2244. }
  2245. /**
  2246. * 设置矩阵为单位矩阵
  2247. * @param {Float32Array|Array.<number>} out
  2248. */
  2249. function identity(out) {
  2250. out[0] = 1;
  2251. out[1] = 0;
  2252. out[2] = 0;
  2253. out[3] = 1;
  2254. out[4] = 0;
  2255. out[5] = 0;
  2256. return out;
  2257. }
  2258. /**
  2259. * 复制矩阵
  2260. * @param {Float32Array|Array.<number>} out
  2261. * @param {Float32Array|Array.<number>} m
  2262. */
  2263. function copy$1(out, m) {
  2264. out[0] = m[0];
  2265. out[1] = m[1];
  2266. out[2] = m[2];
  2267. out[3] = m[3];
  2268. out[4] = m[4];
  2269. out[5] = m[5];
  2270. return out;
  2271. }
  2272. /**
  2273. * 矩阵相乘
  2274. * @param {Float32Array|Array.<number>} out
  2275. * @param {Float32Array|Array.<number>} m1
  2276. * @param {Float32Array|Array.<number>} m2
  2277. */
  2278. function mul$1(out, m1, m2) {
  2279. // Consider matrix.mul(m, m2, m);
  2280. // where out is the same as m2.
  2281. // So use temp variable to escape error.
  2282. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2283. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2284. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2285. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2286. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2287. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2288. out[0] = out0;
  2289. out[1] = out1;
  2290. out[2] = out2;
  2291. out[3] = out3;
  2292. out[4] = out4;
  2293. out[5] = out5;
  2294. return out;
  2295. }
  2296. /**
  2297. * 平移变换
  2298. * @param {Float32Array|Array.<number>} out
  2299. * @param {Float32Array|Array.<number>} a
  2300. * @param {Float32Array|Array.<number>} v
  2301. */
  2302. function translate(out, a, v) {
  2303. out[0] = a[0];
  2304. out[1] = a[1];
  2305. out[2] = a[2];
  2306. out[3] = a[3];
  2307. out[4] = a[4] + v[0];
  2308. out[5] = a[5] + v[1];
  2309. return out;
  2310. }
  2311. /**
  2312. * 旋转变换
  2313. * @param {Float32Array|Array.<number>} out
  2314. * @param {Float32Array|Array.<number>} a
  2315. * @param {number} rad
  2316. */
  2317. function rotate(out, a, rad) {
  2318. var aa = a[0];
  2319. var ac = a[2];
  2320. var atx = a[4];
  2321. var ab = a[1];
  2322. var ad = a[3];
  2323. var aty = a[5];
  2324. var st = Math.sin(rad);
  2325. var ct = Math.cos(rad);
  2326. out[0] = aa * ct + ab * st;
  2327. out[1] = -aa * st + ab * ct;
  2328. out[2] = ac * ct + ad * st;
  2329. out[3] = -ac * st + ct * ad;
  2330. out[4] = ct * atx + st * aty;
  2331. out[5] = ct * aty - st * atx;
  2332. return out;
  2333. }
  2334. /**
  2335. * 缩放变换
  2336. * @param {Float32Array|Array.<number>} out
  2337. * @param {Float32Array|Array.<number>} a
  2338. * @param {Float32Array|Array.<number>} v
  2339. */
  2340. function scale$1(out, a, v) {
  2341. var vx = v[0];
  2342. var vy = v[1];
  2343. out[0] = a[0] * vx;
  2344. out[1] = a[1] * vy;
  2345. out[2] = a[2] * vx;
  2346. out[3] = a[3] * vy;
  2347. out[4] = a[4] * vx;
  2348. out[5] = a[5] * vy;
  2349. return out;
  2350. }
  2351. /**
  2352. * 求逆矩阵
  2353. * @param {Float32Array|Array.<number>} out
  2354. * @param {Float32Array|Array.<number>} a
  2355. */
  2356. function invert(out, a) {
  2357. var aa = a[0];
  2358. var ac = a[2];
  2359. var atx = a[4];
  2360. var ab = a[1];
  2361. var ad = a[3];
  2362. var aty = a[5];
  2363. var det = aa * ad - ab * ac;
  2364. if (!det) {
  2365. return null;
  2366. }
  2367. det = 1.0 / det;
  2368. out[0] = ad * det;
  2369. out[1] = -ab * det;
  2370. out[2] = -ac * det;
  2371. out[3] = aa * det;
  2372. out[4] = (ac * aty - ad * atx) * det;
  2373. out[5] = (ab * atx - aa * aty) * det;
  2374. return out;
  2375. }
  2376. /**
  2377. * Clone a new matrix.
  2378. * @param {Float32Array|Array.<number>} a
  2379. */
  2380. function clone$2(a) {
  2381. var b = create$1();
  2382. copy$1(b, a);
  2383. return b;
  2384. }
  2385. var matrix = (Object.freeze || Object)({
  2386. create: create$1,
  2387. identity: identity,
  2388. copy: copy$1,
  2389. mul: mul$1,
  2390. translate: translate,
  2391. rotate: rotate,
  2392. scale: scale$1,
  2393. invert: invert,
  2394. clone: clone$2
  2395. });
  2396. /**
  2397. * 提供变换扩展
  2398. * @module zrender/mixin/Transformable
  2399. * @author pissang (https://www.github.com/pissang)
  2400. */
  2401. var mIdentity = identity;
  2402. var EPSILON = 5e-5;
  2403. function isNotAroundZero(val) {
  2404. return val > EPSILON || val < -EPSILON;
  2405. }
  2406. /**
  2407. * @alias module:zrender/mixin/Transformable
  2408. * @constructor
  2409. */
  2410. var Transformable = function (opts) {
  2411. opts = opts || {}; // If there are no given position, rotation, scale
  2412. if (!opts.position) {
  2413. /**
  2414. * 平移
  2415. * @type {Array.<number>}
  2416. * @default [0, 0]
  2417. */
  2418. this.position = [0, 0];
  2419. }
  2420. if (opts.rotation == null) {
  2421. /**
  2422. * 旋转
  2423. * @type {Array.<number>}
  2424. * @default 0
  2425. */
  2426. this.rotation = 0;
  2427. }
  2428. if (!opts.scale) {
  2429. /**
  2430. * 缩放
  2431. * @type {Array.<number>}
  2432. * @default [1, 1]
  2433. */
  2434. this.scale = [1, 1];
  2435. }
  2436. /**
  2437. * 旋转和缩放的原点
  2438. * @type {Array.<number>}
  2439. * @default null
  2440. */
  2441. this.origin = this.origin || null;
  2442. };
  2443. var transformableProto = Transformable.prototype;
  2444. transformableProto.transform = null;
  2445. /**
  2446. * 判断是否需要有坐标变换
  2447. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2448. */
  2449. transformableProto.needLocalTransform = function () {
  2450. return isNotAroundZero(this.rotation) || isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) || isNotAroundZero(this.scale[0] - 1) || isNotAroundZero(this.scale[1] - 1);
  2451. };
  2452. var scaleTmp = [];
  2453. transformableProto.updateTransform = function () {
  2454. var parent = this.parent;
  2455. var parentHasTransform = parent && parent.transform;
  2456. var needLocalTransform = this.needLocalTransform();
  2457. var m = this.transform;
  2458. if (!(needLocalTransform || parentHasTransform)) {
  2459. m && mIdentity(m);
  2460. return;
  2461. }
  2462. m = m || create$1();
  2463. if (needLocalTransform) {
  2464. this.getLocalTransform(m);
  2465. } else {
  2466. mIdentity(m);
  2467. } // 应用父节点变换
  2468. if (parentHasTransform) {
  2469. if (needLocalTransform) {
  2470. mul$1(m, parent.transform, m);
  2471. } else {
  2472. copy$1(m, parent.transform);
  2473. }
  2474. } // 保存这个变换矩阵
  2475. this.transform = m;
  2476. var globalScaleRatio = this.globalScaleRatio;
  2477. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2478. this.getGlobalScale(scaleTmp);
  2479. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2480. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2481. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2482. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2483. m[0] *= sx;
  2484. m[1] *= sx;
  2485. m[2] *= sy;
  2486. m[3] *= sy;
  2487. }
  2488. this.invTransform = this.invTransform || create$1();
  2489. invert(this.invTransform, m);
  2490. };
  2491. transformableProto.getLocalTransform = function (m) {
  2492. return Transformable.getLocalTransform(this, m);
  2493. };
  2494. /**
  2495. * 将自己的transform应用到context上
  2496. * @param {CanvasRenderingContext2D} ctx
  2497. */
  2498. transformableProto.setTransform = function (ctx) {
  2499. var m = this.transform;
  2500. var dpr = ctx.dpr || 1;
  2501. if (m) {
  2502. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2503. } else {
  2504. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2505. }
  2506. };
  2507. transformableProto.restoreTransform = function (ctx) {
  2508. var dpr = ctx.dpr || 1;
  2509. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2510. };
  2511. var tmpTransform = [];
  2512. var originTransform = create$1();
  2513. transformableProto.setLocalTransform = function (m) {
  2514. if (!m) {
  2515. // TODO return or set identity?
  2516. return;
  2517. }
  2518. var sx = m[0] * m[0] + m[1] * m[1];
  2519. var sy = m[2] * m[2] + m[3] * m[3];
  2520. var position = this.position;
  2521. var scale$$1 = this.scale;
  2522. if (isNotAroundZero(sx - 1)) {
  2523. sx = Math.sqrt(sx);
  2524. }
  2525. if (isNotAroundZero(sy - 1)) {
  2526. sy = Math.sqrt(sy);
  2527. }
  2528. if (m[0] < 0) {
  2529. sx = -sx;
  2530. }
  2531. if (m[3] < 0) {
  2532. sy = -sy;
  2533. }
  2534. position[0] = m[4];
  2535. position[1] = m[5];
  2536. scale$$1[0] = sx;
  2537. scale$$1[1] = sy;
  2538. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2539. };
  2540. /**
  2541. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2542. */
  2543. transformableProto.decomposeTransform = function () {
  2544. if (!this.transform) {
  2545. return;
  2546. }
  2547. var parent = this.parent;
  2548. var m = this.transform;
  2549. if (parent && parent.transform) {
  2550. // Get local transform and decompose them to position, scale, rotation
  2551. mul$1(tmpTransform, parent.invTransform, m);
  2552. m = tmpTransform;
  2553. }
  2554. var origin = this.origin;
  2555. if (origin && (origin[0] || origin[1])) {
  2556. originTransform[4] = origin[0];
  2557. originTransform[5] = origin[1];
  2558. mul$1(tmpTransform, m, originTransform);
  2559. tmpTransform[4] -= origin[0];
  2560. tmpTransform[5] -= origin[1];
  2561. m = tmpTransform;
  2562. }
  2563. this.setLocalTransform(m);
  2564. };
  2565. /**
  2566. * Get global scale
  2567. * @return {Array.<number>}
  2568. */
  2569. transformableProto.getGlobalScale = function (out) {
  2570. var m = this.transform;
  2571. out = out || [];
  2572. if (!m) {
  2573. out[0] = 1;
  2574. out[1] = 1;
  2575. return out;
  2576. }
  2577. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2578. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2579. if (m[0] < 0) {
  2580. out[0] = -out[0];
  2581. }
  2582. if (m[3] < 0) {
  2583. out[1] = -out[1];
  2584. }
  2585. return out;
  2586. };
  2587. /**
  2588. * 变换坐标位置到 shape 的局部坐标空间
  2589. * @method
  2590. * @param {number} x
  2591. * @param {number} y
  2592. * @return {Array.<number>}
  2593. */
  2594. transformableProto.transformCoordToLocal = function (x, y) {
  2595. var v2 = [x, y];
  2596. var invTransform = this.invTransform;
  2597. if (invTransform) {
  2598. applyTransform(v2, v2, invTransform);
  2599. }
  2600. return v2;
  2601. };
  2602. /**
  2603. * 变换局部坐标位置到全局坐标空间
  2604. * @method
  2605. * @param {number} x
  2606. * @param {number} y
  2607. * @return {Array.<number>}
  2608. */
  2609. transformableProto.transformCoordToGlobal = function (x, y) {
  2610. var v2 = [x, y];
  2611. var transform = this.transform;
  2612. if (transform) {
  2613. applyTransform(v2, v2, transform);
  2614. }
  2615. return v2;
  2616. };
  2617. /**
  2618. * @static
  2619. * @param {Object} target
  2620. * @param {Array.<number>} target.origin
  2621. * @param {number} target.rotation
  2622. * @param {Array.<number>} target.position
  2623. * @param {Array.<number>} [m]
  2624. */
  2625. Transformable.getLocalTransform = function (target, m) {
  2626. m = m || [];
  2627. mIdentity(m);
  2628. var origin = target.origin;
  2629. var scale$$1 = target.scale || [1, 1];
  2630. var rotation = target.rotation || 0;
  2631. var position = target.position || [0, 0];
  2632. if (origin) {
  2633. // Translate to origin
  2634. m[4] -= origin[0];
  2635. m[5] -= origin[1];
  2636. }
  2637. scale$1(m, m, scale$$1);
  2638. if (rotation) {
  2639. rotate(m, m, rotation);
  2640. }
  2641. if (origin) {
  2642. // Translate back from origin
  2643. m[4] += origin[0];
  2644. m[5] += origin[1];
  2645. }
  2646. m[4] += position[0];
  2647. m[5] += position[1];
  2648. return m;
  2649. };
  2650. /**
  2651. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2652. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2653. * @exports zrender/animation/easing
  2654. */
  2655. var easing = {
  2656. /**
  2657. * @param {number} k
  2658. * @return {number}
  2659. */
  2660. linear: function (k) {
  2661. return k;
  2662. },
  2663. /**
  2664. * @param {number} k
  2665. * @return {number}
  2666. */
  2667. quadraticIn: function (k) {
  2668. return k * k;
  2669. },
  2670. /**
  2671. * @param {number} k
  2672. * @return {number}
  2673. */
  2674. quadraticOut: function (k) {
  2675. return k * (2 - k);
  2676. },
  2677. /**
  2678. * @param {number} k
  2679. * @return {number}
  2680. */
  2681. quadraticInOut: function (k) {
  2682. if ((k *= 2) < 1) {
  2683. return 0.5 * k * k;
  2684. }
  2685. return -0.5 * (--k * (k - 2) - 1);
  2686. },
  2687. // 三次方的缓动(t^3)
  2688. /**
  2689. * @param {number} k
  2690. * @return {number}
  2691. */
  2692. cubicIn: function (k) {
  2693. return k * k * k;
  2694. },
  2695. /**
  2696. * @param {number} k
  2697. * @return {number}
  2698. */
  2699. cubicOut: function (k) {
  2700. return --k * k * k + 1;
  2701. },
  2702. /**
  2703. * @param {number} k
  2704. * @return {number}
  2705. */
  2706. cubicInOut: function (k) {
  2707. if ((k *= 2) < 1) {
  2708. return 0.5 * k * k * k;
  2709. }
  2710. return 0.5 * ((k -= 2) * k * k + 2);
  2711. },
  2712. // 四次方的缓动(t^4)
  2713. /**
  2714. * @param {number} k
  2715. * @return {number}
  2716. */
  2717. quarticIn: function (k) {
  2718. return k * k * k * k;
  2719. },
  2720. /**
  2721. * @param {number} k
  2722. * @return {number}
  2723. */
  2724. quarticOut: function (k) {
  2725. return 1 - --k * k * k * k;
  2726. },
  2727. /**
  2728. * @param {number} k
  2729. * @return {number}
  2730. */
  2731. quarticInOut: function (k) {
  2732. if ((k *= 2) < 1) {
  2733. return 0.5 * k * k * k * k;
  2734. }
  2735. return -0.5 * ((k -= 2) * k * k * k - 2);
  2736. },
  2737. // 五次方的缓动(t^5)
  2738. /**
  2739. * @param {number} k
  2740. * @return {number}
  2741. */
  2742. quinticIn: function (k) {
  2743. return k * k * k * k * k;
  2744. },
  2745. /**
  2746. * @param {number} k
  2747. * @return {number}
  2748. */
  2749. quinticOut: function (k) {
  2750. return --k * k * k * k * k + 1;
  2751. },
  2752. /**
  2753. * @param {number} k
  2754. * @return {number}
  2755. */
  2756. quinticInOut: function (k) {
  2757. if ((k *= 2) < 1) {
  2758. return 0.5 * k * k * k * k * k;
  2759. }
  2760. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2761. },
  2762. // 正弦曲线的缓动(sin(t))
  2763. /**
  2764. * @param {number} k
  2765. * @return {number}
  2766. */
  2767. sinusoidalIn: function (k) {
  2768. return 1 - Math.cos(k * Math.PI / 2);
  2769. },
  2770. /**
  2771. * @param {number} k
  2772. * @return {number}
  2773. */
  2774. sinusoidalOut: function (k) {
  2775. return Math.sin(k * Math.PI / 2);
  2776. },
  2777. /**
  2778. * @param {number} k
  2779. * @return {number}
  2780. */
  2781. sinusoidalInOut: function (k) {
  2782. return 0.5 * (1 - Math.cos(Math.PI * k));
  2783. },
  2784. // 指数曲线的缓动(2^t)
  2785. /**
  2786. * @param {number} k
  2787. * @return {number}
  2788. */
  2789. exponentialIn: function (k) {
  2790. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2791. },
  2792. /**
  2793. * @param {number} k
  2794. * @return {number}
  2795. */
  2796. exponentialOut: function (k) {
  2797. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2798. },
  2799. /**
  2800. * @param {number} k
  2801. * @return {number}
  2802. */
  2803. exponentialInOut: function (k) {
  2804. if (k === 0) {
  2805. return 0;
  2806. }
  2807. if (k === 1) {
  2808. return 1;
  2809. }
  2810. if ((k *= 2) < 1) {
  2811. return 0.5 * Math.pow(1024, k - 1);
  2812. }
  2813. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2814. },
  2815. // 圆形曲线的缓动(sqrt(1-t^2))
  2816. /**
  2817. * @param {number} k
  2818. * @return {number}
  2819. */
  2820. circularIn: function (k) {
  2821. return 1 - Math.sqrt(1 - k * k);
  2822. },
  2823. /**
  2824. * @param {number} k
  2825. * @return {number}
  2826. */
  2827. circularOut: function (k) {
  2828. return Math.sqrt(1 - --k * k);
  2829. },
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. circularInOut: function (k) {
  2835. if ((k *= 2) < 1) {
  2836. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2837. }
  2838. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2839. },
  2840. // 创建类似于弹簧在停止前来回振荡的动画
  2841. /**
  2842. * @param {number} k
  2843. * @return {number}
  2844. */
  2845. elasticIn: function (k) {
  2846. var s;
  2847. var a = 0.1;
  2848. var p = 0.4;
  2849. if (k === 0) {
  2850. return 0;
  2851. }
  2852. if (k === 1) {
  2853. return 1;
  2854. }
  2855. if (!a || a < 1) {
  2856. a = 1;
  2857. s = p / 4;
  2858. } else {
  2859. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2860. }
  2861. return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
  2862. },
  2863. /**
  2864. * @param {number} k
  2865. * @return {number}
  2866. */
  2867. elasticOut: function (k) {
  2868. var s;
  2869. var a = 0.1;
  2870. var p = 0.4;
  2871. if (k === 0) {
  2872. return 0;
  2873. }
  2874. if (k === 1) {
  2875. return 1;
  2876. }
  2877. if (!a || a < 1) {
  2878. a = 1;
  2879. s = p / 4;
  2880. } else {
  2881. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2882. }
  2883. return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
  2884. },
  2885. /**
  2886. * @param {number} k
  2887. * @return {number}
  2888. */
  2889. elasticInOut: function (k) {
  2890. var s;
  2891. var a = 0.1;
  2892. var p = 0.4;
  2893. if (k === 0) {
  2894. return 0;
  2895. }
  2896. if (k === 1) {
  2897. return 1;
  2898. }
  2899. if (!a || a < 1) {
  2900. a = 1;
  2901. s = p / 4;
  2902. } else {
  2903. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2904. }
  2905. if ((k *= 2) < 1) {
  2906. return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
  2907. }
  2908. return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2909. },
  2910. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2911. /**
  2912. * @param {number} k
  2913. * @return {number}
  2914. */
  2915. backIn: function (k) {
  2916. var s = 1.70158;
  2917. return k * k * ((s + 1) * k - s);
  2918. },
  2919. /**
  2920. * @param {number} k
  2921. * @return {number}
  2922. */
  2923. backOut: function (k) {
  2924. var s = 1.70158;
  2925. return --k * k * ((s + 1) * k + s) + 1;
  2926. },
  2927. /**
  2928. * @param {number} k
  2929. * @return {number}
  2930. */
  2931. backInOut: function (k) {
  2932. var s = 1.70158 * 1.525;
  2933. if ((k *= 2) < 1) {
  2934. return 0.5 * (k * k * ((s + 1) * k - s));
  2935. }
  2936. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2937. },
  2938. // 创建弹跳效果
  2939. /**
  2940. * @param {number} k
  2941. * @return {number}
  2942. */
  2943. bounceIn: function (k) {
  2944. return 1 - easing.bounceOut(1 - k);
  2945. },
  2946. /**
  2947. * @param {number} k
  2948. * @return {number}
  2949. */
  2950. bounceOut: function (k) {
  2951. if (k < 1 / 2.75) {
  2952. return 7.5625 * k * k;
  2953. } else if (k < 2 / 2.75) {
  2954. return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
  2955. } else if (k < 2.5 / 2.75) {
  2956. return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
  2957. } else {
  2958. return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
  2959. }
  2960. },
  2961. /**
  2962. * @param {number} k
  2963. * @return {number}
  2964. */
  2965. bounceInOut: function (k) {
  2966. if (k < 0.5) {
  2967. return easing.bounceIn(k * 2) * 0.5;
  2968. }
  2969. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2970. }
  2971. };
  2972. /**
  2973. * 动画主控制器
  2974. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2975. * @config life(1000) 动画时长
  2976. * @config delay(0) 动画延迟时间
  2977. * @config loop(true)
  2978. * @config gap(0) 循环的间隔时间
  2979. * @config onframe
  2980. * @config easing(optional)
  2981. * @config ondestroy(optional)
  2982. * @config onrestart(optional)
  2983. *
  2984. * TODO pause
  2985. */
  2986. function Clip(options) {
  2987. this._target = options.target; // 生命周期
  2988. this._life = options.life || 1000; // 延时
  2989. this._delay = options.delay || 0; // 开始时间
  2990. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2991. this._initialized = false; // 是否循环
  2992. this.loop = options.loop == null ? false : options.loop;
  2993. this.gap = options.gap || 0;
  2994. this.easing = options.easing || 'Linear';
  2995. this.onframe = options.onframe;
  2996. this.ondestroy = options.ondestroy;
  2997. this.onrestart = options.onrestart;
  2998. this._pausedTime = 0;
  2999. this._paused = false;
  3000. }
  3001. Clip.prototype = {
  3002. constructor: Clip,
  3003. step: function (globalTime, deltaTime) {
  3004. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3005. // PENDING
  3006. if (!this._initialized) {
  3007. this._startTime = globalTime + this._delay;
  3008. this._initialized = true;
  3009. }
  3010. if (this._paused) {
  3011. this._pausedTime += deltaTime;
  3012. return;
  3013. }
  3014. var percent = (globalTime - this._startTime - this._pausedTime) / this._life; // 还没开始
  3015. if (percent < 0) {
  3016. return;
  3017. }
  3018. percent = Math.min(percent, 1);
  3019. var easing$$1 = this.easing;
  3020. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3021. var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent;
  3022. this.fire('frame', schedule); // 结束
  3023. if (percent === 1) {
  3024. if (this.loop) {
  3025. this.restart(globalTime); // 重新开始周期
  3026. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3027. return 'restart';
  3028. } // 动画完成将这个控制器标识为待删除
  3029. // 在Animation.update中进行批量删除
  3030. this._needsRemove = true;
  3031. return 'destroy';
  3032. }
  3033. return null;
  3034. },
  3035. restart: function (globalTime) {
  3036. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3037. this._startTime = globalTime - remainder + this.gap;
  3038. this._pausedTime = 0;
  3039. this._needsRemove = false;
  3040. },
  3041. fire: function (eventType, arg) {
  3042. eventType = 'on' + eventType;
  3043. if (this[eventType]) {
  3044. this[eventType](this._target, arg);
  3045. }
  3046. },
  3047. pause: function () {
  3048. this._paused = true;
  3049. },
  3050. resume: function () {
  3051. this._paused = false;
  3052. }
  3053. };
  3054. // Simple LRU cache use doubly linked list
  3055. // @module zrender/core/LRU
  3056. /**
  3057. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3058. * @constructor
  3059. */
  3060. var LinkedList = function () {
  3061. /**
  3062. * @type {module:zrender/core/LRU~Entry}
  3063. */
  3064. this.head = null;
  3065. /**
  3066. * @type {module:zrender/core/LRU~Entry}
  3067. */
  3068. this.tail = null;
  3069. this._len = 0;
  3070. };
  3071. var linkedListProto = LinkedList.prototype;
  3072. /**
  3073. * Insert a new value at the tail
  3074. * @param {} val
  3075. * @return {module:zrender/core/LRU~Entry}
  3076. */
  3077. linkedListProto.insert = function (val) {
  3078. var entry = new Entry(val);
  3079. this.insertEntry(entry);
  3080. return entry;
  3081. };
  3082. /**
  3083. * Insert an entry at the tail
  3084. * @param {module:zrender/core/LRU~Entry} entry
  3085. */
  3086. linkedListProto.insertEntry = function (entry) {
  3087. if (!this.head) {
  3088. this.head = this.tail = entry;
  3089. } else {
  3090. this.tail.next = entry;
  3091. entry.prev = this.tail;
  3092. entry.next = null;
  3093. this.tail = entry;
  3094. }
  3095. this._len++;
  3096. };
  3097. /**
  3098. * Remove entry.
  3099. * @param {module:zrender/core/LRU~Entry} entry
  3100. */
  3101. linkedListProto.remove = function (entry) {
  3102. var prev = entry.prev;
  3103. var next = entry.next;
  3104. if (prev) {
  3105. prev.next = next;
  3106. } else {
  3107. // Is head
  3108. this.head = next;
  3109. }
  3110. if (next) {
  3111. next.prev = prev;
  3112. } else {
  3113. // Is tail
  3114. this.tail = prev;
  3115. }
  3116. entry.next = entry.prev = null;
  3117. this._len--;
  3118. };
  3119. /**
  3120. * @return {number}
  3121. */
  3122. linkedListProto.len = function () {
  3123. return this._len;
  3124. };
  3125. /**
  3126. * Clear list
  3127. */
  3128. linkedListProto.clear = function () {
  3129. this.head = this.tail = null;
  3130. this._len = 0;
  3131. };
  3132. /**
  3133. * @constructor
  3134. * @param {} val
  3135. */
  3136. var Entry = function (val) {
  3137. /**
  3138. * @type {}
  3139. */
  3140. this.value = val;
  3141. /**
  3142. * @type {module:zrender/core/LRU~Entry}
  3143. */
  3144. this.next;
  3145. /**
  3146. * @type {module:zrender/core/LRU~Entry}
  3147. */
  3148. this.prev;
  3149. };
  3150. /**
  3151. * LRU Cache
  3152. * @constructor
  3153. * @alias module:zrender/core/LRU
  3154. */
  3155. var LRU = function (maxSize) {
  3156. this._list = new LinkedList();
  3157. this._map = {};
  3158. this._maxSize = maxSize || 10;
  3159. this._lastRemovedEntry = null;
  3160. };
  3161. var LRUProto = LRU.prototype;
  3162. /**
  3163. * @param {string} key
  3164. * @param {} value
  3165. * @return {} Removed value
  3166. */
  3167. LRUProto.put = function (key, value) {
  3168. var list = this._list;
  3169. var map = this._map;
  3170. var removed = null;
  3171. if (map[key] == null) {
  3172. var len = list.len(); // Reuse last removed entry
  3173. var entry = this._lastRemovedEntry;
  3174. if (len >= this._maxSize && len > 0) {
  3175. // Remove the least recently used
  3176. var leastUsedEntry = list.head;
  3177. list.remove(leastUsedEntry);
  3178. delete map[leastUsedEntry.key];
  3179. removed = leastUsedEntry.value;
  3180. this._lastRemovedEntry = leastUsedEntry;
  3181. }
  3182. if (entry) {
  3183. entry.value = value;
  3184. } else {
  3185. entry = new Entry(value);
  3186. }
  3187. entry.key = key;
  3188. list.insertEntry(entry);
  3189. map[key] = entry;
  3190. }
  3191. return removed;
  3192. };
  3193. /**
  3194. * @param {string} key
  3195. * @return {}
  3196. */
  3197. LRUProto.get = function (key) {
  3198. var entry = this._map[key];
  3199. var list = this._list;
  3200. if (entry != null) {
  3201. // Put the latest used entry in the tail
  3202. if (entry !== list.tail) {
  3203. list.remove(entry);
  3204. list.insertEntry(entry);
  3205. }
  3206. return entry.value;
  3207. }
  3208. };
  3209. /**
  3210. * Clear the cache
  3211. */
  3212. LRUProto.clear = function () {
  3213. this._list.clear();
  3214. this._map = {};
  3215. };
  3216. var kCSSColorTable = {
  3217. 'transparent': [0, 0, 0, 0],
  3218. 'aliceblue': [240, 248, 255, 1],
  3219. 'antiquewhite': [250, 235, 215, 1],
  3220. 'aqua': [0, 255, 255, 1],
  3221. 'aquamarine': [127, 255, 212, 1],
  3222. 'azure': [240, 255, 255, 1],
  3223. 'beige': [245, 245, 220, 1],
  3224. 'bisque': [255, 228, 196, 1],
  3225. 'black': [0, 0, 0, 1],
  3226. 'blanchedalmond': [255, 235, 205, 1],
  3227. 'blue': [0, 0, 255, 1],
  3228. 'blueviolet': [138, 43, 226, 1],
  3229. 'brown': [165, 42, 42, 1],
  3230. 'burlywood': [222, 184, 135, 1],
  3231. 'cadetblue': [95, 158, 160, 1],
  3232. 'chartreuse': [127, 255, 0, 1],
  3233. 'chocolate': [210, 105, 30, 1],
  3234. 'coral': [255, 127, 80, 1],
  3235. 'cornflowerblue': [100, 149, 237, 1],
  3236. 'cornsilk': [255, 248, 220, 1],
  3237. 'crimson': [220, 20, 60, 1],
  3238. 'cyan': [0, 255, 255, 1],
  3239. 'darkblue': [0, 0, 139, 1],
  3240. 'darkcyan': [0, 139, 139, 1],
  3241. 'darkgoldenrod': [184, 134, 11, 1],
  3242. 'darkgray': [169, 169, 169, 1],
  3243. 'darkgreen': [0, 100, 0, 1],
  3244. 'darkgrey': [169, 169, 169, 1],
  3245. 'darkkhaki': [189, 183, 107, 1],
  3246. 'darkmagenta': [139, 0, 139, 1],
  3247. 'darkolivegreen': [85, 107, 47, 1],
  3248. 'darkorange': [255, 140, 0, 1],
  3249. 'darkorchid': [153, 50, 204, 1],
  3250. 'darkred': [139, 0, 0, 1],
  3251. 'darksalmon': [233, 150, 122, 1],
  3252. 'darkseagreen': [143, 188, 143, 1],
  3253. 'darkslateblue': [72, 61, 139, 1],
  3254. 'darkslategray': [47, 79, 79, 1],
  3255. 'darkslategrey': [47, 79, 79, 1],
  3256. 'darkturquoise': [0, 206, 209, 1],
  3257. 'darkviolet': [148, 0, 211, 1],
  3258. 'deeppink': [255, 20, 147, 1],
  3259. 'deepskyblue': [0, 191, 255, 1],
  3260. 'dimgray': [105, 105, 105, 1],
  3261. 'dimgrey': [105, 105, 105, 1],
  3262. 'dodgerblue': [30, 144, 255, 1],
  3263. 'firebrick': [178, 34, 34, 1],
  3264. 'floralwhite': [255, 250, 240, 1],
  3265. 'forestgreen': [34, 139, 34, 1],
  3266. 'fuchsia': [255, 0, 255, 1],
  3267. 'gainsboro': [220, 220, 220, 1],
  3268. 'ghostwhite': [248, 248, 255, 1],
  3269. 'gold': [255, 215, 0, 1],
  3270. 'goldenrod': [218, 165, 32, 1],
  3271. 'gray': [128, 128, 128, 1],
  3272. 'green': [0, 128, 0, 1],
  3273. 'greenyellow': [173, 255, 47, 1],
  3274. 'grey': [128, 128, 128, 1],
  3275. 'honeydew': [240, 255, 240, 1],
  3276. 'hotpink': [255, 105, 180, 1],
  3277. 'indianred': [205, 92, 92, 1],
  3278. 'indigo': [75, 0, 130, 1],
  3279. 'ivory': [255, 255, 240, 1],
  3280. 'khaki': [240, 230, 140, 1],
  3281. 'lavender': [230, 230, 250, 1],
  3282. 'lavenderblush': [255, 240, 245, 1],
  3283. 'lawngreen': [124, 252, 0, 1],
  3284. 'lemonchiffon': [255, 250, 205, 1],
  3285. 'lightblue': [173, 216, 230, 1],
  3286. 'lightcoral': [240, 128, 128, 1],
  3287. 'lightcyan': [224, 255, 255, 1],
  3288. 'lightgoldenrodyellow': [250, 250, 210, 1],
  3289. 'lightgray': [211, 211, 211, 1],
  3290. 'lightgreen': [144, 238, 144, 1],
  3291. 'lightgrey': [211, 211, 211, 1],
  3292. 'lightpink': [255, 182, 193, 1],
  3293. 'lightsalmon': [255, 160, 122, 1],
  3294. 'lightseagreen': [32, 178, 170, 1],
  3295. 'lightskyblue': [135, 206, 250, 1],
  3296. 'lightslategray': [119, 136, 153, 1],
  3297. 'lightslategrey': [119, 136, 153, 1],
  3298. 'lightsteelblue': [176, 196, 222, 1],
  3299. 'lightyellow': [255, 255, 224, 1],
  3300. 'lime': [0, 255, 0, 1],
  3301. 'limegreen': [50, 205, 50, 1],
  3302. 'linen': [250, 240, 230, 1],
  3303. 'magenta': [255, 0, 255, 1],
  3304. 'maroon': [128, 0, 0, 1],
  3305. 'mediumaquamarine': [102, 205, 170, 1],
  3306. 'mediumblue': [0, 0, 205, 1],
  3307. 'mediumorchid': [186, 85, 211, 1],
  3308. 'mediumpurple': [147, 112, 219, 1],
  3309. 'mediumseagreen': [60, 179, 113, 1],
  3310. 'mediumslateblue': [123, 104, 238, 1],
  3311. 'mediumspringgreen': [0, 250, 154, 1],
  3312. 'mediumturquoise': [72, 209, 204, 1],
  3313. 'mediumvioletred': [199, 21, 133, 1],
  3314. 'midnightblue': [25, 25, 112, 1],
  3315. 'mintcream': [245, 255, 250, 1],
  3316. 'mistyrose': [255, 228, 225, 1],
  3317. 'moccasin': [255, 228, 181, 1],
  3318. 'navajowhite': [255, 222, 173, 1],
  3319. 'navy': [0, 0, 128, 1],
  3320. 'oldlace': [253, 245, 230, 1],
  3321. 'olive': [128, 128, 0, 1],
  3322. 'olivedrab': [107, 142, 35, 1],
  3323. 'orange': [255, 165, 0, 1],
  3324. 'orangered': [255, 69, 0, 1],
  3325. 'orchid': [218, 112, 214, 1],
  3326. 'palegoldenrod': [238, 232, 170, 1],
  3327. 'palegreen': [152, 251, 152, 1],
  3328. 'paleturquoise': [175, 238, 238, 1],
  3329. 'palevioletred': [219, 112, 147, 1],
  3330. 'papayawhip': [255, 239, 213, 1],
  3331. 'peachpuff': [255, 218, 185, 1],
  3332. 'peru': [205, 133, 63, 1],
  3333. 'pink': [255, 192, 203, 1],
  3334. 'plum': [221, 160, 221, 1],
  3335. 'powderblue': [176, 224, 230, 1],
  3336. 'purple': [128, 0, 128, 1],
  3337. 'red': [255, 0, 0, 1],
  3338. 'rosybrown': [188, 143, 143, 1],
  3339. 'royalblue': [65, 105, 225, 1],
  3340. 'saddlebrown': [139, 69, 19, 1],
  3341. 'salmon': [250, 128, 114, 1],
  3342. 'sandybrown': [244, 164, 96, 1],
  3343. 'seagreen': [46, 139, 87, 1],
  3344. 'seashell': [255, 245, 238, 1],
  3345. 'sienna': [160, 82, 45, 1],
  3346. 'silver': [192, 192, 192, 1],
  3347. 'skyblue': [135, 206, 235, 1],
  3348. 'slateblue': [106, 90, 205, 1],
  3349. 'slategray': [112, 128, 144, 1],
  3350. 'slategrey': [112, 128, 144, 1],
  3351. 'snow': [255, 250, 250, 1],
  3352. 'springgreen': [0, 255, 127, 1],
  3353. 'steelblue': [70, 130, 180, 1],
  3354. 'tan': [210, 180, 140, 1],
  3355. 'teal': [0, 128, 128, 1],
  3356. 'thistle': [216, 191, 216, 1],
  3357. 'tomato': [255, 99, 71, 1],
  3358. 'turquoise': [64, 224, 208, 1],
  3359. 'violet': [238, 130, 238, 1],
  3360. 'wheat': [245, 222, 179, 1],
  3361. 'white': [255, 255, 255, 1],
  3362. 'whitesmoke': [245, 245, 245, 1],
  3363. 'yellow': [255, 255, 0, 1],
  3364. 'yellowgreen': [154, 205, 50, 1]
  3365. };
  3366. function clampCssByte(i) {
  3367. // Clamp to integer 0 .. 255.
  3368. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3369. return i < 0 ? 0 : i > 255 ? 255 : i;
  3370. }
  3371. function clampCssAngle(i) {
  3372. // Clamp to integer 0 .. 360.
  3373. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3374. return i < 0 ? 0 : i > 360 ? 360 : i;
  3375. }
  3376. function clampCssFloat(f) {
  3377. // Clamp to float 0.0 .. 1.0.
  3378. return f < 0 ? 0 : f > 1 ? 1 : f;
  3379. }
  3380. function parseCssInt(str) {
  3381. // int or percentage.
  3382. if (str.length && str.charAt(str.length - 1) === '%') {
  3383. return clampCssByte(parseFloat(str) / 100 * 255);
  3384. }
  3385. return clampCssByte(parseInt(str, 10));
  3386. }
  3387. function parseCssFloat(str) {
  3388. // float or percentage.
  3389. if (str.length && str.charAt(str.length - 1) === '%') {
  3390. return clampCssFloat(parseFloat(str) / 100);
  3391. }
  3392. return clampCssFloat(parseFloat(str));
  3393. }
  3394. function cssHueToRgb(m1, m2, h) {
  3395. if (h < 0) {
  3396. h += 1;
  3397. } else if (h > 1) {
  3398. h -= 1;
  3399. }
  3400. if (h * 6 < 1) {
  3401. return m1 + (m2 - m1) * h * 6;
  3402. }
  3403. if (h * 2 < 1) {
  3404. return m2;
  3405. }
  3406. if (h * 3 < 2) {
  3407. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3408. }
  3409. return m1;
  3410. }
  3411. function lerpNumber(a, b, p) {
  3412. return a + (b - a) * p;
  3413. }
  3414. function setRgba(out, r, g, b, a) {
  3415. out[0] = r;
  3416. out[1] = g;
  3417. out[2] = b;
  3418. out[3] = a;
  3419. return out;
  3420. }
  3421. function copyRgba(out, a) {
  3422. out[0] = a[0];
  3423. out[1] = a[1];
  3424. out[2] = a[2];
  3425. out[3] = a[3];
  3426. return out;
  3427. }
  3428. var colorCache = new LRU(20);
  3429. var lastRemovedArr = null;
  3430. function putToCache(colorStr, rgbaArr) {
  3431. // Reuse removed array
  3432. if (lastRemovedArr) {
  3433. copyRgba(lastRemovedArr, rgbaArr);
  3434. }
  3435. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || rgbaArr.slice());
  3436. }
  3437. /**
  3438. * @param {string} colorStr
  3439. * @param {Array.<number>} out
  3440. * @return {Array.<number>}
  3441. * @memberOf module:zrender/util/color
  3442. */
  3443. function parse(colorStr, rgbaArr) {
  3444. if (!colorStr) {
  3445. return;
  3446. }
  3447. rgbaArr = rgbaArr || [];
  3448. var cached = colorCache.get(colorStr);
  3449. if (cached) {
  3450. return copyRgba(rgbaArr, cached);
  3451. } // colorStr may be not string
  3452. colorStr = colorStr + ''; // Remove all whitespace, not compliant, but should just be more accepting.
  3453. var str = colorStr.replace(/ /g, '').toLowerCase(); // Color keywords (and transparent) lookup.
  3454. if (str in kCSSColorTable) {
  3455. copyRgba(rgbaArr, kCSSColorTable[str]);
  3456. putToCache(colorStr, rgbaArr);
  3457. return rgbaArr;
  3458. } // #abc and #abc123 syntax.
  3459. if (str.charAt(0) === '#') {
  3460. if (str.length === 4) {
  3461. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3462. if (!(iv >= 0 && iv <= 0xfff)) {
  3463. setRgba(rgbaArr, 0, 0, 0, 1);
  3464. return; // Covers NaN.
  3465. }
  3466. setRgba(rgbaArr, (iv & 0xf00) >> 4 | (iv & 0xf00) >> 8, iv & 0xf0 | (iv & 0xf0) >> 4, iv & 0xf | (iv & 0xf) << 4, 1);
  3467. putToCache(colorStr, rgbaArr);
  3468. return rgbaArr;
  3469. } else if (str.length === 7) {
  3470. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3471. if (!(iv >= 0 && iv <= 0xffffff)) {
  3472. setRgba(rgbaArr, 0, 0, 0, 1);
  3473. return; // Covers NaN.
  3474. }
  3475. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1);
  3476. putToCache(colorStr, rgbaArr);
  3477. return rgbaArr;
  3478. }
  3479. return;
  3480. }
  3481. var op = str.indexOf('(');
  3482. var ep = str.indexOf(')');
  3483. if (op !== -1 && ep + 1 === str.length) {
  3484. var fname = str.substr(0, op);
  3485. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3486. var alpha = 1; // To allow case fallthrough.
  3487. switch (fname) {
  3488. case 'rgba':
  3489. if (params.length !== 4) {
  3490. setRgba(rgbaArr, 0, 0, 0, 1);
  3491. return;
  3492. }
  3493. alpha = parseCssFloat(params.pop());
  3494. // jshint ignore:line
  3495. // Fall through.
  3496. case 'rgb':
  3497. if (params.length !== 3) {
  3498. setRgba(rgbaArr, 0, 0, 0, 1);
  3499. return;
  3500. }
  3501. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  3502. putToCache(colorStr, rgbaArr);
  3503. return rgbaArr;
  3504. case 'hsla':
  3505. if (params.length !== 4) {
  3506. setRgba(rgbaArr, 0, 0, 0, 1);
  3507. return;
  3508. }
  3509. params[3] = parseCssFloat(params[3]);
  3510. hsla2rgba(params, rgbaArr);
  3511. putToCache(colorStr, rgbaArr);
  3512. return rgbaArr;
  3513. case 'hsl':
  3514. if (params.length !== 3) {
  3515. setRgba(rgbaArr, 0, 0, 0, 1);
  3516. return;
  3517. }
  3518. hsla2rgba(params, rgbaArr);
  3519. putToCache(colorStr, rgbaArr);
  3520. return rgbaArr;
  3521. default:
  3522. return;
  3523. }
  3524. }
  3525. setRgba(rgbaArr, 0, 0, 0, 1);
  3526. return;
  3527. }
  3528. /**
  3529. * @param {Array.<number>} hsla
  3530. * @param {Array.<number>} rgba
  3531. * @return {Array.<number>} rgba
  3532. */
  3533. function hsla2rgba(hsla, rgba) {
  3534. var h = (parseFloat(hsla[0]) % 360 + 360) % 360 / 360; // 0 .. 1
  3535. // NOTE(deanm): According to the CSS spec s/l should only be
  3536. // percentages, but we don't bother and let float or percentage.
  3537. var s = parseCssFloat(hsla[1]);
  3538. var l = parseCssFloat(hsla[2]);
  3539. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3540. var m1 = l * 2 - m2;
  3541. rgba = rgba || [];
  3542. 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);
  3543. if (hsla.length === 4) {
  3544. rgba[3] = hsla[3];
  3545. }
  3546. return rgba;
  3547. }
  3548. /**
  3549. * @param {Array.<number>} rgba
  3550. * @return {Array.<number>} hsla
  3551. */
  3552. function rgba2hsla(rgba) {
  3553. if (!rgba) {
  3554. return;
  3555. } // RGB from 0 to 255
  3556. var R = rgba[0] / 255;
  3557. var G = rgba[1] / 255;
  3558. var B = rgba[2] / 255;
  3559. var vMin = Math.min(R, G, B); // Min. value of RGB
  3560. var vMax = Math.max(R, G, B); // Max. value of RGB
  3561. var delta = vMax - vMin; // Delta RGB value
  3562. var L = (vMax + vMin) / 2;
  3563. var H;
  3564. var S; // HSL results from 0 to 1
  3565. if (delta === 0) {
  3566. H = 0;
  3567. S = 0;
  3568. } else {
  3569. if (L < 0.5) {
  3570. S = delta / (vMax + vMin);
  3571. } else {
  3572. S = delta / (2 - vMax - vMin);
  3573. }
  3574. var deltaR = ((vMax - R) / 6 + delta / 2) / delta;
  3575. var deltaG = ((vMax - G) / 6 + delta / 2) / delta;
  3576. var deltaB = ((vMax - B) / 6 + delta / 2) / delta;
  3577. if (R === vMax) {
  3578. H = deltaB - deltaG;
  3579. } else if (G === vMax) {
  3580. H = 1 / 3 + deltaR - deltaB;
  3581. } else if (B === vMax) {
  3582. H = 2 / 3 + deltaG - deltaR;
  3583. }
  3584. if (H < 0) {
  3585. H += 1;
  3586. }
  3587. if (H > 1) {
  3588. H -= 1;
  3589. }
  3590. }
  3591. var hsla = [H * 360, S, L];
  3592. if (rgba[3] != null) {
  3593. hsla.push(rgba[3]);
  3594. }
  3595. return hsla;
  3596. }
  3597. /**
  3598. * @param {string} color
  3599. * @param {number} level
  3600. * @return {string}
  3601. * @memberOf module:zrender/util/color
  3602. */
  3603. function lift(color, level) {
  3604. var colorArr = parse(color);
  3605. if (colorArr) {
  3606. for (var i = 0; i < 3; i++) {
  3607. if (level < 0) {
  3608. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3609. } else {
  3610. colorArr[i] = (255 - colorArr[i]) * level + colorArr[i] | 0;
  3611. }
  3612. if (colorArr[i] > 255) {
  3613. colorArr[i] = 255;
  3614. } else if (color[i] < 0) {
  3615. colorArr[i] = 0;
  3616. }
  3617. }
  3618. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3619. }
  3620. }
  3621. /**
  3622. * @param {string} color
  3623. * @return {string}
  3624. * @memberOf module:zrender/util/color
  3625. */
  3626. function toHex(color) {
  3627. var colorArr = parse(color);
  3628. if (colorArr) {
  3629. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + +colorArr[2]).toString(16).slice(1);
  3630. }
  3631. }
  3632. /**
  3633. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3634. * @param {number} normalizedValue A float between 0 and 1.
  3635. * @param {Array.<Array.<number>>} colors List of rgba color array
  3636. * @param {Array.<number>} [out] Mapped gba color array
  3637. * @return {Array.<number>} will be null/undefined if input illegal.
  3638. */
  3639. function fastLerp(normalizedValue, colors, out) {
  3640. if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3641. return;
  3642. }
  3643. out = out || [];
  3644. var value = normalizedValue * (colors.length - 1);
  3645. var leftIndex = Math.floor(value);
  3646. var rightIndex = Math.ceil(value);
  3647. var leftColor = colors[leftIndex];
  3648. var rightColor = colors[rightIndex];
  3649. var dv = value - leftIndex;
  3650. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3651. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3652. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3653. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3654. return out;
  3655. }
  3656. /**
  3657. * @deprecated
  3658. */
  3659. var fastMapToColor = fastLerp;
  3660. /**
  3661. * @param {number} normalizedValue A float between 0 and 1.
  3662. * @param {Array.<string>} colors Color list.
  3663. * @param {boolean=} fullOutput Default false.
  3664. * @return {(string|Object)} Result color. If fullOutput,
  3665. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3666. * @memberOf module:zrender/util/color
  3667. */
  3668. function lerp$1(normalizedValue, colors, fullOutput) {
  3669. if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3670. return;
  3671. }
  3672. var value = normalizedValue * (colors.length - 1);
  3673. var leftIndex = Math.floor(value);
  3674. var rightIndex = Math.ceil(value);
  3675. var leftColor = parse(colors[leftIndex]);
  3676. var rightColor = parse(colors[rightIndex]);
  3677. var dv = value - leftIndex;
  3678. var color = stringify([clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)), clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)), clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)), clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))], 'rgba');
  3679. return fullOutput ? {
  3680. color: color,
  3681. leftIndex: leftIndex,
  3682. rightIndex: rightIndex,
  3683. value: value
  3684. } : color;
  3685. }
  3686. /**
  3687. * @deprecated
  3688. */
  3689. var mapToColor = lerp$1;
  3690. /**
  3691. * @param {string} color
  3692. * @param {number=} h 0 ~ 360, ignore when null.
  3693. * @param {number=} s 0 ~ 1, ignore when null.
  3694. * @param {number=} l 0 ~ 1, ignore when null.
  3695. * @return {string} Color string in rgba format.
  3696. * @memberOf module:zrender/util/color
  3697. */
  3698. function modifyHSL(color, h, s, l) {
  3699. color = parse(color);
  3700. if (color) {
  3701. color = rgba2hsla(color);
  3702. h != null && (color[0] = clampCssAngle(h));
  3703. s != null && (color[1] = parseCssFloat(s));
  3704. l != null && (color[2] = parseCssFloat(l));
  3705. return stringify(hsla2rgba(color), 'rgba');
  3706. }
  3707. }
  3708. /**
  3709. * @param {string} color
  3710. * @param {number=} alpha 0 ~ 1
  3711. * @return {string} Color string in rgba format.
  3712. * @memberOf module:zrender/util/color
  3713. */
  3714. function modifyAlpha(color, alpha) {
  3715. color = parse(color);
  3716. if (color && alpha != null) {
  3717. color[3] = clampCssFloat(alpha);
  3718. return stringify(color, 'rgba');
  3719. }
  3720. }
  3721. /**
  3722. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3723. * @param {string} type 'rgba', 'hsva', ...
  3724. * @return {string} Result color. (If input illegal, return undefined).
  3725. */
  3726. function stringify(arrColor, type) {
  3727. if (!arrColor || !arrColor.length) {
  3728. return;
  3729. }
  3730. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3731. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3732. colorStr += ',' + arrColor[3];
  3733. }
  3734. return type + '(' + colorStr + ')';
  3735. }
  3736. var color = (Object.freeze || Object)({
  3737. parse: parse,
  3738. lift: lift,
  3739. toHex: toHex,
  3740. fastLerp: fastLerp,
  3741. fastMapToColor: fastMapToColor,
  3742. lerp: lerp$1,
  3743. mapToColor: mapToColor,
  3744. modifyHSL: modifyHSL,
  3745. modifyAlpha: modifyAlpha,
  3746. stringify: stringify
  3747. });
  3748. /**
  3749. * @module echarts/animation/Animator
  3750. */
  3751. var arraySlice = Array.prototype.slice;
  3752. function defaultGetter(target, key) {
  3753. return target[key];
  3754. }
  3755. function defaultSetter(target, key, value) {
  3756. target[key] = value;
  3757. }
  3758. /**
  3759. * @param {number} p0
  3760. * @param {number} p1
  3761. * @param {number} percent
  3762. * @return {number}
  3763. */
  3764. function interpolateNumber(p0, p1, percent) {
  3765. return (p1 - p0) * percent + p0;
  3766. }
  3767. /**
  3768. * @param {string} p0
  3769. * @param {string} p1
  3770. * @param {number} percent
  3771. * @return {string}
  3772. */
  3773. function interpolateString(p0, p1, percent) {
  3774. return percent > 0.5 ? p1 : p0;
  3775. }
  3776. /**
  3777. * @param {Array} p0
  3778. * @param {Array} p1
  3779. * @param {number} percent
  3780. * @param {Array} out
  3781. * @param {number} arrDim
  3782. */
  3783. function interpolateArray(p0, p1, percent, out, arrDim) {
  3784. var len = p0.length;
  3785. if (arrDim === 1) {
  3786. for (var i = 0; i < len; i++) {
  3787. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3788. }
  3789. } else {
  3790. var len2 = len && p0[0].length;
  3791. for (var i = 0; i < len; i++) {
  3792. for (var j = 0; j < len2; j++) {
  3793. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  3794. }
  3795. }
  3796. }
  3797. } // arr0 is source array, arr1 is target array.
  3798. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3799. function fillArr(arr0, arr1, arrDim) {
  3800. var arr0Len = arr0.length;
  3801. var arr1Len = arr1.length;
  3802. if (arr0Len !== arr1Len) {
  3803. // FIXME Not work for TypedArray
  3804. var isPreviousLarger = arr0Len > arr1Len;
  3805. if (isPreviousLarger) {
  3806. // Cut the previous
  3807. arr0.length = arr1Len;
  3808. } else {
  3809. // Fill the previous
  3810. for (var i = arr0Len; i < arr1Len; i++) {
  3811. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  3812. }
  3813. }
  3814. } // Handling NaN value
  3815. var len2 = arr0[0] && arr0[0].length;
  3816. for (var i = 0; i < arr0.length; i++) {
  3817. if (arrDim === 1) {
  3818. if (isNaN(arr0[i])) {
  3819. arr0[i] = arr1[i];
  3820. }
  3821. } else {
  3822. for (var j = 0; j < len2; j++) {
  3823. if (isNaN(arr0[i][j])) {
  3824. arr0[i][j] = arr1[i][j];
  3825. }
  3826. }
  3827. }
  3828. }
  3829. }
  3830. /**
  3831. * @param {Array} arr0
  3832. * @param {Array} arr1
  3833. * @param {number} arrDim
  3834. * @return {boolean}
  3835. */
  3836. function isArraySame(arr0, arr1, arrDim) {
  3837. if (arr0 === arr1) {
  3838. return true;
  3839. }
  3840. var len = arr0.length;
  3841. if (len !== arr1.length) {
  3842. return false;
  3843. }
  3844. if (arrDim === 1) {
  3845. for (var i = 0; i < len; i++) {
  3846. if (arr0[i] !== arr1[i]) {
  3847. return false;
  3848. }
  3849. }
  3850. } else {
  3851. var len2 = arr0[0].length;
  3852. for (var i = 0; i < len; i++) {
  3853. for (var j = 0; j < len2; j++) {
  3854. if (arr0[i][j] !== arr1[i][j]) {
  3855. return false;
  3856. }
  3857. }
  3858. }
  3859. }
  3860. return true;
  3861. }
  3862. /**
  3863. * Catmull Rom interpolate array
  3864. * @param {Array} p0
  3865. * @param {Array} p1
  3866. * @param {Array} p2
  3867. * @param {Array} p3
  3868. * @param {number} t
  3869. * @param {number} t2
  3870. * @param {number} t3
  3871. * @param {Array} out
  3872. * @param {number} arrDim
  3873. */
  3874. function catmullRomInterpolateArray(p0, p1, p2, p3, t, t2, t3, out, arrDim) {
  3875. var len = p0.length;
  3876. if (arrDim === 1) {
  3877. for (var i = 0; i < len; i++) {
  3878. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  3879. }
  3880. } else {
  3881. var len2 = p0[0].length;
  3882. for (var i = 0; i < len; i++) {
  3883. for (var j = 0; j < len2; j++) {
  3884. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  3885. }
  3886. }
  3887. }
  3888. }
  3889. /**
  3890. * Catmull Rom interpolate number
  3891. * @param {number} p0
  3892. * @param {number} p1
  3893. * @param {number} p2
  3894. * @param {number} p3
  3895. * @param {number} t
  3896. * @param {number} t2
  3897. * @param {number} t3
  3898. * @return {number}
  3899. */
  3900. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3901. var v0 = (p2 - p0) * 0.5;
  3902. var v1 = (p3 - p1) * 0.5;
  3903. return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1;
  3904. }
  3905. function cloneValue(value) {
  3906. if (isArrayLike(value)) {
  3907. var len = value.length;
  3908. if (isArrayLike(value[0])) {
  3909. var ret = [];
  3910. for (var i = 0; i < len; i++) {
  3911. ret.push(arraySlice.call(value[i]));
  3912. }
  3913. return ret;
  3914. }
  3915. return arraySlice.call(value);
  3916. }
  3917. return value;
  3918. }
  3919. function rgba2String(rgba) {
  3920. rgba[0] = Math.floor(rgba[0]);
  3921. rgba[1] = Math.floor(rgba[1]);
  3922. rgba[2] = Math.floor(rgba[2]);
  3923. return 'rgba(' + rgba.join(',') + ')';
  3924. }
  3925. function getArrayDim(keyframes) {
  3926. var lastValue = keyframes[keyframes.length - 1].value;
  3927. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3928. }
  3929. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3930. var getter = animator._getter;
  3931. var setter = animator._setter;
  3932. var useSpline = easing === 'spline';
  3933. var trackLen = keyframes.length;
  3934. if (!trackLen) {
  3935. return;
  3936. } // Guess data type
  3937. var firstVal = keyframes[0].value;
  3938. var isValueArray = isArrayLike(firstVal);
  3939. var isValueColor = false;
  3940. var isValueString = false; // For vertices morphing
  3941. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3942. var trackMaxTime; // Sort keyframe as ascending
  3943. keyframes.sort(function (a, b) {
  3944. return a.time - b.time;
  3945. });
  3946. trackMaxTime = keyframes[trackLen - 1].time; // Percents of each keyframe
  3947. var kfPercents = []; // Value of each keyframe
  3948. var kfValues = [];
  3949. var prevValue = keyframes[0].value;
  3950. var isAllValueEqual = true;
  3951. for (var i = 0; i < trackLen; i++) {
  3952. kfPercents.push(keyframes[i].time / trackMaxTime); // Assume value is a color when it is a string
  3953. var value = keyframes[i].value; // Check if value is equal, deep check if value is array
  3954. if (!(isValueArray && isArraySame(value, prevValue, arrDim) || !isValueArray && value === prevValue)) {
  3955. isAllValueEqual = false;
  3956. }
  3957. prevValue = value; // Try converting a string to a color array
  3958. if (typeof value === 'string') {
  3959. var colorArray = parse(value);
  3960. if (colorArray) {
  3961. value = colorArray;
  3962. isValueColor = true;
  3963. } else {
  3964. isValueString = true;
  3965. }
  3966. }
  3967. kfValues.push(value);
  3968. }
  3969. if (!forceAnimate && isAllValueEqual) {
  3970. return;
  3971. }
  3972. var lastValue = kfValues[trackLen - 1]; // Polyfill array and NaN value
  3973. for (var i = 0; i < trackLen - 1; i++) {
  3974. if (isValueArray) {
  3975. fillArr(kfValues[i], lastValue, arrDim);
  3976. } else {
  3977. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3978. kfValues[i] = lastValue;
  3979. }
  3980. }
  3981. }
  3982. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim); // Cache the key of last frame to speed up when
  3983. // animation playback is sequency
  3984. var lastFrame = 0;
  3985. var lastFramePercent = 0;
  3986. var start;
  3987. var w;
  3988. var p0;
  3989. var p1;
  3990. var p2;
  3991. var p3;
  3992. if (isValueColor) {
  3993. var rgba = [0, 0, 0, 0];
  3994. }
  3995. var onframe = function (target, percent) {
  3996. // Find the range keyframes
  3997. // kf1-----kf2---------current--------kf3
  3998. // find kf2 and kf3 and do interpolation
  3999. var frame; // In the easing function like elasticOut, percent may less than 0
  4000. if (percent < 0) {
  4001. frame = 0;
  4002. } else if (percent < lastFramePercent) {
  4003. // Start from next key
  4004. // PENDING start from lastFrame ?
  4005. start = Math.min(lastFrame + 1, trackLen - 1);
  4006. for (frame = start; frame >= 0; frame--) {
  4007. if (kfPercents[frame] <= percent) {
  4008. break;
  4009. }
  4010. } // PENDING really need to do this ?
  4011. frame = Math.min(frame, trackLen - 2);
  4012. } else {
  4013. for (frame = lastFrame; frame < trackLen; frame++) {
  4014. if (kfPercents[frame] > percent) {
  4015. break;
  4016. }
  4017. }
  4018. frame = Math.min(frame - 1, trackLen - 2);
  4019. }
  4020. lastFrame = frame;
  4021. lastFramePercent = percent;
  4022. var range = kfPercents[frame + 1] - kfPercents[frame];
  4023. if (range === 0) {
  4024. return;
  4025. } else {
  4026. w = (percent - kfPercents[frame]) / range;
  4027. }
  4028. if (useSpline) {
  4029. p1 = kfValues[frame];
  4030. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4031. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4032. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4033. if (isValueArray) {
  4034. catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, getter(target, propName), arrDim);
  4035. } else {
  4036. var value;
  4037. if (isValueColor) {
  4038. value = catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, rgba, 1);
  4039. value = rgba2String(rgba);
  4040. } else if (isValueString) {
  4041. // String is step(0.5)
  4042. return interpolateString(p1, p2, w);
  4043. } else {
  4044. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  4045. }
  4046. setter(target, propName, value);
  4047. }
  4048. } else {
  4049. if (isValueArray) {
  4050. interpolateArray(kfValues[frame], kfValues[frame + 1], w, getter(target, propName), arrDim);
  4051. } else {
  4052. var value;
  4053. if (isValueColor) {
  4054. interpolateArray(kfValues[frame], kfValues[frame + 1], w, rgba, 1);
  4055. value = rgba2String(rgba);
  4056. } else if (isValueString) {
  4057. // String is step(0.5)
  4058. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4059. } else {
  4060. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4061. }
  4062. setter(target, propName, value);
  4063. }
  4064. }
  4065. };
  4066. var clip = new Clip({
  4067. target: animator._target,
  4068. life: trackMaxTime,
  4069. loop: animator._loop,
  4070. delay: animator._delay,
  4071. onframe: onframe,
  4072. ondestroy: oneTrackDone
  4073. });
  4074. if (easing && easing !== 'spline') {
  4075. clip.easing = easing;
  4076. }
  4077. return clip;
  4078. }
  4079. /**
  4080. * @alias module:zrender/animation/Animator
  4081. * @constructor
  4082. * @param {Object} target
  4083. * @param {boolean} loop
  4084. * @param {Function} getter
  4085. * @param {Function} setter
  4086. */
  4087. var Animator = function (target, loop, getter, setter) {
  4088. this._tracks = {};
  4089. this._target = target;
  4090. this._loop = loop || false;
  4091. this._getter = getter || defaultGetter;
  4092. this._setter = setter || defaultSetter;
  4093. this._clipCount = 0;
  4094. this._delay = 0;
  4095. this._doneList = [];
  4096. this._onframeList = [];
  4097. this._clipList = [];
  4098. };
  4099. Animator.prototype = {
  4100. /**
  4101. * Set Animation keyframe
  4102. * @param {number} time 关键帧时间,单位是ms
  4103. * @param {Object} props 关键帧的属性值,key-value表示
  4104. * @return {module:zrender/animation/Animator}
  4105. */
  4106. when: function (time
  4107. /* ms */
  4108. , props) {
  4109. var tracks = this._tracks;
  4110. for (var propName in props) {
  4111. if (!props.hasOwnProperty(propName)) {
  4112. continue;
  4113. }
  4114. if (!tracks[propName]) {
  4115. tracks[propName] = []; // Invalid value
  4116. var value = this._getter(this._target, propName);
  4117. if (value == null) {
  4118. // zrLog('Invalid property ' + propName);
  4119. continue;
  4120. } // If time is 0
  4121. // Then props is given initialize value
  4122. // Else
  4123. // Initialize value from current prop value
  4124. if (time !== 0) {
  4125. tracks[propName].push({
  4126. time: 0,
  4127. value: cloneValue(value)
  4128. });
  4129. }
  4130. }
  4131. tracks[propName].push({
  4132. time: time,
  4133. value: props[propName]
  4134. });
  4135. }
  4136. return this;
  4137. },
  4138. /**
  4139. * 添加动画每一帧的回调函数
  4140. * @param {Function} callback
  4141. * @return {module:zrender/animation/Animator}
  4142. */
  4143. during: function (callback) {
  4144. this._onframeList.push(callback);
  4145. return this;
  4146. },
  4147. pause: function () {
  4148. for (var i = 0; i < this._clipList.length; i++) {
  4149. this._clipList[i].pause();
  4150. }
  4151. this._paused = true;
  4152. },
  4153. resume: function () {
  4154. for (var i = 0; i < this._clipList.length; i++) {
  4155. this._clipList[i].resume();
  4156. }
  4157. this._paused = false;
  4158. },
  4159. isPaused: function () {
  4160. return !!this._paused;
  4161. },
  4162. _doneCallback: function () {
  4163. // Clear all tracks
  4164. this._tracks = {}; // Clear all clips
  4165. this._clipList.length = 0;
  4166. var doneList = this._doneList;
  4167. var len = doneList.length;
  4168. for (var i = 0; i < len; i++) {
  4169. doneList[i].call(this);
  4170. }
  4171. },
  4172. /**
  4173. * Start the animation
  4174. * @param {string|Function} [easing]
  4175. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4176. * @param {boolean} forceAnimate
  4177. * @return {module:zrender/animation/Animator}
  4178. */
  4179. start: function (easing, forceAnimate) {
  4180. var self = this;
  4181. var clipCount = 0;
  4182. var oneTrackDone = function () {
  4183. clipCount--;
  4184. if (!clipCount) {
  4185. self._doneCallback();
  4186. }
  4187. };
  4188. var lastClip;
  4189. for (var propName in this._tracks) {
  4190. if (!this._tracks.hasOwnProperty(propName)) {
  4191. continue;
  4192. }
  4193. var clip = createTrackClip(this, easing, oneTrackDone, this._tracks[propName], propName, forceAnimate);
  4194. if (clip) {
  4195. this._clipList.push(clip);
  4196. clipCount++; // If start after added to animation
  4197. if (this.animation) {
  4198. this.animation.addClip(clip);
  4199. }
  4200. lastClip = clip;
  4201. }
  4202. } // Add during callback on the last clip
  4203. if (lastClip) {
  4204. var oldOnFrame = lastClip.onframe;
  4205. lastClip.onframe = function (target, percent) {
  4206. oldOnFrame(target, percent);
  4207. for (var i = 0; i < self._onframeList.length; i++) {
  4208. self._onframeList[i](target, percent);
  4209. }
  4210. };
  4211. } // This optimization will help the case that in the upper application
  4212. // the view may be refreshed frequently, where animation will be
  4213. // called repeatly but nothing changed.
  4214. if (!clipCount) {
  4215. this._doneCallback();
  4216. }
  4217. return this;
  4218. },
  4219. /**
  4220. * Stop animation
  4221. * @param {boolean} forwardToLast If move to last frame before stop
  4222. */
  4223. stop: function (forwardToLast) {
  4224. var clipList = this._clipList;
  4225. var animation = this.animation;
  4226. for (var i = 0; i < clipList.length; i++) {
  4227. var clip = clipList[i];
  4228. if (forwardToLast) {
  4229. // Move to last frame before stop
  4230. clip.onframe(this._target, 1);
  4231. }
  4232. animation && animation.removeClip(clip);
  4233. }
  4234. clipList.length = 0;
  4235. },
  4236. /**
  4237. * Set when animation delay starts
  4238. * @param {number} time 单位ms
  4239. * @return {module:zrender/animation/Animator}
  4240. */
  4241. delay: function (time) {
  4242. this._delay = time;
  4243. return this;
  4244. },
  4245. /**
  4246. * Add callback for animation end
  4247. * @param {Function} cb
  4248. * @return {module:zrender/animation/Animator}
  4249. */
  4250. done: function (cb) {
  4251. if (cb) {
  4252. this._doneList.push(cb);
  4253. }
  4254. return this;
  4255. },
  4256. /**
  4257. * @return {Array.<module:zrender/animation/Clip>}
  4258. */
  4259. getClips: function () {
  4260. return this._clipList;
  4261. }
  4262. };
  4263. var dpr = 1; // If in browser environment
  4264. if (typeof window !== 'undefined') {
  4265. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4266. }
  4267. /**
  4268. * config默认配置项
  4269. * @exports zrender/config
  4270. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4271. */
  4272. /**
  4273. * Debug log mode:
  4274. * 0: Do nothing, for release.
  4275. * 1: console.error, for debug.
  4276. */
  4277. var debugMode = 0; // retina 屏幕优化
  4278. var devicePixelRatio = dpr;
  4279. var logError = function () {};
  4280. if (debugMode === 1) {
  4281. logError = console.error;
  4282. }
  4283. var logError$1 = logError;
  4284. /**
  4285. * @alias module:zrender/mixin/Animatable
  4286. * @constructor
  4287. */
  4288. var Animatable = function () {
  4289. /**
  4290. * @type {Array.<module:zrender/animation/Animator>}
  4291. * @readOnly
  4292. */
  4293. this.animators = [];
  4294. };
  4295. Animatable.prototype = {
  4296. constructor: Animatable,
  4297. /**
  4298. * 动画
  4299. *
  4300. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4301. * @param {boolean} [loop] Whether to loop animation.
  4302. * @return {module:zrender/animation/Animator}
  4303. * @example:
  4304. * el.animate('style', false)
  4305. * .when(1000, {x: 10} )
  4306. * .done(function(){ // Animation done })
  4307. * .start()
  4308. */
  4309. animate: function (path, loop) {
  4310. var target;
  4311. var animatingShape = false;
  4312. var el = this;
  4313. var zr = this.__zr;
  4314. if (path) {
  4315. var pathSplitted = path.split('.');
  4316. var prop = el; // If animating shape
  4317. animatingShape = pathSplitted[0] === 'shape';
  4318. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4319. if (!prop) {
  4320. continue;
  4321. }
  4322. prop = prop[pathSplitted[i]];
  4323. }
  4324. if (prop) {
  4325. target = prop;
  4326. }
  4327. } else {
  4328. target = el;
  4329. }
  4330. if (!target) {
  4331. logError$1('Property "' + path + '" is not existed in element ' + el.id);
  4332. return;
  4333. }
  4334. var animators = el.animators;
  4335. var animator = new Animator(target, loop);
  4336. animator.during(function (target) {
  4337. el.dirty(animatingShape);
  4338. }).done(function () {
  4339. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4340. animators.splice(indexOf(animators, animator), 1);
  4341. });
  4342. animators.push(animator); // If animate after added to the zrender
  4343. if (zr) {
  4344. zr.animation.addAnimator(animator);
  4345. }
  4346. return animator;
  4347. },
  4348. /**
  4349. * 停止动画
  4350. * @param {boolean} forwardToLast If move to last frame before stop
  4351. */
  4352. stopAnimation: function (forwardToLast) {
  4353. var animators = this.animators;
  4354. var len = animators.length;
  4355. for (var i = 0; i < len; i++) {
  4356. animators[i].stop(forwardToLast);
  4357. }
  4358. animators.length = 0;
  4359. return this;
  4360. },
  4361. /**
  4362. * Caution: this method will stop previous animation.
  4363. * So do not use this method to one element twice before
  4364. * animation starts, unless you know what you are doing.
  4365. * @param {Object} target
  4366. * @param {number} [time=500] Time in ms
  4367. * @param {string} [easing='linear']
  4368. * @param {number} [delay=0]
  4369. * @param {Function} [callback]
  4370. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4371. * immediently when target values are the same as current values.
  4372. *
  4373. * @example
  4374. * // Animate position
  4375. * el.animateTo({
  4376. * position: [10, 10]
  4377. * }, function () { // done })
  4378. *
  4379. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4380. * el.animateTo({
  4381. * shape: {
  4382. * width: 500
  4383. * },
  4384. * style: {
  4385. * fill: 'red'
  4386. * }
  4387. * position: [10, 10]
  4388. * }, 100, 100, 'cubicOut', function () { // done })
  4389. */
  4390. // TODO Return animation key
  4391. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4392. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4393. },
  4394. /**
  4395. * Animate from the target state to current state.
  4396. * The params and the return value are the same as `this.animateTo`.
  4397. */
  4398. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4399. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4400. }
  4401. };
  4402. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4403. // animateTo(target, time, easing, callback);
  4404. if (isString(delay)) {
  4405. callback = easing;
  4406. easing = delay;
  4407. delay = 0;
  4408. } // animateTo(target, time, delay, callback);
  4409. else if (isFunction$1(easing)) {
  4410. callback = easing;
  4411. easing = 'linear';
  4412. delay = 0;
  4413. } // animateTo(target, time, callback);
  4414. else if (isFunction$1(delay)) {
  4415. callback = delay;
  4416. delay = 0;
  4417. } // animateTo(target, callback)
  4418. else if (isFunction$1(time)) {
  4419. callback = time;
  4420. time = 500;
  4421. } // animateTo(target)
  4422. else if (!time) {
  4423. time = 500;
  4424. } // Stop all previous animations
  4425. animatable.stopAnimation();
  4426. animateToShallow(animatable, '', animatable, target, time, delay, reverse); // Animators may be removed immediately after start
  4427. // if there is nothing to animate
  4428. var animators = animatable.animators.slice();
  4429. var count = animators.length;
  4430. function done() {
  4431. count--;
  4432. if (!count) {
  4433. callback && callback();
  4434. }
  4435. } // No animators. This should be checked before animators[i].start(),
  4436. // because 'done' may be executed immediately if no need to animate.
  4437. if (!count) {
  4438. callback && callback();
  4439. } // Start after all animators created
  4440. // Incase any animator is done immediately when all animation properties are not changed
  4441. for (var i = 0; i < animators.length; i++) {
  4442. animators[i].done(done).start(easing, forceAnimate);
  4443. }
  4444. }
  4445. /**
  4446. * @param {string} path=''
  4447. * @param {Object} source=animatable
  4448. * @param {Object} target
  4449. * @param {number} [time=500]
  4450. * @param {number} [delay=0]
  4451. * @param {boolean} [reverse] If `true`, animate
  4452. * from the `target` to current state.
  4453. *
  4454. * @example
  4455. * // Animate position
  4456. * el._animateToShallow({
  4457. * position: [10, 10]
  4458. * })
  4459. *
  4460. * // Animate shape, style and position in 100ms, delayed 100ms
  4461. * el._animateToShallow({
  4462. * shape: {
  4463. * width: 500
  4464. * },
  4465. * style: {
  4466. * fill: 'red'
  4467. * }
  4468. * position: [10, 10]
  4469. * }, 100, 100)
  4470. */
  4471. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4472. var objShallow = {};
  4473. var propertyCount = 0;
  4474. for (var name in target) {
  4475. if (!target.hasOwnProperty(name)) {
  4476. continue;
  4477. }
  4478. if (source[name] != null) {
  4479. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4480. animateToShallow(animatable, path ? path + '.' + name : name, source[name], target[name], time, delay, reverse);
  4481. } else {
  4482. if (reverse) {
  4483. objShallow[name] = source[name];
  4484. setAttrByPath(animatable, path, name, target[name]);
  4485. } else {
  4486. objShallow[name] = target[name];
  4487. }
  4488. propertyCount++;
  4489. }
  4490. } else if (target[name] != null && !reverse) {
  4491. setAttrByPath(animatable, path, name, target[name]);
  4492. }
  4493. }
  4494. if (propertyCount > 0) {
  4495. animatable.animate(path, false).when(time == null ? 500 : time, objShallow).delay(delay || 0);
  4496. }
  4497. }
  4498. function setAttrByPath(el, path, name, value) {
  4499. // Attr directly if not has property
  4500. // FIXME, if some property not needed for element ?
  4501. if (!path) {
  4502. el.attr(name, value);
  4503. } else {
  4504. // Only support set shape or style
  4505. var props = {};
  4506. props[path] = {};
  4507. props[path][name] = value;
  4508. el.attr(props);
  4509. }
  4510. }
  4511. /**
  4512. * @alias module:zrender/Element
  4513. * @constructor
  4514. * @extends {module:zrender/mixin/Animatable}
  4515. * @extends {module:zrender/mixin/Transformable}
  4516. * @extends {module:zrender/mixin/Eventful}
  4517. */
  4518. var Element = function (opts) {
  4519. // jshint ignore:line
  4520. Transformable.call(this, opts);
  4521. Eventful.call(this, opts);
  4522. Animatable.call(this, opts);
  4523. /**
  4524. * 画布元素ID
  4525. * @type {string}
  4526. */
  4527. this.id = opts.id || guid();
  4528. };
  4529. Element.prototype = {
  4530. /**
  4531. * 元素类型
  4532. * Element type
  4533. * @type {string}
  4534. */
  4535. type: 'element',
  4536. /**
  4537. * 元素名字
  4538. * Element name
  4539. * @type {string}
  4540. */
  4541. name: '',
  4542. /**
  4543. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4544. * ZRender instance will be assigned when element is associated with zrender
  4545. * @name module:/zrender/Element#__zr
  4546. * @type {module:zrender/ZRender}
  4547. */
  4548. __zr: null,
  4549. /**
  4550. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4551. * If ignore drawing and events of the element object
  4552. * @name module:/zrender/Element#ignore
  4553. * @type {boolean}
  4554. * @default false
  4555. */
  4556. ignore: false,
  4557. /**
  4558. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4559. * 该路径会继承被裁减对象的变换
  4560. * @type {module:zrender/graphic/Path}
  4561. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4562. * @readOnly
  4563. */
  4564. clipPath: null,
  4565. /**
  4566. * 是否是 Group
  4567. * @type {boolean}
  4568. */
  4569. isGroup: false,
  4570. /**
  4571. * Drift element
  4572. * @param {number} dx dx on the global space
  4573. * @param {number} dy dy on the global space
  4574. */
  4575. drift: function (dx, dy) {
  4576. switch (this.draggable) {
  4577. case 'horizontal':
  4578. dy = 0;
  4579. break;
  4580. case 'vertical':
  4581. dx = 0;
  4582. break;
  4583. }
  4584. var m = this.transform;
  4585. if (!m) {
  4586. m = this.transform = [1, 0, 0, 1, 0, 0];
  4587. }
  4588. m[4] += dx;
  4589. m[5] += dy;
  4590. this.decomposeTransform();
  4591. this.dirty(false);
  4592. },
  4593. /**
  4594. * Hook before update
  4595. */
  4596. beforeUpdate: function () {},
  4597. /**
  4598. * Hook after update
  4599. */
  4600. afterUpdate: function () {},
  4601. /**
  4602. * Update each frame
  4603. */
  4604. update: function () {
  4605. this.updateTransform();
  4606. },
  4607. /**
  4608. * @param {Function} cb
  4609. * @param {} context
  4610. */
  4611. traverse: function (cb, context) {},
  4612. /**
  4613. * @protected
  4614. */
  4615. attrKV: function (key, value) {
  4616. if (key === 'position' || key === 'scale' || key === 'origin') {
  4617. // Copy the array
  4618. if (value) {
  4619. var target = this[key];
  4620. if (!target) {
  4621. target = this[key] = [];
  4622. }
  4623. target[0] = value[0];
  4624. target[1] = value[1];
  4625. }
  4626. } else {
  4627. this[key] = value;
  4628. }
  4629. },
  4630. /**
  4631. * Hide the element
  4632. */
  4633. hide: function () {
  4634. this.ignore = true;
  4635. this.__zr && this.__zr.refresh();
  4636. },
  4637. /**
  4638. * Show the element
  4639. */
  4640. show: function () {
  4641. this.ignore = false;
  4642. this.__zr && this.__zr.refresh();
  4643. },
  4644. /**
  4645. * @param {string|Object} key
  4646. * @param {*} value
  4647. */
  4648. attr: function (key, value) {
  4649. if (typeof key === 'string') {
  4650. this.attrKV(key, value);
  4651. } else if (isObject$1(key)) {
  4652. for (var name in key) {
  4653. if (key.hasOwnProperty(name)) {
  4654. this.attrKV(name, key[name]);
  4655. }
  4656. }
  4657. }
  4658. this.dirty(false);
  4659. return this;
  4660. },
  4661. /**
  4662. * @param {module:zrender/graphic/Path} clipPath
  4663. */
  4664. setClipPath: function (clipPath) {
  4665. var zr = this.__zr;
  4666. if (zr) {
  4667. clipPath.addSelfToZr(zr);
  4668. } // Remove previous clip path
  4669. if (this.clipPath && this.clipPath !== clipPath) {
  4670. this.removeClipPath();
  4671. }
  4672. this.clipPath = clipPath;
  4673. clipPath.__zr = zr;
  4674. clipPath.__clipTarget = this;
  4675. this.dirty(false);
  4676. },
  4677. /**
  4678. */
  4679. removeClipPath: function () {
  4680. var clipPath = this.clipPath;
  4681. if (clipPath) {
  4682. if (clipPath.__zr) {
  4683. clipPath.removeSelfFromZr(clipPath.__zr);
  4684. }
  4685. clipPath.__zr = null;
  4686. clipPath.__clipTarget = null;
  4687. this.clipPath = null;
  4688. this.dirty(false);
  4689. }
  4690. },
  4691. /**
  4692. * Add self from zrender instance.
  4693. * Not recursively because it will be invoked when element added to storage.
  4694. * @param {module:zrender/ZRender} zr
  4695. */
  4696. addSelfToZr: function (zr) {
  4697. this.__zr = zr; // 添加动画
  4698. var animators = this.animators;
  4699. if (animators) {
  4700. for (var i = 0; i < animators.length; i++) {
  4701. zr.animation.addAnimator(animators[i]);
  4702. }
  4703. }
  4704. if (this.clipPath) {
  4705. this.clipPath.addSelfToZr(zr);
  4706. }
  4707. },
  4708. /**
  4709. * Remove self from zrender instance.
  4710. * Not recursively because it will be invoked when element added to storage.
  4711. * @param {module:zrender/ZRender} zr
  4712. */
  4713. removeSelfFromZr: function (zr) {
  4714. this.__zr = null; // 移除动画
  4715. var animators = this.animators;
  4716. if (animators) {
  4717. for (var i = 0; i < animators.length; i++) {
  4718. zr.animation.removeAnimator(animators[i]);
  4719. }
  4720. }
  4721. if (this.clipPath) {
  4722. this.clipPath.removeSelfFromZr(zr);
  4723. }
  4724. }
  4725. };
  4726. mixin(Element, Animatable);
  4727. mixin(Element, Transformable);
  4728. mixin(Element, Eventful);
  4729. /**
  4730. * @module echarts/core/BoundingRect
  4731. */
  4732. var v2ApplyTransform = applyTransform;
  4733. var mathMin = Math.min;
  4734. var mathMax = Math.max;
  4735. /**
  4736. * @alias module:echarts/core/BoundingRect
  4737. */
  4738. function BoundingRect(x, y, width, height) {
  4739. if (width < 0) {
  4740. x = x + width;
  4741. width = -width;
  4742. }
  4743. if (height < 0) {
  4744. y = y + height;
  4745. height = -height;
  4746. }
  4747. /**
  4748. * @type {number}
  4749. */
  4750. this.x = x;
  4751. /**
  4752. * @type {number}
  4753. */
  4754. this.y = y;
  4755. /**
  4756. * @type {number}
  4757. */
  4758. this.width = width;
  4759. /**
  4760. * @type {number}
  4761. */
  4762. this.height = height;
  4763. }
  4764. BoundingRect.prototype = {
  4765. constructor: BoundingRect,
  4766. /**
  4767. * @param {module:echarts/core/BoundingRect} other
  4768. */
  4769. union: function (other) {
  4770. var x = mathMin(other.x, this.x);
  4771. var y = mathMin(other.y, this.y);
  4772. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  4773. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  4774. this.x = x;
  4775. this.y = y;
  4776. },
  4777. /**
  4778. * @param {Array.<number>} m
  4779. * @methods
  4780. */
  4781. applyTransform: function () {
  4782. var lt = [];
  4783. var rb = [];
  4784. var lb = [];
  4785. var rt = [];
  4786. return function (m) {
  4787. // In case usage like this
  4788. // el.getBoundingRect().applyTransform(el.transform)
  4789. // And element has no transform
  4790. if (!m) {
  4791. return;
  4792. }
  4793. lt[0] = lb[0] = this.x;
  4794. lt[1] = rt[1] = this.y;
  4795. rb[0] = rt[0] = this.x + this.width;
  4796. rb[1] = lb[1] = this.y + this.height;
  4797. v2ApplyTransform(lt, lt, m);
  4798. v2ApplyTransform(rb, rb, m);
  4799. v2ApplyTransform(lb, lb, m);
  4800. v2ApplyTransform(rt, rt, m);
  4801. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4802. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4803. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4804. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4805. this.width = maxX - this.x;
  4806. this.height = maxY - this.y;
  4807. };
  4808. }(),
  4809. /**
  4810. * Calculate matrix of transforming from self to target rect
  4811. * @param {module:zrender/core/BoundingRect} b
  4812. * @return {Array.<number>}
  4813. */
  4814. calculateTransform: function (b) {
  4815. var a = this;
  4816. var sx = b.width / a.width;
  4817. var sy = b.height / a.height;
  4818. var m = create$1(); // 矩阵右乘
  4819. translate(m, m, [-a.x, -a.y]);
  4820. scale$1(m, m, [sx, sy]);
  4821. translate(m, m, [b.x, b.y]);
  4822. return m;
  4823. },
  4824. /**
  4825. * @param {(module:echarts/core/BoundingRect|Object)} b
  4826. * @return {boolean}
  4827. */
  4828. intersect: function (b) {
  4829. if (!b) {
  4830. return false;
  4831. }
  4832. if (!(b instanceof BoundingRect)) {
  4833. // Normalize negative width/height.
  4834. b = BoundingRect.create(b);
  4835. }
  4836. var a = this;
  4837. var ax0 = a.x;
  4838. var ax1 = a.x + a.width;
  4839. var ay0 = a.y;
  4840. var ay1 = a.y + a.height;
  4841. var bx0 = b.x;
  4842. var bx1 = b.x + b.width;
  4843. var by0 = b.y;
  4844. var by1 = b.y + b.height;
  4845. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4846. },
  4847. contain: function (x, y) {
  4848. var rect = this;
  4849. return x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height;
  4850. },
  4851. /**
  4852. * @return {module:echarts/core/BoundingRect}
  4853. */
  4854. clone: function () {
  4855. return new BoundingRect(this.x, this.y, this.width, this.height);
  4856. },
  4857. /**
  4858. * Copy from another rect
  4859. */
  4860. copy: function (other) {
  4861. this.x = other.x;
  4862. this.y = other.y;
  4863. this.width = other.width;
  4864. this.height = other.height;
  4865. },
  4866. plain: function () {
  4867. return {
  4868. x: this.x,
  4869. y: this.y,
  4870. width: this.width,
  4871. height: this.height
  4872. };
  4873. }
  4874. };
  4875. /**
  4876. * @param {Object|module:zrender/core/BoundingRect} rect
  4877. * @param {number} rect.x
  4878. * @param {number} rect.y
  4879. * @param {number} rect.width
  4880. * @param {number} rect.height
  4881. * @return {module:zrender/core/BoundingRect}
  4882. */
  4883. BoundingRect.create = function (rect) {
  4884. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4885. };
  4886. /**
  4887. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4888. * @module zrender/graphic/Group
  4889. * @example
  4890. * var Group = require('zrender/container/Group');
  4891. * var Circle = require('zrender/graphic/shape/Circle');
  4892. * var g = new Group();
  4893. * g.position[0] = 100;
  4894. * g.position[1] = 100;
  4895. * g.add(new Circle({
  4896. * style: {
  4897. * x: 100,
  4898. * y: 100,
  4899. * r: 20,
  4900. * }
  4901. * }));
  4902. * zr.add(g);
  4903. */
  4904. /**
  4905. * @alias module:zrender/graphic/Group
  4906. * @constructor
  4907. * @extends module:zrender/mixin/Transformable
  4908. * @extends module:zrender/mixin/Eventful
  4909. */
  4910. var Group = function (opts) {
  4911. opts = opts || {};
  4912. Element.call(this, opts);
  4913. for (var key in opts) {
  4914. if (opts.hasOwnProperty(key)) {
  4915. this[key] = opts[key];
  4916. }
  4917. }
  4918. this._children = [];
  4919. this.__storage = null;
  4920. this.__dirty = true;
  4921. };
  4922. Group.prototype = {
  4923. constructor: Group,
  4924. isGroup: true,
  4925. /**
  4926. * @type {string}
  4927. */
  4928. type: 'group',
  4929. /**
  4930. * 所有子孙元素是否响应鼠标事件
  4931. * @name module:/zrender/container/Group#silent
  4932. * @type {boolean}
  4933. * @default false
  4934. */
  4935. silent: false,
  4936. /**
  4937. * @return {Array.<module:zrender/Element>}
  4938. */
  4939. children: function () {
  4940. return this._children.slice();
  4941. },
  4942. /**
  4943. * 获取指定 index 的儿子节点
  4944. * @param {number} idx
  4945. * @return {module:zrender/Element}
  4946. */
  4947. childAt: function (idx) {
  4948. return this._children[idx];
  4949. },
  4950. /**
  4951. * 获取指定名字的儿子节点
  4952. * @param {string} name
  4953. * @return {module:zrender/Element}
  4954. */
  4955. childOfName: function (name) {
  4956. var children = this._children;
  4957. for (var i = 0; i < children.length; i++) {
  4958. if (children[i].name === name) {
  4959. return children[i];
  4960. }
  4961. }
  4962. },
  4963. /**
  4964. * @return {number}
  4965. */
  4966. childCount: function () {
  4967. return this._children.length;
  4968. },
  4969. /**
  4970. * 添加子节点到最后
  4971. * @param {module:zrender/Element} child
  4972. */
  4973. add: function (child) {
  4974. if (child && child !== this && child.parent !== this) {
  4975. this._children.push(child);
  4976. this._doAdd(child);
  4977. }
  4978. return this;
  4979. },
  4980. /**
  4981. * 添加子节点在 nextSibling 之前
  4982. * @param {module:zrender/Element} child
  4983. * @param {module:zrender/Element} nextSibling
  4984. */
  4985. addBefore: function (child, nextSibling) {
  4986. if (child && child !== this && child.parent !== this && nextSibling && nextSibling.parent === this) {
  4987. var children = this._children;
  4988. var idx = children.indexOf(nextSibling);
  4989. if (idx >= 0) {
  4990. children.splice(idx, 0, child);
  4991. this._doAdd(child);
  4992. }
  4993. }
  4994. return this;
  4995. },
  4996. _doAdd: function (child) {
  4997. if (child.parent) {
  4998. child.parent.remove(child);
  4999. }
  5000. child.parent = this;
  5001. var storage = this.__storage;
  5002. var zr = this.__zr;
  5003. if (storage && storage !== child.__storage) {
  5004. storage.addToStorage(child);
  5005. if (child instanceof Group) {
  5006. child.addChildrenToStorage(storage);
  5007. }
  5008. }
  5009. zr && zr.refresh();
  5010. },
  5011. /**
  5012. * 移除子节点
  5013. * @param {module:zrender/Element} child
  5014. */
  5015. remove: function (child) {
  5016. var zr = this.__zr;
  5017. var storage = this.__storage;
  5018. var children = this._children;
  5019. var idx = indexOf(children, child);
  5020. if (idx < 0) {
  5021. return this;
  5022. }
  5023. children.splice(idx, 1);
  5024. child.parent = null;
  5025. if (storage) {
  5026. storage.delFromStorage(child);
  5027. if (child instanceof Group) {
  5028. child.delChildrenFromStorage(storage);
  5029. }
  5030. }
  5031. zr && zr.refresh();
  5032. return this;
  5033. },
  5034. /**
  5035. * 移除所有子节点
  5036. */
  5037. removeAll: function () {
  5038. var children = this._children;
  5039. var storage = this.__storage;
  5040. var child;
  5041. var i;
  5042. for (i = 0; i < children.length; i++) {
  5043. child = children[i];
  5044. if (storage) {
  5045. storage.delFromStorage(child);
  5046. if (child instanceof Group) {
  5047. child.delChildrenFromStorage(storage);
  5048. }
  5049. }
  5050. child.parent = null;
  5051. }
  5052. children.length = 0;
  5053. return this;
  5054. },
  5055. /**
  5056. * 遍历所有子节点
  5057. * @param {Function} cb
  5058. * @param {} context
  5059. */
  5060. eachChild: function (cb, context) {
  5061. var children = this._children;
  5062. for (var i = 0; i < children.length; i++) {
  5063. var child = children[i];
  5064. cb.call(context, child, i);
  5065. }
  5066. return this;
  5067. },
  5068. /**
  5069. * 深度优先遍历所有子孙节点
  5070. * @param {Function} cb
  5071. * @param {} context
  5072. */
  5073. traverse: function (cb, context) {
  5074. for (var i = 0; i < this._children.length; i++) {
  5075. var child = this._children[i];
  5076. cb.call(context, child);
  5077. if (child.type === 'group') {
  5078. child.traverse(cb, context);
  5079. }
  5080. }
  5081. return this;
  5082. },
  5083. addChildrenToStorage: function (storage) {
  5084. for (var i = 0; i < this._children.length; i++) {
  5085. var child = this._children[i];
  5086. storage.addToStorage(child);
  5087. if (child instanceof Group) {
  5088. child.addChildrenToStorage(storage);
  5089. }
  5090. }
  5091. },
  5092. delChildrenFromStorage: function (storage) {
  5093. for (var i = 0; i < this._children.length; i++) {
  5094. var child = this._children[i];
  5095. storage.delFromStorage(child);
  5096. if (child instanceof Group) {
  5097. child.delChildrenFromStorage(storage);
  5098. }
  5099. }
  5100. },
  5101. dirty: function () {
  5102. this.__dirty = true;
  5103. this.__zr && this.__zr.refresh();
  5104. return this;
  5105. },
  5106. /**
  5107. * @return {module:zrender/core/BoundingRect}
  5108. */
  5109. getBoundingRect: function (includeChildren) {
  5110. // TODO Caching
  5111. var rect = null;
  5112. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5113. var children = includeChildren || this._children;
  5114. var tmpMat = [];
  5115. for (var i = 0; i < children.length; i++) {
  5116. var child = children[i];
  5117. if (child.ignore || child.invisible) {
  5118. continue;
  5119. }
  5120. var childRect = child.getBoundingRect();
  5121. var transform = child.getLocalTransform(tmpMat); // TODO
  5122. // The boundingRect cacluated by transforming original
  5123. // rect may be bigger than the actual bundingRect when rotation
  5124. // is used. (Consider a circle rotated aginst its center, where
  5125. // the actual boundingRect should be the same as that not be
  5126. // rotated.) But we can not find better approach to calculate
  5127. // actual boundingRect yet, considering performance.
  5128. if (transform) {
  5129. tmpRect.copy(childRect);
  5130. tmpRect.applyTransform(transform);
  5131. rect = rect || tmpRect.clone();
  5132. rect.union(tmpRect);
  5133. } else {
  5134. rect = rect || childRect.clone();
  5135. rect.union(childRect);
  5136. }
  5137. }
  5138. return rect || tmpRect;
  5139. }
  5140. };
  5141. inherits(Group, Element);
  5142. // https://github.com/mziccard/node-timsort
  5143. var DEFAULT_MIN_MERGE = 32;
  5144. var DEFAULT_MIN_GALLOPING = 7;
  5145. function minRunLength(n) {
  5146. var r = 0;
  5147. while (n >= DEFAULT_MIN_MERGE) {
  5148. r |= n & 1;
  5149. n >>= 1;
  5150. }
  5151. return n + r;
  5152. }
  5153. function makeAscendingRun(array, lo, hi, compare) {
  5154. var runHi = lo + 1;
  5155. if (runHi === hi) {
  5156. return 1;
  5157. }
  5158. if (compare(array[runHi++], array[lo]) < 0) {
  5159. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5160. runHi++;
  5161. }
  5162. reverseRun(array, lo, runHi);
  5163. } else {
  5164. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5165. runHi++;
  5166. }
  5167. }
  5168. return runHi - lo;
  5169. }
  5170. function reverseRun(array, lo, hi) {
  5171. hi--;
  5172. while (lo < hi) {
  5173. var t = array[lo];
  5174. array[lo++] = array[hi];
  5175. array[hi--] = t;
  5176. }
  5177. }
  5178. function binaryInsertionSort(array, lo, hi, start, compare) {
  5179. if (start === lo) {
  5180. start++;
  5181. }
  5182. for (; start < hi; start++) {
  5183. var pivot = array[start];
  5184. var left = lo;
  5185. var right = start;
  5186. var mid;
  5187. while (left < right) {
  5188. mid = left + right >>> 1;
  5189. if (compare(pivot, array[mid]) < 0) {
  5190. right = mid;
  5191. } else {
  5192. left = mid + 1;
  5193. }
  5194. }
  5195. var n = start - left;
  5196. switch (n) {
  5197. case 3:
  5198. array[left + 3] = array[left + 2];
  5199. case 2:
  5200. array[left + 2] = array[left + 1];
  5201. case 1:
  5202. array[left + 1] = array[left];
  5203. break;
  5204. default:
  5205. while (n > 0) {
  5206. array[left + n] = array[left + n - 1];
  5207. n--;
  5208. }
  5209. }
  5210. array[left] = pivot;
  5211. }
  5212. }
  5213. function gallopLeft(value, array, start, length, hint, compare) {
  5214. var lastOffset = 0;
  5215. var maxOffset = 0;
  5216. var offset = 1;
  5217. if (compare(value, array[start + hint]) > 0) {
  5218. maxOffset = length - hint;
  5219. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5220. lastOffset = offset;
  5221. offset = (offset << 1) + 1;
  5222. if (offset <= 0) {
  5223. offset = maxOffset;
  5224. }
  5225. }
  5226. if (offset > maxOffset) {
  5227. offset = maxOffset;
  5228. }
  5229. lastOffset += hint;
  5230. offset += hint;
  5231. } else {
  5232. maxOffset = hint + 1;
  5233. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5234. lastOffset = offset;
  5235. offset = (offset << 1) + 1;
  5236. if (offset <= 0) {
  5237. offset = maxOffset;
  5238. }
  5239. }
  5240. if (offset > maxOffset) {
  5241. offset = maxOffset;
  5242. }
  5243. var tmp = lastOffset;
  5244. lastOffset = hint - offset;
  5245. offset = hint - tmp;
  5246. }
  5247. lastOffset++;
  5248. while (lastOffset < offset) {
  5249. var m = lastOffset + (offset - lastOffset >>> 1);
  5250. if (compare(value, array[start + m]) > 0) {
  5251. lastOffset = m + 1;
  5252. } else {
  5253. offset = m;
  5254. }
  5255. }
  5256. return offset;
  5257. }
  5258. function gallopRight(value, array, start, length, hint, compare) {
  5259. var lastOffset = 0;
  5260. var maxOffset = 0;
  5261. var offset = 1;
  5262. if (compare(value, array[start + hint]) < 0) {
  5263. maxOffset = hint + 1;
  5264. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5265. lastOffset = offset;
  5266. offset = (offset << 1) + 1;
  5267. if (offset <= 0) {
  5268. offset = maxOffset;
  5269. }
  5270. }
  5271. if (offset > maxOffset) {
  5272. offset = maxOffset;
  5273. }
  5274. var tmp = lastOffset;
  5275. lastOffset = hint - offset;
  5276. offset = hint - tmp;
  5277. } else {
  5278. maxOffset = length - hint;
  5279. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5280. lastOffset = offset;
  5281. offset = (offset << 1) + 1;
  5282. if (offset <= 0) {
  5283. offset = maxOffset;
  5284. }
  5285. }
  5286. if (offset > maxOffset) {
  5287. offset = maxOffset;
  5288. }
  5289. lastOffset += hint;
  5290. offset += hint;
  5291. }
  5292. lastOffset++;
  5293. while (lastOffset < offset) {
  5294. var m = lastOffset + (offset - lastOffset >>> 1);
  5295. if (compare(value, array[start + m]) < 0) {
  5296. offset = m;
  5297. } else {
  5298. lastOffset = m + 1;
  5299. }
  5300. }
  5301. return offset;
  5302. }
  5303. function TimSort(array, compare) {
  5304. var minGallop = DEFAULT_MIN_GALLOPING;
  5305. var runStart;
  5306. var runLength;
  5307. var stackSize = 0;
  5308. var tmp = [];
  5309. runStart = [];
  5310. runLength = [];
  5311. function pushRun(_runStart, _runLength) {
  5312. runStart[stackSize] = _runStart;
  5313. runLength[stackSize] = _runLength;
  5314. stackSize += 1;
  5315. }
  5316. function mergeRuns() {
  5317. while (stackSize > 1) {
  5318. var n = stackSize - 2;
  5319. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  5320. if (runLength[n - 1] < runLength[n + 1]) {
  5321. n--;
  5322. }
  5323. } else if (runLength[n] > runLength[n + 1]) {
  5324. break;
  5325. }
  5326. mergeAt(n);
  5327. }
  5328. }
  5329. function forceMergeRuns() {
  5330. while (stackSize > 1) {
  5331. var n = stackSize - 2;
  5332. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5333. n--;
  5334. }
  5335. mergeAt(n);
  5336. }
  5337. }
  5338. function mergeAt(i) {
  5339. var start1 = runStart[i];
  5340. var length1 = runLength[i];
  5341. var start2 = runStart[i + 1];
  5342. var length2 = runLength[i + 1];
  5343. runLength[i] = length1 + length2;
  5344. if (i === stackSize - 3) {
  5345. runStart[i + 1] = runStart[i + 2];
  5346. runLength[i + 1] = runLength[i + 2];
  5347. }
  5348. stackSize--;
  5349. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5350. start1 += k;
  5351. length1 -= k;
  5352. if (length1 === 0) {
  5353. return;
  5354. }
  5355. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5356. if (length2 === 0) {
  5357. return;
  5358. }
  5359. if (length1 <= length2) {
  5360. mergeLow(start1, length1, start2, length2);
  5361. } else {
  5362. mergeHigh(start1, length1, start2, length2);
  5363. }
  5364. }
  5365. function mergeLow(start1, length1, start2, length2) {
  5366. var i = 0;
  5367. for (i = 0; i < length1; i++) {
  5368. tmp[i] = array[start1 + i];
  5369. }
  5370. var cursor1 = 0;
  5371. var cursor2 = start2;
  5372. var dest = start1;
  5373. array[dest++] = array[cursor2++];
  5374. if (--length2 === 0) {
  5375. for (i = 0; i < length1; i++) {
  5376. array[dest + i] = tmp[cursor1 + i];
  5377. }
  5378. return;
  5379. }
  5380. if (length1 === 1) {
  5381. for (i = 0; i < length2; i++) {
  5382. array[dest + i] = array[cursor2 + i];
  5383. }
  5384. array[dest + length2] = tmp[cursor1];
  5385. return;
  5386. }
  5387. var _minGallop = minGallop;
  5388. var count1;
  5389. var count2;
  5390. var exit;
  5391. while (1) {
  5392. count1 = 0;
  5393. count2 = 0;
  5394. exit = false;
  5395. do {
  5396. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5397. array[dest++] = array[cursor2++];
  5398. count2++;
  5399. count1 = 0;
  5400. if (--length2 === 0) {
  5401. exit = true;
  5402. break;
  5403. }
  5404. } else {
  5405. array[dest++] = tmp[cursor1++];
  5406. count1++;
  5407. count2 = 0;
  5408. if (--length1 === 1) {
  5409. exit = true;
  5410. break;
  5411. }
  5412. }
  5413. } while ((count1 | count2) < _minGallop);
  5414. if (exit) {
  5415. break;
  5416. }
  5417. do {
  5418. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5419. if (count1 !== 0) {
  5420. for (i = 0; i < count1; i++) {
  5421. array[dest + i] = tmp[cursor1 + i];
  5422. }
  5423. dest += count1;
  5424. cursor1 += count1;
  5425. length1 -= count1;
  5426. if (length1 <= 1) {
  5427. exit = true;
  5428. break;
  5429. }
  5430. }
  5431. array[dest++] = array[cursor2++];
  5432. if (--length2 === 0) {
  5433. exit = true;
  5434. break;
  5435. }
  5436. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5437. if (count2 !== 0) {
  5438. for (i = 0; i < count2; i++) {
  5439. array[dest + i] = array[cursor2 + i];
  5440. }
  5441. dest += count2;
  5442. cursor2 += count2;
  5443. length2 -= count2;
  5444. if (length2 === 0) {
  5445. exit = true;
  5446. break;
  5447. }
  5448. }
  5449. array[dest++] = tmp[cursor1++];
  5450. if (--length1 === 1) {
  5451. exit = true;
  5452. break;
  5453. }
  5454. _minGallop--;
  5455. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5456. if (exit) {
  5457. break;
  5458. }
  5459. if (_minGallop < 0) {
  5460. _minGallop = 0;
  5461. }
  5462. _minGallop += 2;
  5463. }
  5464. minGallop = _minGallop;
  5465. minGallop < 1 && (minGallop = 1);
  5466. if (length1 === 1) {
  5467. for (i = 0; i < length2; i++) {
  5468. array[dest + i] = array[cursor2 + i];
  5469. }
  5470. array[dest + length2] = tmp[cursor1];
  5471. } else if (length1 === 0) {
  5472. throw new Error(); // throw new Error('mergeLow preconditions were not respected');
  5473. } else {
  5474. for (i = 0; i < length1; i++) {
  5475. array[dest + i] = tmp[cursor1 + i];
  5476. }
  5477. }
  5478. }
  5479. function mergeHigh(start1, length1, start2, length2) {
  5480. var i = 0;
  5481. for (i = 0; i < length2; i++) {
  5482. tmp[i] = array[start2 + i];
  5483. }
  5484. var cursor1 = start1 + length1 - 1;
  5485. var cursor2 = length2 - 1;
  5486. var dest = start2 + length2 - 1;
  5487. var customCursor = 0;
  5488. var customDest = 0;
  5489. array[dest--] = array[cursor1--];
  5490. if (--length1 === 0) {
  5491. customCursor = dest - (length2 - 1);
  5492. for (i = 0; i < length2; i++) {
  5493. array[customCursor + i] = tmp[i];
  5494. }
  5495. return;
  5496. }
  5497. if (length2 === 1) {
  5498. dest -= length1;
  5499. cursor1 -= length1;
  5500. customDest = dest + 1;
  5501. customCursor = cursor1 + 1;
  5502. for (i = length1 - 1; i >= 0; i--) {
  5503. array[customDest + i] = array[customCursor + i];
  5504. }
  5505. array[dest] = tmp[cursor2];
  5506. return;
  5507. }
  5508. var _minGallop = minGallop;
  5509. while (true) {
  5510. var count1 = 0;
  5511. var count2 = 0;
  5512. var exit = false;
  5513. do {
  5514. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5515. array[dest--] = array[cursor1--];
  5516. count1++;
  5517. count2 = 0;
  5518. if (--length1 === 0) {
  5519. exit = true;
  5520. break;
  5521. }
  5522. } else {
  5523. array[dest--] = tmp[cursor2--];
  5524. count2++;
  5525. count1 = 0;
  5526. if (--length2 === 1) {
  5527. exit = true;
  5528. break;
  5529. }
  5530. }
  5531. } while ((count1 | count2) < _minGallop);
  5532. if (exit) {
  5533. break;
  5534. }
  5535. do {
  5536. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5537. if (count1 !== 0) {
  5538. dest -= count1;
  5539. cursor1 -= count1;
  5540. length1 -= count1;
  5541. customDest = dest + 1;
  5542. customCursor = cursor1 + 1;
  5543. for (i = count1 - 1; i >= 0; i--) {
  5544. array[customDest + i] = array[customCursor + i];
  5545. }
  5546. if (length1 === 0) {
  5547. exit = true;
  5548. break;
  5549. }
  5550. }
  5551. array[dest--] = tmp[cursor2--];
  5552. if (--length2 === 1) {
  5553. exit = true;
  5554. break;
  5555. }
  5556. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5557. if (count2 !== 0) {
  5558. dest -= count2;
  5559. cursor2 -= count2;
  5560. length2 -= count2;
  5561. customDest = dest + 1;
  5562. customCursor = cursor2 + 1;
  5563. for (i = 0; i < count2; i++) {
  5564. array[customDest + i] = tmp[customCursor + i];
  5565. }
  5566. if (length2 <= 1) {
  5567. exit = true;
  5568. break;
  5569. }
  5570. }
  5571. array[dest--] = array[cursor1--];
  5572. if (--length1 === 0) {
  5573. exit = true;
  5574. break;
  5575. }
  5576. _minGallop--;
  5577. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5578. if (exit) {
  5579. break;
  5580. }
  5581. if (_minGallop < 0) {
  5582. _minGallop = 0;
  5583. }
  5584. _minGallop += 2;
  5585. }
  5586. minGallop = _minGallop;
  5587. if (minGallop < 1) {
  5588. minGallop = 1;
  5589. }
  5590. if (length2 === 1) {
  5591. dest -= length1;
  5592. cursor1 -= length1;
  5593. customDest = dest + 1;
  5594. customCursor = cursor1 + 1;
  5595. for (i = length1 - 1; i >= 0; i--) {
  5596. array[customDest + i] = array[customCursor + i];
  5597. }
  5598. array[dest] = tmp[cursor2];
  5599. } else if (length2 === 0) {
  5600. throw new Error(); // throw new Error('mergeHigh preconditions were not respected');
  5601. } else {
  5602. customCursor = dest - (length2 - 1);
  5603. for (i = 0; i < length2; i++) {
  5604. array[customCursor + i] = tmp[i];
  5605. }
  5606. }
  5607. }
  5608. this.mergeRuns = mergeRuns;
  5609. this.forceMergeRuns = forceMergeRuns;
  5610. this.pushRun = pushRun;
  5611. }
  5612. function sort(array, compare, lo, hi) {
  5613. if (!lo) {
  5614. lo = 0;
  5615. }
  5616. if (!hi) {
  5617. hi = array.length;
  5618. }
  5619. var remaining = hi - lo;
  5620. if (remaining < 2) {
  5621. return;
  5622. }
  5623. var runLength = 0;
  5624. if (remaining < DEFAULT_MIN_MERGE) {
  5625. runLength = makeAscendingRun(array, lo, hi, compare);
  5626. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5627. return;
  5628. }
  5629. var ts = new TimSort(array, compare);
  5630. var minRun = minRunLength(remaining);
  5631. do {
  5632. runLength = makeAscendingRun(array, lo, hi, compare);
  5633. if (runLength < minRun) {
  5634. var force = remaining;
  5635. if (force > minRun) {
  5636. force = minRun;
  5637. }
  5638. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5639. runLength = force;
  5640. }
  5641. ts.pushRun(lo, runLength);
  5642. ts.mergeRuns();
  5643. remaining -= runLength;
  5644. lo += runLength;
  5645. } while (remaining !== 0);
  5646. ts.forceMergeRuns();
  5647. }
  5648. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5649. function shapeCompareFunc(a, b) {
  5650. if (a.zlevel === b.zlevel) {
  5651. if (a.z === b.z) {
  5652. // if (a.z2 === b.z2) {
  5653. // // FIXME Slow has renderidx compare
  5654. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5655. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5656. // return a.__renderidx - b.__renderidx;
  5657. // }
  5658. return a.z2 - b.z2;
  5659. }
  5660. return a.z - b.z;
  5661. }
  5662. return a.zlevel - b.zlevel;
  5663. }
  5664. /**
  5665. * 内容仓库 (M)
  5666. * @alias module:zrender/Storage
  5667. * @constructor
  5668. */
  5669. var Storage = function () {
  5670. // jshint ignore:line
  5671. this._roots = [];
  5672. this._displayList = [];
  5673. this._displayListLen = 0;
  5674. };
  5675. Storage.prototype = {
  5676. constructor: Storage,
  5677. /**
  5678. * @param {Function} cb
  5679. *
  5680. */
  5681. traverse: function (cb, context) {
  5682. for (var i = 0; i < this._roots.length; i++) {
  5683. this._roots[i].traverse(cb, context);
  5684. }
  5685. },
  5686. /**
  5687. * 返回所有图形的绘制队列
  5688. * @param {boolean} [update=false] 是否在返回前更新该数组
  5689. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5690. *
  5691. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5692. * @return {Array.<module:zrender/graphic/Displayable>}
  5693. */
  5694. getDisplayList: function (update, includeIgnore) {
  5695. includeIgnore = includeIgnore || false;
  5696. if (update) {
  5697. this.updateDisplayList(includeIgnore);
  5698. }
  5699. return this._displayList;
  5700. },
  5701. /**
  5702. * 更新图形的绘制队列。
  5703. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5704. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5705. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5706. */
  5707. updateDisplayList: function (includeIgnore) {
  5708. this._displayListLen = 0;
  5709. var roots = this._roots;
  5710. var displayList = this._displayList;
  5711. for (var i = 0, len = roots.length; i < len; i++) {
  5712. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5713. }
  5714. displayList.length = this._displayListLen;
  5715. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5716. },
  5717. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5718. if (el.ignore && !includeIgnore) {
  5719. return;
  5720. }
  5721. el.beforeUpdate();
  5722. if (el.__dirty) {
  5723. el.update();
  5724. }
  5725. el.afterUpdate();
  5726. var userSetClipPath = el.clipPath;
  5727. if (userSetClipPath) {
  5728. // FIXME 效率影响
  5729. if (clipPaths) {
  5730. clipPaths = clipPaths.slice();
  5731. } else {
  5732. clipPaths = [];
  5733. }
  5734. var currentClipPath = userSetClipPath;
  5735. var parentClipPath = el; // Recursively add clip path
  5736. while (currentClipPath) {
  5737. // clipPath 的变换是基于使用这个 clipPath 的元素
  5738. currentClipPath.parent = parentClipPath;
  5739. currentClipPath.updateTransform();
  5740. clipPaths.push(currentClipPath);
  5741. parentClipPath = currentClipPath;
  5742. currentClipPath = currentClipPath.clipPath;
  5743. }
  5744. }
  5745. if (el.isGroup) {
  5746. var children = el._children;
  5747. for (var i = 0; i < children.length; i++) {
  5748. var child = children[i]; // Force to mark as dirty if group is dirty
  5749. // FIXME __dirtyPath ?
  5750. if (el.__dirty) {
  5751. child.__dirty = true;
  5752. }
  5753. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5754. } // Mark group clean here
  5755. el.__dirty = false;
  5756. } else {
  5757. el.__clipPaths = clipPaths;
  5758. this._displayList[this._displayListLen++] = el;
  5759. }
  5760. },
  5761. /**
  5762. * 添加图形(Shape)或者组(Group)到根节点
  5763. * @param {module:zrender/Element} el
  5764. */
  5765. addRoot: function (el) {
  5766. if (el.__storage === this) {
  5767. return;
  5768. }
  5769. if (el instanceof Group) {
  5770. el.addChildrenToStorage(this);
  5771. }
  5772. this.addToStorage(el);
  5773. this._roots.push(el);
  5774. },
  5775. /**
  5776. * 删除指定的图形(Shape)或者组(Group)
  5777. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5778. */
  5779. delRoot: function (el) {
  5780. if (el == null) {
  5781. // 不指定el清空
  5782. for (var i = 0; i < this._roots.length; i++) {
  5783. var root = this._roots[i];
  5784. if (root instanceof Group) {
  5785. root.delChildrenFromStorage(this);
  5786. }
  5787. }
  5788. this._roots = [];
  5789. this._displayList = [];
  5790. this._displayListLen = 0;
  5791. return;
  5792. }
  5793. if (el instanceof Array) {
  5794. for (var i = 0, l = el.length; i < l; i++) {
  5795. this.delRoot(el[i]);
  5796. }
  5797. return;
  5798. }
  5799. var idx = indexOf(this._roots, el);
  5800. if (idx >= 0) {
  5801. this.delFromStorage(el);
  5802. this._roots.splice(idx, 1);
  5803. if (el instanceof Group) {
  5804. el.delChildrenFromStorage(this);
  5805. }
  5806. }
  5807. },
  5808. addToStorage: function (el) {
  5809. if (el) {
  5810. el.__storage = this;
  5811. el.dirty(false);
  5812. }
  5813. return this;
  5814. },
  5815. delFromStorage: function (el) {
  5816. if (el) {
  5817. el.__storage = null;
  5818. }
  5819. return this;
  5820. },
  5821. /**
  5822. * 清空并且释放Storage
  5823. */
  5824. dispose: function () {
  5825. this._renderList = this._roots = null;
  5826. },
  5827. displayableSortFunc: shapeCompareFunc
  5828. };
  5829. var SHADOW_PROPS = {
  5830. 'shadowBlur': 1,
  5831. 'shadowOffsetX': 1,
  5832. 'shadowOffsetY': 1,
  5833. 'textShadowBlur': 1,
  5834. 'textShadowOffsetX': 1,
  5835. 'textShadowOffsetY': 1,
  5836. 'textBoxShadowBlur': 1,
  5837. 'textBoxShadowOffsetX': 1,
  5838. 'textBoxShadowOffsetY': 1
  5839. };
  5840. var fixShadow = function (ctx, propName, value) {
  5841. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5842. return value *= ctx.dpr;
  5843. }
  5844. return value;
  5845. };
  5846. var ContextCachedBy = {
  5847. NONE: 0,
  5848. STYLE_BIND: 1,
  5849. PLAIN_TEXT: 2
  5850. }; // Avoid confused with 0/false.
  5851. var WILL_BE_RESTORED = 9;
  5852. var STYLE_COMMON_PROPS = [['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'], ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]]; // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5853. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5854. var Style = function (opts) {
  5855. this.extendFrom(opts, false);
  5856. };
  5857. function createLinearGradient(ctx, obj, rect) {
  5858. var x = obj.x == null ? 0 : obj.x;
  5859. var x2 = obj.x2 == null ? 1 : obj.x2;
  5860. var y = obj.y == null ? 0 : obj.y;
  5861. var y2 = obj.y2 == null ? 0 : obj.y2;
  5862. if (!obj.global) {
  5863. x = x * rect.width + rect.x;
  5864. x2 = x2 * rect.width + rect.x;
  5865. y = y * rect.height + rect.y;
  5866. y2 = y2 * rect.height + rect.y;
  5867. } // Fix NaN when rect is Infinity
  5868. x = isNaN(x) ? 0 : x;
  5869. x2 = isNaN(x2) ? 1 : x2;
  5870. y = isNaN(y) ? 0 : y;
  5871. y2 = isNaN(y2) ? 0 : y2;
  5872. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5873. return canvasGradient;
  5874. }
  5875. function createRadialGradient(ctx, obj, rect) {
  5876. var width = rect.width;
  5877. var height = rect.height;
  5878. var min = Math.min(width, height);
  5879. var x = obj.x == null ? 0.5 : obj.x;
  5880. var y = obj.y == null ? 0.5 : obj.y;
  5881. var r = obj.r == null ? 0.5 : obj.r;
  5882. if (!obj.global) {
  5883. x = x * width + rect.x;
  5884. y = y * height + rect.y;
  5885. r = r * min;
  5886. }
  5887. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5888. return canvasGradient;
  5889. }
  5890. Style.prototype = {
  5891. constructor: Style,
  5892. /**
  5893. * @type {string}
  5894. */
  5895. fill: '#000',
  5896. /**
  5897. * @type {string}
  5898. */
  5899. stroke: null,
  5900. /**
  5901. * @type {number}
  5902. */
  5903. opacity: 1,
  5904. /**
  5905. * @type {number}
  5906. */
  5907. fillOpacity: null,
  5908. /**
  5909. * @type {number}
  5910. */
  5911. strokeOpacity: null,
  5912. /**
  5913. * `true` is not supported.
  5914. * `false`/`null`/`undefined` are the same.
  5915. * `false` is used to remove lineDash in some
  5916. * case that `null`/`undefined` can not be set.
  5917. * (e.g., emphasis.lineStyle in echarts)
  5918. * @type {Array.<number>|boolean}
  5919. */
  5920. lineDash: null,
  5921. /**
  5922. * @type {number}
  5923. */
  5924. lineDashOffset: 0,
  5925. /**
  5926. * @type {number}
  5927. */
  5928. shadowBlur: 0,
  5929. /**
  5930. * @type {number}
  5931. */
  5932. shadowOffsetX: 0,
  5933. /**
  5934. * @type {number}
  5935. */
  5936. shadowOffsetY: 0,
  5937. /**
  5938. * @type {number}
  5939. */
  5940. lineWidth: 1,
  5941. /**
  5942. * If stroke ignore scale
  5943. * @type {Boolean}
  5944. */
  5945. strokeNoScale: false,
  5946. // Bounding rect text configuration
  5947. // Not affected by element transform
  5948. /**
  5949. * @type {string}
  5950. */
  5951. text: null,
  5952. /**
  5953. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5954. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5955. * So do not visit it directly in upper application (like echarts),
  5956. * but use `contain/text#makeFont` instead.
  5957. * @type {string}
  5958. */
  5959. font: null,
  5960. /**
  5961. * The same as font. Use font please.
  5962. * @deprecated
  5963. * @type {string}
  5964. */
  5965. textFont: null,
  5966. /**
  5967. * It helps merging respectively, rather than parsing an entire font string.
  5968. * @type {string}
  5969. */
  5970. fontStyle: null,
  5971. /**
  5972. * It helps merging respectively, rather than parsing an entire font string.
  5973. * @type {string}
  5974. */
  5975. fontWeight: null,
  5976. /**
  5977. * It helps merging respectively, rather than parsing an entire font string.
  5978. * Should be 12 but not '12px'.
  5979. * @type {number}
  5980. */
  5981. fontSize: null,
  5982. /**
  5983. * It helps merging respectively, rather than parsing an entire font string.
  5984. * @type {string}
  5985. */
  5986. fontFamily: null,
  5987. /**
  5988. * Reserved for special functinality, like 'hr'.
  5989. * @type {string}
  5990. */
  5991. textTag: null,
  5992. /**
  5993. * @type {string}
  5994. */
  5995. textFill: '#000',
  5996. /**
  5997. * @type {string}
  5998. */
  5999. textStroke: null,
  6000. /**
  6001. * @type {number}
  6002. */
  6003. textWidth: null,
  6004. /**
  6005. * Only for textBackground.
  6006. * @type {number}
  6007. */
  6008. textHeight: null,
  6009. /**
  6010. * textStroke may be set as some color as a default
  6011. * value in upper applicaion, where the default value
  6012. * of textStrokeWidth should be 0 to make sure that
  6013. * user can choose to do not use text stroke.
  6014. * @type {number}
  6015. */
  6016. textStrokeWidth: 0,
  6017. /**
  6018. * @type {number}
  6019. */
  6020. textLineHeight: null,
  6021. /**
  6022. * 'inside', 'left', 'right', 'top', 'bottom'
  6023. * [x, y]
  6024. * Based on x, y of rect.
  6025. * @type {string|Array.<number>}
  6026. * @default 'inside'
  6027. */
  6028. textPosition: 'inside',
  6029. /**
  6030. * If not specified, use the boundingRect of a `displayable`.
  6031. * @type {Object}
  6032. */
  6033. textRect: null,
  6034. /**
  6035. * [x, y]
  6036. * @type {Array.<number>}
  6037. */
  6038. textOffset: null,
  6039. /**
  6040. * @type {string}
  6041. */
  6042. textAlign: null,
  6043. /**
  6044. * @type {string}
  6045. */
  6046. textVerticalAlign: null,
  6047. /**
  6048. * @type {number}
  6049. */
  6050. textDistance: 5,
  6051. /**
  6052. * @type {string}
  6053. */
  6054. textShadowColor: 'transparent',
  6055. /**
  6056. * @type {number}
  6057. */
  6058. textShadowBlur: 0,
  6059. /**
  6060. * @type {number}
  6061. */
  6062. textShadowOffsetX: 0,
  6063. /**
  6064. * @type {number}
  6065. */
  6066. textShadowOffsetY: 0,
  6067. /**
  6068. * @type {string}
  6069. */
  6070. textBoxShadowColor: 'transparent',
  6071. /**
  6072. * @type {number}
  6073. */
  6074. textBoxShadowBlur: 0,
  6075. /**
  6076. * @type {number}
  6077. */
  6078. textBoxShadowOffsetX: 0,
  6079. /**
  6080. * @type {number}
  6081. */
  6082. textBoxShadowOffsetY: 0,
  6083. /**
  6084. * Whether transform text.
  6085. * Only available in Path and Image element,
  6086. * where the text is called as `RectText`.
  6087. * @type {boolean}
  6088. */
  6089. transformText: false,
  6090. /**
  6091. * Text rotate around position of Path or Image.
  6092. * The origin of the rotation can be specified by `textOrigin`.
  6093. * Only available in Path and Image element,
  6094. * where the text is called as `RectText`.
  6095. */
  6096. textRotation: 0,
  6097. /**
  6098. * Text origin of text rotation.
  6099. * Useful in the case like label rotation of circular symbol.
  6100. * Only available in Path and Image element, where the text is called
  6101. * as `RectText` and the element is called as "host element".
  6102. * The value can be:
  6103. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6104. * base on the left-top corner of the rect of its host element.
  6105. * + If specified as a string `center`, it is the center of the rect of
  6106. * its host element.
  6107. * + By default, this origin is the `textPosition`.
  6108. * @type {string|Array.<number>}
  6109. */
  6110. textOrigin: null,
  6111. /**
  6112. * @type {string}
  6113. */
  6114. textBackgroundColor: null,
  6115. /**
  6116. * @type {string}
  6117. */
  6118. textBorderColor: null,
  6119. /**
  6120. * @type {number}
  6121. */
  6122. textBorderWidth: 0,
  6123. /**
  6124. * @type {number}
  6125. */
  6126. textBorderRadius: 0,
  6127. /**
  6128. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6129. * @type {number|Array.<number>}
  6130. */
  6131. textPadding: null,
  6132. /**
  6133. * Text styles for rich text.
  6134. * @type {Object}
  6135. */
  6136. rich: null,
  6137. /**
  6138. * {outerWidth, outerHeight, ellipsis, placeholder}
  6139. * @type {Object}
  6140. */
  6141. truncate: null,
  6142. /**
  6143. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6144. * @type {string}
  6145. */
  6146. blend: null,
  6147. /**
  6148. * @param {CanvasRenderingContext2D} ctx
  6149. */
  6150. bind: function (ctx, el, prevEl) {
  6151. var style = this;
  6152. var prevStyle = prevEl && prevEl.style; // If no prevStyle, it means first draw.
  6153. // Only apply cache if the last time cachced by this function.
  6154. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6155. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6156. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6157. var prop = STYLE_COMMON_PROPS[i];
  6158. var styleName = prop[0];
  6159. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6160. // FIXME Invalid property value will cause style leak from previous element.
  6161. ctx[styleName] = fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6162. }
  6163. }
  6164. if (notCheckCache || style.fill !== prevStyle.fill) {
  6165. ctx.fillStyle = style.fill;
  6166. }
  6167. if (notCheckCache || style.stroke !== prevStyle.stroke) {
  6168. ctx.strokeStyle = style.stroke;
  6169. }
  6170. if (notCheckCache || style.opacity !== prevStyle.opacity) {
  6171. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6172. }
  6173. if (notCheckCache || style.blend !== prevStyle.blend) {
  6174. ctx.globalCompositeOperation = style.blend || 'source-over';
  6175. }
  6176. if (this.hasStroke()) {
  6177. var lineWidth = style.lineWidth;
  6178. ctx.lineWidth = lineWidth / (this.strokeNoScale && el && el.getLineScale ? el.getLineScale() : 1);
  6179. }
  6180. },
  6181. hasFill: function () {
  6182. var fill = this.fill;
  6183. return fill != null && fill !== 'none';
  6184. },
  6185. hasStroke: function () {
  6186. var stroke = this.stroke;
  6187. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6188. },
  6189. /**
  6190. * Extend from other style
  6191. * @param {zrender/graphic/Style} otherStyle
  6192. * @param {boolean} overwrite true: overwrirte any way.
  6193. * false: overwrite only when !target.hasOwnProperty
  6194. * others: overwrite when property is not null/undefined.
  6195. */
  6196. extendFrom: function (otherStyle, overwrite) {
  6197. if (otherStyle) {
  6198. for (var name in otherStyle) {
  6199. if (otherStyle.hasOwnProperty(name) && (overwrite === true || (overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null))) {
  6200. this[name] = otherStyle[name];
  6201. }
  6202. }
  6203. }
  6204. },
  6205. /**
  6206. * Batch setting style with a given object
  6207. * @param {Object|string} obj
  6208. * @param {*} [obj]
  6209. */
  6210. set: function (obj, value) {
  6211. if (typeof obj === 'string') {
  6212. this[obj] = value;
  6213. } else {
  6214. this.extendFrom(obj, true);
  6215. }
  6216. },
  6217. /**
  6218. * Clone
  6219. * @return {zrender/graphic/Style} [description]
  6220. */
  6221. clone: function () {
  6222. var newStyle = new this.constructor();
  6223. newStyle.extendFrom(this, true);
  6224. return newStyle;
  6225. },
  6226. getGradient: function (ctx, obj, rect) {
  6227. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6228. var canvasGradient = method(ctx, obj, rect);
  6229. var colorStops = obj.colorStops;
  6230. for (var i = 0; i < colorStops.length; i++) {
  6231. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  6232. }
  6233. return canvasGradient;
  6234. }
  6235. };
  6236. var styleProto = Style.prototype;
  6237. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6238. var prop = STYLE_COMMON_PROPS[i];
  6239. if (!(prop[0] in styleProto)) {
  6240. styleProto[prop[0]] = prop[1];
  6241. }
  6242. } // Provide for others
  6243. Style.getGradient = styleProto.getGradient;
  6244. var Pattern = function (image, repeat) {
  6245. // Should do nothing more in this constructor. Because gradient can be
  6246. // declard by `color: {image: ...}`, where this constructor will not be called.
  6247. this.image = image;
  6248. this.repeat = repeat; // Can be cloned
  6249. this.type = 'pattern';
  6250. };
  6251. Pattern.prototype.getCanvasPattern = function (ctx) {
  6252. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6253. };
  6254. /**
  6255. * @module zrender/Layer
  6256. * @author pissang(https://www.github.com/pissang)
  6257. */
  6258. function returnFalse() {
  6259. return false;
  6260. }
  6261. /**
  6262. * 创建dom
  6263. *
  6264. * @inner
  6265. * @param {string} id dom id 待用
  6266. * @param {Painter} painter painter instance
  6267. * @param {number} number
  6268. */
  6269. function createDom(id, painter, dpr) {
  6270. var newDom = createCanvas();
  6271. var width = painter.getWidth();
  6272. var height = painter.getHeight();
  6273. var newDomStyle = newDom.style;
  6274. if (newDomStyle) {
  6275. // In node or some other non-browser environment
  6276. newDomStyle.position = 'absolute';
  6277. newDomStyle.left = 0;
  6278. newDomStyle.top = 0;
  6279. newDomStyle.width = width + 'px';
  6280. newDomStyle.height = height + 'px';
  6281. newDom.setAttribute('data-zr-dom-id', id);
  6282. }
  6283. newDom.width = width * dpr;
  6284. newDom.height = height * dpr;
  6285. return newDom;
  6286. }
  6287. /**
  6288. * @alias module:zrender/Layer
  6289. * @constructor
  6290. * @extends module:zrender/mixin/Transformable
  6291. * @param {string} id
  6292. * @param {module:zrender/Painter} painter
  6293. * @param {number} [dpr]
  6294. */
  6295. var Layer = function (id, painter, dpr) {
  6296. var dom;
  6297. dpr = dpr || devicePixelRatio;
  6298. if (typeof id === 'string') {
  6299. dom = createDom(id, painter, dpr);
  6300. } // Not using isDom because in node it will return false
  6301. else if (isObject$1(id)) {
  6302. dom = id;
  6303. id = dom.id;
  6304. }
  6305. this.id = id;
  6306. this.dom = dom;
  6307. var domStyle = dom.style;
  6308. if (domStyle) {
  6309. // Not in node
  6310. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6311. domStyle['-webkit-user-select'] = 'none';
  6312. domStyle['user-select'] = 'none';
  6313. domStyle['-webkit-touch-callout'] = 'none';
  6314. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6315. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6316. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6317. domStyle['border-width'] = 0;
  6318. }
  6319. this.domBack = null;
  6320. this.ctxBack = null;
  6321. this.painter = painter;
  6322. this.config = null; // Configs
  6323. /**
  6324. * 每次清空画布的颜色
  6325. * @type {string}
  6326. * @default 0
  6327. */
  6328. this.clearColor = 0;
  6329. /**
  6330. * 是否开启动态模糊
  6331. * @type {boolean}
  6332. * @default false
  6333. */
  6334. this.motionBlur = false;
  6335. /**
  6336. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6337. * @type {number}
  6338. * @default 0.7
  6339. */
  6340. this.lastFrameAlpha = 0.7;
  6341. /**
  6342. * Layer dpr
  6343. * @type {number}
  6344. */
  6345. this.dpr = dpr;
  6346. };
  6347. Layer.prototype = {
  6348. constructor: Layer,
  6349. __dirty: true,
  6350. __used: false,
  6351. __drawIndex: 0,
  6352. __startIndex: 0,
  6353. __endIndex: 0,
  6354. incremental: false,
  6355. getElementCount: function () {
  6356. return this.__endIndex - this.__startIndex;
  6357. },
  6358. initContext: function () {
  6359. this.ctx = this.dom.getContext('2d');
  6360. this.ctx.dpr = this.dpr;
  6361. },
  6362. createBackBuffer: function () {
  6363. var dpr = this.dpr;
  6364. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6365. this.ctxBack = this.domBack.getContext('2d');
  6366. if (dpr !== 1) {
  6367. this.ctxBack.scale(dpr, dpr);
  6368. }
  6369. },
  6370. /**
  6371. * @param {number} width
  6372. * @param {number} height
  6373. */
  6374. resize: function (width, height) {
  6375. var dpr = this.dpr;
  6376. var dom = this.dom;
  6377. var domStyle = dom.style;
  6378. var domBack = this.domBack;
  6379. if (domStyle) {
  6380. domStyle.width = width + 'px';
  6381. domStyle.height = height + 'px';
  6382. }
  6383. dom.width = width * dpr;
  6384. dom.height = height * dpr;
  6385. if (domBack) {
  6386. domBack.width = width * dpr;
  6387. domBack.height = height * dpr;
  6388. if (dpr !== 1) {
  6389. this.ctxBack.scale(dpr, dpr);
  6390. }
  6391. }
  6392. },
  6393. /**
  6394. * 清空该层画布
  6395. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6396. * @param {Color} [clearColor]
  6397. */
  6398. clear: function (clearAll, clearColor) {
  6399. var dom = this.dom;
  6400. var ctx = this.ctx;
  6401. var width = dom.width;
  6402. var height = dom.height;
  6403. var clearColor = clearColor || this.clearColor;
  6404. var haveMotionBLur = this.motionBlur && !clearAll;
  6405. var lastFrameAlpha = this.lastFrameAlpha;
  6406. var dpr = this.dpr;
  6407. if (haveMotionBLur) {
  6408. if (!this.domBack) {
  6409. this.createBackBuffer();
  6410. }
  6411. this.ctxBack.globalCompositeOperation = 'copy';
  6412. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  6413. }
  6414. ctx.clearRect(0, 0, width, height);
  6415. if (clearColor && clearColor !== 'transparent') {
  6416. var clearColorGradientOrPattern; // Gradient
  6417. if (clearColor.colorStops) {
  6418. // Cache canvas gradient
  6419. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6420. x: 0,
  6421. y: 0,
  6422. width: width,
  6423. height: height
  6424. });
  6425. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6426. } // Pattern
  6427. else if (clearColor.image) {
  6428. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6429. }
  6430. ctx.save();
  6431. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6432. ctx.fillRect(0, 0, width, height);
  6433. ctx.restore();
  6434. }
  6435. if (haveMotionBLur) {
  6436. var domBack = this.domBack;
  6437. ctx.save();
  6438. ctx.globalAlpha = lastFrameAlpha;
  6439. ctx.drawImage(domBack, 0, 0, width, height);
  6440. ctx.restore();
  6441. }
  6442. }
  6443. };
  6444. var requestAnimationFrame = typeof window !== 'undefined' && (window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6445. window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window) || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame) || function (func) {
  6446. setTimeout(func, 16);
  6447. };
  6448. var globalImageCache = new LRU(50);
  6449. /**
  6450. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6451. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6452. */
  6453. function findExistImage(newImageOrSrc) {
  6454. if (typeof newImageOrSrc === 'string') {
  6455. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6456. return cachedImgObj && cachedImgObj.image;
  6457. } else {
  6458. return newImageOrSrc;
  6459. }
  6460. }
  6461. /**
  6462. * Caution: User should cache loaded images, but not just count on LRU.
  6463. * Consider if required images more than LRU size, will dead loop occur?
  6464. *
  6465. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6466. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6467. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6468. * @param {Function} [cb] params: (image, cbPayload)
  6469. * @param {Object} [cbPayload] Payload on cb calling.
  6470. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6471. */
  6472. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6473. if (!newImageOrSrc) {
  6474. return image;
  6475. } else if (typeof newImageOrSrc === 'string') {
  6476. // Image should not be loaded repeatly.
  6477. if (image && image.__zrImageSrc === newImageOrSrc || !hostEl) {
  6478. return image;
  6479. } // Only when there is no existent image or existent image src
  6480. // is different, this method is responsible for load.
  6481. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6482. var pendingWrap = {
  6483. hostEl: hostEl,
  6484. cb: cb,
  6485. cbPayload: cbPayload
  6486. };
  6487. if (cachedImgObj) {
  6488. image = cachedImgObj.image;
  6489. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6490. } else {
  6491. image = new Image();
  6492. image.onload = image.onerror = imageOnLoad;
  6493. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  6494. image: image,
  6495. pending: [pendingWrap]
  6496. });
  6497. image.src = image.__zrImageSrc = newImageOrSrc;
  6498. }
  6499. return image;
  6500. } // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6501. else {
  6502. return newImageOrSrc;
  6503. }
  6504. }
  6505. function imageOnLoad() {
  6506. var cachedImgObj = this.__cachedImgObj;
  6507. this.onload = this.onerror = this.__cachedImgObj = null;
  6508. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6509. var pendingWrap = cachedImgObj.pending[i];
  6510. var cb = pendingWrap.cb;
  6511. cb && cb(this, pendingWrap.cbPayload);
  6512. pendingWrap.hostEl.dirty();
  6513. }
  6514. cachedImgObj.pending.length = 0;
  6515. }
  6516. function isImageReady(image) {
  6517. return image && image.width && image.height;
  6518. }
  6519. var textWidthCache = {};
  6520. var textWidthCacheCounter = 0;
  6521. var TEXT_CACHE_MAX = 5000;
  6522. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6523. var DEFAULT_FONT$1 = '12px sans-serif'; // Avoid assign to an exported variable, for transforming to cjs.
  6524. var methods$1 = {};
  6525. /**
  6526. * @public
  6527. * @param {string} text
  6528. * @param {string} font
  6529. * @return {number} width
  6530. */
  6531. function getWidth(text, font) {
  6532. font = font || DEFAULT_FONT$1;
  6533. var key = text + ':' + font;
  6534. if (textWidthCache[key]) {
  6535. return textWidthCache[key];
  6536. }
  6537. var textLines = (text + '').split('\n');
  6538. var width = 0;
  6539. for (var i = 0, l = textLines.length; i < l; i++) {
  6540. // textContain.measureText may be overrided in SVG or VML
  6541. width = Math.max(measureText(textLines[i], font).width, width);
  6542. }
  6543. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6544. textWidthCacheCounter = 0;
  6545. textWidthCache = {};
  6546. }
  6547. textWidthCacheCounter++;
  6548. textWidthCache[key] = width;
  6549. return width;
  6550. }
  6551. /**
  6552. * @public
  6553. * @param {string} text
  6554. * @param {string} font
  6555. * @param {string} [textAlign='left']
  6556. * @param {string} [textVerticalAlign='top']
  6557. * @param {Array.<number>} [textPadding]
  6558. * @param {Object} [rich]
  6559. * @param {Object} [truncate]
  6560. * @return {Object} {x, y, width, height, lineHeight}
  6561. */
  6562. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6563. return rich ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6564. }
  6565. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6566. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6567. var outerWidth = getWidth(text, font);
  6568. if (textPadding) {
  6569. outerWidth += textPadding[1] + textPadding[3];
  6570. }
  6571. var outerHeight = contentBlock.outerHeight;
  6572. var x = adjustTextX(0, outerWidth, textAlign);
  6573. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6574. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6575. rect.lineHeight = contentBlock.lineHeight;
  6576. return rect;
  6577. }
  6578. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6579. var contentBlock = parseRichText(text, {
  6580. rich: rich,
  6581. truncate: truncate,
  6582. font: font,
  6583. textAlign: textAlign,
  6584. textPadding: textPadding,
  6585. textLineHeight: textLineHeight
  6586. });
  6587. var outerWidth = contentBlock.outerWidth;
  6588. var outerHeight = contentBlock.outerHeight;
  6589. var x = adjustTextX(0, outerWidth, textAlign);
  6590. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6591. return new BoundingRect(x, y, outerWidth, outerHeight);
  6592. }
  6593. /**
  6594. * @public
  6595. * @param {number} x
  6596. * @param {number} width
  6597. * @param {string} [textAlign='left']
  6598. * @return {number} Adjusted x.
  6599. */
  6600. function adjustTextX(x, width, textAlign) {
  6601. // FIXME Right to left language
  6602. if (textAlign === 'right') {
  6603. x -= width;
  6604. } else if (textAlign === 'center') {
  6605. x -= width / 2;
  6606. }
  6607. return x;
  6608. }
  6609. /**
  6610. * @public
  6611. * @param {number} y
  6612. * @param {number} height
  6613. * @param {string} [textVerticalAlign='top']
  6614. * @return {number} Adjusted y.
  6615. */
  6616. function adjustTextY(y, height, textVerticalAlign) {
  6617. if (textVerticalAlign === 'middle') {
  6618. y -= height / 2;
  6619. } else if (textVerticalAlign === 'bottom') {
  6620. y -= height;
  6621. }
  6622. return y;
  6623. }
  6624. /**
  6625. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6626. * @public
  6627. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6628. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6629. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6630. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6631. */
  6632. function calculateTextPosition(out, style, rect) {
  6633. var textPosition = style.textPosition;
  6634. var distance = style.textDistance;
  6635. var x = rect.x;
  6636. var y = rect.y;
  6637. distance = distance || 0;
  6638. var height = rect.height;
  6639. var width = rect.width;
  6640. var halfHeight = height / 2;
  6641. var textAlign = 'left';
  6642. var textVerticalAlign = 'top';
  6643. switch (textPosition) {
  6644. case 'left':
  6645. x -= distance;
  6646. y += halfHeight;
  6647. textAlign = 'right';
  6648. textVerticalAlign = 'middle';
  6649. break;
  6650. case 'right':
  6651. x += distance + width;
  6652. y += halfHeight;
  6653. textVerticalAlign = 'middle';
  6654. break;
  6655. case 'top':
  6656. x += width / 2;
  6657. y -= distance;
  6658. textAlign = 'center';
  6659. textVerticalAlign = 'bottom';
  6660. break;
  6661. case 'bottom':
  6662. x += width / 2;
  6663. y += height + distance;
  6664. textAlign = 'center';
  6665. break;
  6666. case 'inside':
  6667. x += width / 2;
  6668. y += halfHeight;
  6669. textAlign = 'center';
  6670. textVerticalAlign = 'middle';
  6671. break;
  6672. case 'insideLeft':
  6673. x += distance;
  6674. y += halfHeight;
  6675. textVerticalAlign = 'middle';
  6676. break;
  6677. case 'insideRight':
  6678. x += width - distance;
  6679. y += halfHeight;
  6680. textAlign = 'right';
  6681. textVerticalAlign = 'middle';
  6682. break;
  6683. case 'insideTop':
  6684. x += width / 2;
  6685. y += distance;
  6686. textAlign = 'center';
  6687. break;
  6688. case 'insideBottom':
  6689. x += width / 2;
  6690. y += height - distance;
  6691. textAlign = 'center';
  6692. textVerticalAlign = 'bottom';
  6693. break;
  6694. case 'insideTopLeft':
  6695. x += distance;
  6696. y += distance;
  6697. break;
  6698. case 'insideTopRight':
  6699. x += width - distance;
  6700. y += distance;
  6701. textAlign = 'right';
  6702. break;
  6703. case 'insideBottomLeft':
  6704. x += distance;
  6705. y += height - distance;
  6706. textVerticalAlign = 'bottom';
  6707. break;
  6708. case 'insideBottomRight':
  6709. x += width - distance;
  6710. y += height - distance;
  6711. textAlign = 'right';
  6712. textVerticalAlign = 'bottom';
  6713. break;
  6714. }
  6715. out = out || {};
  6716. out.x = x;
  6717. out.y = y;
  6718. out.textAlign = textAlign;
  6719. out.textVerticalAlign = textVerticalAlign;
  6720. return out;
  6721. }
  6722. /**
  6723. * To be removed. But still do not remove in case that some one has imported it.
  6724. * @deprecated
  6725. * @public
  6726. * @param {stirng} textPosition
  6727. * @param {Object} rect {x, y, width, height}
  6728. * @param {number} distance
  6729. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6730. */
  6731. /**
  6732. * Show ellipsis if overflow.
  6733. *
  6734. * @public
  6735. * @param {string} text
  6736. * @param {string} containerWidth
  6737. * @param {string} font
  6738. * @param {number} [ellipsis='...']
  6739. * @param {Object} [options]
  6740. * @param {number} [options.maxIterations=3]
  6741. * @param {number} [options.minChar=0] If truncate result are less
  6742. * then minChar, ellipsis will not show, which is
  6743. * better for user hint in some cases.
  6744. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6745. * @return {string}
  6746. */
  6747. function truncateText(text, containerWidth, font, ellipsis, options) {
  6748. if (!containerWidth) {
  6749. return '';
  6750. }
  6751. var textLines = (text + '').split('\n');
  6752. options = prepareTruncateOptions(containerWidth, font, ellipsis, options); // FIXME
  6753. // It is not appropriate that every line has '...' when truncate multiple lines.
  6754. for (var i = 0, len = textLines.length; i < len; i++) {
  6755. textLines[i] = truncateSingleLine(textLines[i], options);
  6756. }
  6757. return textLines.join('\n');
  6758. }
  6759. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6760. options = extend({}, options);
  6761. options.font = font;
  6762. var ellipsis = retrieve2(ellipsis, '...');
  6763. options.maxIterations = retrieve2(options.maxIterations, 2);
  6764. var minChar = options.minChar = retrieve2(options.minChar, 0); // FIXME
  6765. // Other languages?
  6766. options.cnCharWidth = getWidth('国', font); // FIXME
  6767. // Consider proportional font?
  6768. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6769. options.placeholder = retrieve2(options.placeholder, ''); // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6770. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6771. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6772. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6773. contentWidth -= ascCharWidth;
  6774. }
  6775. var ellipsisWidth = getWidth(ellipsis, font);
  6776. if (ellipsisWidth > contentWidth) {
  6777. ellipsis = '';
  6778. ellipsisWidth = 0;
  6779. }
  6780. contentWidth = containerWidth - ellipsisWidth;
  6781. options.ellipsis = ellipsis;
  6782. options.ellipsisWidth = ellipsisWidth;
  6783. options.contentWidth = contentWidth;
  6784. options.containerWidth = containerWidth;
  6785. return options;
  6786. }
  6787. function truncateSingleLine(textLine, options) {
  6788. var containerWidth = options.containerWidth;
  6789. var font = options.font;
  6790. var contentWidth = options.contentWidth;
  6791. if (!containerWidth) {
  6792. return '';
  6793. }
  6794. var lineWidth = getWidth(textLine, font);
  6795. if (lineWidth <= containerWidth) {
  6796. return textLine;
  6797. }
  6798. for (var j = 0;; j++) {
  6799. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6800. textLine += options.ellipsis;
  6801. break;
  6802. }
  6803. var subLength = j === 0 ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth) : lineWidth > 0 ? Math.floor(textLine.length * contentWidth / lineWidth) : 0;
  6804. textLine = textLine.substr(0, subLength);
  6805. lineWidth = getWidth(textLine, font);
  6806. }
  6807. if (textLine === '') {
  6808. textLine = options.placeholder;
  6809. }
  6810. return textLine;
  6811. }
  6812. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6813. var width = 0;
  6814. var i = 0;
  6815. for (var len = text.length; i < len && width < contentWidth; i++) {
  6816. var charCode = text.charCodeAt(i);
  6817. width += 0 <= charCode && charCode <= 127 ? ascCharWidth : cnCharWidth;
  6818. }
  6819. return i;
  6820. }
  6821. /**
  6822. * @public
  6823. * @param {string} font
  6824. * @return {number} line height
  6825. */
  6826. function getLineHeight(font) {
  6827. // FIXME A rough approach.
  6828. return getWidth('国', font);
  6829. }
  6830. /**
  6831. * @public
  6832. * @param {string} text
  6833. * @param {string} font
  6834. * @return {Object} width
  6835. */
  6836. function measureText(text, font) {
  6837. return methods$1.measureText(text, font);
  6838. } // Avoid assign to an exported variable, for transforming to cjs.
  6839. methods$1.measureText = function (text, font) {
  6840. var ctx = getContext();
  6841. ctx.font = font || DEFAULT_FONT$1;
  6842. return ctx.measureText(text);
  6843. };
  6844. /**
  6845. * @public
  6846. * @param {string} text
  6847. * @param {string} font
  6848. * @param {Object} [truncate]
  6849. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  6850. * Notice: for performance, do not calculate outerWidth util needed.
  6851. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  6852. * Thus we can simply comparing the `input` text to determin whether the result changed,
  6853. * without travel the result `lines`.
  6854. */
  6855. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6856. text != null && (text += '');
  6857. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6858. var lines = text ? text.split('\n') : [];
  6859. var height = lines.length * lineHeight;
  6860. var outerHeight = height;
  6861. var canCacheByTextString = true;
  6862. if (padding) {
  6863. outerHeight += padding[0] + padding[2];
  6864. }
  6865. if (text && truncate) {
  6866. canCacheByTextString = false;
  6867. var truncOuterHeight = truncate.outerHeight;
  6868. var truncOuterWidth = truncate.outerWidth;
  6869. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6870. text = '';
  6871. lines = [];
  6872. } else if (truncOuterWidth != null) {
  6873. var options = prepareTruncateOptions(truncOuterWidth - (padding ? padding[1] + padding[3] : 0), font, truncate.ellipsis, {
  6874. minChar: truncate.minChar,
  6875. placeholder: truncate.placeholder
  6876. }); // FIXME
  6877. // It is not appropriate that every line has '...' when truncate multiple lines.
  6878. for (var i = 0, len = lines.length; i < len; i++) {
  6879. lines[i] = truncateSingleLine(lines[i], options);
  6880. }
  6881. }
  6882. }
  6883. return {
  6884. lines: lines,
  6885. height: height,
  6886. outerHeight: outerHeight,
  6887. lineHeight: lineHeight,
  6888. canCacheByTextString: canCacheByTextString
  6889. };
  6890. }
  6891. /**
  6892. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6893. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6894. *
  6895. * @public
  6896. * @param {string} text
  6897. * @param {Object} style
  6898. * @return {Object} block
  6899. * {
  6900. * width,
  6901. * height,
  6902. * lines: [{
  6903. * lineHeight,
  6904. * width,
  6905. * tokens: [[{
  6906. * styleName,
  6907. * text,
  6908. * width, // include textPadding
  6909. * height, // include textPadding
  6910. * textWidth, // pure text width
  6911. * textHeight, // pure text height
  6912. * lineHeihgt,
  6913. * font,
  6914. * textAlign,
  6915. * textVerticalAlign
  6916. * }], [...], ...]
  6917. * }, ...]
  6918. * }
  6919. * If styleName is undefined, it is plain text.
  6920. */
  6921. function parseRichText(text, style) {
  6922. var contentBlock = {
  6923. lines: [],
  6924. width: 0,
  6925. height: 0
  6926. };
  6927. text != null && (text += '');
  6928. if (!text) {
  6929. return contentBlock;
  6930. }
  6931. var lastIndex = STYLE_REG.lastIndex = 0;
  6932. var result;
  6933. while ((result = STYLE_REG.exec(text)) != null) {
  6934. var matchedIndex = result.index;
  6935. if (matchedIndex > lastIndex) {
  6936. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6937. }
  6938. pushTokens(contentBlock, result[2], result[1]);
  6939. lastIndex = STYLE_REG.lastIndex;
  6940. }
  6941. if (lastIndex < text.length) {
  6942. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6943. }
  6944. var lines = contentBlock.lines;
  6945. var contentHeight = 0;
  6946. var contentWidth = 0; // For `textWidth: 100%`
  6947. var pendingList = [];
  6948. var stlPadding = style.textPadding;
  6949. var truncate = style.truncate;
  6950. var truncateWidth = truncate && truncate.outerWidth;
  6951. var truncateHeight = truncate && truncate.outerHeight;
  6952. if (stlPadding) {
  6953. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6954. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6955. } // Calculate layout info of tokens.
  6956. for (var i = 0; i < lines.length; i++) {
  6957. var line = lines[i];
  6958. var lineHeight = 0;
  6959. var lineWidth = 0;
  6960. for (var j = 0; j < line.tokens.length; j++) {
  6961. var token = line.tokens[j];
  6962. var tokenStyle = token.styleName && style.rich[token.styleName] || {}; // textPadding should not inherit from style.
  6963. var textPadding = token.textPadding = tokenStyle.textPadding; // textFont has been asigned to font by `normalizeStyle`.
  6964. var font = token.font = tokenStyle.font || style.font; // textHeight can be used when textVerticalAlign is specified in token.
  6965. var tokenHeight = token.textHeight = retrieve2( // textHeight should not be inherited, consider it can be specified
  6966. // as box height of the block.
  6967. tokenStyle.textHeight, getLineHeight(font));
  6968. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6969. token.height = tokenHeight;
  6970. token.lineHeight = retrieve3(tokenStyle.textLineHeight, style.textLineHeight, tokenHeight);
  6971. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6972. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6973. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6974. return {
  6975. lines: [],
  6976. width: 0,
  6977. height: 0
  6978. };
  6979. }
  6980. token.textWidth = getWidth(token.text, font);
  6981. var tokenWidth = tokenStyle.textWidth;
  6982. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto'; // Percent width, can be `100%`, can be used in drawing separate
  6983. // line when box width is needed to be auto.
  6984. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6985. token.percentWidth = tokenWidth;
  6986. pendingList.push(token);
  6987. tokenWidth = 0; // Do not truncate in this case, because there is no user case
  6988. // and it is too complicated.
  6989. } else {
  6990. if (tokenWidthNotSpecified) {
  6991. tokenWidth = token.textWidth; // FIXME: If image is not loaded and textWidth is not specified, calling
  6992. // `getBoundingRect()` will not get correct result.
  6993. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6994. var bgImg = textBackgroundColor && textBackgroundColor.image; // Use cases:
  6995. // (1) If image is not loaded, it will be loaded at render phase and call
  6996. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6997. // image, and then the right size will be calculated here at the next tick.
  6998. // See `graphic/helper/text.js`.
  6999. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7000. // use `imageHelper.findExistImage` to find cached image.
  7001. // `imageHelper.findExistImage` will always be called here before
  7002. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7003. // which ensures that image will not be rendered before correct size calcualted.
  7004. if (bgImg) {
  7005. bgImg = findExistImage(bgImg);
  7006. if (isImageReady(bgImg)) {
  7007. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7008. }
  7009. }
  7010. }
  7011. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7012. tokenWidth += paddingW;
  7013. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7014. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7015. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7016. token.text = '';
  7017. token.textWidth = tokenWidth = 0;
  7018. } else {
  7019. token.text = truncateText(token.text, remianTruncWidth - paddingW, font, truncate.ellipsis, {
  7020. minChar: truncate.minChar
  7021. });
  7022. token.textWidth = getWidth(token.text, font);
  7023. tokenWidth = token.textWidth + paddingW;
  7024. }
  7025. }
  7026. }
  7027. lineWidth += token.width = tokenWidth;
  7028. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7029. }
  7030. line.width = lineWidth;
  7031. line.lineHeight = lineHeight;
  7032. contentHeight += lineHeight;
  7033. contentWidth = Math.max(contentWidth, lineWidth);
  7034. }
  7035. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7036. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7037. if (stlPadding) {
  7038. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7039. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7040. }
  7041. for (var i = 0; i < pendingList.length; i++) {
  7042. var token = pendingList[i];
  7043. var percentWidth = token.percentWidth; // Should not base on outerWidth, because token can not be placed out of padding.
  7044. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7045. }
  7046. return contentBlock;
  7047. }
  7048. function pushTokens(block, str, styleName) {
  7049. var isEmptyStr = str === '';
  7050. var strs = str.split('\n');
  7051. var lines = block.lines;
  7052. for (var i = 0; i < strs.length; i++) {
  7053. var text = strs[i];
  7054. var token = {
  7055. styleName: styleName,
  7056. text: text,
  7057. isLineHolder: !text && !isEmptyStr
  7058. }; // The first token should be appended to the last line.
  7059. if (!i) {
  7060. var tokens = (lines[lines.length - 1] || (lines[0] = {
  7061. tokens: []
  7062. })).tokens; // Consider cases:
  7063. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7064. // (which is a placeholder) should be replaced by new token.
  7065. // (2) A image backage, where token likes {a|}.
  7066. // (3) A redundant '' will affect textAlign in line.
  7067. // (4) tokens with the same tplName should not be merged, because
  7068. // they should be displayed in different box (with border and padding).
  7069. var tokensLen = tokens.length;
  7070. tokensLen === 1 && tokens[0].isLineHolder ? tokens[0] = token : // Consider text is '', only insert when it is the "lineHolder" or
  7071. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7072. (text || !tokensLen || isEmptyStr) && tokens.push(token);
  7073. } // Other tokens always start a new line.
  7074. else {
  7075. // If there is '', insert it as a placeholder.
  7076. lines.push({
  7077. tokens: [token]
  7078. });
  7079. }
  7080. }
  7081. }
  7082. function makeFont(style) {
  7083. // FIXME in node-canvas fontWeight is before fontStyle
  7084. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7085. var font = (style.fontSize || style.fontFamily) && [style.fontStyle, style.fontWeight, (style.fontSize || 12) + 'px', // If font properties are defined, `fontFamily` should not be ignored.
  7086. style.fontFamily || 'sans-serif'].join(' ');
  7087. return font && trim(font) || style.textFont || style.font;
  7088. }
  7089. /**
  7090. * @param {Object} ctx
  7091. * @param {Object} shape
  7092. * @param {number} shape.x
  7093. * @param {number} shape.y
  7094. * @param {number} shape.width
  7095. * @param {number} shape.height
  7096. * @param {number} shape.r
  7097. */
  7098. function buildPath(ctx, shape) {
  7099. var x = shape.x;
  7100. var y = shape.y;
  7101. var width = shape.width;
  7102. var height = shape.height;
  7103. var r = shape.r;
  7104. var r1;
  7105. var r2;
  7106. var r3;
  7107. var r4; // Convert width and height to positive for better borderRadius
  7108. if (width < 0) {
  7109. x = x + width;
  7110. width = -width;
  7111. }
  7112. if (height < 0) {
  7113. y = y + height;
  7114. height = -height;
  7115. }
  7116. if (typeof r === 'number') {
  7117. r1 = r2 = r3 = r4 = r;
  7118. } else if (r instanceof Array) {
  7119. if (r.length === 1) {
  7120. r1 = r2 = r3 = r4 = r[0];
  7121. } else if (r.length === 2) {
  7122. r1 = r3 = r[0];
  7123. r2 = r4 = r[1];
  7124. } else if (r.length === 3) {
  7125. r1 = r[0];
  7126. r2 = r4 = r[1];
  7127. r3 = r[2];
  7128. } else {
  7129. r1 = r[0];
  7130. r2 = r[1];
  7131. r3 = r[2];
  7132. r4 = r[3];
  7133. }
  7134. } else {
  7135. r1 = r2 = r3 = r4 = 0;
  7136. }
  7137. var total;
  7138. if (r1 + r2 > width) {
  7139. total = r1 + r2;
  7140. r1 *= width / total;
  7141. r2 *= width / total;
  7142. }
  7143. if (r3 + r4 > width) {
  7144. total = r3 + r4;
  7145. r3 *= width / total;
  7146. r4 *= width / total;
  7147. }
  7148. if (r2 + r3 > height) {
  7149. total = r2 + r3;
  7150. r2 *= height / total;
  7151. r3 *= height / total;
  7152. }
  7153. if (r1 + r4 > height) {
  7154. total = r1 + r4;
  7155. r1 *= height / total;
  7156. r4 *= height / total;
  7157. }
  7158. ctx.moveTo(x + r1, y);
  7159. ctx.lineTo(x + width - r2, y);
  7160. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7161. ctx.lineTo(x + width, y + height - r3);
  7162. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7163. ctx.lineTo(x + r4, y + height);
  7164. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7165. ctx.lineTo(x, y + r1);
  7166. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7167. }
  7168. var DEFAULT_FONT = DEFAULT_FONT$1; // TODO: Have not support 'start', 'end' yet.
  7169. var VALID_TEXT_ALIGN = {
  7170. left: 1,
  7171. right: 1,
  7172. center: 1
  7173. };
  7174. var VALID_TEXT_VERTICAL_ALIGN = {
  7175. top: 1,
  7176. bottom: 1,
  7177. middle: 1
  7178. }; // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7179. // the default value of shadowColor is `'transparent'`.
  7180. var SHADOW_STYLE_COMMON_PROPS = [['textShadowBlur', 'shadowBlur', 0], ['textShadowOffsetX', 'shadowOffsetX', 0], ['textShadowOffsetY', 'shadowOffsetY', 0], ['textShadowColor', 'shadowColor', 'transparent']];
  7181. var _tmpTextPositionResult = {};
  7182. var _tmpBoxPositionResult = {};
  7183. /**
  7184. * @param {module:zrender/graphic/Style} style
  7185. * @return {module:zrender/graphic/Style} The input style.
  7186. */
  7187. function normalizeTextStyle(style) {
  7188. normalizeStyle(style);
  7189. each$1(style.rich, normalizeStyle);
  7190. return style;
  7191. }
  7192. function normalizeStyle(style) {
  7193. if (style) {
  7194. style.font = makeFont(style);
  7195. var textAlign = style.textAlign;
  7196. textAlign === 'middle' && (textAlign = 'center');
  7197. style.textAlign = textAlign == null || VALID_TEXT_ALIGN[textAlign] ? textAlign : 'left'; // Compatible with textBaseline.
  7198. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7199. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7200. style.textVerticalAlign = textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign] ? textVerticalAlign : 'top';
  7201. var textPadding = style.textPadding;
  7202. if (textPadding) {
  7203. style.textPadding = normalizeCssArray(style.textPadding);
  7204. }
  7205. }
  7206. }
  7207. /**
  7208. * @param {CanvasRenderingContext2D} ctx
  7209. * @param {string} text
  7210. * @param {module:zrender/graphic/Style} style
  7211. * @param {Object|boolean} [rect] {x, y, width, height}
  7212. * If set false, rect text is not used.
  7213. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7214. */
  7215. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7216. style.rich ? renderRichText(hostEl, ctx, text, style, rect, prevEl) : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7217. } // Avoid setting to ctx according to prevEl if possible for
  7218. // performance in scenarios of large amount text.
  7219. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7220. 'use strict';
  7221. var needDrawBg = needDrawBackground(style);
  7222. var prevStyle;
  7223. var checkCache = false;
  7224. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT; // Only take and check cache for `Text` el, but not RectText.
  7225. if (prevEl !== WILL_BE_RESTORED) {
  7226. if (prevEl) {
  7227. prevStyle = prevEl.style;
  7228. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7229. } // Prevent from using cache in `Style::bind`, because of the case:
  7230. // ctx property is modified by other properties than `Style::bind`
  7231. // used, and Style::bind is called next.
  7232. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7233. } // Since this will be restored, prevent from using these props to check cache in the next
  7234. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7235. else if (cachedByMe) {
  7236. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7237. }
  7238. var styleFont = style.font || DEFAULT_FONT; // PENDING
  7239. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7240. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7241. // But layer save/restore needed to be considered.
  7242. // if (styleFont !== ctx.__fontCache) {
  7243. // ctx.font = styleFont;
  7244. // if (prevEl !== WILL_BE_RESTORED) {
  7245. // ctx.__fontCache = styleFont;
  7246. // }
  7247. // }
  7248. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7249. ctx.font = styleFont;
  7250. } // Use the final font from context-2d, because the final
  7251. // font might not be the style.font when it is illegal.
  7252. // But get `ctx.font` might be time consuming.
  7253. var computedFont = hostEl.__computedFont;
  7254. if (hostEl.__styleFont !== styleFont) {
  7255. hostEl.__styleFont = styleFont;
  7256. computedFont = hostEl.__computedFont = ctx.font;
  7257. }
  7258. var textPadding = style.textPadding;
  7259. var textLineHeight = style.textLineHeight;
  7260. var contentBlock = hostEl.__textCotentBlock;
  7261. if (!contentBlock || hostEl.__dirtyText) {
  7262. contentBlock = hostEl.__textCotentBlock = parsePlainText(text, computedFont, textPadding, textLineHeight, style.truncate);
  7263. }
  7264. var outerHeight = contentBlock.outerHeight;
  7265. var textLines = contentBlock.lines;
  7266. var lineHeight = contentBlock.lineHeight;
  7267. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7268. var baseX = boxPos.baseX;
  7269. var baseY = boxPos.baseY;
  7270. var textAlign = boxPos.textAlign || 'left';
  7271. var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing.
  7272. applyTextRotation(ctx, style, rect, baseX, baseY);
  7273. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7274. var textX = baseX;
  7275. var textY = boxY;
  7276. if (needDrawBg || textPadding) {
  7277. // Consider performance, do not call getTextWidth util necessary.
  7278. var textWidth = getWidth(text, computedFont);
  7279. var outerWidth = textWidth;
  7280. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7281. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7282. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7283. if (textPadding) {
  7284. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7285. textY += textPadding[0];
  7286. }
  7287. } // Always set textAlign and textBase line, because it is difficute to calculate
  7288. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7289. // font set happened.
  7290. ctx.textAlign = textAlign; // Force baseline to be "middle". Otherwise, if using "top", the
  7291. // text will offset downward a little bit in font "Microsoft YaHei".
  7292. ctx.textBaseline = 'middle'; // Set text opacity
  7293. ctx.globalAlpha = style.opacity || 1; // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7294. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7295. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7296. var styleProp = propItem[0];
  7297. var ctxProp = propItem[1];
  7298. var val = style[styleProp];
  7299. if (!checkCache || val !== prevStyle[styleProp]) {
  7300. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7301. }
  7302. } // `textBaseline` is set as 'middle'.
  7303. textY += lineHeight / 2;
  7304. var textStrokeWidth = style.textStrokeWidth;
  7305. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7306. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7307. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7308. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7309. var textFill = getFill(style.textFill);
  7310. if (textStroke) {
  7311. if (strokeWidthChanged) {
  7312. ctx.lineWidth = textStrokeWidth;
  7313. }
  7314. if (strokeChanged) {
  7315. ctx.strokeStyle = textStroke;
  7316. }
  7317. }
  7318. if (textFill) {
  7319. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7320. ctx.fillStyle = textFill;
  7321. }
  7322. } // Optimize simply, in most cases only one line exists.
  7323. if (textLines.length === 1) {
  7324. // Fill after stroke so the outline will not cover the main part.
  7325. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7326. textFill && ctx.fillText(textLines[0], textX, textY);
  7327. } else {
  7328. for (var i = 0; i < textLines.length; i++) {
  7329. // Fill after stroke so the outline will not cover the main part.
  7330. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7331. textFill && ctx.fillText(textLines[i], textX, textY);
  7332. textY += lineHeight;
  7333. }
  7334. }
  7335. }
  7336. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7337. // Do not do cache for rich text because of the complexity.
  7338. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7339. if (prevEl !== WILL_BE_RESTORED) {
  7340. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7341. }
  7342. var contentBlock = hostEl.__textCotentBlock;
  7343. if (!contentBlock || hostEl.__dirtyText) {
  7344. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7345. }
  7346. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7347. }
  7348. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7349. var contentWidth = contentBlock.width;
  7350. var outerWidth = contentBlock.outerWidth;
  7351. var outerHeight = contentBlock.outerHeight;
  7352. var textPadding = style.textPadding;
  7353. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7354. var baseX = boxPos.baseX;
  7355. var baseY = boxPos.baseY;
  7356. var textAlign = boxPos.textAlign;
  7357. var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing.
  7358. applyTextRotation(ctx, style, rect, baseX, baseY);
  7359. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7360. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7361. var xLeft = boxX;
  7362. var lineTop = boxY;
  7363. if (textPadding) {
  7364. xLeft += textPadding[3];
  7365. lineTop += textPadding[0];
  7366. }
  7367. var xRight = xLeft + contentWidth;
  7368. needDrawBackground(style) && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7369. for (var i = 0; i < contentBlock.lines.length; i++) {
  7370. var line = contentBlock.lines[i];
  7371. var tokens = line.tokens;
  7372. var tokenCount = tokens.length;
  7373. var lineHeight = line.lineHeight;
  7374. var usedWidth = line.width;
  7375. var leftIndex = 0;
  7376. var lineXLeft = xLeft;
  7377. var lineXRight = xRight;
  7378. var rightIndex = tokenCount - 1;
  7379. var token;
  7380. while (leftIndex < tokenCount && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')) {
  7381. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7382. usedWidth -= token.width;
  7383. lineXLeft += token.width;
  7384. leftIndex++;
  7385. }
  7386. while (rightIndex >= 0 && (token = tokens[rightIndex], token.textAlign === 'right')) {
  7387. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7388. usedWidth -= token.width;
  7389. lineXRight -= token.width;
  7390. rightIndex--;
  7391. } // The other tokens are placed as textAlign 'center' if there is enough space.
  7392. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7393. while (leftIndex <= rightIndex) {
  7394. token = tokens[leftIndex]; // Consider width specified by user, use 'center' rather than 'left'.
  7395. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7396. lineXLeft += token.width;
  7397. leftIndex++;
  7398. }
  7399. lineTop += lineHeight;
  7400. }
  7401. }
  7402. function applyTextRotation(ctx, style, rect, x, y) {
  7403. // textRotation only apply in RectText.
  7404. if (rect && style.textRotation) {
  7405. var origin = style.textOrigin;
  7406. if (origin === 'center') {
  7407. x = rect.width / 2 + rect.x;
  7408. y = rect.height / 2 + rect.y;
  7409. } else if (origin) {
  7410. x = origin[0] + rect.x;
  7411. y = origin[1] + rect.y;
  7412. }
  7413. ctx.translate(x, y); // Positive: anticlockwise
  7414. ctx.rotate(-style.textRotation);
  7415. ctx.translate(-x, -y);
  7416. }
  7417. }
  7418. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7419. var tokenStyle = style.rich[token.styleName] || {};
  7420. tokenStyle.text = token.text; // 'ctx.textBaseline' is always set as 'middle', for sake of
  7421. // the bias of "Microsoft YaHei".
  7422. var textVerticalAlign = token.textVerticalAlign;
  7423. var y = lineTop + lineHeight / 2;
  7424. if (textVerticalAlign === 'top') {
  7425. y = lineTop + token.height / 2;
  7426. } else if (textVerticalAlign === 'bottom') {
  7427. y = lineTop + lineHeight - token.height / 2;
  7428. }
  7429. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(hostEl, ctx, tokenStyle, textAlign === 'right' ? x - token.width : textAlign === 'center' ? x - token.width / 2 : x, y - token.height / 2, token.width, token.height);
  7430. var textPadding = token.textPadding;
  7431. if (textPadding) {
  7432. x = getTextXForPadding(x, textAlign, textPadding);
  7433. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7434. }
  7435. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7436. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7437. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7438. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7439. setCtx(ctx, 'textAlign', textAlign); // Force baseline to be "middle". Otherwise, if using "top", the
  7440. // text will offset downward a little bit in font "Microsoft YaHei".
  7441. setCtx(ctx, 'textBaseline', 'middle');
  7442. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7443. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7444. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7445. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth); // Fill after stroke so the outline will not cover the main part.
  7446. if (textStroke) {
  7447. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7448. setCtx(ctx, 'strokeStyle', textStroke);
  7449. ctx.strokeText(token.text, x, y);
  7450. }
  7451. if (textFill) {
  7452. setCtx(ctx, 'fillStyle', textFill);
  7453. ctx.fillText(token.text, x, y);
  7454. }
  7455. }
  7456. function needDrawBackground(style) {
  7457. return !!(style.textBackgroundColor || style.textBorderWidth && style.textBorderColor);
  7458. } // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7459. // shape: {x, y, width, height}
  7460. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7461. var textBackgroundColor = style.textBackgroundColor;
  7462. var textBorderWidth = style.textBorderWidth;
  7463. var textBorderColor = style.textBorderColor;
  7464. var isPlainBg = isString(textBackgroundColor);
  7465. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7466. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7467. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7468. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7469. if (isPlainBg || textBorderWidth && textBorderColor) {
  7470. ctx.beginPath();
  7471. var textBorderRadius = style.textBorderRadius;
  7472. if (!textBorderRadius) {
  7473. ctx.rect(x, y, width, height);
  7474. } else {
  7475. buildPath(ctx, {
  7476. x: x,
  7477. y: y,
  7478. width: width,
  7479. height: height,
  7480. r: textBorderRadius
  7481. });
  7482. }
  7483. ctx.closePath();
  7484. }
  7485. if (isPlainBg) {
  7486. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7487. if (style.fillOpacity != null) {
  7488. var originalGlobalAlpha = ctx.globalAlpha;
  7489. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7490. ctx.fill();
  7491. ctx.globalAlpha = originalGlobalAlpha;
  7492. } else {
  7493. ctx.fill();
  7494. }
  7495. } else if (isObject$1(textBackgroundColor)) {
  7496. var image = textBackgroundColor.image;
  7497. image = createOrUpdateImage(image, null, hostEl, onBgImageLoaded, textBackgroundColor);
  7498. if (image && isImageReady(image)) {
  7499. ctx.drawImage(image, x, y, width, height);
  7500. }
  7501. }
  7502. if (textBorderWidth && textBorderColor) {
  7503. setCtx(ctx, 'lineWidth', textBorderWidth);
  7504. setCtx(ctx, 'strokeStyle', textBorderColor);
  7505. if (style.strokeOpacity != null) {
  7506. var originalGlobalAlpha = ctx.globalAlpha;
  7507. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7508. ctx.stroke();
  7509. ctx.globalAlpha = originalGlobalAlpha;
  7510. } else {
  7511. ctx.stroke();
  7512. }
  7513. }
  7514. }
  7515. function onBgImageLoaded(image, textBackgroundColor) {
  7516. // Replace image, so that `contain/text.js#parseRichText`
  7517. // will get correct result in next tick.
  7518. textBackgroundColor.image = image;
  7519. }
  7520. function getBoxPosition(out, hostEl, style, rect) {
  7521. var baseX = style.x || 0;
  7522. var baseY = style.y || 0;
  7523. var textAlign = style.textAlign;
  7524. var textVerticalAlign = style.textVerticalAlign; // Text position represented by coord
  7525. if (rect) {
  7526. var textPosition = style.textPosition;
  7527. if (textPosition instanceof Array) {
  7528. // Percent
  7529. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7530. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7531. } else {
  7532. var res = hostEl && hostEl.calculateTextPosition ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect) : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7533. baseX = res.x;
  7534. baseY = res.y; // Default align and baseline when has textPosition
  7535. textAlign = textAlign || res.textAlign;
  7536. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7537. } // textOffset is only support in RectText, otherwise
  7538. // we have to adjust boundingRect for textOffset.
  7539. var textOffset = style.textOffset;
  7540. if (textOffset) {
  7541. baseX += textOffset[0];
  7542. baseY += textOffset[1];
  7543. }
  7544. }
  7545. out = out || {};
  7546. out.baseX = baseX;
  7547. out.baseY = baseY;
  7548. out.textAlign = textAlign;
  7549. out.textVerticalAlign = textVerticalAlign;
  7550. return out;
  7551. }
  7552. function setCtx(ctx, prop, value) {
  7553. ctx[prop] = fixShadow(ctx, prop, value);
  7554. return ctx[prop];
  7555. }
  7556. /**
  7557. * @param {string} [stroke] If specified, do not check style.textStroke.
  7558. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7559. * @param {number} style
  7560. */
  7561. function getStroke(stroke, lineWidth) {
  7562. return stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none' ? null // TODO pattern and gradient?
  7563. : stroke.image || stroke.colorStops ? '#000' : stroke;
  7564. }
  7565. function getFill(fill) {
  7566. return fill == null || fill === 'none' ? null // TODO pattern and gradient?
  7567. : fill.image || fill.colorStops ? '#000' : fill;
  7568. }
  7569. function parsePercent(value, maxValue) {
  7570. if (typeof value === 'string') {
  7571. if (value.lastIndexOf('%') >= 0) {
  7572. return parseFloat(value) / 100 * maxValue;
  7573. }
  7574. return parseFloat(value);
  7575. }
  7576. return value;
  7577. }
  7578. function getTextXForPadding(x, textAlign, textPadding) {
  7579. return textAlign === 'right' ? x - textPadding[1] : textAlign === 'center' ? x + textPadding[3] / 2 - textPadding[1] / 2 : x + textPadding[3];
  7580. }
  7581. /**
  7582. * @param {string} text
  7583. * @param {module:zrender/Style} style
  7584. * @return {boolean}
  7585. */
  7586. function needDrawText(text, style) {
  7587. return text != null && (text || style.textBackgroundColor || style.textBorderWidth && style.textBorderColor || style.textPadding);
  7588. }
  7589. /**
  7590. * Mixin for drawing text in a element bounding rect
  7591. * @module zrender/mixin/RectText
  7592. */
  7593. var tmpRect$1 = new BoundingRect();
  7594. var RectText = function () {};
  7595. RectText.prototype = {
  7596. constructor: RectText,
  7597. /**
  7598. * Draw text in a rect with specified position.
  7599. * @param {CanvasRenderingContext2D} ctx
  7600. * @param {Object} rect Displayable rect
  7601. */
  7602. drawRectText: function (ctx, rect) {
  7603. var style = this.style;
  7604. rect = style.textRect || rect; // Optimize, avoid normalize every time.
  7605. this.__dirty && normalizeTextStyle(style, true);
  7606. var text = style.text; // Convert to string
  7607. text != null && (text += '');
  7608. if (!needDrawText(text, style)) {
  7609. return;
  7610. } // FIXME
  7611. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7612. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7613. // text propably break the cache for its host elements.
  7614. ctx.save(); // Transform rect to view space
  7615. var transform = this.transform;
  7616. if (!style.transformText) {
  7617. if (transform) {
  7618. tmpRect$1.copy(rect);
  7619. tmpRect$1.applyTransform(transform);
  7620. rect = tmpRect$1;
  7621. }
  7622. } else {
  7623. this.setTransform(ctx);
  7624. } // transformText and textRotation can not be used at the same time.
  7625. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7626. ctx.restore();
  7627. }
  7628. };
  7629. /**
  7630. * Base class of all displayable graphic objects
  7631. * @module zrender/graphic/Displayable
  7632. */
  7633. /**
  7634. * @alias module:zrender/graphic/Displayable
  7635. * @extends module:zrender/Element
  7636. * @extends module:zrender/graphic/mixin/RectText
  7637. */
  7638. function Displayable(opts) {
  7639. opts = opts || {};
  7640. Element.call(this, opts); // Extend properties
  7641. for (var name in opts) {
  7642. if (opts.hasOwnProperty(name) && name !== 'style') {
  7643. this[name] = opts[name];
  7644. }
  7645. }
  7646. /**
  7647. * @type {module:zrender/graphic/Style}
  7648. */
  7649. this.style = new Style(opts.style, this);
  7650. this._rect = null; // Shapes for cascade clipping.
  7651. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  7652. // because it is easy to only using null to check whether clipPaths changed.
  7653. this.__clipPaths = null; // FIXME Stateful must be mixined after style is setted
  7654. // Stateful.call(this, opts);
  7655. }
  7656. Displayable.prototype = {
  7657. constructor: Displayable,
  7658. type: 'displayable',
  7659. /**
  7660. * Dirty flag. From which painter will determine if this displayable object needs brush.
  7661. * @name module:zrender/graphic/Displayable#__dirty
  7662. * @type {boolean}
  7663. */
  7664. __dirty: true,
  7665. /**
  7666. * Whether the displayable object is visible. when it is true, the displayable object
  7667. * is not drawn, but the mouse event can still trigger the object.
  7668. * @name module:/zrender/graphic/Displayable#invisible
  7669. * @type {boolean}
  7670. * @default false
  7671. */
  7672. invisible: false,
  7673. /**
  7674. * @name module:/zrender/graphic/Displayable#z
  7675. * @type {number}
  7676. * @default 0
  7677. */
  7678. z: 0,
  7679. /**
  7680. * @name module:/zrender/graphic/Displayable#z
  7681. * @type {number}
  7682. * @default 0
  7683. */
  7684. z2: 0,
  7685. /**
  7686. * The z level determines the displayable object can be drawn in which layer canvas.
  7687. * @name module:/zrender/graphic/Displayable#zlevel
  7688. * @type {number}
  7689. * @default 0
  7690. */
  7691. zlevel: 0,
  7692. /**
  7693. * Whether it can be dragged.
  7694. * @name module:/zrender/graphic/Displayable#draggable
  7695. * @type {boolean}
  7696. * @default false
  7697. */
  7698. draggable: false,
  7699. /**
  7700. * Whether is it dragging.
  7701. * @name module:/zrender/graphic/Displayable#draggable
  7702. * @type {boolean}
  7703. * @default false
  7704. */
  7705. dragging: false,
  7706. /**
  7707. * Whether to respond to mouse events.
  7708. * @name module:/zrender/graphic/Displayable#silent
  7709. * @type {boolean}
  7710. * @default false
  7711. */
  7712. silent: false,
  7713. /**
  7714. * If enable culling
  7715. * @type {boolean}
  7716. * @default false
  7717. */
  7718. culling: false,
  7719. /**
  7720. * Mouse cursor when hovered
  7721. * @name module:/zrender/graphic/Displayable#cursor
  7722. * @type {string}
  7723. */
  7724. cursor: 'pointer',
  7725. /**
  7726. * If hover area is bounding rect
  7727. * @name module:/zrender/graphic/Displayable#rectHover
  7728. * @type {string}
  7729. */
  7730. rectHover: false,
  7731. /**
  7732. * Render the element progressively when the value >= 0,
  7733. * usefull for large data.
  7734. * @type {boolean}
  7735. */
  7736. progressive: false,
  7737. /**
  7738. * @type {boolean}
  7739. */
  7740. incremental: false,
  7741. /**
  7742. * Scale ratio for global scale.
  7743. * @type {boolean}
  7744. */
  7745. globalScaleRatio: 1,
  7746. beforeBrush: function (ctx) {},
  7747. afterBrush: function (ctx) {},
  7748. /**
  7749. * Graphic drawing method.
  7750. * @param {CanvasRenderingContext2D} ctx
  7751. */
  7752. // Interface
  7753. brush: function (ctx, prevEl) {},
  7754. /**
  7755. * Get the minimum bounding box.
  7756. * @return {module:zrender/core/BoundingRect}
  7757. */
  7758. // Interface
  7759. getBoundingRect: function () {},
  7760. /**
  7761. * If displayable element contain coord x, y
  7762. * @param {number} x
  7763. * @param {number} y
  7764. * @return {boolean}
  7765. */
  7766. contain: function (x, y) {
  7767. return this.rectContain(x, y);
  7768. },
  7769. /**
  7770. * @param {Function} cb
  7771. * @param {} context
  7772. */
  7773. traverse: function (cb, context) {
  7774. cb.call(context, this);
  7775. },
  7776. /**
  7777. * If bounding rect of element contain coord x, y
  7778. * @param {number} x
  7779. * @param {number} y
  7780. * @return {boolean}
  7781. */
  7782. rectContain: function (x, y) {
  7783. var coord = this.transformCoordToLocal(x, y);
  7784. var rect = this.getBoundingRect();
  7785. return rect.contain(coord[0], coord[1]);
  7786. },
  7787. /**
  7788. * Mark displayable element dirty and refresh next frame
  7789. */
  7790. dirty: function () {
  7791. this.__dirty = this.__dirtyText = true;
  7792. this._rect = null;
  7793. this.__zr && this.__zr.refresh();
  7794. },
  7795. /**
  7796. * If displayable object binded any event
  7797. * @return {boolean}
  7798. */
  7799. // TODO, events bound by bind
  7800. // isSilent: function () {
  7801. // return !(
  7802. // this.hoverable || this.draggable
  7803. // || this.onmousemove || this.onmouseover || this.onmouseout
  7804. // || this.onmousedown || this.onmouseup || this.onclick
  7805. // || this.ondragenter || this.ondragover || this.ondragleave
  7806. // || this.ondrop
  7807. // );
  7808. // },
  7809. /**
  7810. * Alias for animate('style')
  7811. * @param {boolean} loop
  7812. */
  7813. animateStyle: function (loop) {
  7814. return this.animate('style', loop);
  7815. },
  7816. attrKV: function (key, value) {
  7817. if (key !== 'style') {
  7818. Element.prototype.attrKV.call(this, key, value);
  7819. } else {
  7820. this.style.set(value);
  7821. }
  7822. },
  7823. /**
  7824. * @param {Object|string} key
  7825. * @param {*} value
  7826. */
  7827. setStyle: function (key, value) {
  7828. this.style.set(key, value);
  7829. this.dirty(false);
  7830. return this;
  7831. },
  7832. /**
  7833. * Use given style object
  7834. * @param {Object} obj
  7835. */
  7836. useStyle: function (obj) {
  7837. this.style = new Style(obj, this);
  7838. this.dirty(false);
  7839. return this;
  7840. },
  7841. /**
  7842. * The string value of `textPosition` needs to be calculated to a real postion.
  7843. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  7844. * by default. See `contain/text.js#calculateTextPosition` for more details.
  7845. * But some coutom shapes like "pin", "flag" have center that is not exactly
  7846. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  7847. * for those shapes. It will be called if the `style.textPosition` is a string.
  7848. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  7849. * be responsible for creating one.
  7850. * @param {module:zrender/graphic/Style} style
  7851. * @param {Object} rect {x, y, width, height}
  7852. * @return {Obejct} out The same as the input out.
  7853. * {
  7854. * x: number. mandatory.
  7855. * y: number. mandatory.
  7856. * textAlign: string. optional. use style.textAlign by default.
  7857. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  7858. * }
  7859. */
  7860. calculateTextPosition: null
  7861. };
  7862. inherits(Displayable, Element);
  7863. mixin(Displayable, RectText); // zrUtil.mixin(Displayable, Stateful);
  7864. /**
  7865. * @alias zrender/graphic/Image
  7866. * @extends module:zrender/graphic/Displayable
  7867. * @constructor
  7868. * @param {Object} opts
  7869. */
  7870. function ZImage(opts) {
  7871. Displayable.call(this, opts);
  7872. }
  7873. ZImage.prototype = {
  7874. constructor: ZImage,
  7875. type: 'image',
  7876. brush: function (ctx, prevEl) {
  7877. var style = this.style;
  7878. var src = style.image; // Must bind each time
  7879. style.bind(ctx, this, prevEl);
  7880. var image = this._image = createOrUpdateImage(src, this._image, this, this.onload);
  7881. if (!image || !isImageReady(image)) {
  7882. return;
  7883. } // 图片已经加载完成
  7884. // if (image.nodeName.toUpperCase() == 'IMG') {
  7885. // if (!image.complete) {
  7886. // return;
  7887. // }
  7888. // }
  7889. // Else is canvas
  7890. var x = style.x || 0;
  7891. var y = style.y || 0;
  7892. var width = style.width;
  7893. var height = style.height;
  7894. var aspect = image.width / image.height;
  7895. if (width == null && height != null) {
  7896. // Keep image/height ratio
  7897. width = height * aspect;
  7898. } else if (height == null && width != null) {
  7899. height = width / aspect;
  7900. } else if (width == null && height == null) {
  7901. width = image.width;
  7902. height = image.height;
  7903. } // 设置transform
  7904. this.setTransform(ctx);
  7905. if (style.sWidth && style.sHeight) {
  7906. var sx = style.sx || 0;
  7907. var sy = style.sy || 0;
  7908. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  7909. } else if (style.sx && style.sy) {
  7910. var sx = style.sx;
  7911. var sy = style.sy;
  7912. var sWidth = width - sx;
  7913. var sHeight = height - sy;
  7914. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  7915. } else {
  7916. ctx.drawImage(image, x, y, width, height);
  7917. } // Draw rect text
  7918. if (style.text != null) {
  7919. // Only restore transform when needs draw text.
  7920. this.restoreTransform(ctx);
  7921. this.drawRectText(ctx, this.getBoundingRect());
  7922. }
  7923. },
  7924. getBoundingRect: function () {
  7925. var style = this.style;
  7926. if (!this._rect) {
  7927. this._rect = new BoundingRect(style.x || 0, style.y || 0, style.width || 0, style.height || 0);
  7928. }
  7929. return this._rect;
  7930. }
  7931. };
  7932. inherits(ZImage, Displayable);
  7933. var HOVER_LAYER_ZLEVEL = 1e5;
  7934. var CANVAS_ZLEVEL = 314159;
  7935. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7936. var INCREMENTAL_INC = 0.001;
  7937. function parseInt10(val) {
  7938. return parseInt(val, 10);
  7939. }
  7940. function isLayerValid(layer) {
  7941. if (!layer) {
  7942. return false;
  7943. }
  7944. if (layer.__builtin__) {
  7945. return true;
  7946. }
  7947. if (typeof layer.resize !== 'function' || typeof layer.refresh !== 'function') {
  7948. return false;
  7949. }
  7950. return true;
  7951. }
  7952. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7953. var viewRect = new BoundingRect(0, 0, 0, 0);
  7954. function isDisplayableCulled(el, width, height) {
  7955. tmpRect.copy(el.getBoundingRect());
  7956. if (el.transform) {
  7957. tmpRect.applyTransform(el.transform);
  7958. }
  7959. viewRect.width = width;
  7960. viewRect.height = height;
  7961. return !tmpRect.intersect(viewRect);
  7962. }
  7963. function isClipPathChanged(clipPaths, prevClipPaths) {
  7964. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  7965. if (clipPaths === prevClipPaths) {
  7966. return false;
  7967. }
  7968. if (!clipPaths || !prevClipPaths || clipPaths.length !== prevClipPaths.length) {
  7969. return true;
  7970. }
  7971. for (var i = 0; i < clipPaths.length; i++) {
  7972. if (clipPaths[i] !== prevClipPaths[i]) {
  7973. return true;
  7974. }
  7975. }
  7976. return false;
  7977. }
  7978. function doClip(clipPaths, ctx) {
  7979. for (var i = 0; i < clipPaths.length; i++) {
  7980. var clipPath = clipPaths[i];
  7981. clipPath.setTransform(ctx);
  7982. ctx.beginPath();
  7983. clipPath.buildPath(ctx, clipPath.shape);
  7984. ctx.clip(); // Transform back
  7985. clipPath.restoreTransform(ctx);
  7986. }
  7987. }
  7988. function createRoot(width, height) {
  7989. var domRoot = document.createElement('div'); // domRoot.onselectstart = returnFalse; // Avoid page selected
  7990. domRoot.style.cssText = ['position:relative', // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  7991. // dom does not act as expected) when some of the parent dom has
  7992. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  7993. // the canvas is not at the top part of the page.
  7994. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  7995. // this `overflow:hidden` to avoid the bug.
  7996. // 'overflow:hidden',
  7997. 'width:' + width + 'px', 'height:' + height + 'px', 'padding:0', 'margin:0', 'border-width:0'].join(';') + ';';
  7998. return domRoot;
  7999. }
  8000. /**
  8001. * @alias module:zrender/Painter
  8002. * @constructor
  8003. * @param {HTMLElement} root 绘图容器
  8004. * @param {module:zrender/Storage} storage
  8005. * @param {Object} opts
  8006. */
  8007. var Painter = function (root, storage, opts) {
  8008. this.type = 'canvas'; // In node environment using node-canvas
  8009. var singleCanvas = !root.nodeName // In node ?
  8010. || root.nodeName.toUpperCase() === 'CANVAS';
  8011. this._opts = opts = extend({}, opts || {});
  8012. /**
  8013. * @type {number}
  8014. */
  8015. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8016. /**
  8017. * @type {boolean}
  8018. * @private
  8019. */
  8020. this._singleCanvas = singleCanvas;
  8021. /**
  8022. * 绘图容器
  8023. * @type {HTMLElement}
  8024. */
  8025. this.root = root;
  8026. var rootStyle = root.style;
  8027. if (rootStyle) {
  8028. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8029. rootStyle['-webkit-user-select'] = rootStyle['user-select'] = rootStyle['-webkit-touch-callout'] = 'none';
  8030. root.innerHTML = '';
  8031. }
  8032. /**
  8033. * @type {module:zrender/Storage}
  8034. */
  8035. this.storage = storage;
  8036. /**
  8037. * @type {Array.<number>}
  8038. * @private
  8039. */
  8040. var zlevelList = this._zlevelList = [];
  8041. /**
  8042. * @type {Object.<string, module:zrender/Layer>}
  8043. * @private
  8044. */
  8045. var layers = this._layers = {};
  8046. /**
  8047. * @type {Object.<string, Object>}
  8048. * @private
  8049. */
  8050. this._layerConfig = {};
  8051. /**
  8052. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8053. */
  8054. this._needsManuallyCompositing = false;
  8055. if (!singleCanvas) {
  8056. this._width = this._getSize(0);
  8057. this._height = this._getSize(1);
  8058. var domRoot = this._domRoot = createRoot(this._width, this._height);
  8059. root.appendChild(domRoot);
  8060. } else {
  8061. var width = root.width;
  8062. var height = root.height;
  8063. if (opts.width != null) {
  8064. width = opts.width;
  8065. }
  8066. if (opts.height != null) {
  8067. height = opts.height;
  8068. }
  8069. this.dpr = opts.devicePixelRatio || 1; // Use canvas width and height directly
  8070. root.width = width * this.dpr;
  8071. root.height = height * this.dpr;
  8072. this._width = width;
  8073. this._height = height; // Create layer if only one given canvas
  8074. // Device can be specified to create a high dpi image.
  8075. var mainLayer = new Layer(root, this, this.dpr);
  8076. mainLayer.__builtin__ = true;
  8077. mainLayer.initContext(); // FIXME Use canvas width and height
  8078. // mainLayer.resize(width, height);
  8079. layers[CANVAS_ZLEVEL] = mainLayer;
  8080. mainLayer.zlevel = CANVAS_ZLEVEL; // Not use common zlevel.
  8081. zlevelList.push(CANVAS_ZLEVEL);
  8082. this._domRoot = root;
  8083. }
  8084. /**
  8085. * @type {module:zrender/Layer}
  8086. * @private
  8087. */
  8088. this._hoverlayer = null;
  8089. this._hoverElements = [];
  8090. };
  8091. Painter.prototype = {
  8092. constructor: Painter,
  8093. getType: function () {
  8094. return 'canvas';
  8095. },
  8096. /**
  8097. * If painter use a single canvas
  8098. * @return {boolean}
  8099. */
  8100. isSingleCanvas: function () {
  8101. return this._singleCanvas;
  8102. },
  8103. /**
  8104. * @return {HTMLDivElement}
  8105. */
  8106. getViewportRoot: function () {
  8107. return this._domRoot;
  8108. },
  8109. getViewportRootOffset: function () {
  8110. var viewportRoot = this.getViewportRoot();
  8111. if (viewportRoot) {
  8112. return {
  8113. offsetLeft: viewportRoot.offsetLeft || 0,
  8114. offsetTop: viewportRoot.offsetTop || 0
  8115. };
  8116. }
  8117. },
  8118. /**
  8119. * 刷新
  8120. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8121. */
  8122. refresh: function (paintAll) {
  8123. var list = this.storage.getDisplayList(true);
  8124. var zlevelList = this._zlevelList;
  8125. this._redrawId = Math.random();
  8126. this._paintList(list, paintAll, this._redrawId); // Paint custum layers
  8127. for (var i = 0; i < zlevelList.length; i++) {
  8128. var z = zlevelList[i];
  8129. var layer = this._layers[z];
  8130. if (!layer.__builtin__ && layer.refresh) {
  8131. var clearColor = i === 0 ? this._backgroundColor : null;
  8132. layer.refresh(clearColor);
  8133. }
  8134. }
  8135. this.refreshHover();
  8136. return this;
  8137. },
  8138. addHover: function (el, hoverStyle) {
  8139. if (el.__hoverMir) {
  8140. return;
  8141. }
  8142. var elMirror = new el.constructor({
  8143. style: el.style,
  8144. shape: el.shape,
  8145. z: el.z,
  8146. z2: el.z2,
  8147. silent: el.silent
  8148. });
  8149. elMirror.__from = el;
  8150. el.__hoverMir = elMirror;
  8151. hoverStyle && elMirror.setStyle(hoverStyle);
  8152. this._hoverElements.push(elMirror);
  8153. return elMirror;
  8154. },
  8155. removeHover: function (el) {
  8156. var elMirror = el.__hoverMir;
  8157. var hoverElements = this._hoverElements;
  8158. var idx = indexOf(hoverElements, elMirror);
  8159. if (idx >= 0) {
  8160. hoverElements.splice(idx, 1);
  8161. }
  8162. el.__hoverMir = null;
  8163. },
  8164. clearHover: function (el) {
  8165. var hoverElements = this._hoverElements;
  8166. for (var i = 0; i < hoverElements.length; i++) {
  8167. var from = hoverElements[i].__from;
  8168. if (from) {
  8169. from.__hoverMir = null;
  8170. }
  8171. }
  8172. hoverElements.length = 0;
  8173. },
  8174. refreshHover: function () {
  8175. var hoverElements = this._hoverElements;
  8176. var len = hoverElements.length;
  8177. var hoverLayer = this._hoverlayer;
  8178. hoverLayer && hoverLayer.clear();
  8179. if (!len) {
  8180. return;
  8181. }
  8182. sort(hoverElements, this.storage.displayableSortFunc); // Use a extream large zlevel
  8183. // FIXME?
  8184. if (!hoverLayer) {
  8185. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8186. }
  8187. var scope = {};
  8188. hoverLayer.ctx.save();
  8189. for (var i = 0; i < len;) {
  8190. var el = hoverElements[i];
  8191. var originalEl = el.__from; // Original el is removed
  8192. // PENDING
  8193. if (!(originalEl && originalEl.__zr)) {
  8194. hoverElements.splice(i, 1);
  8195. originalEl.__hoverMir = null;
  8196. len--;
  8197. continue;
  8198. }
  8199. i++; // Use transform
  8200. // FIXME style and shape ?
  8201. if (!originalEl.invisible) {
  8202. el.transform = originalEl.transform;
  8203. el.invTransform = originalEl.invTransform;
  8204. el.__clipPaths = originalEl.__clipPaths; // el.
  8205. this._doPaintEl(el, hoverLayer, true, scope);
  8206. }
  8207. }
  8208. hoverLayer.ctx.restore();
  8209. },
  8210. getHoverLayer: function () {
  8211. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8212. },
  8213. _paintList: function (list, paintAll, redrawId) {
  8214. if (this._redrawId !== redrawId) {
  8215. return;
  8216. }
  8217. paintAll = paintAll || false;
  8218. this._updateLayerStatus(list);
  8219. var finished = this._doPaintList(list, paintAll);
  8220. if (this._needsManuallyCompositing) {
  8221. this._compositeManually();
  8222. }
  8223. if (!finished) {
  8224. var self = this;
  8225. requestAnimationFrame(function () {
  8226. self._paintList(list, paintAll, redrawId);
  8227. });
  8228. }
  8229. },
  8230. _compositeManually: function () {
  8231. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8232. var width = this._domRoot.width;
  8233. var height = this._domRoot.height;
  8234. ctx.clearRect(0, 0, width, height); // PENDING, If only builtin layer?
  8235. this.eachBuiltinLayer(function (layer) {
  8236. if (layer.virtual) {
  8237. ctx.drawImage(layer.dom, 0, 0, width, height);
  8238. }
  8239. });
  8240. },
  8241. _doPaintList: function (list, paintAll) {
  8242. var layerList = [];
  8243. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8244. var zlevel = this._zlevelList[zi];
  8245. var layer = this._layers[zlevel];
  8246. if (layer.__builtin__ && layer !== this._hoverlayer && (layer.__dirty || paintAll)) {
  8247. layerList.push(layer);
  8248. }
  8249. }
  8250. var finished = true;
  8251. for (var k = 0; k < layerList.length; k++) {
  8252. var layer = layerList[k];
  8253. var ctx = layer.ctx;
  8254. var scope = {};
  8255. ctx.save();
  8256. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8257. var useTimer = !paintAll && layer.incremental && Date.now;
  8258. var startTime = useTimer && Date.now();
  8259. var clearColor = layer.zlevel === this._zlevelList[0] ? this._backgroundColor : null; // All elements in this layer are cleared.
  8260. if (layer.__startIndex === layer.__endIndex) {
  8261. layer.clear(false, clearColor);
  8262. } else if (start === layer.__startIndex) {
  8263. var firstEl = list[start];
  8264. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8265. layer.clear(false, clearColor);
  8266. }
  8267. }
  8268. if (start === -1) {
  8269. console.error('For some unknown reason. drawIndex is -1');
  8270. start = layer.__startIndex;
  8271. }
  8272. for (var i = start; i < layer.__endIndex; i++) {
  8273. var el = list[i];
  8274. this._doPaintEl(el, layer, paintAll, scope);
  8275. el.__dirty = el.__dirtyText = false;
  8276. if (useTimer) {
  8277. // Date.now can be executed in 13,025,305 ops/second.
  8278. var dTime = Date.now() - startTime; // Give 15 millisecond to draw.
  8279. // The rest elements will be drawn in the next frame.
  8280. if (dTime > 15) {
  8281. break;
  8282. }
  8283. }
  8284. }
  8285. layer.__drawIndex = i;
  8286. if (layer.__drawIndex < layer.__endIndex) {
  8287. finished = false;
  8288. }
  8289. if (scope.prevElClipPaths) {
  8290. // Needs restore the state. If last drawn element is in the clipping area.
  8291. ctx.restore();
  8292. }
  8293. ctx.restore();
  8294. }
  8295. if (env$1.wxa) {
  8296. // Flush for weixin application
  8297. each$1(this._layers, function (layer) {
  8298. if (layer && layer.ctx && layer.ctx.draw) {
  8299. layer.ctx.draw();
  8300. }
  8301. });
  8302. }
  8303. return finished;
  8304. },
  8305. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8306. var ctx = currentLayer.ctx;
  8307. var m = el.transform;
  8308. if ((currentLayer.__dirty || forcePaint) && // Ignore invisible element
  8309. !el.invisible // Ignore transparent element
  8310. && el.style.opacity !== 0 // Ignore scale 0 element, in some environment like node-canvas
  8311. // Draw a scale 0 element can cause all following draw wrong
  8312. // And setTransform with scale 0 will cause set back transform failed.
  8313. && !(m && !m[0] && !m[3]) // Ignore culled element
  8314. && !(el.culling && isDisplayableCulled(el, this._width, this._height))) {
  8315. var clipPaths = el.__clipPaths;
  8316. var prevElClipPaths = scope.prevElClipPaths; // Optimize when clipping on group with several elements
  8317. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8318. // If has previous clipping state, restore from it
  8319. if (prevElClipPaths) {
  8320. ctx.restore();
  8321. scope.prevElClipPaths = null; // Reset prevEl since context has been restored
  8322. scope.prevEl = null;
  8323. } // New clipping state
  8324. if (clipPaths) {
  8325. ctx.save();
  8326. doClip(clipPaths, ctx);
  8327. scope.prevElClipPaths = clipPaths;
  8328. }
  8329. }
  8330. el.beforeBrush && el.beforeBrush(ctx);
  8331. el.brush(ctx, scope.prevEl || null);
  8332. scope.prevEl = el;
  8333. el.afterBrush && el.afterBrush(ctx);
  8334. }
  8335. },
  8336. /**
  8337. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8338. * @param {number} zlevel
  8339. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8340. * @return {module:zrender/Layer}
  8341. */
  8342. getLayer: function (zlevel, virtual) {
  8343. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8344. zlevel = CANVAS_ZLEVEL;
  8345. }
  8346. var layer = this._layers[zlevel];
  8347. if (!layer) {
  8348. // Create a new layer
  8349. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8350. layer.zlevel = zlevel;
  8351. layer.__builtin__ = true;
  8352. if (this._layerConfig[zlevel]) {
  8353. merge(layer, this._layerConfig[zlevel], true);
  8354. } // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8355. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  8356. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  8357. }
  8358. if (virtual) {
  8359. layer.virtual = virtual;
  8360. }
  8361. this.insertLayer(zlevel, layer); // Context is created after dom inserted to document
  8362. // Or excanvas will get 0px clientWidth and clientHeight
  8363. layer.initContext();
  8364. }
  8365. return layer;
  8366. },
  8367. insertLayer: function (zlevel, layer) {
  8368. var layersMap = this._layers;
  8369. var zlevelList = this._zlevelList;
  8370. var len = zlevelList.length;
  8371. var prevLayer = null;
  8372. var i = -1;
  8373. var domRoot = this._domRoot;
  8374. if (layersMap[zlevel]) {
  8375. logError$1('ZLevel ' + zlevel + ' has been used already');
  8376. return;
  8377. } // Check if is a valid layer
  8378. if (!isLayerValid(layer)) {
  8379. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8380. return;
  8381. }
  8382. if (len > 0 && zlevel > zlevelList[0]) {
  8383. for (i = 0; i < len - 1; i++) {
  8384. if (zlevelList[i] < zlevel && zlevelList[i + 1] > zlevel) {
  8385. break;
  8386. }
  8387. }
  8388. prevLayer = layersMap[zlevelList[i]];
  8389. }
  8390. zlevelList.splice(i + 1, 0, zlevel);
  8391. layersMap[zlevel] = layer; // Vitual layer will not directly show on the screen.
  8392. // (It can be a WebGL layer and assigned to a ZImage element)
  8393. // But it still under management of zrender.
  8394. if (!layer.virtual) {
  8395. if (prevLayer) {
  8396. var prevDom = prevLayer.dom;
  8397. if (prevDom.nextSibling) {
  8398. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  8399. } else {
  8400. domRoot.appendChild(layer.dom);
  8401. }
  8402. } else {
  8403. if (domRoot.firstChild) {
  8404. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8405. } else {
  8406. domRoot.appendChild(layer.dom);
  8407. }
  8408. }
  8409. }
  8410. },
  8411. // Iterate each layer
  8412. eachLayer: function (cb, context) {
  8413. var zlevelList = this._zlevelList;
  8414. var z;
  8415. var i;
  8416. for (i = 0; i < zlevelList.length; i++) {
  8417. z = zlevelList[i];
  8418. cb.call(context, this._layers[z], z);
  8419. }
  8420. },
  8421. // Iterate each buildin layer
  8422. eachBuiltinLayer: function (cb, context) {
  8423. var zlevelList = this._zlevelList;
  8424. var layer;
  8425. var z;
  8426. var i;
  8427. for (i = 0; i < zlevelList.length; i++) {
  8428. z = zlevelList[i];
  8429. layer = this._layers[z];
  8430. if (layer.__builtin__) {
  8431. cb.call(context, layer, z);
  8432. }
  8433. }
  8434. },
  8435. // Iterate each other layer except buildin layer
  8436. eachOtherLayer: function (cb, context) {
  8437. var zlevelList = this._zlevelList;
  8438. var layer;
  8439. var z;
  8440. var i;
  8441. for (i = 0; i < zlevelList.length; i++) {
  8442. z = zlevelList[i];
  8443. layer = this._layers[z];
  8444. if (!layer.__builtin__) {
  8445. cb.call(context, layer, z);
  8446. }
  8447. }
  8448. },
  8449. /**
  8450. * 获取所有已创建的层
  8451. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8452. */
  8453. getLayers: function () {
  8454. return this._layers;
  8455. },
  8456. _updateLayerStatus: function (list) {
  8457. this.eachBuiltinLayer(function (layer, z) {
  8458. layer.__dirty = layer.__used = false;
  8459. });
  8460. function updatePrevLayer(idx) {
  8461. if (prevLayer) {
  8462. if (prevLayer.__endIndex !== idx) {
  8463. prevLayer.__dirty = true;
  8464. }
  8465. prevLayer.__endIndex = idx;
  8466. }
  8467. }
  8468. if (this._singleCanvas) {
  8469. for (var i = 1; i < list.length; i++) {
  8470. var el = list[i];
  8471. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8472. this._needsManuallyCompositing = true;
  8473. break;
  8474. }
  8475. }
  8476. }
  8477. var prevLayer = null;
  8478. var incrementalLayerCount = 0;
  8479. var prevZlevel;
  8480. for (var i = 0; i < list.length; i++) {
  8481. var el = list[i];
  8482. var zlevel = el.zlevel;
  8483. var layer;
  8484. if (prevZlevel !== zlevel) {
  8485. prevZlevel = zlevel;
  8486. incrementalLayerCount = 0;
  8487. } // TODO Not use magic number on zlevel.
  8488. // Each layer with increment element can be separated to 3 layers.
  8489. // (Other Element drawn after incremental element)
  8490. // -----------------zlevel + EL_AFTER_INCREMENTAL_INC--------------------
  8491. // (Incremental element)
  8492. // ----------------------zlevel + INCREMENTAL_INC------------------------
  8493. // (Element drawn before incremental element)
  8494. // --------------------------------zlevel--------------------------------
  8495. if (el.incremental) {
  8496. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8497. layer.incremental = true;
  8498. incrementalLayerCount = 1;
  8499. } else {
  8500. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8501. }
  8502. if (!layer.__builtin__) {
  8503. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8504. }
  8505. if (layer !== prevLayer) {
  8506. layer.__used = true;
  8507. if (layer.__startIndex !== i) {
  8508. layer.__dirty = true;
  8509. }
  8510. layer.__startIndex = i;
  8511. if (!layer.incremental) {
  8512. layer.__drawIndex = i;
  8513. } else {
  8514. // Mark layer draw index needs to update.
  8515. layer.__drawIndex = -1;
  8516. }
  8517. updatePrevLayer(i);
  8518. prevLayer = layer;
  8519. }
  8520. if (el.__dirty) {
  8521. layer.__dirty = true;
  8522. if (layer.incremental && layer.__drawIndex < 0) {
  8523. // Start draw from the first dirty element.
  8524. layer.__drawIndex = i;
  8525. }
  8526. }
  8527. }
  8528. updatePrevLayer(i);
  8529. this.eachBuiltinLayer(function (layer, z) {
  8530. // Used in last frame but not in this frame. Needs clear
  8531. if (!layer.__used && layer.getElementCount() > 0) {
  8532. layer.__dirty = true;
  8533. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8534. } // For incremental layer. In case start index changed and no elements are dirty.
  8535. if (layer.__dirty && layer.__drawIndex < 0) {
  8536. layer.__drawIndex = layer.__startIndex;
  8537. }
  8538. });
  8539. },
  8540. /**
  8541. * 清除hover层外所有内容
  8542. */
  8543. clear: function () {
  8544. this.eachBuiltinLayer(this._clearLayer);
  8545. return this;
  8546. },
  8547. _clearLayer: function (layer) {
  8548. layer.clear();
  8549. },
  8550. setBackgroundColor: function (backgroundColor) {
  8551. this._backgroundColor = backgroundColor;
  8552. },
  8553. /**
  8554. * 修改指定zlevel的绘制参数
  8555. *
  8556. * @param {string} zlevel
  8557. * @param {Object} config 配置对象
  8558. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8559. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8560. * @param {number} [config.lastFrameAlpha=0.7]
  8561. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8562. */
  8563. configLayer: function (zlevel, config) {
  8564. if (config) {
  8565. var layerConfig = this._layerConfig;
  8566. if (!layerConfig[zlevel]) {
  8567. layerConfig[zlevel] = config;
  8568. } else {
  8569. merge(layerConfig[zlevel], config, true);
  8570. }
  8571. for (var i = 0; i < this._zlevelList.length; i++) {
  8572. var _zlevel = this._zlevelList[i]; // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8573. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8574. var layer = this._layers[_zlevel];
  8575. merge(layer, layerConfig[zlevel], true);
  8576. }
  8577. }
  8578. }
  8579. },
  8580. /**
  8581. * 删除指定层
  8582. * @param {number} zlevel 层所在的zlevel
  8583. */
  8584. delLayer: function (zlevel) {
  8585. var layers = this._layers;
  8586. var zlevelList = this._zlevelList;
  8587. var layer = layers[zlevel];
  8588. if (!layer) {
  8589. return;
  8590. }
  8591. layer.dom.parentNode.removeChild(layer.dom);
  8592. delete layers[zlevel];
  8593. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8594. },
  8595. /**
  8596. * 区域大小变化后重绘
  8597. */
  8598. resize: function (width, height) {
  8599. if (!this._domRoot.style) {
  8600. // Maybe in node or worker
  8601. if (width == null || height == null) {
  8602. return;
  8603. }
  8604. this._width = width;
  8605. this._height = height;
  8606. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8607. } else {
  8608. var domRoot = this._domRoot; // FIXME Why ?
  8609. domRoot.style.display = 'none'; // Save input w/h
  8610. var opts = this._opts;
  8611. width != null && (opts.width = width);
  8612. height != null && (opts.height = height);
  8613. width = this._getSize(0);
  8614. height = this._getSize(1);
  8615. domRoot.style.display = ''; // 优化没有实际改变的resize
  8616. if (this._width !== width || height !== this._height) {
  8617. domRoot.style.width = width + 'px';
  8618. domRoot.style.height = height + 'px';
  8619. for (var id in this._layers) {
  8620. if (this._layers.hasOwnProperty(id)) {
  8621. this._layers[id].resize(width, height);
  8622. }
  8623. }
  8624. each$1(this._progressiveLayers, function (layer) {
  8625. layer.resize(width, height);
  8626. });
  8627. this.refresh(true);
  8628. }
  8629. this._width = width;
  8630. this._height = height;
  8631. }
  8632. return this;
  8633. },
  8634. /**
  8635. * 清除单独的一个层
  8636. * @param {number} zlevel
  8637. */
  8638. clearLayer: function (zlevel) {
  8639. var layer = this._layers[zlevel];
  8640. if (layer) {
  8641. layer.clear();
  8642. }
  8643. },
  8644. /**
  8645. * 释放
  8646. */
  8647. dispose: function () {
  8648. this.root.innerHTML = '';
  8649. this.root = this.storage = this._domRoot = this._layers = null;
  8650. },
  8651. /**
  8652. * Get canvas which has all thing rendered
  8653. * @param {Object} opts
  8654. * @param {string} [opts.backgroundColor]
  8655. * @param {number} [opts.pixelRatio]
  8656. */
  8657. getRenderedCanvas: function (opts) {
  8658. opts = opts || {};
  8659. if (this._singleCanvas && !this._compositeManually) {
  8660. return this._layers[CANVAS_ZLEVEL].dom;
  8661. }
  8662. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8663. imageLayer.initContext();
  8664. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8665. if (opts.pixelRatio <= this.dpr) {
  8666. this.refresh();
  8667. var width = imageLayer.dom.width;
  8668. var height = imageLayer.dom.height;
  8669. var ctx = imageLayer.ctx;
  8670. this.eachLayer(function (layer) {
  8671. if (layer.__builtin__) {
  8672. ctx.drawImage(layer.dom, 0, 0, width, height);
  8673. } else if (layer.renderToCanvas) {
  8674. imageLayer.ctx.save();
  8675. layer.renderToCanvas(imageLayer.ctx);
  8676. imageLayer.ctx.restore();
  8677. }
  8678. });
  8679. } else {
  8680. // PENDING, echarts-gl and incremental rendering.
  8681. var scope = {};
  8682. var displayList = this.storage.getDisplayList(true);
  8683. for (var i = 0; i < displayList.length; i++) {
  8684. var el = displayList[i];
  8685. this._doPaintEl(el, imageLayer, true, scope);
  8686. }
  8687. }
  8688. return imageLayer.dom;
  8689. },
  8690. /**
  8691. * 获取绘图区域宽度
  8692. */
  8693. getWidth: function () {
  8694. return this._width;
  8695. },
  8696. /**
  8697. * 获取绘图区域高度
  8698. */
  8699. getHeight: function () {
  8700. return this._height;
  8701. },
  8702. _getSize: function (whIdx) {
  8703. var opts = this._opts;
  8704. var wh = ['width', 'height'][whIdx];
  8705. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8706. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8707. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8708. if (opts[wh] != null && opts[wh] !== 'auto') {
  8709. return parseFloat(opts[wh]);
  8710. }
  8711. var root = this.root; // IE8 does not support getComputedStyle, but it use VML.
  8712. var stl = document.defaultView.getComputedStyle(root);
  8713. return (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh])) - (parseInt10(stl[plt]) || 0) - (parseInt10(stl[prb]) || 0) | 0;
  8714. },
  8715. pathToImage: function (path, dpr) {
  8716. dpr = dpr || this.dpr;
  8717. var canvas = document.createElement('canvas');
  8718. var ctx = canvas.getContext('2d');
  8719. var rect = path.getBoundingRect();
  8720. var style = path.style;
  8721. var shadowBlurSize = style.shadowBlur * dpr;
  8722. var shadowOffsetX = style.shadowOffsetX * dpr;
  8723. var shadowOffsetY = style.shadowOffsetY * dpr;
  8724. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8725. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8726. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8727. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8728. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8729. var width = rect.width + leftMargin + rightMargin;
  8730. var height = rect.height + topMargin + bottomMargin;
  8731. canvas.width = width * dpr;
  8732. canvas.height = height * dpr;
  8733. ctx.scale(dpr, dpr);
  8734. ctx.clearRect(0, 0, width, height);
  8735. ctx.dpr = dpr;
  8736. var pathTransform = {
  8737. position: path.position,
  8738. rotation: path.rotation,
  8739. scale: path.scale
  8740. };
  8741. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8742. path.rotation = 0;
  8743. path.scale = [1, 1];
  8744. path.updateTransform();
  8745. if (path) {
  8746. path.brush(ctx);
  8747. }
  8748. var ImageShape = ZImage;
  8749. var imgShape = new ImageShape({
  8750. style: {
  8751. x: 0,
  8752. y: 0,
  8753. image: canvas
  8754. }
  8755. });
  8756. if (pathTransform.position != null) {
  8757. imgShape.position = path.position = pathTransform.position;
  8758. }
  8759. if (pathTransform.rotation != null) {
  8760. imgShape.rotation = path.rotation = pathTransform.rotation;
  8761. }
  8762. if (pathTransform.scale != null) {
  8763. imgShape.scale = path.scale = pathTransform.scale;
  8764. }
  8765. return imgShape;
  8766. }
  8767. };
  8768. /**
  8769. * Animation main class, dispatch and manage all animation controllers
  8770. *
  8771. * @module zrender/animation/Animation
  8772. * @author pissang(https://github.com/pissang)
  8773. */
  8774. // TODO Additive animation
  8775. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8776. // https://developer.apple.com/videos/wwdc2014/#236
  8777. /**
  8778. * @typedef {Object} IZRenderStage
  8779. * @property {Function} update
  8780. */
  8781. /**
  8782. * @alias module:zrender/animation/Animation
  8783. * @constructor
  8784. * @param {Object} [options]
  8785. * @param {Function} [options.onframe]
  8786. * @param {IZRenderStage} [options.stage]
  8787. * @example
  8788. * var animation = new Animation();
  8789. * var obj = {
  8790. * x: 100,
  8791. * y: 100
  8792. * };
  8793. * animation.animate(node.position)
  8794. * .when(1000, {
  8795. * x: 500,
  8796. * y: 500
  8797. * })
  8798. * .when(2000, {
  8799. * x: 100,
  8800. * y: 100
  8801. * })
  8802. * .start('spline');
  8803. */
  8804. var Animation = function (options) {
  8805. options = options || {};
  8806. this.stage = options.stage || {};
  8807. this.onframe = options.onframe || function () {}; // private properties
  8808. this._clips = [];
  8809. this._running = false;
  8810. this._time;
  8811. this._pausedTime;
  8812. this._pauseStart;
  8813. this._paused = false;
  8814. Eventful.call(this);
  8815. };
  8816. Animation.prototype = {
  8817. constructor: Animation,
  8818. /**
  8819. * Add clip
  8820. * @param {module:zrender/animation/Clip} clip
  8821. */
  8822. addClip: function (clip) {
  8823. this._clips.push(clip);
  8824. },
  8825. /**
  8826. * Add animator
  8827. * @param {module:zrender/animation/Animator} animator
  8828. */
  8829. addAnimator: function (animator) {
  8830. animator.animation = this;
  8831. var clips = animator.getClips();
  8832. for (var i = 0; i < clips.length; i++) {
  8833. this.addClip(clips[i]);
  8834. }
  8835. },
  8836. /**
  8837. * Delete animation clip
  8838. * @param {module:zrender/animation/Clip} clip
  8839. */
  8840. removeClip: function (clip) {
  8841. var idx = indexOf(this._clips, clip);
  8842. if (idx >= 0) {
  8843. this._clips.splice(idx, 1);
  8844. }
  8845. },
  8846. /**
  8847. * Delete animation clip
  8848. * @param {module:zrender/animation/Animator} animator
  8849. */
  8850. removeAnimator: function (animator) {
  8851. var clips = animator.getClips();
  8852. for (var i = 0; i < clips.length; i++) {
  8853. this.removeClip(clips[i]);
  8854. }
  8855. animator.animation = null;
  8856. },
  8857. _update: function () {
  8858. var time = new Date().getTime() - this._pausedTime;
  8859. var delta = time - this._time;
  8860. var clips = this._clips;
  8861. var len = clips.length;
  8862. var deferredEvents = [];
  8863. var deferredClips = [];
  8864. for (var i = 0; i < len; i++) {
  8865. var clip = clips[i];
  8866. var e = clip.step(time, delta); // Throw out the events need to be called after
  8867. // stage.update, like destroy
  8868. if (e) {
  8869. deferredEvents.push(e);
  8870. deferredClips.push(clip);
  8871. }
  8872. } // Remove the finished clip
  8873. for (var i = 0; i < len;) {
  8874. if (clips[i]._needsRemove) {
  8875. clips[i] = clips[len - 1];
  8876. clips.pop();
  8877. len--;
  8878. } else {
  8879. i++;
  8880. }
  8881. }
  8882. len = deferredEvents.length;
  8883. for (var i = 0; i < len; i++) {
  8884. deferredClips[i].fire(deferredEvents[i]);
  8885. }
  8886. this._time = time;
  8887. this.onframe(delta); // 'frame' should be triggered before stage, because upper application
  8888. // depends on the sequence (e.g., echarts-stream and finish
  8889. // event judge)
  8890. this.trigger('frame', delta);
  8891. if (this.stage.update) {
  8892. this.stage.update();
  8893. }
  8894. },
  8895. _startLoop: function () {
  8896. var self = this;
  8897. this._running = true;
  8898. function step() {
  8899. if (self._running) {
  8900. requestAnimationFrame(step);
  8901. !self._paused && self._update();
  8902. }
  8903. }
  8904. requestAnimationFrame(step);
  8905. },
  8906. /**
  8907. * Start animation.
  8908. */
  8909. start: function () {
  8910. this._time = new Date().getTime();
  8911. this._pausedTime = 0;
  8912. this._startLoop();
  8913. },
  8914. /**
  8915. * Stop animation.
  8916. */
  8917. stop: function () {
  8918. this._running = false;
  8919. },
  8920. /**
  8921. * Pause animation.
  8922. */
  8923. pause: function () {
  8924. if (!this._paused) {
  8925. this._pauseStart = new Date().getTime();
  8926. this._paused = true;
  8927. }
  8928. },
  8929. /**
  8930. * Resume animation.
  8931. */
  8932. resume: function () {
  8933. if (this._paused) {
  8934. this._pausedTime += new Date().getTime() - this._pauseStart;
  8935. this._paused = false;
  8936. }
  8937. },
  8938. /**
  8939. * Clear animation.
  8940. */
  8941. clear: function () {
  8942. this._clips = [];
  8943. },
  8944. /**
  8945. * Whether animation finished.
  8946. */
  8947. isFinished: function () {
  8948. return !this._clips.length;
  8949. },
  8950. /**
  8951. * Creat animator for a target, whose props can be animated.
  8952. *
  8953. * @param {Object} target
  8954. * @param {Object} options
  8955. * @param {boolean} [options.loop=false] Whether loop animation.
  8956. * @param {Function} [options.getter=null] Get value from target.
  8957. * @param {Function} [options.setter=null] Set value to target.
  8958. * @return {module:zrender/animation/Animation~Animator}
  8959. */
  8960. // TODO Gap
  8961. animate: function (target, options) {
  8962. options = options || {};
  8963. var animator = new Animator(target, options.loop, options.getter, options.setter);
  8964. this.addAnimator(animator);
  8965. return animator;
  8966. }
  8967. };
  8968. mixin(Animation, Eventful);
  8969. /* global document */
  8970. var TOUCH_CLICK_DELAY = 300;
  8971. var globalEventSupported = env$1.domSupported;
  8972. var localNativeListenerNames = function () {
  8973. var mouseHandlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  8974. var touchHandlerNames = ['touchstart', 'touchend', 'touchmove'];
  8975. var pointerEventNameMap = {
  8976. pointerdown: 1,
  8977. pointerup: 1,
  8978. pointermove: 1,
  8979. pointerout: 1
  8980. };
  8981. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8982. var nm = name.replace('mouse', 'pointer');
  8983. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  8984. });
  8985. return {
  8986. mouse: mouseHandlerNames,
  8987. touch: touchHandlerNames,
  8988. pointer: pointerHandlerNames
  8989. };
  8990. }();
  8991. var globalNativeListenerNames = {
  8992. mouse: ['mousemove', 'mouseup'],
  8993. pointer: ['pointermove', 'pointerup']
  8994. };
  8995. function eventNameFix(name) {
  8996. return name === 'mousewheel' && env$1.browser.firefox ? 'DOMMouseScroll' : name;
  8997. }
  8998. function isPointerFromTouch(event) {
  8999. var pointerType = event.pointerType;
  9000. return pointerType === 'pen' || pointerType === 'touch';
  9001. } // function useMSGuesture(handlerProxy, event) {
  9002. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9003. // }
  9004. // function onMSGestureChange(proxy, event) {
  9005. // if (event.translationX || event.translationY) {
  9006. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9007. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9008. // }
  9009. // if (event.scale !== 1) {
  9010. // event.pinchX = event.offsetX;
  9011. // event.pinchY = event.offsetY;
  9012. // event.pinchScale = event.scale;
  9013. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9014. // }
  9015. // }
  9016. /**
  9017. * Prevent mouse event from being dispatched after Touch Events action
  9018. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9019. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9020. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9021. * Result: Blocking Mouse Events for 700ms.
  9022. *
  9023. * @param {DOMHandlerScope} scope
  9024. */
  9025. function setTouchTimer(scope) {
  9026. scope.touching = true;
  9027. if (scope.touchTimer != null) {
  9028. clearTimeout(scope.touchTimer);
  9029. scope.touchTimer = null;
  9030. }
  9031. scope.touchTimer = setTimeout(function () {
  9032. scope.touching = false;
  9033. scope.touchTimer = null;
  9034. }, 700);
  9035. } // Mark touch, which is useful in distinguish touch and
  9036. // mouse event in upper applicatoin.
  9037. function markTouch(event) {
  9038. event && (event.zrByTouch = true);
  9039. } // function markTriggeredFromLocal(event) {
  9040. // event && (event.__zrIsFromLocal = true);
  9041. // }
  9042. // function isTriggeredFromLocal(instance, event) {
  9043. // return !!(event && event.__zrIsFromLocal);
  9044. // }
  9045. function normalizeGlobalEvent(instance, event) {
  9046. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9047. // handlers of the upper applications. Set `true` to force calculate them.
  9048. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9049. }
  9050. /**
  9051. * Detect whether the given el is in `painterRoot`.
  9052. */
  9053. function isLocalEl(instance, el) {
  9054. var elTmp = el;
  9055. var isLocal = false;
  9056. while (elTmp && elTmp.nodeType !== 9 && !(isLocal = elTmp.domBelongToZr || elTmp !== el && elTmp === instance.painterRoot)) {
  9057. elTmp = elTmp.parentNode;
  9058. }
  9059. return isLocal;
  9060. }
  9061. /**
  9062. * Make a fake event but not change the original event,
  9063. * becuase the global event probably be used by other
  9064. * listeners not belonging to zrender.
  9065. * @class
  9066. */
  9067. function FakeGlobalEvent(instance, event) {
  9068. this.type = event.type;
  9069. this.target = this.currentTarget = instance.dom;
  9070. this.pointerType = event.pointerType; // Necessray for the force calculation of zrX, zrY
  9071. this.clientX = event.clientX;
  9072. this.clientY = event.clientY; // Because we do not mount global listeners to touch events,
  9073. // we do not copy `targetTouches` and `changedTouches` here.
  9074. }
  9075. var fakeGlobalEventProto = FakeGlobalEvent.prototype; // we make the default methods on the event do nothing,
  9076. // otherwise it is dangerous. See more details in
  9077. // [Drag outside] in `Handler.js`.
  9078. fakeGlobalEventProto.stopPropagation = fakeGlobalEventProto.stopImmediatePropagation = fakeGlobalEventProto.preventDefault = noop;
  9079. /**
  9080. * Local DOM Handlers
  9081. * @this {HandlerProxy}
  9082. */
  9083. var localDOMHandlers = {
  9084. mousedown: function (event) {
  9085. event = normalizeEvent(this.dom, event);
  9086. this._mayPointerCapture = [event.zrX, event.zrY];
  9087. this.trigger('mousedown', event);
  9088. },
  9089. mousemove: function (event) {
  9090. event = normalizeEvent(this.dom, event);
  9091. var downPoint = this._mayPointerCapture;
  9092. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9093. togglePointerCapture(this, true);
  9094. }
  9095. this.trigger('mousemove', event);
  9096. },
  9097. mouseup: function (event) {
  9098. event = normalizeEvent(this.dom, event);
  9099. togglePointerCapture(this, false);
  9100. this.trigger('mouseup', event);
  9101. },
  9102. mouseout: function (event) {
  9103. event = normalizeEvent(this.dom, event); // Similarly to the browser did on `document` and touch event,
  9104. // `globalout` will be delayed to final pointer cature release.
  9105. if (this._pointerCapturing) {
  9106. event.zrEventControl = 'no_globalout';
  9107. } // There might be some doms created by upper layer application
  9108. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9109. // dom created by echarts), where 'globalout' event should not
  9110. // be triggered when mouse enters these doms. (But 'mouseout'
  9111. // should be triggered at the original hovered element as usual).
  9112. var element = event.toElement || event.relatedTarget;
  9113. event.zrIsToLocalDOM = isLocalEl(this, element);
  9114. this.trigger('mouseout', event);
  9115. },
  9116. touchstart: function (event) {
  9117. // Default mouse behaviour should not be disabled here.
  9118. // For example, page may needs to be slided.
  9119. event = normalizeEvent(this.dom, event);
  9120. markTouch(event);
  9121. this._lastTouchMoment = new Date();
  9122. this.handler.processGesture(event, 'start'); // For consistent event listener for both touch device and mouse device,
  9123. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9124. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9125. // `mousedown`.
  9126. localDOMHandlers.mousemove.call(this, event);
  9127. localDOMHandlers.mousedown.call(this, event);
  9128. },
  9129. touchmove: function (event) {
  9130. event = normalizeEvent(this.dom, event);
  9131. markTouch(event);
  9132. this.handler.processGesture(event, 'change'); // Mouse move should always be triggered no matter whether
  9133. // there is gestrue event, because mouse move and pinch may
  9134. // be used at the same time.
  9135. localDOMHandlers.mousemove.call(this, event);
  9136. },
  9137. touchend: function (event) {
  9138. event = normalizeEvent(this.dom, event);
  9139. markTouch(event);
  9140. this.handler.processGesture(event, 'end');
  9141. localDOMHandlers.mouseup.call(this, event); // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9142. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9143. // we can conveniently implement "hover style" in both PC and touch device just
  9144. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9145. // to remove "hover style" on an element, without any additional code for
  9146. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9147. // style" will remain for user view)
  9148. // click event should always be triggered no matter whether
  9149. // there is gestrue event. System click can not be prevented.
  9150. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9151. localDOMHandlers.click.call(this, event);
  9152. }
  9153. },
  9154. pointerdown: function (event) {
  9155. localDOMHandlers.mousedown.call(this, event); // if (useMSGuesture(this, event)) {
  9156. // this._msGesture.addPointer(event.pointerId);
  9157. // }
  9158. },
  9159. pointermove: function (event) {
  9160. // FIXME
  9161. // pointermove is so sensitive that it always triggered when
  9162. // tap(click) on touch screen, which affect some judgement in
  9163. // upper application. So, we dont support mousemove on MS touch
  9164. // device yet.
  9165. if (!isPointerFromTouch(event)) {
  9166. localDOMHandlers.mousemove.call(this, event);
  9167. }
  9168. },
  9169. pointerup: function (event) {
  9170. localDOMHandlers.mouseup.call(this, event);
  9171. },
  9172. pointerout: function (event) {
  9173. // pointerout will be triggered when tap on touch screen
  9174. // (IE11+/Edge on MS Surface) after click event triggered,
  9175. // which is inconsistent with the mousout behavior we defined
  9176. // in touchend. So we unify them.
  9177. // (check localDOMHandlers.touchend for detailed explanation)
  9178. if (!isPointerFromTouch(event)) {
  9179. localDOMHandlers.mouseout.call(this, event);
  9180. }
  9181. }
  9182. };
  9183. /**
  9184. * Othere DOM UI Event handlers for zr dom.
  9185. * @this {HandlerProxy}
  9186. */
  9187. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9188. localDOMHandlers[name] = function (event) {
  9189. event = normalizeEvent(this.dom, event);
  9190. this.trigger(name, event);
  9191. };
  9192. });
  9193. /**
  9194. * DOM UI Event handlers for global page.
  9195. *
  9196. * [Caution]:
  9197. * those handlers should both support in capture phase and bubble phase!
  9198. *
  9199. * @this {HandlerProxy}
  9200. */
  9201. var globalDOMHandlers = {
  9202. pointermove: function (event) {
  9203. // FIXME
  9204. // pointermove is so sensitive that it always triggered when
  9205. // tap(click) on touch screen, which affect some judgement in
  9206. // upper application. So, we dont support mousemove on MS touch
  9207. // device yet.
  9208. if (!isPointerFromTouch(event)) {
  9209. globalDOMHandlers.mousemove.call(this, event);
  9210. }
  9211. },
  9212. pointerup: function (event) {
  9213. globalDOMHandlers.mouseup.call(this, event);
  9214. },
  9215. mousemove: function (event) {
  9216. this.trigger('mousemove', event);
  9217. },
  9218. mouseup: function (event) {
  9219. var pointerCaptureReleasing = this._pointerCapturing;
  9220. togglePointerCapture(this, false);
  9221. this.trigger('mouseup', event);
  9222. if (pointerCaptureReleasing) {
  9223. event.zrEventControl = 'only_globalout';
  9224. this.trigger('mouseout', event);
  9225. }
  9226. }
  9227. };
  9228. /**
  9229. * @param {HandlerProxy} instance
  9230. * @param {DOMHandlerScope} scope
  9231. */
  9232. function mountLocalDOMEventListeners(instance, scope) {
  9233. var domHandlers = scope.domHandlers;
  9234. if (env$1.pointerEventsSupported) {
  9235. // Only IE11+/Edge
  9236. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9237. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9238. // at the same time.
  9239. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9240. // screen, which do not occurs in pointer event.
  9241. // So we use pointer event to both detect touch gesture and mouse behavior.
  9242. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9243. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9244. // markTriggeredFromLocal(event);
  9245. domHandlers[nativeEventName].call(instance, event);
  9246. });
  9247. }); // FIXME
  9248. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9249. // which does not prevent defuault behavior occasionally (which may cause view port
  9250. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9251. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9252. // touch screen. And we only support click behavior on MS touch screen now.
  9253. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9254. // We dont support touch on IE on win7.
  9255. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9256. // if (typeof MSGesture === 'function') {
  9257. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9258. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9259. // }
  9260. } else {
  9261. if (env$1.touchEventsSupported) {
  9262. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9263. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9264. // markTriggeredFromLocal(event);
  9265. domHandlers[nativeEventName].call(instance, event);
  9266. setTouchTimer(scope);
  9267. });
  9268. }); // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9269. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9270. } // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9271. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9272. // mouse event can not be handle in those devices.
  9273. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9274. // mouseevent after touch event triggered, see `setTouchTimer`.
  9275. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9276. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9277. event = getNativeEvent(event);
  9278. if (!scope.touching) {
  9279. // markTriggeredFromLocal(event);
  9280. domHandlers[nativeEventName].call(instance, event);
  9281. }
  9282. });
  9283. });
  9284. }
  9285. }
  9286. /**
  9287. * @param {HandlerProxy} instance
  9288. * @param {DOMHandlerScope} scope
  9289. */
  9290. function mountGlobalDOMEventListeners(instance, scope) {
  9291. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9292. if (env$1.pointerEventsSupported) {
  9293. each$1(globalNativeListenerNames.pointer, mount);
  9294. } // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9295. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9296. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9297. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9298. else if (!env$1.touchEventsSupported) {
  9299. each$1(globalNativeListenerNames.mouse, mount);
  9300. }
  9301. function mount(nativeEventName) {
  9302. function nativeEventListener(event) {
  9303. event = getNativeEvent(event); // See the reason in [Drag outside] in `Handler.js`
  9304. // This checking supports both `useCapture` or not.
  9305. // PENDING: if there is performance issue in some devices,
  9306. // we probably can not use `useCapture` and change a easier
  9307. // to judes whether local (mark).
  9308. if (!isLocalEl(instance, event.target)) {
  9309. event = normalizeGlobalEvent(instance, event);
  9310. scope.domHandlers[nativeEventName].call(instance, event);
  9311. }
  9312. }
  9313. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, {
  9314. capture: true // See [Drag Outside] in `Handler.js`
  9315. });
  9316. }
  9317. }
  9318. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9319. scope.mounted[nativeEventName] = listener;
  9320. scope.listenerOpts[nativeEventName] = opt;
  9321. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9322. }
  9323. function unmountDOMEventListeners(scope) {
  9324. var mounted = scope.mounted;
  9325. for (var nativeEventName in mounted) {
  9326. if (mounted.hasOwnProperty(nativeEventName)) {
  9327. removeEventListener(scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  9328. }
  9329. }
  9330. scope.mounted = {};
  9331. }
  9332. /**
  9333. * See [Drag Outside] in `Handler.js`.
  9334. * @implement
  9335. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9336. * `true`: start to capture pointer if it is not capturing.
  9337. * `false`: end the capture if it is capturing.
  9338. */
  9339. function togglePointerCapture(instance, isPointerCapturing) {
  9340. instance._mayPointerCapture = null;
  9341. if (globalEventSupported && instance._pointerCapturing ^ isPointerCapturing) {
  9342. instance._pointerCapturing = isPointerCapturing;
  9343. var globalHandlerScope = instance._globalHandlerScope;
  9344. isPointerCapturing ? mountGlobalDOMEventListeners(instance, globalHandlerScope) : unmountDOMEventListeners(globalHandlerScope);
  9345. }
  9346. }
  9347. /**
  9348. * @inner
  9349. * @class
  9350. */
  9351. function DOMHandlerScope(domTarget, domHandlers) {
  9352. this.domTarget = domTarget;
  9353. this.domHandlers = domHandlers; // Key: eventName, value: mounted handler funcitons.
  9354. // Used for unmount.
  9355. this.mounted = {};
  9356. this.listenerOpts = {};
  9357. this.touchTimer = null;
  9358. this.touching = false;
  9359. }
  9360. /**
  9361. * @public
  9362. * @class
  9363. */
  9364. function HandlerDomProxy(dom, painterRoot) {
  9365. Eventful.call(this);
  9366. this.dom = dom;
  9367. this.painterRoot = painterRoot;
  9368. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9369. if (globalEventSupported) {
  9370. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9371. }
  9372. /**
  9373. * @type {boolean}
  9374. */
  9375. this._pointerCapturing = false;
  9376. /**
  9377. * @type {Array.<number>} [x, y] or null.
  9378. */
  9379. this._mayPointerCapture = null;
  9380. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9381. }
  9382. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9383. handlerDomProxyProto.dispose = function () {
  9384. unmountDOMEventListeners(this._localHandlerScope);
  9385. if (globalEventSupported) {
  9386. unmountDOMEventListeners(this._globalHandlerScope);
  9387. }
  9388. };
  9389. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9390. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9391. };
  9392. mixin(HandlerDomProxy, Eventful);
  9393. /*!
  9394. * ZRender, a high performance 2d drawing library.
  9395. *
  9396. * Copyright (c) 2013, Baidu Inc.
  9397. * All rights reserved.
  9398. *
  9399. * LICENSE
  9400. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9401. */
  9402. var useVML = !env$1.canvasSupported;
  9403. var painterCtors = {
  9404. canvas: Painter
  9405. };
  9406. var instances$1 = {}; // ZRender实例map索引
  9407. /**
  9408. * @type {string}
  9409. */
  9410. var version$1 = '4.3.1';
  9411. /**
  9412. * Initializing a zrender instance
  9413. * @param {HTMLElement} dom
  9414. * @param {Object} [opts]
  9415. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9416. * @param {number} [opts.devicePixelRatio]
  9417. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9418. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9419. * @return {module:zrender/ZRender}
  9420. */
  9421. function init$1(dom, opts) {
  9422. var zr = new ZRender(guid(), dom, opts);
  9423. instances$1[zr.id] = zr;
  9424. return zr;
  9425. }
  9426. /**
  9427. * Dispose zrender instance
  9428. * @param {module:zrender/ZRender} zr
  9429. */
  9430. function dispose$1(zr) {
  9431. if (zr) {
  9432. zr.dispose();
  9433. } else {
  9434. for (var key in instances$1) {
  9435. if (instances$1.hasOwnProperty(key)) {
  9436. instances$1[key].dispose();
  9437. }
  9438. }
  9439. instances$1 = {};
  9440. }
  9441. return this;
  9442. }
  9443. /**
  9444. * Get zrender instance by id
  9445. * @param {string} id zrender instance id
  9446. * @return {module:zrender/ZRender}
  9447. */
  9448. function getInstance(id) {
  9449. return instances$1[id];
  9450. }
  9451. function registerPainter(name, Ctor) {
  9452. painterCtors[name] = Ctor;
  9453. }
  9454. function delInstance(id) {
  9455. delete instances$1[id];
  9456. }
  9457. /**
  9458. * @module zrender/ZRender
  9459. */
  9460. /**
  9461. * @constructor
  9462. * @alias module:zrender/ZRender
  9463. * @param {string} id
  9464. * @param {HTMLElement} dom
  9465. * @param {Object} opts
  9466. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9467. * @param {number} [opts.devicePixelRatio]
  9468. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9469. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9470. */
  9471. var ZRender = function (id, dom, opts) {
  9472. opts = opts || {};
  9473. /**
  9474. * @type {HTMLDomElement}
  9475. */
  9476. this.dom = dom;
  9477. /**
  9478. * @type {string}
  9479. */
  9480. this.id = id;
  9481. var self = this;
  9482. var storage = new Storage();
  9483. var rendererType = opts.renderer; // TODO WebGL
  9484. if (useVML) {
  9485. if (!painterCtors.vml) {
  9486. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9487. }
  9488. rendererType = 'vml';
  9489. } else if (!rendererType || !painterCtors[rendererType]) {
  9490. rendererType = 'canvas';
  9491. }
  9492. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9493. this.storage = storage;
  9494. this.painter = painter;
  9495. var handerProxy = !env$1.node && !env$1.worker ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  9496. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9497. /**
  9498. * @type {module:zrender/animation/Animation}
  9499. */
  9500. this.animation = new Animation({
  9501. stage: {
  9502. update: bind(this.flush, this)
  9503. }
  9504. });
  9505. this.animation.start();
  9506. /**
  9507. * @type {boolean}
  9508. * @private
  9509. */
  9510. this._needsRefresh; // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9511. // FIXME 有点ugly
  9512. var oldDelFromStorage = storage.delFromStorage;
  9513. var oldAddToStorage = storage.addToStorage;
  9514. storage.delFromStorage = function (el) {
  9515. oldDelFromStorage.call(storage, el);
  9516. el && el.removeSelfFromZr(self);
  9517. };
  9518. storage.addToStorage = function (el) {
  9519. oldAddToStorage.call(storage, el);
  9520. el.addSelfToZr(self);
  9521. };
  9522. };
  9523. ZRender.prototype = {
  9524. constructor: ZRender,
  9525. /**
  9526. * 获取实例唯一标识
  9527. * @return {string}
  9528. */
  9529. getId: function () {
  9530. return this.id;
  9531. },
  9532. /**
  9533. * 添加元素
  9534. * @param {module:zrender/Element} el
  9535. */
  9536. add: function (el) {
  9537. this.storage.addRoot(el);
  9538. this._needsRefresh = true;
  9539. },
  9540. /**
  9541. * 删除元素
  9542. * @param {module:zrender/Element} el
  9543. */
  9544. remove: function (el) {
  9545. this.storage.delRoot(el);
  9546. this._needsRefresh = true;
  9547. },
  9548. /**
  9549. * Change configuration of layer
  9550. * @param {string} zLevel
  9551. * @param {Object} config
  9552. * @param {string} [config.clearColor=0] Clear color
  9553. * @param {string} [config.motionBlur=false] If enable motion blur
  9554. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9555. */
  9556. configLayer: function (zLevel, config) {
  9557. if (this.painter.configLayer) {
  9558. this.painter.configLayer(zLevel, config);
  9559. }
  9560. this._needsRefresh = true;
  9561. },
  9562. /**
  9563. * Set background color
  9564. * @param {string} backgroundColor
  9565. */
  9566. setBackgroundColor: function (backgroundColor) {
  9567. if (this.painter.setBackgroundColor) {
  9568. this.painter.setBackgroundColor(backgroundColor);
  9569. }
  9570. this._needsRefresh = true;
  9571. },
  9572. /**
  9573. * Repaint the canvas immediately
  9574. */
  9575. refreshImmediately: function () {
  9576. // var start = new Date();
  9577. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9578. // Or it will cause zrender refreshes again and again.
  9579. this._needsRefresh = this._needsRefreshHover = false;
  9580. this.painter.refresh(); // Avoid trigger zr.refresh in Element#beforeUpdate hook
  9581. this._needsRefresh = this._needsRefreshHover = false; // var end = new Date();
  9582. // var log = document.getElementById('log');
  9583. // if (log) {
  9584. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9585. // }
  9586. },
  9587. /**
  9588. * Mark and repaint the canvas in the next frame of browser
  9589. */
  9590. refresh: function () {
  9591. this._needsRefresh = true;
  9592. },
  9593. /**
  9594. * Perform all refresh
  9595. */
  9596. flush: function () {
  9597. var triggerRendered;
  9598. if (this._needsRefresh) {
  9599. triggerRendered = true;
  9600. this.refreshImmediately();
  9601. }
  9602. if (this._needsRefreshHover) {
  9603. triggerRendered = true;
  9604. this.refreshHoverImmediately();
  9605. }
  9606. triggerRendered && this.trigger('rendered');
  9607. },
  9608. /**
  9609. * Add element to hover layer
  9610. * @param {module:zrender/Element} el
  9611. * @param {Object} style
  9612. */
  9613. addHover: function (el, style) {
  9614. if (this.painter.addHover) {
  9615. var elMirror = this.painter.addHover(el, style);
  9616. this.refreshHover();
  9617. return elMirror;
  9618. }
  9619. },
  9620. /**
  9621. * Add element from hover layer
  9622. * @param {module:zrender/Element} el
  9623. */
  9624. removeHover: function (el) {
  9625. if (this.painter.removeHover) {
  9626. this.painter.removeHover(el);
  9627. this.refreshHover();
  9628. }
  9629. },
  9630. /**
  9631. * Clear all hover elements in hover layer
  9632. * @param {module:zrender/Element} el
  9633. */
  9634. clearHover: function () {
  9635. if (this.painter.clearHover) {
  9636. this.painter.clearHover();
  9637. this.refreshHover();
  9638. }
  9639. },
  9640. /**
  9641. * Refresh hover in next frame
  9642. */
  9643. refreshHover: function () {
  9644. this._needsRefreshHover = true;
  9645. },
  9646. /**
  9647. * Refresh hover immediately
  9648. */
  9649. refreshHoverImmediately: function () {
  9650. this._needsRefreshHover = false;
  9651. this.painter.refreshHover && this.painter.refreshHover();
  9652. },
  9653. /**
  9654. * Resize the canvas.
  9655. * Should be invoked when container size is changed
  9656. * @param {Object} [opts]
  9657. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9658. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9659. */
  9660. resize: function (opts) {
  9661. opts = opts || {};
  9662. this.painter.resize(opts.width, opts.height);
  9663. this.handler.resize();
  9664. },
  9665. /**
  9666. * Stop and clear all animation immediately
  9667. */
  9668. clearAnimation: function () {
  9669. this.animation.clear();
  9670. },
  9671. /**
  9672. * Get container width
  9673. */
  9674. getWidth: function () {
  9675. return this.painter.getWidth();
  9676. },
  9677. /**
  9678. * Get container height
  9679. */
  9680. getHeight: function () {
  9681. return this.painter.getHeight();
  9682. },
  9683. /**
  9684. * Export the canvas as Base64 URL
  9685. * @param {string} type
  9686. * @param {string} [backgroundColor='#fff']
  9687. * @return {string} Base64 URL
  9688. */
  9689. // toDataURL: function(type, backgroundColor) {
  9690. // return this.painter.getRenderedCanvas({
  9691. // backgroundColor: backgroundColor
  9692. // }).toDataURL(type);
  9693. // },
  9694. /**
  9695. * Converting a path to image.
  9696. * It has much better performance of drawing image rather than drawing a vector path.
  9697. * @param {module:zrender/graphic/Path} e
  9698. * @param {number} width
  9699. * @param {number} height
  9700. */
  9701. pathToImage: function (e, dpr) {
  9702. return this.painter.pathToImage(e, dpr);
  9703. },
  9704. /**
  9705. * Set default cursor
  9706. * @param {string} [cursorStyle='default'] 例如 crosshair
  9707. */
  9708. setCursorStyle: function (cursorStyle) {
  9709. this.handler.setCursorStyle(cursorStyle);
  9710. },
  9711. /**
  9712. * Find hovered element
  9713. * @param {number} x
  9714. * @param {number} y
  9715. * @return {Object} {target, topTarget}
  9716. */
  9717. findHover: function (x, y) {
  9718. return this.handler.findHover(x, y);
  9719. },
  9720. /**
  9721. * Bind event
  9722. *
  9723. * @param {string} eventName Event name
  9724. * @param {Function} eventHandler Handler function
  9725. * @param {Object} [context] Context object
  9726. */
  9727. on: function (eventName, eventHandler, context) {
  9728. this.handler.on(eventName, eventHandler, context);
  9729. },
  9730. /**
  9731. * Unbind event
  9732. * @param {string} eventName Event name
  9733. * @param {Function} [eventHandler] Handler function
  9734. */
  9735. off: function (eventName, eventHandler) {
  9736. this.handler.off(eventName, eventHandler);
  9737. },
  9738. /**
  9739. * Trigger event manually
  9740. *
  9741. * @param {string} eventName Event name
  9742. * @param {event=} event Event object
  9743. */
  9744. trigger: function (eventName, event) {
  9745. this.handler.trigger(eventName, event);
  9746. },
  9747. /**
  9748. * Clear all objects and the canvas.
  9749. */
  9750. clear: function () {
  9751. this.storage.delRoot();
  9752. this.painter.clear();
  9753. },
  9754. /**
  9755. * Dispose self.
  9756. */
  9757. dispose: function () {
  9758. this.animation.stop();
  9759. this.clear();
  9760. this.storage.dispose();
  9761. this.painter.dispose();
  9762. this.handler.dispose();
  9763. this.animation = this.storage = this.painter = this.handler = null;
  9764. delInstance(this.id);
  9765. }
  9766. };
  9767. var zrender = (Object.freeze || Object)({
  9768. version: version$1,
  9769. init: init$1,
  9770. dispose: dispose$1,
  9771. getInstance: getInstance,
  9772. registerPainter: registerPainter
  9773. });
  9774. /*
  9775. * Licensed to the Apache Software Foundation (ASF) under one
  9776. * or more contributor license agreements. See the NOTICE file
  9777. * distributed with this work for additional information
  9778. * regarding copyright ownership. The ASF licenses this file
  9779. * to you under the Apache License, Version 2.0 (the
  9780. * "License"); you may not use this file except in compliance
  9781. * with the License. You may obtain a copy of the License at
  9782. *
  9783. * http://www.apache.org/licenses/LICENSE-2.0
  9784. *
  9785. * Unless required by applicable law or agreed to in writing,
  9786. * software distributed under the License is distributed on an
  9787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9788. * KIND, either express or implied. See the License for the
  9789. * specific language governing permissions and limitations
  9790. * under the License.
  9791. */
  9792. var each$2 = each$1;
  9793. var isObject$2 = isObject$1;
  9794. var isArray$1 = isArray;
  9795. /**
  9796. * Make the name displayable. But we should
  9797. * make sure it is not duplicated with user
  9798. * specified name, so use '\0';
  9799. */
  9800. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9801. /**
  9802. * If value is not array, then translate it to array.
  9803. * @param {*} value
  9804. * @return {Array} [value] or value
  9805. */
  9806. function normalizeToArray(value) {
  9807. return value instanceof Array ? value : value == null ? [] : [value];
  9808. }
  9809. /**
  9810. * Sync default option between normal and emphasis like `position` and `show`
  9811. * In case some one will write code like
  9812. * label: {
  9813. * show: false,
  9814. * position: 'outside',
  9815. * fontSize: 18
  9816. * },
  9817. * emphasis: {
  9818. * label: { show: true }
  9819. * }
  9820. * @param {Object} opt
  9821. * @param {string} key
  9822. * @param {Array.<string>} subOpts
  9823. */
  9824. function defaultEmphasis(opt, key, subOpts) {
  9825. // Caution: performance sensitive.
  9826. if (opt) {
  9827. opt[key] = opt[key] || {};
  9828. opt.emphasis = opt.emphasis || {};
  9829. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  9830. for (var i = 0, len = subOpts.length; i < len; i++) {
  9831. var subOptName = subOpts[i];
  9832. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  9833. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9834. }
  9835. }
  9836. }
  9837. }
  9838. 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([
  9839. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9840. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9841. // // FIXME: deprecated, check and remove it.
  9842. // 'textStyle'
  9843. // ]);
  9844. /**
  9845. * The method do not ensure performance.
  9846. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9847. * This helper method retieves value from data.
  9848. * @param {string|number|Date|Array|Object} dataItem
  9849. * @return {number|string|Date|Array.<number|string|Date>}
  9850. */
  9851. function getDataItemValue(dataItem) {
  9852. return isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  9853. }
  9854. /**
  9855. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9856. * This helper method determine if dataItem has extra option besides value
  9857. * @param {string|number|Date|Array|Object} dataItem
  9858. */
  9859. function isDataItemOption(dataItem) {
  9860. return isObject$2(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  9861. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9862. }
  9863. /**
  9864. * Mapping to exists for merge.
  9865. *
  9866. * @public
  9867. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9868. * @param {Object|Array.<Object>} newCptOptions
  9869. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9870. * index of which is the same as exists.
  9871. */
  9872. function mappingToExists(exists, newCptOptions) {
  9873. // Mapping by the order by original option (but not order of
  9874. // new option) in merge mode. Because we should ensure
  9875. // some specified index (like xAxisIndex) is consistent with
  9876. // original option, which is easy to understand, espatially in
  9877. // media query. And in most case, merge option is used to
  9878. // update partial option but not be expected to change order.
  9879. newCptOptions = (newCptOptions || []).slice();
  9880. var result = map(exists || [], function (obj, index) {
  9881. return {
  9882. exist: obj
  9883. };
  9884. }); // Mapping by id or name if specified.
  9885. each$2(newCptOptions, function (cptOption, index) {
  9886. if (!isObject$2(cptOption)) {
  9887. return;
  9888. } // id has highest priority.
  9889. for (var i = 0; i < result.length; i++) {
  9890. if (!result[i].option // Consider name: two map to one.
  9891. && cptOption.id != null && result[i].exist.id === cptOption.id + '') {
  9892. result[i].option = cptOption;
  9893. newCptOptions[index] = null;
  9894. return;
  9895. }
  9896. }
  9897. for (var i = 0; i < result.length; i++) {
  9898. var exist = result[i].exist;
  9899. if (!result[i].option // Consider name: two map to one.
  9900. // Can not match when both ids exist but different.
  9901. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !isIdInner(cptOption) && !isIdInner(exist) && exist.name === cptOption.name + '') {
  9902. result[i].option = cptOption;
  9903. newCptOptions[index] = null;
  9904. return;
  9905. }
  9906. }
  9907. }); // Otherwise mapping by index.
  9908. each$2(newCptOptions, function (cptOption, index) {
  9909. if (!isObject$2(cptOption)) {
  9910. return;
  9911. }
  9912. var i = 0;
  9913. for (; i < result.length; i++) {
  9914. var exist = result[i].exist;
  9915. if (!result[i].option // Existing model that already has id should be able to
  9916. // mapped to (because after mapping performed model may
  9917. // be assigned with a id, whish should not affect next
  9918. // mapping), except those has inner id.
  9919. && !isIdInner(exist) // Caution:
  9920. // Do not overwrite id. But name can be overwritten,
  9921. // because axis use name as 'show label text'.
  9922. // 'exist' always has id and name and we dont
  9923. // need to check it.
  9924. && cptOption.id == null) {
  9925. result[i].option = cptOption;
  9926. break;
  9927. }
  9928. }
  9929. if (i >= result.length) {
  9930. result.push({
  9931. option: cptOption
  9932. });
  9933. }
  9934. });
  9935. return result;
  9936. }
  9937. /**
  9938. * Make id and name for mapping result (result of mappingToExists)
  9939. * into `keyInfo` field.
  9940. *
  9941. * @public
  9942. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9943. * which order is the same as exists.
  9944. * @return {Array.<Object>} The input.
  9945. */
  9946. function makeIdAndName(mapResult) {
  9947. // We use this id to hash component models and view instances
  9948. // in echarts. id can be specified by user, or auto generated.
  9949. // The id generation rule ensures new view instance are able
  9950. // to mapped to old instance when setOption are called in
  9951. // no-merge mode. So we generate model id by name and plus
  9952. // type in view id.
  9953. // name can be duplicated among components, which is convenient
  9954. // to specify multi components (like series) by one name.
  9955. // Ensure that each id is distinct.
  9956. var idMap = createHashMap();
  9957. each$2(mapResult, function (item, index) {
  9958. var existCpt = item.exist;
  9959. existCpt && idMap.set(existCpt.id, item);
  9960. });
  9961. each$2(mapResult, function (item, index) {
  9962. var opt = item.option;
  9963. assert$1(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  9964. opt && opt.id != null && idMap.set(opt.id, item);
  9965. !item.keyInfo && (item.keyInfo = {});
  9966. }); // Make name and id.
  9967. each$2(mapResult, function (item, index) {
  9968. var existCpt = item.exist;
  9969. var opt = item.option;
  9970. var keyInfo = item.keyInfo;
  9971. if (!isObject$2(opt)) {
  9972. return;
  9973. } // name can be overwitten. Consider case: axis.name = '20km'.
  9974. // But id generated by name will not be changed, which affect
  9975. // only in that case: setOption with 'not merge mode' and view
  9976. // instance will be recreated, which can be accepted.
  9977. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name // Avoid diffferent series has the same name,
  9978. // because name may be used like in color pallet.
  9979. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9980. if (existCpt) {
  9981. keyInfo.id = existCpt.id;
  9982. } else if (opt.id != null) {
  9983. keyInfo.id = opt.id + '';
  9984. } else {
  9985. // Consider this situatoin:
  9986. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9987. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9988. // Series with the same name between optionA and optionB
  9989. // should be mapped.
  9990. var idNum = 0;
  9991. do {
  9992. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9993. } while (idMap.get(keyInfo.id));
  9994. }
  9995. idMap.set(keyInfo.id, item);
  9996. });
  9997. }
  9998. function isNameSpecified(componentModel) {
  9999. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  10000. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10001. }
  10002. /**
  10003. * @public
  10004. * @param {Object} cptOption
  10005. * @return {boolean}
  10006. */
  10007. function isIdInner(cptOption) {
  10008. return isObject$2(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10009. }
  10010. /**
  10011. * A helper for removing duplicate items between batchA and batchB,
  10012. * and in themselves, and categorize by series.
  10013. *
  10014. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10015. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10016. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10017. */
  10018. /**
  10019. * @param {module:echarts/data/List} data
  10020. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10021. * each of which can be Array or primary type.
  10022. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10023. */
  10024. function queryDataIndex(data, payload) {
  10025. if (payload.dataIndexInside != null) {
  10026. return payload.dataIndexInside;
  10027. } else if (payload.dataIndex != null) {
  10028. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  10029. return data.indexOfRawIndex(value);
  10030. }) : data.indexOfRawIndex(payload.dataIndex);
  10031. } else if (payload.name != null) {
  10032. return isArray(payload.name) ? map(payload.name, function (value) {
  10033. return data.indexOfName(value);
  10034. }) : data.indexOfName(payload.name);
  10035. }
  10036. }
  10037. /**
  10038. * Enable property storage to any host object.
  10039. * Notice: Serialization is not supported.
  10040. *
  10041. * For example:
  10042. * var inner = zrUitl.makeInner();
  10043. *
  10044. * function some1(hostObj) {
  10045. * inner(hostObj).someProperty = 1212;
  10046. * ...
  10047. * }
  10048. * function some2() {
  10049. * var fields = inner(this);
  10050. * fields.someProperty1 = 1212;
  10051. * fields.someProperty2 = 'xx';
  10052. * ...
  10053. * }
  10054. *
  10055. * @return {Function}
  10056. */
  10057. function makeInner() {
  10058. // Consider different scope by es module import.
  10059. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10060. return function (hostObj) {
  10061. return hostObj[key] || (hostObj[key] = {});
  10062. };
  10063. }
  10064. var innerUniqueIndex = 0;
  10065. /**
  10066. * @param {module:echarts/model/Global} ecModel
  10067. * @param {string|Object} finder
  10068. * If string, e.g., 'geo', means {geoIndex: 0}.
  10069. * If Object, could contain some of these properties below:
  10070. * {
  10071. * seriesIndex, seriesId, seriesName,
  10072. * geoIndex, geoId, geoName,
  10073. * bmapIndex, bmapId, bmapName,
  10074. * xAxisIndex, xAxisId, xAxisName,
  10075. * yAxisIndex, yAxisId, yAxisName,
  10076. * gridIndex, gridId, gridName,
  10077. * ... (can be extended)
  10078. * }
  10079. * Each properties can be number|string|Array.<number>|Array.<string>
  10080. * For example, a finder could be
  10081. * {
  10082. * seriesIndex: 3,
  10083. * geoId: ['aa', 'cc'],
  10084. * gridName: ['xx', 'rr']
  10085. * }
  10086. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10087. * If nothing or null/undefined specified, return nothing.
  10088. * @param {Object} [opt]
  10089. * @param {string} [opt.defaultMainType]
  10090. * @param {Array.<string>} [opt.includeMainTypes]
  10091. * @return {Object} result like:
  10092. * {
  10093. * seriesModels: [seriesModel1, seriesModel2],
  10094. * seriesModel: seriesModel1, // The first model
  10095. * geoModels: [geoModel1, geoModel2],
  10096. * geoModel: geoModel1, // The first model
  10097. * ...
  10098. * }
  10099. */
  10100. function parseFinder(ecModel, finder, opt) {
  10101. if (isString(finder)) {
  10102. var obj = {};
  10103. obj[finder + 'Index'] = 0;
  10104. finder = obj;
  10105. }
  10106. var defaultMainType = opt && opt.defaultMainType;
  10107. if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name')) {
  10108. finder[defaultMainType + 'Index'] = 0;
  10109. }
  10110. var result = {};
  10111. each$2(finder, function (value, key) {
  10112. var value = finder[key]; // Exclude 'dataIndex' and other illgal keys.
  10113. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10114. result[key] = value;
  10115. return;
  10116. }
  10117. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10118. var mainType = parsedKey[1];
  10119. var queryType = (parsedKey[2] || '').toLowerCase();
  10120. if (!mainType || !queryType || value == null || queryType === 'index' && value === 'none' || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  10121. return;
  10122. }
  10123. var queryParam = {
  10124. mainType: mainType
  10125. };
  10126. if (queryType !== 'index' || value !== 'all') {
  10127. queryParam[queryType] = value;
  10128. }
  10129. var models = ecModel.queryComponents(queryParam);
  10130. result[mainType + 'Models'] = models;
  10131. result[mainType + 'Model'] = models[0];
  10132. });
  10133. return result;
  10134. }
  10135. function has(obj, prop) {
  10136. return obj && obj.hasOwnProperty(prop);
  10137. }
  10138. function setAttribute(dom, key, value) {
  10139. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  10140. }
  10141. function getAttribute(dom, key) {
  10142. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  10143. }
  10144. function getTooltipRenderMode(renderModeOption) {
  10145. if (renderModeOption === 'auto') {
  10146. // Using html when `document` exists, use richText otherwise
  10147. return env$1.domSupported ? 'html' : 'richText';
  10148. } else {
  10149. return renderModeOption || 'html';
  10150. }
  10151. }
  10152. /**
  10153. * Group a list by key.
  10154. *
  10155. * @param {Array} array
  10156. * @param {Function} getKey
  10157. * param {*} Array item
  10158. * return {string} key
  10159. * @return {Object} Result
  10160. * {Array}: keys,
  10161. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10162. */
  10163. /*
  10164. * Licensed to the Apache Software Foundation (ASF) under one
  10165. * or more contributor license agreements. See the NOTICE file
  10166. * distributed with this work for additional information
  10167. * regarding copyright ownership. The ASF licenses this file
  10168. * to you under the Apache License, Version 2.0 (the
  10169. * "License"); you may not use this file except in compliance
  10170. * with the License. You may obtain a copy of the License at
  10171. *
  10172. * http://www.apache.org/licenses/LICENSE-2.0
  10173. *
  10174. * Unless required by applicable law or agreed to in writing,
  10175. * software distributed under the License is distributed on an
  10176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10177. * KIND, either express or implied. See the License for the
  10178. * specific language governing permissions and limitations
  10179. * under the License.
  10180. */
  10181. var TYPE_DELIMITER = '.';
  10182. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10183. /**
  10184. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10185. * @public
  10186. */
  10187. function parseClassType$1(componentType) {
  10188. var ret = {
  10189. main: '',
  10190. sub: ''
  10191. };
  10192. if (componentType) {
  10193. componentType = componentType.split(TYPE_DELIMITER);
  10194. ret.main = componentType[0] || '';
  10195. ret.sub = componentType[1] || '';
  10196. }
  10197. return ret;
  10198. }
  10199. /**
  10200. * @public
  10201. */
  10202. function checkClassType(componentType) {
  10203. assert$1(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  10204. }
  10205. /**
  10206. * @public
  10207. */
  10208. function enableClassExtend(RootClass, mandatoryMethods) {
  10209. RootClass.$constructor = RootClass;
  10210. RootClass.extend = function (proto) {
  10211. var superClass = this;
  10212. var ExtendedClass = function () {
  10213. if (!proto.$constructor) {
  10214. superClass.apply(this, arguments);
  10215. } else {
  10216. proto.$constructor.apply(this, arguments);
  10217. }
  10218. };
  10219. extend(ExtendedClass.prototype, proto);
  10220. ExtendedClass.extend = this.extend;
  10221. ExtendedClass.superCall = superCall;
  10222. ExtendedClass.superApply = superApply;
  10223. inherits(ExtendedClass, this);
  10224. ExtendedClass.superClass = superClass;
  10225. return ExtendedClass;
  10226. };
  10227. }
  10228. var classBase = 0;
  10229. /**
  10230. * Can not use instanceof, consider different scope by
  10231. * cross domain or es module import in ec extensions.
  10232. * Mount a method "isInstance()" to Clz.
  10233. */
  10234. function enableClassCheck(Clz) {
  10235. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10236. Clz.prototype[classAttr] = true;
  10237. Clz.isInstance = function (obj) {
  10238. return !!(obj && obj[classAttr]);
  10239. };
  10240. } // superCall should have class info, which can not be fetch from 'this'.
  10241. // Consider this case:
  10242. // class A has method f,
  10243. // class B inherits class A, overrides method f, f call superApply('f'),
  10244. // class C inherits class B, do not overrides method f,
  10245. // then when method of class C is called, dead loop occured.
  10246. function superCall(context, methodName) {
  10247. var args = slice(arguments, 2);
  10248. return this.superClass.prototype[methodName].apply(context, args);
  10249. }
  10250. function superApply(context, methodName, args) {
  10251. return this.superClass.prototype[methodName].apply(context, args);
  10252. }
  10253. /**
  10254. * @param {Object} entity
  10255. * @param {Object} options
  10256. * @param {boolean} [options.registerWhenExtend]
  10257. * @public
  10258. */
  10259. function enableClassManagement(entity, options) {
  10260. options = options || {};
  10261. /**
  10262. * Component model classes
  10263. * key: componentType,
  10264. * value:
  10265. * componentClass, when componentType is 'xxx'
  10266. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10267. * @type {Object}
  10268. */
  10269. var storage = {};
  10270. entity.registerClass = function (Clazz, componentType) {
  10271. if (componentType) {
  10272. checkClassType(componentType);
  10273. componentType = parseClassType$1(componentType);
  10274. if (!componentType.sub) {
  10275. storage[componentType.main] = Clazz;
  10276. } else if (componentType.sub !== IS_CONTAINER) {
  10277. var container = makeContainer(componentType);
  10278. container[componentType.sub] = Clazz;
  10279. }
  10280. }
  10281. return Clazz;
  10282. };
  10283. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10284. var Clazz = storage[componentMainType];
  10285. if (Clazz && Clazz[IS_CONTAINER]) {
  10286. Clazz = subType ? Clazz[subType] : null;
  10287. }
  10288. if (throwWhenNotFound && !Clazz) {
  10289. throw new Error(!subType ? componentMainType + '.' + 'type should be specified.' : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.');
  10290. }
  10291. return Clazz;
  10292. };
  10293. entity.getClassesByMainType = function (componentType) {
  10294. componentType = parseClassType$1(componentType);
  10295. var result = [];
  10296. var obj = storage[componentType.main];
  10297. if (obj && obj[IS_CONTAINER]) {
  10298. each$1(obj, function (o, type) {
  10299. type !== IS_CONTAINER && result.push(o);
  10300. });
  10301. } else {
  10302. result.push(obj);
  10303. }
  10304. return result;
  10305. };
  10306. entity.hasClass = function (componentType) {
  10307. // Just consider componentType.main.
  10308. componentType = parseClassType$1(componentType);
  10309. return !!storage[componentType.main];
  10310. };
  10311. /**
  10312. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10313. */
  10314. entity.getAllClassMainTypes = function () {
  10315. var types = [];
  10316. each$1(storage, function (obj, type) {
  10317. types.push(type);
  10318. });
  10319. return types;
  10320. };
  10321. /**
  10322. * If a main type is container and has sub types
  10323. * @param {string} mainType
  10324. * @return {boolean}
  10325. */
  10326. entity.hasSubTypes = function (componentType) {
  10327. componentType = parseClassType$1(componentType);
  10328. var obj = storage[componentType.main];
  10329. return obj && obj[IS_CONTAINER];
  10330. };
  10331. entity.parseClassType = parseClassType$1;
  10332. function makeContainer(componentType) {
  10333. var container = storage[componentType.main];
  10334. if (!container || !container[IS_CONTAINER]) {
  10335. container = storage[componentType.main] = {};
  10336. container[IS_CONTAINER] = true;
  10337. }
  10338. return container;
  10339. }
  10340. if (options.registerWhenExtend) {
  10341. var originalExtend = entity.extend;
  10342. if (originalExtend) {
  10343. entity.extend = function (proto) {
  10344. var ExtendedClass = originalExtend.call(this, proto);
  10345. return entity.registerClass(ExtendedClass, proto.type);
  10346. };
  10347. }
  10348. }
  10349. return entity;
  10350. }
  10351. /**
  10352. * @param {string|Array.<string>} properties
  10353. */
  10354. /*
  10355. * Licensed to the Apache Software Foundation (ASF) under one
  10356. * or more contributor license agreements. See the NOTICE file
  10357. * distributed with this work for additional information
  10358. * regarding copyright ownership. The ASF licenses this file
  10359. * to you under the Apache License, Version 2.0 (the
  10360. * "License"); you may not use this file except in compliance
  10361. * with the License. You may obtain a copy of the License at
  10362. *
  10363. * http://www.apache.org/licenses/LICENSE-2.0
  10364. *
  10365. * Unless required by applicable law or agreed to in writing,
  10366. * software distributed under the License is distributed on an
  10367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10368. * KIND, either express or implied. See the License for the
  10369. * specific language governing permissions and limitations
  10370. * under the License.
  10371. */
  10372. // TODO Parse shadow style
  10373. // TODO Only shallow path support
  10374. var makeStyleMapper = function (properties) {
  10375. // Normalize
  10376. for (var i = 0; i < properties.length; i++) {
  10377. if (!properties[i][1]) {
  10378. properties[i][1] = properties[i][0];
  10379. }
  10380. }
  10381. return function (model, excludes, includes) {
  10382. var style = {};
  10383. for (var i = 0; i < properties.length; i++) {
  10384. var propName = properties[i][1];
  10385. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  10386. continue;
  10387. }
  10388. var val = model.getShallow(propName);
  10389. if (val != null) {
  10390. style[properties[i][0]] = val;
  10391. }
  10392. }
  10393. return style;
  10394. };
  10395. };
  10396. /*
  10397. * Licensed to the Apache Software Foundation (ASF) under one
  10398. * or more contributor license agreements. See the NOTICE file
  10399. * distributed with this work for additional information
  10400. * regarding copyright ownership. The ASF licenses this file
  10401. * to you under the Apache License, Version 2.0 (the
  10402. * "License"); you may not use this file except in compliance
  10403. * with the License. You may obtain a copy of the License at
  10404. *
  10405. * http://www.apache.org/licenses/LICENSE-2.0
  10406. *
  10407. * Unless required by applicable law or agreed to in writing,
  10408. * software distributed under the License is distributed on an
  10409. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10410. * KIND, either express or implied. See the License for the
  10411. * specific language governing permissions and limitations
  10412. * under the License.
  10413. */
  10414. var getLineStyle = makeStyleMapper([['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor']]);
  10415. var lineStyleMixin = {
  10416. getLineStyle: function (excludes) {
  10417. var style = getLineStyle(this, excludes); // Always set lineDash whether dashed, otherwise we can not
  10418. // erase the previous style when assigning to el.style.
  10419. style.lineDash = this.getLineDash(style.lineWidth);
  10420. return style;
  10421. },
  10422. getLineDash: function (lineWidth) {
  10423. if (lineWidth == null) {
  10424. lineWidth = 1;
  10425. }
  10426. var lineType = this.get('type');
  10427. var dotSize = Math.max(lineWidth, 2);
  10428. var dashSize = lineWidth * 4;
  10429. return lineType === 'solid' || lineType == null ? // Use `false` but not `null` for the solid line here, because `null` might be
  10430. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  10431. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  10432. // `lineDash` gotten form the latter one is not able to erase that from the former
  10433. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  10434. false : lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize];
  10435. }
  10436. };
  10437. /*
  10438. * Licensed to the Apache Software Foundation (ASF) under one
  10439. * or more contributor license agreements. See the NOTICE file
  10440. * distributed with this work for additional information
  10441. * regarding copyright ownership. The ASF licenses this file
  10442. * to you under the Apache License, Version 2.0 (the
  10443. * "License"); you may not use this file except in compliance
  10444. * with the License. You may obtain a copy of the License at
  10445. *
  10446. * http://www.apache.org/licenses/LICENSE-2.0
  10447. *
  10448. * Unless required by applicable law or agreed to in writing,
  10449. * software distributed under the License is distributed on an
  10450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10451. * KIND, either express or implied. See the License for the
  10452. * specific language governing permissions and limitations
  10453. * under the License.
  10454. */
  10455. var getAreaStyle = makeStyleMapper([['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']]);
  10456. var areaStyleMixin = {
  10457. getAreaStyle: function (excludes, includes) {
  10458. return getAreaStyle(this, excludes, includes);
  10459. }
  10460. };
  10461. /**
  10462. * 曲线辅助模块
  10463. * @module zrender/core/curve
  10464. * @author pissang(https://www.github.com/pissang)
  10465. */
  10466. var mathPow = Math.pow;
  10467. var mathSqrt$2 = Math.sqrt;
  10468. var EPSILON$1 = 1e-8;
  10469. var EPSILON_NUMERIC = 1e-4;
  10470. var THREE_SQRT = mathSqrt$2(3);
  10471. var ONE_THIRD = 1 / 3; // 临时变量
  10472. var _v0 = create();
  10473. var _v1 = create();
  10474. var _v2 = create();
  10475. function isAroundZero(val) {
  10476. return val > -EPSILON$1 && val < EPSILON$1;
  10477. }
  10478. function isNotAroundZero$1(val) {
  10479. return val > EPSILON$1 || val < -EPSILON$1;
  10480. }
  10481. /**
  10482. * 计算三次贝塞尔值
  10483. * @memberOf module:zrender/core/curve
  10484. * @param {number} p0
  10485. * @param {number} p1
  10486. * @param {number} p2
  10487. * @param {number} p3
  10488. * @param {number} t
  10489. * @return {number}
  10490. */
  10491. function cubicAt(p0, p1, p2, p3, t) {
  10492. var onet = 1 - t;
  10493. return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2);
  10494. }
  10495. /**
  10496. * 计算三次贝塞尔导数值
  10497. * @memberOf module:zrender/core/curve
  10498. * @param {number} p0
  10499. * @param {number} p1
  10500. * @param {number} p2
  10501. * @param {number} p3
  10502. * @param {number} t
  10503. * @return {number}
  10504. */
  10505. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10506. var onet = 1 - t;
  10507. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t);
  10508. }
  10509. /**
  10510. * 计算三次贝塞尔方程根,使用盛金公式
  10511. * @memberOf module:zrender/core/curve
  10512. * @param {number} p0
  10513. * @param {number} p1
  10514. * @param {number} p2
  10515. * @param {number} p3
  10516. * @param {number} val
  10517. * @param {Array.<number>} roots
  10518. * @return {number} 有效根数目
  10519. */
  10520. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10521. // Evaluate roots of cubic functions
  10522. var a = p3 + 3 * (p1 - p2) - p0;
  10523. var b = 3 * (p2 - p1 * 2 + p0);
  10524. var c = 3 * (p1 - p0);
  10525. var d = p0 - val;
  10526. var A = b * b - 3 * a * c;
  10527. var B = b * c - 9 * a * d;
  10528. var C = c * c - 3 * b * d;
  10529. var n = 0;
  10530. if (isAroundZero(A) && isAroundZero(B)) {
  10531. if (isAroundZero(b)) {
  10532. roots[0] = 0;
  10533. } else {
  10534. var t1 = -c / b; //t1, t2, t3, b is not zero
  10535. if (t1 >= 0 && t1 <= 1) {
  10536. roots[n++] = t1;
  10537. }
  10538. }
  10539. } else {
  10540. var disc = B * B - 4 * A * C;
  10541. if (isAroundZero(disc)) {
  10542. var K = B / A;
  10543. var t1 = -b / a + K; // t1, a is not zero
  10544. var t2 = -K / 2; // t2, t3
  10545. if (t1 >= 0 && t1 <= 1) {
  10546. roots[n++] = t1;
  10547. }
  10548. if (t2 >= 0 && t2 <= 1) {
  10549. roots[n++] = t2;
  10550. }
  10551. } else if (disc > 0) {
  10552. var discSqrt = mathSqrt$2(disc);
  10553. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10554. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10555. if (Y1 < 0) {
  10556. Y1 = -mathPow(-Y1, ONE_THIRD);
  10557. } else {
  10558. Y1 = mathPow(Y1, ONE_THIRD);
  10559. }
  10560. if (Y2 < 0) {
  10561. Y2 = -mathPow(-Y2, ONE_THIRD);
  10562. } else {
  10563. Y2 = mathPow(Y2, ONE_THIRD);
  10564. }
  10565. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10566. if (t1 >= 0 && t1 <= 1) {
  10567. roots[n++] = t1;
  10568. }
  10569. } else {
  10570. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10571. var theta = Math.acos(T) / 3;
  10572. var ASqrt = mathSqrt$2(A);
  10573. var tmp = Math.cos(theta);
  10574. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10575. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10576. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10577. if (t1 >= 0 && t1 <= 1) {
  10578. roots[n++] = t1;
  10579. }
  10580. if (t2 >= 0 && t2 <= 1) {
  10581. roots[n++] = t2;
  10582. }
  10583. if (t3 >= 0 && t3 <= 1) {
  10584. roots[n++] = t3;
  10585. }
  10586. }
  10587. }
  10588. return n;
  10589. }
  10590. /**
  10591. * 计算三次贝塞尔方程极限值的位置
  10592. * @memberOf module:zrender/core/curve
  10593. * @param {number} p0
  10594. * @param {number} p1
  10595. * @param {number} p2
  10596. * @param {number} p3
  10597. * @param {Array.<number>} extrema
  10598. * @return {number} 有效数目
  10599. */
  10600. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10601. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10602. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10603. var c = 3 * p1 - 3 * p0;
  10604. var n = 0;
  10605. if (isAroundZero(a)) {
  10606. if (isNotAroundZero$1(b)) {
  10607. var t1 = -c / b;
  10608. if (t1 >= 0 && t1 <= 1) {
  10609. extrema[n++] = t1;
  10610. }
  10611. }
  10612. } else {
  10613. var disc = b * b - 4 * a * c;
  10614. if (isAroundZero(disc)) {
  10615. extrema[0] = -b / (2 * a);
  10616. } else if (disc > 0) {
  10617. var discSqrt = mathSqrt$2(disc);
  10618. var t1 = (-b + discSqrt) / (2 * a);
  10619. var t2 = (-b - discSqrt) / (2 * a);
  10620. if (t1 >= 0 && t1 <= 1) {
  10621. extrema[n++] = t1;
  10622. }
  10623. if (t2 >= 0 && t2 <= 1) {
  10624. extrema[n++] = t2;
  10625. }
  10626. }
  10627. }
  10628. return n;
  10629. }
  10630. /**
  10631. * 细分三次贝塞尔曲线
  10632. * @memberOf module:zrender/core/curve
  10633. * @param {number} p0
  10634. * @param {number} p1
  10635. * @param {number} p2
  10636. * @param {number} p3
  10637. * @param {number} t
  10638. * @param {Array.<number>} out
  10639. */
  10640. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10641. var p01 = (p1 - p0) * t + p0;
  10642. var p12 = (p2 - p1) * t + p1;
  10643. var p23 = (p3 - p2) * t + p2;
  10644. var p012 = (p12 - p01) * t + p01;
  10645. var p123 = (p23 - p12) * t + p12;
  10646. var p0123 = (p123 - p012) * t + p012; // Seg0
  10647. out[0] = p0;
  10648. out[1] = p01;
  10649. out[2] = p012;
  10650. out[3] = p0123; // Seg1
  10651. out[4] = p0123;
  10652. out[5] = p123;
  10653. out[6] = p23;
  10654. out[7] = p3;
  10655. }
  10656. /**
  10657. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10658. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10659. * @param {number} x0
  10660. * @param {number} y0
  10661. * @param {number} x1
  10662. * @param {number} y1
  10663. * @param {number} x2
  10664. * @param {number} y2
  10665. * @param {number} x3
  10666. * @param {number} y3
  10667. * @param {number} x
  10668. * @param {number} y
  10669. * @param {Array.<number>} [out] 投射点
  10670. * @return {number}
  10671. */
  10672. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  10673. // http://pomax.github.io/bezierinfo/#projections
  10674. var t;
  10675. var interval = 0.005;
  10676. var d = Infinity;
  10677. var prev;
  10678. var next;
  10679. var d1;
  10680. var d2;
  10681. _v0[0] = x;
  10682. _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值
  10683. // PENDING
  10684. for (var _t = 0; _t < 1; _t += 0.05) {
  10685. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10686. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10687. d1 = distSquare(_v0, _v1);
  10688. if (d1 < d) {
  10689. t = _t;
  10690. d = d1;
  10691. }
  10692. }
  10693. d = Infinity; // At most 32 iteration
  10694. for (var i = 0; i < 32; i++) {
  10695. if (interval < EPSILON_NUMERIC) {
  10696. break;
  10697. }
  10698. prev = t - interval;
  10699. next = t + interval; // t - interval
  10700. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10701. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10702. d1 = distSquare(_v1, _v0);
  10703. if (prev >= 0 && d1 < d) {
  10704. t = prev;
  10705. d = d1;
  10706. } else {
  10707. // t + interval
  10708. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10709. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10710. d2 = distSquare(_v2, _v0);
  10711. if (next <= 1 && d2 < d) {
  10712. t = next;
  10713. d = d2;
  10714. } else {
  10715. interval *= 0.5;
  10716. }
  10717. }
  10718. } // t
  10719. if (out) {
  10720. out[0] = cubicAt(x0, x1, x2, x3, t);
  10721. out[1] = cubicAt(y0, y1, y2, y3, t);
  10722. } // console.log(interval, i);
  10723. return mathSqrt$2(d);
  10724. }
  10725. /**
  10726. * 计算二次方贝塞尔值
  10727. * @param {number} p0
  10728. * @param {number} p1
  10729. * @param {number} p2
  10730. * @param {number} t
  10731. * @return {number}
  10732. */
  10733. function quadraticAt(p0, p1, p2, t) {
  10734. var onet = 1 - t;
  10735. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10736. }
  10737. /**
  10738. * 计算二次方贝塞尔导数值
  10739. * @param {number} p0
  10740. * @param {number} p1
  10741. * @param {number} p2
  10742. * @param {number} t
  10743. * @return {number}
  10744. */
  10745. function quadraticDerivativeAt(p0, p1, p2, t) {
  10746. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10747. }
  10748. /**
  10749. * 计算二次方贝塞尔方程根
  10750. * @param {number} p0
  10751. * @param {number} p1
  10752. * @param {number} p2
  10753. * @param {number} t
  10754. * @param {Array.<number>} roots
  10755. * @return {number} 有效根数目
  10756. */
  10757. function quadraticRootAt(p0, p1, p2, val, roots) {
  10758. var a = p0 - 2 * p1 + p2;
  10759. var b = 2 * (p1 - p0);
  10760. var c = p0 - val;
  10761. var n = 0;
  10762. if (isAroundZero(a)) {
  10763. if (isNotAroundZero$1(b)) {
  10764. var t1 = -c / b;
  10765. if (t1 >= 0 && t1 <= 1) {
  10766. roots[n++] = t1;
  10767. }
  10768. }
  10769. } else {
  10770. var disc = b * b - 4 * a * c;
  10771. if (isAroundZero(disc)) {
  10772. var t1 = -b / (2 * a);
  10773. if (t1 >= 0 && t1 <= 1) {
  10774. roots[n++] = t1;
  10775. }
  10776. } else if (disc > 0) {
  10777. var discSqrt = mathSqrt$2(disc);
  10778. var t1 = (-b + discSqrt) / (2 * a);
  10779. var t2 = (-b - discSqrt) / (2 * a);
  10780. if (t1 >= 0 && t1 <= 1) {
  10781. roots[n++] = t1;
  10782. }
  10783. if (t2 >= 0 && t2 <= 1) {
  10784. roots[n++] = t2;
  10785. }
  10786. }
  10787. }
  10788. return n;
  10789. }
  10790. /**
  10791. * 计算二次贝塞尔方程极限值
  10792. * @memberOf module:zrender/core/curve
  10793. * @param {number} p0
  10794. * @param {number} p1
  10795. * @param {number} p2
  10796. * @return {number}
  10797. */
  10798. function quadraticExtremum(p0, p1, p2) {
  10799. var divider = p0 + p2 - 2 * p1;
  10800. if (divider === 0) {
  10801. // p1 is center of p0 and p2
  10802. return 0.5;
  10803. } else {
  10804. return (p0 - p1) / divider;
  10805. }
  10806. }
  10807. /**
  10808. * 细分二次贝塞尔曲线
  10809. * @memberOf module:zrender/core/curve
  10810. * @param {number} p0
  10811. * @param {number} p1
  10812. * @param {number} p2
  10813. * @param {number} t
  10814. * @param {Array.<number>} out
  10815. */
  10816. function quadraticSubdivide(p0, p1, p2, t, out) {
  10817. var p01 = (p1 - p0) * t + p0;
  10818. var p12 = (p2 - p1) * t + p1;
  10819. var p012 = (p12 - p01) * t + p01; // Seg0
  10820. out[0] = p0;
  10821. out[1] = p01;
  10822. out[2] = p012; // Seg1
  10823. out[3] = p012;
  10824. out[4] = p12;
  10825. out[5] = p2;
  10826. }
  10827. /**
  10828. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10829. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10830. * @param {number} x0
  10831. * @param {number} y0
  10832. * @param {number} x1
  10833. * @param {number} y1
  10834. * @param {number} x2
  10835. * @param {number} y2
  10836. * @param {number} x
  10837. * @param {number} y
  10838. * @param {Array.<number>} out 投射点
  10839. * @return {number}
  10840. */
  10841. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  10842. // http://pomax.github.io/bezierinfo/#projections
  10843. var t;
  10844. var interval = 0.005;
  10845. var d = Infinity;
  10846. _v0[0] = x;
  10847. _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值
  10848. // PENDING
  10849. for (var _t = 0; _t < 1; _t += 0.05) {
  10850. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10851. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10852. var d1 = distSquare(_v0, _v1);
  10853. if (d1 < d) {
  10854. t = _t;
  10855. d = d1;
  10856. }
  10857. }
  10858. d = Infinity; // At most 32 iteration
  10859. for (var i = 0; i < 32; i++) {
  10860. if (interval < EPSILON_NUMERIC) {
  10861. break;
  10862. }
  10863. var prev = t - interval;
  10864. var next = t + interval; // t - interval
  10865. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10866. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10867. var d1 = distSquare(_v1, _v0);
  10868. if (prev >= 0 && d1 < d) {
  10869. t = prev;
  10870. d = d1;
  10871. } else {
  10872. // t + interval
  10873. _v2[0] = quadraticAt(x0, x1, x2, next);
  10874. _v2[1] = quadraticAt(y0, y1, y2, next);
  10875. var d2 = distSquare(_v2, _v0);
  10876. if (next <= 1 && d2 < d) {
  10877. t = next;
  10878. d = d2;
  10879. } else {
  10880. interval *= 0.5;
  10881. }
  10882. }
  10883. } // t
  10884. if (out) {
  10885. out[0] = quadraticAt(x0, x1, x2, t);
  10886. out[1] = quadraticAt(y0, y1, y2, t);
  10887. } // console.log(interval, i);
  10888. return mathSqrt$2(d);
  10889. }
  10890. /**
  10891. * @author Yi Shen(https://github.com/pissang)
  10892. */
  10893. var mathMin$3 = Math.min;
  10894. var mathMax$3 = Math.max;
  10895. var mathSin$2 = Math.sin;
  10896. var mathCos$2 = Math.cos;
  10897. var PI2 = Math.PI * 2;
  10898. var start = create();
  10899. var end = create();
  10900. var extremity = create();
  10901. /**
  10902. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10903. * @module zrender/core/bbox
  10904. * @param {Array<Object>} points 顶点数组
  10905. * @param {number} min
  10906. * @param {number} max
  10907. */
  10908. function fromPoints(points, min$$1, max$$1) {
  10909. if (points.length === 0) {
  10910. return;
  10911. }
  10912. var p = points[0];
  10913. var left = p[0];
  10914. var right = p[0];
  10915. var top = p[1];
  10916. var bottom = p[1];
  10917. var i;
  10918. for (i = 1; i < points.length; i++) {
  10919. p = points[i];
  10920. left = mathMin$3(left, p[0]);
  10921. right = mathMax$3(right, p[0]);
  10922. top = mathMin$3(top, p[1]);
  10923. bottom = mathMax$3(bottom, p[1]);
  10924. }
  10925. min$$1[0] = left;
  10926. min$$1[1] = top;
  10927. max$$1[0] = right;
  10928. max$$1[1] = bottom;
  10929. }
  10930. /**
  10931. * @memberOf module:zrender/core/bbox
  10932. * @param {number} x0
  10933. * @param {number} y0
  10934. * @param {number} x1
  10935. * @param {number} y1
  10936. * @param {Array.<number>} min
  10937. * @param {Array.<number>} max
  10938. */
  10939. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10940. min$$1[0] = mathMin$3(x0, x1);
  10941. min$$1[1] = mathMin$3(y0, y1);
  10942. max$$1[0] = mathMax$3(x0, x1);
  10943. max$$1[1] = mathMax$3(y0, y1);
  10944. }
  10945. var xDim = [];
  10946. var yDim = [];
  10947. /**
  10948. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10949. * @memberOf module:zrender/core/bbox
  10950. * @param {number} x0
  10951. * @param {number} y0
  10952. * @param {number} x1
  10953. * @param {number} y1
  10954. * @param {number} x2
  10955. * @param {number} y2
  10956. * @param {number} x3
  10957. * @param {number} y3
  10958. * @param {Array.<number>} min
  10959. * @param {Array.<number>} max
  10960. */
  10961. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1) {
  10962. var cubicExtrema$$1 = cubicExtrema;
  10963. var cubicAt$$1 = cubicAt;
  10964. var i;
  10965. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10966. min$$1[0] = Infinity;
  10967. min$$1[1] = Infinity;
  10968. max$$1[0] = -Infinity;
  10969. max$$1[1] = -Infinity;
  10970. for (i = 0; i < n; i++) {
  10971. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10972. min$$1[0] = mathMin$3(x, min$$1[0]);
  10973. max$$1[0] = mathMax$3(x, max$$1[0]);
  10974. }
  10975. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10976. for (i = 0; i < n; i++) {
  10977. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10978. min$$1[1] = mathMin$3(y, min$$1[1]);
  10979. max$$1[1] = mathMax$3(y, max$$1[1]);
  10980. }
  10981. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10982. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10983. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10984. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10985. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10986. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10987. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10988. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10989. }
  10990. /**
  10991. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10992. * @memberOf module:zrender/core/bbox
  10993. * @param {number} x0
  10994. * @param {number} y0
  10995. * @param {number} x1
  10996. * @param {number} y1
  10997. * @param {number} x2
  10998. * @param {number} y2
  10999. * @param {Array.<number>} min
  11000. * @param {Array.<number>} max
  11001. */
  11002. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11003. var quadraticExtremum$$1 = quadraticExtremum;
  11004. var quadraticAt$$1 = quadraticAt; // Find extremities, where derivative in x dim or y dim is zero
  11005. var tx = mathMax$3(mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0);
  11006. var ty = mathMax$3(mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0);
  11007. var x = quadraticAt$$1(x0, x1, x2, tx);
  11008. var y = quadraticAt$$1(y0, y1, y2, ty);
  11009. min$$1[0] = mathMin$3(x0, x2, x);
  11010. min$$1[1] = mathMin$3(y0, y2, y);
  11011. max$$1[0] = mathMax$3(x0, x2, x);
  11012. max$$1[1] = mathMax$3(y0, y2, y);
  11013. }
  11014. /**
  11015. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11016. * @method
  11017. * @memberOf module:zrender/core/bbox
  11018. * @param {number} x
  11019. * @param {number} y
  11020. * @param {number} rx
  11021. * @param {number} ry
  11022. * @param {number} startAngle
  11023. * @param {number} endAngle
  11024. * @param {number} anticlockwise
  11025. * @param {Array.<number>} min
  11026. * @param {Array.<number>} max
  11027. */
  11028. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1) {
  11029. var vec2Min = min;
  11030. var vec2Max = max;
  11031. var diff = Math.abs(startAngle - endAngle);
  11032. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11033. // Is a circle
  11034. min$$1[0] = x - rx;
  11035. min$$1[1] = y - ry;
  11036. max$$1[0] = x + rx;
  11037. max$$1[1] = y + ry;
  11038. return;
  11039. }
  11040. start[0] = mathCos$2(startAngle) * rx + x;
  11041. start[1] = mathSin$2(startAngle) * ry + y;
  11042. end[0] = mathCos$2(endAngle) * rx + x;
  11043. end[1] = mathSin$2(endAngle) * ry + y;
  11044. vec2Min(min$$1, start, end);
  11045. vec2Max(max$$1, start, end); // Thresh to [0, Math.PI * 2]
  11046. startAngle = startAngle % PI2;
  11047. if (startAngle < 0) {
  11048. startAngle = startAngle + PI2;
  11049. }
  11050. endAngle = endAngle % PI2;
  11051. if (endAngle < 0) {
  11052. endAngle = endAngle + PI2;
  11053. }
  11054. if (startAngle > endAngle && !anticlockwise) {
  11055. endAngle += PI2;
  11056. } else if (startAngle < endAngle && anticlockwise) {
  11057. startAngle += PI2;
  11058. }
  11059. if (anticlockwise) {
  11060. var tmp = endAngle;
  11061. endAngle = startAngle;
  11062. startAngle = tmp;
  11063. } // var number = 0;
  11064. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11065. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11066. if (angle > startAngle) {
  11067. extremity[0] = mathCos$2(angle) * rx + x;
  11068. extremity[1] = mathSin$2(angle) * ry + y;
  11069. vec2Min(min$$1, extremity, min$$1);
  11070. vec2Max(max$$1, extremity, max$$1);
  11071. }
  11072. }
  11073. }
  11074. /**
  11075. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11076. * 可以用于 isInsidePath 判断以及获取boundingRect
  11077. *
  11078. * @module zrender/core/PathProxy
  11079. * @author Yi Shen (http://www.github.com/pissang)
  11080. */
  11081. // TODO getTotalLength, getPointAtLength
  11082. /* global Float32Array */
  11083. var CMD = {
  11084. M: 1,
  11085. L: 2,
  11086. C: 3,
  11087. Q: 4,
  11088. A: 5,
  11089. Z: 6,
  11090. // Rect
  11091. R: 7
  11092. }; // var CMD_MEM_SIZE = {
  11093. // M: 3,
  11094. // L: 3,
  11095. // C: 7,
  11096. // Q: 5,
  11097. // A: 9,
  11098. // R: 5,
  11099. // Z: 1
  11100. // };
  11101. var min$1 = [];
  11102. var max$1 = [];
  11103. var min2 = [];
  11104. var max2 = [];
  11105. var mathMin$2 = Math.min;
  11106. var mathMax$2 = Math.max;
  11107. var mathCos$1 = Math.cos;
  11108. var mathSin$1 = Math.sin;
  11109. var mathSqrt$1 = Math.sqrt;
  11110. var mathAbs = Math.abs;
  11111. var hasTypedArray = typeof Float32Array !== 'undefined';
  11112. /**
  11113. * @alias module:zrender/core/PathProxy
  11114. * @constructor
  11115. */
  11116. var PathProxy = function (notSaveData) {
  11117. this._saveData = !(notSaveData || false);
  11118. if (this._saveData) {
  11119. /**
  11120. * Path data. Stored as flat array
  11121. * @type {Array.<Object>}
  11122. */
  11123. this.data = [];
  11124. }
  11125. this._ctx = null;
  11126. };
  11127. /**
  11128. * 快速计算Path包围盒(并不是最小包围盒)
  11129. * @return {Object}
  11130. */
  11131. PathProxy.prototype = {
  11132. constructor: PathProxy,
  11133. _xi: 0,
  11134. _yi: 0,
  11135. _x0: 0,
  11136. _y0: 0,
  11137. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11138. _ux: 0,
  11139. _uy: 0,
  11140. _len: 0,
  11141. _lineDash: null,
  11142. _dashOffset: 0,
  11143. _dashIdx: 0,
  11144. _dashSum: 0,
  11145. /**
  11146. * @readOnly
  11147. */
  11148. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11149. // Compat. Previously there is no segmentIgnoreThreshold.
  11150. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11151. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11152. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11153. },
  11154. getContext: function () {
  11155. return this._ctx;
  11156. },
  11157. /**
  11158. * @param {CanvasRenderingContext2D} ctx
  11159. * @return {module:zrender/core/PathProxy}
  11160. */
  11161. beginPath: function (ctx) {
  11162. this._ctx = ctx;
  11163. ctx && ctx.beginPath();
  11164. ctx && (this.dpr = ctx.dpr); // Reset
  11165. if (this._saveData) {
  11166. this._len = 0;
  11167. }
  11168. if (this._lineDash) {
  11169. this._lineDash = null;
  11170. this._dashOffset = 0;
  11171. }
  11172. return this;
  11173. },
  11174. /**
  11175. * @param {number} x
  11176. * @param {number} y
  11177. * @return {module:zrender/core/PathProxy}
  11178. */
  11179. moveTo: function (x, y) {
  11180. this.addData(CMD.M, x, y);
  11181. this._ctx && this._ctx.moveTo(x, y); // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11182. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11183. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11184. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11185. this._x0 = x;
  11186. this._y0 = y;
  11187. this._xi = x;
  11188. this._yi = y;
  11189. return this;
  11190. },
  11191. /**
  11192. * @param {number} x
  11193. * @param {number} y
  11194. * @return {module:zrender/core/PathProxy}
  11195. */
  11196. lineTo: function (x, y) {
  11197. var exceedUnit = mathAbs(x - this._xi) > this._ux || mathAbs(y - this._yi) > this._uy // Force draw the first segment
  11198. || this._len < 5;
  11199. this.addData(CMD.L, x, y);
  11200. if (this._ctx && exceedUnit) {
  11201. this._needsDash() ? this._dashedLineTo(x, y) : this._ctx.lineTo(x, y);
  11202. }
  11203. if (exceedUnit) {
  11204. this._xi = x;
  11205. this._yi = y;
  11206. }
  11207. return this;
  11208. },
  11209. /**
  11210. * @param {number} x1
  11211. * @param {number} y1
  11212. * @param {number} x2
  11213. * @param {number} y2
  11214. * @param {number} x3
  11215. * @param {number} y3
  11216. * @return {module:zrender/core/PathProxy}
  11217. */
  11218. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11219. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11220. if (this._ctx) {
  11221. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3) : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11222. }
  11223. this._xi = x3;
  11224. this._yi = y3;
  11225. return this;
  11226. },
  11227. /**
  11228. * @param {number} x1
  11229. * @param {number} y1
  11230. * @param {number} x2
  11231. * @param {number} y2
  11232. * @return {module:zrender/core/PathProxy}
  11233. */
  11234. quadraticCurveTo: function (x1, y1, x2, y2) {
  11235. this.addData(CMD.Q, x1, y1, x2, y2);
  11236. if (this._ctx) {
  11237. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2) : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11238. }
  11239. this._xi = x2;
  11240. this._yi = y2;
  11241. return this;
  11242. },
  11243. /**
  11244. * @param {number} cx
  11245. * @param {number} cy
  11246. * @param {number} r
  11247. * @param {number} startAngle
  11248. * @param {number} endAngle
  11249. * @param {boolean} anticlockwise
  11250. * @return {module:zrender/core/PathProxy}
  11251. */
  11252. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11253. this.addData(CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1);
  11254. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11255. this._xi = mathCos$1(endAngle) * r + cx;
  11256. this._yi = mathSin$1(endAngle) * r + cy;
  11257. return this;
  11258. },
  11259. // TODO
  11260. arcTo: function (x1, y1, x2, y2, radius) {
  11261. if (this._ctx) {
  11262. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11263. }
  11264. return this;
  11265. },
  11266. // TODO
  11267. rect: function (x, y, w, h) {
  11268. this._ctx && this._ctx.rect(x, y, w, h);
  11269. this.addData(CMD.R, x, y, w, h);
  11270. return this;
  11271. },
  11272. /**
  11273. * @return {module:zrender/core/PathProxy}
  11274. */
  11275. closePath: function () {
  11276. this.addData(CMD.Z);
  11277. var ctx = this._ctx;
  11278. var x0 = this._x0;
  11279. var y0 = this._y0;
  11280. if (ctx) {
  11281. this._needsDash() && this._dashedLineTo(x0, y0);
  11282. ctx.closePath();
  11283. }
  11284. this._xi = x0;
  11285. this._yi = y0;
  11286. return this;
  11287. },
  11288. /**
  11289. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11290. * stroke 同样
  11291. * @param {CanvasRenderingContext2D} ctx
  11292. * @return {module:zrender/core/PathProxy}
  11293. */
  11294. fill: function (ctx) {
  11295. ctx && ctx.fill();
  11296. this.toStatic();
  11297. },
  11298. /**
  11299. * @param {CanvasRenderingContext2D} ctx
  11300. * @return {module:zrender/core/PathProxy}
  11301. */
  11302. stroke: function (ctx) {
  11303. ctx && ctx.stroke();
  11304. this.toStatic();
  11305. },
  11306. /**
  11307. * 必须在其它绘制命令前调用
  11308. * Must be invoked before all other path drawing methods
  11309. * @return {module:zrender/core/PathProxy}
  11310. */
  11311. setLineDash: function (lineDash) {
  11312. if (lineDash instanceof Array) {
  11313. this._lineDash = lineDash;
  11314. this._dashIdx = 0;
  11315. var lineDashSum = 0;
  11316. for (var i = 0; i < lineDash.length; i++) {
  11317. lineDashSum += lineDash[i];
  11318. }
  11319. this._dashSum = lineDashSum;
  11320. }
  11321. return this;
  11322. },
  11323. /**
  11324. * 必须在其它绘制命令前调用
  11325. * Must be invoked before all other path drawing methods
  11326. * @return {module:zrender/core/PathProxy}
  11327. */
  11328. setLineDashOffset: function (offset) {
  11329. this._dashOffset = offset;
  11330. return this;
  11331. },
  11332. /**
  11333. *
  11334. * @return {boolean}
  11335. */
  11336. len: function () {
  11337. return this._len;
  11338. },
  11339. /**
  11340. * 直接设置 Path 数据
  11341. */
  11342. setData: function (data) {
  11343. var len$$1 = data.length;
  11344. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11345. this.data = new Float32Array(len$$1);
  11346. }
  11347. for (var i = 0; i < len$$1; i++) {
  11348. this.data[i] = data[i];
  11349. }
  11350. this._len = len$$1;
  11351. },
  11352. /**
  11353. * 添加子路径
  11354. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11355. */
  11356. appendPath: function (path) {
  11357. if (!(path instanceof Array)) {
  11358. path = [path];
  11359. }
  11360. var len$$1 = path.length;
  11361. var appendSize = 0;
  11362. var offset = this._len;
  11363. for (var i = 0; i < len$$1; i++) {
  11364. appendSize += path[i].len();
  11365. }
  11366. if (hasTypedArray && this.data instanceof Float32Array) {
  11367. this.data = new Float32Array(offset + appendSize);
  11368. }
  11369. for (var i = 0; i < len$$1; i++) {
  11370. var appendPathData = path[i].data;
  11371. for (var k = 0; k < appendPathData.length; k++) {
  11372. this.data[offset++] = appendPathData[k];
  11373. }
  11374. }
  11375. this._len = offset;
  11376. },
  11377. /**
  11378. * 填充 Path 数据。
  11379. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11380. */
  11381. addData: function (cmd) {
  11382. if (!this._saveData) {
  11383. return;
  11384. }
  11385. var data = this.data;
  11386. if (this._len + arguments.length > data.length) {
  11387. // 因为之前的数组已经转换成静态的 Float32Array
  11388. // 所以不够用时需要扩展一个新的动态数组
  11389. this._expandData();
  11390. data = this.data;
  11391. }
  11392. for (var i = 0; i < arguments.length; i++) {
  11393. data[this._len++] = arguments[i];
  11394. }
  11395. this._prevCmd = cmd;
  11396. },
  11397. _expandData: function () {
  11398. // Only if data is Float32Array
  11399. if (!(this.data instanceof Array)) {
  11400. var newData = [];
  11401. for (var i = 0; i < this._len; i++) {
  11402. newData[i] = this.data[i];
  11403. }
  11404. this.data = newData;
  11405. }
  11406. },
  11407. /**
  11408. * If needs js implemented dashed line
  11409. * @return {boolean}
  11410. * @private
  11411. */
  11412. _needsDash: function () {
  11413. return this._lineDash;
  11414. },
  11415. _dashedLineTo: function (x1, y1) {
  11416. var dashSum = this._dashSum;
  11417. var offset = this._dashOffset;
  11418. var lineDash = this._lineDash;
  11419. var ctx = this._ctx;
  11420. var x0 = this._xi;
  11421. var y0 = this._yi;
  11422. var dx = x1 - x0;
  11423. var dy = y1 - y0;
  11424. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11425. var x = x0;
  11426. var y = y0;
  11427. var dash;
  11428. var nDash = lineDash.length;
  11429. var idx;
  11430. dx /= dist$$1;
  11431. dy /= dist$$1;
  11432. if (offset < 0) {
  11433. // Convert to positive offset
  11434. offset = dashSum + offset;
  11435. }
  11436. offset %= dashSum;
  11437. x -= offset * dx;
  11438. y -= offset * dy;
  11439. while (dx > 0 && x <= x1 || dx < 0 && x >= x1 || dx === 0 && (dy > 0 && y <= y1 || dy < 0 && y >= y1)) {
  11440. idx = this._dashIdx;
  11441. dash = lineDash[idx];
  11442. x += dx * dash;
  11443. y += dy * dash;
  11444. this._dashIdx = (idx + 1) % nDash; // Skip positive offset
  11445. if (dx > 0 && x < x0 || dx < 0 && x > x0 || dy > 0 && y < y0 || dy < 0 && y > y0) {
  11446. continue;
  11447. }
  11448. 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));
  11449. } // Offset for next lineTo
  11450. dx = x - x1;
  11451. dy = y - y1;
  11452. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11453. },
  11454. // Not accurate dashed line to
  11455. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11456. var dashSum = this._dashSum;
  11457. var offset = this._dashOffset;
  11458. var lineDash = this._lineDash;
  11459. var ctx = this._ctx;
  11460. var x0 = this._xi;
  11461. var y0 = this._yi;
  11462. var t;
  11463. var dx;
  11464. var dy;
  11465. var cubicAt$$1 = cubicAt;
  11466. var bezierLen = 0;
  11467. var idx = this._dashIdx;
  11468. var nDash = lineDash.length;
  11469. var x;
  11470. var y;
  11471. var tmpLen = 0;
  11472. if (offset < 0) {
  11473. // Convert to positive offset
  11474. offset = dashSum + offset;
  11475. }
  11476. offset %= dashSum; // Bezier approx length
  11477. for (t = 0; t < 1; t += 0.1) {
  11478. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1) - cubicAt$$1(x0, x1, x2, x3, t);
  11479. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1) - cubicAt$$1(y0, y1, y2, y3, t);
  11480. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11481. } // Find idx after add offset
  11482. for (; idx < nDash; idx++) {
  11483. tmpLen += lineDash[idx];
  11484. if (tmpLen > offset) {
  11485. break;
  11486. }
  11487. }
  11488. t = (tmpLen - offset) / bezierLen;
  11489. while (t <= 1) {
  11490. x = cubicAt$$1(x0, x1, x2, x3, t);
  11491. y = cubicAt$$1(y0, y1, y2, y3, t); // Use line to approximate dashed bezier
  11492. // Bad result if dash is long
  11493. idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  11494. t += lineDash[idx] / bezierLen;
  11495. idx = (idx + 1) % nDash;
  11496. } // Finish the last segment and calculate the new offset
  11497. idx % 2 !== 0 && ctx.lineTo(x3, y3);
  11498. dx = x3 - x;
  11499. dy = y3 - y;
  11500. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11501. },
  11502. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11503. // Convert quadratic to cubic using degree elevation
  11504. var x3 = x2;
  11505. var y3 = y2;
  11506. x2 = (x2 + 2 * x1) / 3;
  11507. y2 = (y2 + 2 * y1) / 3;
  11508. x1 = (this._xi + 2 * x1) / 3;
  11509. y1 = (this._yi + 2 * y1) / 3;
  11510. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11511. },
  11512. /**
  11513. * 转成静态的 Float32Array 减少堆内存占用
  11514. * Convert dynamic array to static Float32Array
  11515. */
  11516. toStatic: function () {
  11517. var data = this.data;
  11518. if (data instanceof Array) {
  11519. data.length = this._len;
  11520. if (hasTypedArray) {
  11521. this.data = new Float32Array(data);
  11522. }
  11523. }
  11524. },
  11525. /**
  11526. * @return {module:zrender/core/BoundingRect}
  11527. */
  11528. getBoundingRect: function () {
  11529. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11530. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11531. var data = this.data;
  11532. var xi = 0;
  11533. var yi = 0;
  11534. var x0 = 0;
  11535. var y0 = 0;
  11536. for (var i = 0; i < data.length;) {
  11537. var cmd = data[i++];
  11538. if (i === 1) {
  11539. // 如果第一个命令是 L, C, Q
  11540. // 则 previous point 同绘制命令的第一个 point
  11541. //
  11542. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11543. xi = data[i];
  11544. yi = data[i + 1];
  11545. x0 = xi;
  11546. y0 = yi;
  11547. }
  11548. switch (cmd) {
  11549. case CMD.M:
  11550. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11551. // 在 closePath 的时候使用
  11552. x0 = data[i++];
  11553. y0 = data[i++];
  11554. xi = x0;
  11555. yi = y0;
  11556. min2[0] = x0;
  11557. min2[1] = y0;
  11558. max2[0] = x0;
  11559. max2[1] = y0;
  11560. break;
  11561. case CMD.L:
  11562. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11563. xi = data[i++];
  11564. yi = data[i++];
  11565. break;
  11566. case CMD.C:
  11567. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  11568. xi = data[i++];
  11569. yi = data[i++];
  11570. break;
  11571. case CMD.Q:
  11572. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  11573. xi = data[i++];
  11574. yi = data[i++];
  11575. break;
  11576. case CMD.A:
  11577. // TODO Arc 判断的开销比较大
  11578. var cx = data[i++];
  11579. var cy = data[i++];
  11580. var rx = data[i++];
  11581. var ry = data[i++];
  11582. var startAngle = data[i++];
  11583. var endAngle = data[i++] + startAngle; // TODO Arc 旋转
  11584. i += 1;
  11585. var anticlockwise = 1 - data[i++];
  11586. if (i === 1) {
  11587. // 直接使用 arc 命令
  11588. // 第一个命令起点还未定义
  11589. x0 = mathCos$1(startAngle) * rx + cx;
  11590. y0 = mathSin$1(startAngle) * ry + cy;
  11591. }
  11592. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  11593. xi = mathCos$1(endAngle) * rx + cx;
  11594. yi = mathSin$1(endAngle) * ry + cy;
  11595. break;
  11596. case CMD.R:
  11597. x0 = xi = data[i++];
  11598. y0 = yi = data[i++];
  11599. var width = data[i++];
  11600. var height = data[i++]; // Use fromLine
  11601. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11602. break;
  11603. case CMD.Z:
  11604. xi = x0;
  11605. yi = y0;
  11606. break;
  11607. } // Union
  11608. min(min$1, min$1, min2);
  11609. max(max$1, max$1, max2);
  11610. } // No data
  11611. if (i === 0) {
  11612. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11613. }
  11614. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  11615. },
  11616. /**
  11617. * Rebuild path from current data
  11618. * Rebuild path will not consider javascript implemented line dash.
  11619. * @param {CanvasRenderingContext2D} ctx
  11620. */
  11621. rebuildPath: function (ctx) {
  11622. var d = this.data;
  11623. var x0;
  11624. var y0;
  11625. var xi;
  11626. var yi;
  11627. var x;
  11628. var y;
  11629. var ux = this._ux;
  11630. var uy = this._uy;
  11631. var len$$1 = this._len;
  11632. for (var i = 0; i < len$$1;) {
  11633. var cmd = d[i++];
  11634. if (i === 1) {
  11635. // 如果第一个命令是 L, C, Q
  11636. // 则 previous point 同绘制命令的第一个 point
  11637. //
  11638. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11639. xi = d[i];
  11640. yi = d[i + 1];
  11641. x0 = xi;
  11642. y0 = yi;
  11643. }
  11644. switch (cmd) {
  11645. case CMD.M:
  11646. x0 = xi = d[i++];
  11647. y0 = yi = d[i++];
  11648. ctx.moveTo(xi, yi);
  11649. break;
  11650. case CMD.L:
  11651. x = d[i++];
  11652. y = d[i++]; // Not draw too small seg between
  11653. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11654. ctx.lineTo(x, y);
  11655. xi = x;
  11656. yi = y;
  11657. }
  11658. break;
  11659. case CMD.C:
  11660. ctx.bezierCurveTo(d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]);
  11661. xi = d[i - 2];
  11662. yi = d[i - 1];
  11663. break;
  11664. case CMD.Q:
  11665. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11666. xi = d[i - 2];
  11667. yi = d[i - 1];
  11668. break;
  11669. case CMD.A:
  11670. var cx = d[i++];
  11671. var cy = d[i++];
  11672. var rx = d[i++];
  11673. var ry = d[i++];
  11674. var theta = d[i++];
  11675. var dTheta = d[i++];
  11676. var psi = d[i++];
  11677. var fs = d[i++];
  11678. var r = rx > ry ? rx : ry;
  11679. var scaleX = rx > ry ? 1 : rx / ry;
  11680. var scaleY = rx > ry ? ry / rx : 1;
  11681. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11682. var endAngle = theta + dTheta;
  11683. if (isEllipse) {
  11684. ctx.translate(cx, cy);
  11685. ctx.rotate(psi);
  11686. ctx.scale(scaleX, scaleY);
  11687. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11688. ctx.scale(1 / scaleX, 1 / scaleY);
  11689. ctx.rotate(-psi);
  11690. ctx.translate(-cx, -cy);
  11691. } else {
  11692. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11693. }
  11694. if (i === 1) {
  11695. // 直接使用 arc 命令
  11696. // 第一个命令起点还未定义
  11697. x0 = mathCos$1(theta) * rx + cx;
  11698. y0 = mathSin$1(theta) * ry + cy;
  11699. }
  11700. xi = mathCos$1(endAngle) * rx + cx;
  11701. yi = mathSin$1(endAngle) * ry + cy;
  11702. break;
  11703. case CMD.R:
  11704. x0 = xi = d[i];
  11705. y0 = yi = d[i + 1];
  11706. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11707. break;
  11708. case CMD.Z:
  11709. ctx.closePath();
  11710. xi = x0;
  11711. yi = y0;
  11712. }
  11713. }
  11714. }
  11715. };
  11716. PathProxy.CMD = CMD;
  11717. /**
  11718. * 线段包含判断
  11719. * @param {number} x0
  11720. * @param {number} y0
  11721. * @param {number} x1
  11722. * @param {number} y1
  11723. * @param {number} lineWidth
  11724. * @param {number} x
  11725. * @param {number} y
  11726. * @return {boolean}
  11727. */
  11728. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11729. if (lineWidth === 0) {
  11730. return false;
  11731. }
  11732. var _l = lineWidth;
  11733. var _a = 0;
  11734. var _b = x0; // Quick reject
  11735. if (y > y0 + _l && y > y1 + _l || y < y0 - _l && y < y1 - _l || x > x0 + _l && x > x1 + _l || x < x0 - _l && x < x1 - _l) {
  11736. return false;
  11737. }
  11738. if (x0 !== x1) {
  11739. _a = (y0 - y1) / (x0 - x1);
  11740. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11741. } else {
  11742. return Math.abs(x - x0) <= _l / 2;
  11743. }
  11744. var tmp = _a * x - y + _b;
  11745. var _s = tmp * tmp / (_a * _a + 1);
  11746. return _s <= _l / 2 * _l / 2;
  11747. }
  11748. /**
  11749. * 三次贝塞尔曲线描边包含判断
  11750. * @param {number} x0
  11751. * @param {number} y0
  11752. * @param {number} x1
  11753. * @param {number} y1
  11754. * @param {number} x2
  11755. * @param {number} y2
  11756. * @param {number} x3
  11757. * @param {number} y3
  11758. * @param {number} lineWidth
  11759. * @param {number} x
  11760. * @param {number} y
  11761. * @return {boolean}
  11762. */
  11763. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11764. if (lineWidth === 0) {
  11765. return false;
  11766. }
  11767. var _l = lineWidth; // Quick reject
  11768. if (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l) {
  11769. return false;
  11770. }
  11771. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  11772. return d <= _l / 2;
  11773. }
  11774. /**
  11775. * 二次贝塞尔曲线描边包含判断
  11776. * @param {number} x0
  11777. * @param {number} y0
  11778. * @param {number} x1
  11779. * @param {number} y1
  11780. * @param {number} x2
  11781. * @param {number} y2
  11782. * @param {number} lineWidth
  11783. * @param {number} x
  11784. * @param {number} y
  11785. * @return {boolean}
  11786. */
  11787. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11788. if (lineWidth === 0) {
  11789. return false;
  11790. }
  11791. var _l = lineWidth; // Quick reject
  11792. if (y > y0 + _l && y > y1 + _l && y > y2 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l) {
  11793. return false;
  11794. }
  11795. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  11796. return d <= _l / 2;
  11797. }
  11798. var PI2$3 = Math.PI * 2;
  11799. function normalizeRadian(angle) {
  11800. angle %= PI2$3;
  11801. if (angle < 0) {
  11802. angle += PI2$3;
  11803. }
  11804. return angle;
  11805. }
  11806. var PI2$2 = Math.PI * 2;
  11807. /**
  11808. * 圆弧描边包含判断
  11809. * @param {number} cx
  11810. * @param {number} cy
  11811. * @param {number} r
  11812. * @param {number} startAngle
  11813. * @param {number} endAngle
  11814. * @param {boolean} anticlockwise
  11815. * @param {number} lineWidth
  11816. * @param {number} x
  11817. * @param {number} y
  11818. * @return {Boolean}
  11819. */
  11820. function containStroke$4(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  11821. if (lineWidth === 0) {
  11822. return false;
  11823. }
  11824. var _l = lineWidth;
  11825. x -= cx;
  11826. y -= cy;
  11827. var d = Math.sqrt(x * x + y * y);
  11828. if (d - _l > r || d + _l < r) {
  11829. return false;
  11830. }
  11831. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11832. // Is a circle
  11833. return true;
  11834. }
  11835. if (anticlockwise) {
  11836. var tmp = startAngle;
  11837. startAngle = normalizeRadian(endAngle);
  11838. endAngle = normalizeRadian(tmp);
  11839. } else {
  11840. startAngle = normalizeRadian(startAngle);
  11841. endAngle = normalizeRadian(endAngle);
  11842. }
  11843. if (startAngle > endAngle) {
  11844. endAngle += PI2$2;
  11845. }
  11846. var angle = Math.atan2(y, x);
  11847. if (angle < 0) {
  11848. angle += PI2$2;
  11849. }
  11850. return angle >= startAngle && angle <= endAngle || angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle;
  11851. }
  11852. function windingLine(x0, y0, x1, y1, x, y) {
  11853. if (y > y0 && y > y1 || y < y0 && y < y1) {
  11854. return 0;
  11855. } // Ignore horizontal line
  11856. if (y1 === y0) {
  11857. return 0;
  11858. }
  11859. var dir = y1 < y0 ? 1 : -1;
  11860. var t = (y - y0) / (y1 - y0); // Avoid winding error when intersection point is the connect point of two line of polygon
  11861. if (t === 1 || t === 0) {
  11862. dir = y1 < y0 ? 0.5 : -0.5;
  11863. }
  11864. var x_ = t * (x1 - x0) + x0; // If (x, y) on the line, considered as "contain".
  11865. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11866. }
  11867. var CMD$1 = PathProxy.CMD;
  11868. var PI2$1 = Math.PI * 2;
  11869. var EPSILON$2 = 1e-4;
  11870. function isAroundEqual(a, b) {
  11871. return Math.abs(a - b) < EPSILON$2;
  11872. } // 临时数组
  11873. var roots = [-1, -1, -1];
  11874. var extrema = [-1, -1];
  11875. function swapExtrema() {
  11876. var tmp = extrema[0];
  11877. extrema[0] = extrema[1];
  11878. extrema[1] = tmp;
  11879. }
  11880. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11881. // Quick reject
  11882. if (y > y0 && y > y1 && y > y2 && y > y3 || y < y0 && y < y1 && y < y2 && y < y3) {
  11883. return 0;
  11884. }
  11885. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11886. if (nRoots === 0) {
  11887. return 0;
  11888. } else {
  11889. var w = 0;
  11890. var nExtrema = -1;
  11891. var y0_;
  11892. var y1_;
  11893. for (var i = 0; i < nRoots; i++) {
  11894. var t = roots[i]; // Avoid winding error when intersection point is the connect point of two line of polygon
  11895. var unit = t === 0 || t === 1 ? 0.5 : 1;
  11896. var x_ = cubicAt(x0, x1, x2, x3, t);
  11897. if (x_ < x) {
  11898. // Quick reject
  11899. continue;
  11900. }
  11901. if (nExtrema < 0) {
  11902. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11903. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11904. swapExtrema();
  11905. }
  11906. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11907. if (nExtrema > 1) {
  11908. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11909. }
  11910. }
  11911. if (nExtrema === 2) {
  11912. // 分成三段单调函数
  11913. if (t < extrema[0]) {
  11914. w += y0_ < y0 ? unit : -unit;
  11915. } else if (t < extrema[1]) {
  11916. w += y1_ < y0_ ? unit : -unit;
  11917. } else {
  11918. w += y3 < y1_ ? unit : -unit;
  11919. }
  11920. } else {
  11921. // 分成两段单调函数
  11922. if (t < extrema[0]) {
  11923. w += y0_ < y0 ? unit : -unit;
  11924. } else {
  11925. w += y3 < y0_ ? unit : -unit;
  11926. }
  11927. }
  11928. }
  11929. return w;
  11930. }
  11931. }
  11932. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11933. // Quick reject
  11934. if (y > y0 && y > y1 && y > y2 || y < y0 && y < y1 && y < y2) {
  11935. return 0;
  11936. }
  11937. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11938. if (nRoots === 0) {
  11939. return 0;
  11940. } else {
  11941. var t = quadraticExtremum(y0, y1, y2);
  11942. if (t >= 0 && t <= 1) {
  11943. var w = 0;
  11944. var y_ = quadraticAt(y0, y1, y2, t);
  11945. for (var i = 0; i < nRoots; i++) {
  11946. // Remove one endpoint.
  11947. var unit = roots[i] === 0 || roots[i] === 1 ? 0.5 : 1;
  11948. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11949. if (x_ < x) {
  11950. // Quick reject
  11951. continue;
  11952. }
  11953. if (roots[i] < t) {
  11954. w += y_ < y0 ? unit : -unit;
  11955. } else {
  11956. w += y2 < y_ ? unit : -unit;
  11957. }
  11958. }
  11959. return w;
  11960. } else {
  11961. // Remove one endpoint.
  11962. var unit = roots[0] === 0 || roots[0] === 1 ? 0.5 : 1;
  11963. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11964. if (x_ < x) {
  11965. // Quick reject
  11966. return 0;
  11967. }
  11968. return y2 < y0 ? unit : -unit;
  11969. }
  11970. }
  11971. } // TODO
  11972. // Arc 旋转
  11973. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  11974. y -= cy;
  11975. if (y > r || y < -r) {
  11976. return 0;
  11977. }
  11978. var tmp = Math.sqrt(r * r - y * y);
  11979. roots[0] = -tmp;
  11980. roots[1] = tmp;
  11981. var diff = Math.abs(startAngle - endAngle);
  11982. if (diff < 1e-4) {
  11983. return 0;
  11984. }
  11985. if (diff % PI2$1 < 1e-4) {
  11986. // Is a circle
  11987. startAngle = 0;
  11988. endAngle = PI2$1;
  11989. var dir = anticlockwise ? 1 : -1;
  11990. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11991. return dir;
  11992. } else {
  11993. return 0;
  11994. }
  11995. }
  11996. if (anticlockwise) {
  11997. var tmp = startAngle;
  11998. startAngle = normalizeRadian(endAngle);
  11999. endAngle = normalizeRadian(tmp);
  12000. } else {
  12001. startAngle = normalizeRadian(startAngle);
  12002. endAngle = normalizeRadian(endAngle);
  12003. }
  12004. if (startAngle > endAngle) {
  12005. endAngle += PI2$1;
  12006. }
  12007. var w = 0;
  12008. for (var i = 0; i < 2; i++) {
  12009. var x_ = roots[i];
  12010. if (x_ + cx > x) {
  12011. var angle = Math.atan2(y, x_);
  12012. var dir = anticlockwise ? 1 : -1;
  12013. if (angle < 0) {
  12014. angle = PI2$1 + angle;
  12015. }
  12016. if (angle >= startAngle && angle <= endAngle || angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle) {
  12017. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12018. dir = -dir;
  12019. }
  12020. w += dir;
  12021. }
  12022. }
  12023. }
  12024. return w;
  12025. }
  12026. function containPath(data, lineWidth, isStroke, x, y) {
  12027. var w = 0;
  12028. var xi = 0;
  12029. var yi = 0;
  12030. var x0 = 0;
  12031. var y0 = 0;
  12032. for (var i = 0; i < data.length;) {
  12033. var cmd = data[i++]; // Begin a new subpath
  12034. if (cmd === CMD$1.M && i > 1) {
  12035. // Close previous subpath
  12036. if (!isStroke) {
  12037. w += windingLine(xi, yi, x0, y0, x, y);
  12038. } // 如果被任何一个 subpath 包含
  12039. // if (w !== 0) {
  12040. // return true;
  12041. // }
  12042. }
  12043. if (i === 1) {
  12044. // 如果第一个命令是 L, C, Q
  12045. // 则 previous point 同绘制命令的第一个 point
  12046. //
  12047. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12048. xi = data[i];
  12049. yi = data[i + 1];
  12050. x0 = xi;
  12051. y0 = yi;
  12052. }
  12053. switch (cmd) {
  12054. case CMD$1.M:
  12055. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12056. // 在 closePath 的时候使用
  12057. x0 = data[i++];
  12058. y0 = data[i++];
  12059. xi = x0;
  12060. yi = y0;
  12061. break;
  12062. case CMD$1.L:
  12063. if (isStroke) {
  12064. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12065. return true;
  12066. }
  12067. } else {
  12068. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12069. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12070. }
  12071. xi = data[i++];
  12072. yi = data[i++];
  12073. break;
  12074. case CMD$1.C:
  12075. if (isStroke) {
  12076. if (containStroke$2(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  12077. return true;
  12078. }
  12079. } else {
  12080. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  12081. }
  12082. xi = data[i++];
  12083. yi = data[i++];
  12084. break;
  12085. case CMD$1.Q:
  12086. if (isStroke) {
  12087. if (containStroke$3(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  12088. return true;
  12089. }
  12090. } else {
  12091. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  12092. }
  12093. xi = data[i++];
  12094. yi = data[i++];
  12095. break;
  12096. case CMD$1.A:
  12097. // TODO Arc 判断的开销比较大
  12098. var cx = data[i++];
  12099. var cy = data[i++];
  12100. var rx = data[i++];
  12101. var ry = data[i++];
  12102. var theta = data[i++];
  12103. var dTheta = data[i++]; // TODO Arc 旋转
  12104. i += 1;
  12105. var anticlockwise = 1 - data[i++];
  12106. var x1 = Math.cos(theta) * rx + cx;
  12107. var y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  12108. if (i > 1) {
  12109. w += windingLine(xi, yi, x1, y1, x, y);
  12110. } else {
  12111. // 第一个命令起点还未定义
  12112. x0 = x1;
  12113. y0 = y1;
  12114. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12115. var _x = (x - cx) * ry / rx + cx;
  12116. if (isStroke) {
  12117. if (containStroke$4(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  12118. return true;
  12119. }
  12120. } else {
  12121. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  12122. }
  12123. xi = Math.cos(theta + dTheta) * rx + cx;
  12124. yi = Math.sin(theta + dTheta) * ry + cy;
  12125. break;
  12126. case CMD$1.R:
  12127. x0 = xi = data[i++];
  12128. y0 = yi = data[i++];
  12129. var width = data[i++];
  12130. var height = data[i++];
  12131. var x1 = x0 + width;
  12132. var y1 = y0 + height;
  12133. if (isStroke) {
  12134. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y) || containStroke$1(x1, y0, x1, y1, lineWidth, x, y) || containStroke$1(x1, y1, x0, y1, lineWidth, x, y) || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)) {
  12135. return true;
  12136. }
  12137. } else {
  12138. // FIXME Clockwise ?
  12139. w += windingLine(x1, y0, x1, y1, x, y);
  12140. w += windingLine(x0, y1, x0, y0, x, y);
  12141. }
  12142. break;
  12143. case CMD$1.Z:
  12144. if (isStroke) {
  12145. if (containStroke$1(xi, yi, x0, y0, lineWidth, x, y)) {
  12146. return true;
  12147. }
  12148. } else {
  12149. // Close a subpath
  12150. w += windingLine(xi, yi, x0, y0, x, y); // 如果被任何一个 subpath 包含
  12151. // FIXME subpaths may overlap
  12152. // if (w !== 0) {
  12153. // return true;
  12154. // }
  12155. }
  12156. xi = x0;
  12157. yi = y0;
  12158. break;
  12159. }
  12160. }
  12161. if (!isStroke && !isAroundEqual(yi, y0)) {
  12162. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12163. }
  12164. return w !== 0;
  12165. }
  12166. function contain(pathData, x, y) {
  12167. return containPath(pathData, 0, false, x, y);
  12168. }
  12169. function containStroke(pathData, lineWidth, x, y) {
  12170. return containPath(pathData, lineWidth, true, x, y);
  12171. }
  12172. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12173. var abs = Math.abs;
  12174. var pathProxyForDraw = new PathProxy(true);
  12175. /**
  12176. * @alias module:zrender/graphic/Path
  12177. * @extends module:zrender/graphic/Displayable
  12178. * @constructor
  12179. * @param {Object} opts
  12180. */
  12181. function Path(opts) {
  12182. Displayable.call(this, opts);
  12183. /**
  12184. * @type {module:zrender/core/PathProxy}
  12185. * @readOnly
  12186. */
  12187. this.path = null;
  12188. }
  12189. Path.prototype = {
  12190. constructor: Path,
  12191. type: 'path',
  12192. __dirtyPath: true,
  12193. strokeContainThreshold: 5,
  12194. // This item default to be false. But in map series in echarts,
  12195. // in order to improve performance, it should be set to true,
  12196. // so the shorty segment won't draw.
  12197. segmentIgnoreThreshold: 0,
  12198. /**
  12199. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12200. * @type {boolean}
  12201. */
  12202. subPixelOptimize: false,
  12203. brush: function (ctx, prevEl) {
  12204. var style = this.style;
  12205. var path = this.path || pathProxyForDraw;
  12206. var hasStroke = style.hasStroke();
  12207. var hasFill = style.hasFill();
  12208. var fill = style.fill;
  12209. var stroke = style.stroke;
  12210. var hasFillGradient = hasFill && !!fill.colorStops;
  12211. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  12212. var hasFillPattern = hasFill && !!fill.image;
  12213. var hasStrokePattern = hasStroke && !!stroke.image;
  12214. style.bind(ctx, this, prevEl);
  12215. this.setTransform(ctx);
  12216. if (this.__dirty) {
  12217. var rect; // Update gradient because bounding rect may changed
  12218. if (hasFillGradient) {
  12219. rect = rect || this.getBoundingRect();
  12220. this._fillGradient = style.getGradient(ctx, fill, rect);
  12221. }
  12222. if (hasStrokeGradient) {
  12223. rect = rect || this.getBoundingRect();
  12224. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12225. }
  12226. } // Use the gradient or pattern
  12227. if (hasFillGradient) {
  12228. // PENDING If may have affect the state
  12229. ctx.fillStyle = this._fillGradient;
  12230. } else if (hasFillPattern) {
  12231. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12232. }
  12233. if (hasStrokeGradient) {
  12234. ctx.strokeStyle = this._strokeGradient;
  12235. } else if (hasStrokePattern) {
  12236. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12237. }
  12238. var lineDash = style.lineDash;
  12239. var lineDashOffset = style.lineDashOffset;
  12240. var ctxLineDash = !!ctx.setLineDash; // Update path sx, sy
  12241. var scale = this.getGlobalScale();
  12242. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold); // Proxy context
  12243. // Rebuild path in following 2 cases
  12244. // 1. Path is dirty
  12245. // 2. Path needs javascript implemented lineDash stroking.
  12246. // In this case, lineDash information will not be saved in PathProxy
  12247. if (this.__dirtyPath || lineDash && !ctxLineDash && hasStroke) {
  12248. path.beginPath(ctx); // Setting line dash before build path
  12249. if (lineDash && !ctxLineDash) {
  12250. path.setLineDash(lineDash);
  12251. path.setLineDashOffset(lineDashOffset);
  12252. }
  12253. this.buildPath(path, this.shape, false); // Clear path dirty flag
  12254. if (this.path) {
  12255. this.__dirtyPath = false;
  12256. }
  12257. } else {
  12258. // Replay path building
  12259. ctx.beginPath();
  12260. this.path.rebuildPath(ctx);
  12261. }
  12262. if (hasFill) {
  12263. if (style.fillOpacity != null) {
  12264. var originalGlobalAlpha = ctx.globalAlpha;
  12265. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12266. path.fill(ctx);
  12267. ctx.globalAlpha = originalGlobalAlpha;
  12268. } else {
  12269. path.fill(ctx);
  12270. }
  12271. }
  12272. if (lineDash && ctxLineDash) {
  12273. ctx.setLineDash(lineDash);
  12274. ctx.lineDashOffset = lineDashOffset;
  12275. }
  12276. if (hasStroke) {
  12277. if (style.strokeOpacity != null) {
  12278. var originalGlobalAlpha = ctx.globalAlpha;
  12279. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12280. path.stroke(ctx);
  12281. ctx.globalAlpha = originalGlobalAlpha;
  12282. } else {
  12283. path.stroke(ctx);
  12284. }
  12285. }
  12286. if (lineDash && ctxLineDash) {
  12287. // PENDING
  12288. // Remove lineDash
  12289. ctx.setLineDash([]);
  12290. } // Draw rect text
  12291. if (style.text != null) {
  12292. // Only restore transform when needs draw text.
  12293. this.restoreTransform(ctx);
  12294. this.drawRectText(ctx, this.getBoundingRect());
  12295. }
  12296. },
  12297. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12298. // Like in circle
  12299. buildPath: function (ctx, shapeCfg, inBundle) {},
  12300. createPathProxy: function () {
  12301. this.path = new PathProxy();
  12302. },
  12303. getBoundingRect: function () {
  12304. var rect = this._rect;
  12305. var style = this.style;
  12306. var needsUpdateRect = !rect;
  12307. if (needsUpdateRect) {
  12308. var path = this.path;
  12309. if (!path) {
  12310. // Create path on demand.
  12311. path = this.path = new PathProxy();
  12312. }
  12313. if (this.__dirtyPath) {
  12314. path.beginPath();
  12315. this.buildPath(path, this.shape, false);
  12316. }
  12317. rect = path.getBoundingRect();
  12318. }
  12319. this._rect = rect;
  12320. if (style.hasStroke()) {
  12321. // Needs update rect with stroke lineWidth when
  12322. // 1. Element changes scale or lineWidth
  12323. // 2. Shape is changed
  12324. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12325. if (this.__dirty || needsUpdateRect) {
  12326. rectWithStroke.copy(rect); // FIXME Must after updateTransform
  12327. var w = style.lineWidth; // PENDING, Min line width is needed when line is horizontal or vertical
  12328. var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Only add extra hover lineWidth when there are no fill
  12329. if (!style.hasFill()) {
  12330. w = Math.max(w, this.strokeContainThreshold || 4);
  12331. } // Consider line width
  12332. // Line scale can't be 0;
  12333. if (lineScale > 1e-10) {
  12334. rectWithStroke.width += w / lineScale;
  12335. rectWithStroke.height += w / lineScale;
  12336. rectWithStroke.x -= w / lineScale / 2;
  12337. rectWithStroke.y -= w / lineScale / 2;
  12338. }
  12339. } // Return rect with stroke
  12340. return rectWithStroke;
  12341. }
  12342. return rect;
  12343. },
  12344. contain: function (x, y) {
  12345. var localPos = this.transformCoordToLocal(x, y);
  12346. var rect = this.getBoundingRect();
  12347. var style = this.style;
  12348. x = localPos[0];
  12349. y = localPos[1];
  12350. if (rect.contain(x, y)) {
  12351. var pathData = this.path.data;
  12352. if (style.hasStroke()) {
  12353. var lineWidth = style.lineWidth;
  12354. var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Line scale can't be 0;
  12355. if (lineScale > 1e-10) {
  12356. // Only add extra hover lineWidth when there are no fill
  12357. if (!style.hasFill()) {
  12358. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12359. }
  12360. if (containStroke(pathData, lineWidth / lineScale, x, y)) {
  12361. return true;
  12362. }
  12363. }
  12364. }
  12365. if (style.hasFill()) {
  12366. return contain(pathData, x, y);
  12367. }
  12368. }
  12369. return false;
  12370. },
  12371. /**
  12372. * @param {boolean} dirtyPath
  12373. */
  12374. dirty: function (dirtyPath) {
  12375. if (dirtyPath == null) {
  12376. dirtyPath = true;
  12377. } // Only mark dirty, not mark clean
  12378. if (dirtyPath) {
  12379. this.__dirtyPath = dirtyPath;
  12380. this._rect = null;
  12381. }
  12382. this.__dirty = this.__dirtyText = true;
  12383. this.__zr && this.__zr.refresh(); // Used as a clipping path
  12384. if (this.__clipTarget) {
  12385. this.__clipTarget.dirty();
  12386. }
  12387. },
  12388. /**
  12389. * Alias for animate('shape')
  12390. * @param {boolean} loop
  12391. */
  12392. animateShape: function (loop) {
  12393. return this.animate('shape', loop);
  12394. },
  12395. // Overwrite attrKV
  12396. attrKV: function (key, value) {
  12397. // FIXME
  12398. if (key === 'shape') {
  12399. this.setShape(value);
  12400. this.__dirtyPath = true;
  12401. this._rect = null;
  12402. } else {
  12403. Displayable.prototype.attrKV.call(this, key, value);
  12404. }
  12405. },
  12406. /**
  12407. * @param {Object|string} key
  12408. * @param {*} value
  12409. */
  12410. setShape: function (key, value) {
  12411. var shape = this.shape; // Path from string may not have shape
  12412. if (shape) {
  12413. if (isObject$1(key)) {
  12414. for (var name in key) {
  12415. if (key.hasOwnProperty(name)) {
  12416. shape[name] = key[name];
  12417. }
  12418. }
  12419. } else {
  12420. shape[key] = value;
  12421. }
  12422. this.dirty(true);
  12423. }
  12424. return this;
  12425. },
  12426. getLineScale: function () {
  12427. var m = this.transform; // Get the line scale.
  12428. // Determinant of `m` means how much the area is enlarged by the
  12429. // transformation. So its square root can be used as a scale factor
  12430. // for width.
  12431. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10 ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1])) : 1;
  12432. }
  12433. };
  12434. /**
  12435. * 扩展一个 Path element, 比如星形,圆等。
  12436. * Extend a path element
  12437. * @param {Object} props
  12438. * @param {string} props.type Path type
  12439. * @param {Function} props.init Initialize
  12440. * @param {Function} props.buildPath Overwrite buildPath method
  12441. * @param {Object} [props.style] Extended default style config
  12442. * @param {Object} [props.shape] Extended default shape config
  12443. */
  12444. Path.extend = function (defaults$$1) {
  12445. var Sub = function (opts) {
  12446. Path.call(this, opts);
  12447. if (defaults$$1.style) {
  12448. // Extend default style
  12449. this.style.extendFrom(defaults$$1.style, false);
  12450. } // Extend default shape
  12451. var defaultShape = defaults$$1.shape;
  12452. if (defaultShape) {
  12453. this.shape = this.shape || {};
  12454. var thisShape = this.shape;
  12455. for (var name in defaultShape) {
  12456. if (!thisShape.hasOwnProperty(name) && defaultShape.hasOwnProperty(name)) {
  12457. thisShape[name] = defaultShape[name];
  12458. }
  12459. }
  12460. }
  12461. defaults$$1.init && defaults$$1.init.call(this, opts);
  12462. };
  12463. inherits(Sub, Path); // FIXME 不能 extend position, rotation 等引用对象
  12464. for (var name in defaults$$1) {
  12465. // Extending prototype values and methods
  12466. if (name !== 'style' && name !== 'shape') {
  12467. Sub.prototype[name] = defaults$$1[name];
  12468. }
  12469. }
  12470. return Sub;
  12471. };
  12472. inherits(Path, Displayable);
  12473. var CMD$2 = PathProxy.CMD;
  12474. var points = [[], [], []];
  12475. var mathSqrt$3 = Math.sqrt;
  12476. var mathAtan2 = Math.atan2;
  12477. var transformPath = function (path, m) {
  12478. var data = path.data;
  12479. var cmd;
  12480. var nPoint;
  12481. var i;
  12482. var j;
  12483. var k;
  12484. var p;
  12485. var M = CMD$2.M;
  12486. var C = CMD$2.C;
  12487. var L = CMD$2.L;
  12488. var R = CMD$2.R;
  12489. var A = CMD$2.A;
  12490. var Q = CMD$2.Q;
  12491. for (i = 0, j = 0; i < data.length;) {
  12492. cmd = data[i++];
  12493. j = i;
  12494. nPoint = 0;
  12495. switch (cmd) {
  12496. case M:
  12497. nPoint = 1;
  12498. break;
  12499. case L:
  12500. nPoint = 1;
  12501. break;
  12502. case C:
  12503. nPoint = 3;
  12504. break;
  12505. case Q:
  12506. nPoint = 2;
  12507. break;
  12508. case A:
  12509. var x = m[4];
  12510. var y = m[5];
  12511. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12512. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12513. var angle = mathAtan2(-m[1] / sy, m[0] / sx); // cx
  12514. data[i] *= sx;
  12515. data[i++] += x; // cy
  12516. data[i] *= sy;
  12517. data[i++] += y; // Scale rx and ry
  12518. // FIXME Assume psi is 0 here
  12519. data[i++] *= sx;
  12520. data[i++] *= sy; // Start angle
  12521. data[i++] += angle; // end angle
  12522. data[i++] += angle; // FIXME psi
  12523. i += 2;
  12524. j = i;
  12525. break;
  12526. case R:
  12527. // x0, y0
  12528. p[0] = data[i++];
  12529. p[1] = data[i++];
  12530. applyTransform(p, p, m);
  12531. data[j++] = p[0];
  12532. data[j++] = p[1]; // x1, y1
  12533. p[0] += data[i++];
  12534. p[1] += data[i++];
  12535. applyTransform(p, p, m);
  12536. data[j++] = p[0];
  12537. data[j++] = p[1];
  12538. }
  12539. for (k = 0; k < nPoint; k++) {
  12540. var p = points[k];
  12541. p[0] = data[i++];
  12542. p[1] = data[i++];
  12543. applyTransform(p, p, m); // Write back
  12544. data[j++] = p[0];
  12545. data[j++] = p[1];
  12546. }
  12547. }
  12548. };
  12549. // var cc = [
  12550. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12551. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12552. // ];
  12553. var mathSqrt = Math.sqrt;
  12554. var mathSin = Math.sin;
  12555. var mathCos = Math.cos;
  12556. var PI = Math.PI;
  12557. var vMag = function (v) {
  12558. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12559. };
  12560. var vRatio = function (u, v) {
  12561. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12562. };
  12563. var vAngle = function (u, v) {
  12564. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
  12565. };
  12566. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12567. var psi = psiDeg * (PI / 180.0);
  12568. var xp = mathCos(psi) * (x1 - x2) / 2.0 + mathSin(psi) * (y1 - y2) / 2.0;
  12569. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0 + mathCos(psi) * (y1 - y2) / 2.0;
  12570. var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
  12571. if (lambda > 1) {
  12572. rx *= mathSqrt(lambda);
  12573. ry *= mathSqrt(lambda);
  12574. }
  12575. var f = (fa === fs ? -1 : 1) * mathSqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp))) || 0;
  12576. var cxp = f * rx * yp / ry;
  12577. var cyp = f * -ry * xp / rx;
  12578. var cx = (x1 + x2) / 2.0 + mathCos(psi) * cxp - mathSin(psi) * cyp;
  12579. var cy = (y1 + y2) / 2.0 + mathSin(psi) * cxp + mathCos(psi) * cyp;
  12580. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12581. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12582. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12583. var dTheta = vAngle(u, v);
  12584. if (vRatio(u, v) <= -1) {
  12585. dTheta = PI;
  12586. }
  12587. if (vRatio(u, v) >= 1) {
  12588. dTheta = 0;
  12589. }
  12590. if (fs === 0 && dTheta > 0) {
  12591. dTheta = dTheta - 2 * PI;
  12592. }
  12593. if (fs === 1 && dTheta < 0) {
  12594. dTheta = dTheta + 2 * PI;
  12595. }
  12596. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12597. }
  12598. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig; // Consider case:
  12599. // (1) delimiter can be comma or space, where continuous commas
  12600. // or spaces should be seen as one comma.
  12601. // (2) value can be like:
  12602. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12603. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12604. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g; // var valueSplitReg = /[\s,]+/;
  12605. function createPathProxyFromString(data) {
  12606. if (!data) {
  12607. return new PathProxy();
  12608. } // var data = data.replace(/-/g, ' -')
  12609. // .replace(/ /g, ' ')
  12610. // .replace(/ /g, ',')
  12611. // .replace(/,,/g, ',');
  12612. // var n;
  12613. // create pipes so that we can split the data
  12614. // for (n = 0; n < cc.length; n++) {
  12615. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12616. // }
  12617. // data = data.replace(/-/g, ',-');
  12618. // create array
  12619. // var arr = cs.split('|');
  12620. // init context point
  12621. var cpx = 0;
  12622. var cpy = 0;
  12623. var subpathX = cpx;
  12624. var subpathY = cpy;
  12625. var prevCmd;
  12626. var path = new PathProxy();
  12627. var CMD = PathProxy.CMD; // commandReg.lastIndex = 0;
  12628. // var cmdResult;
  12629. // while ((cmdResult = commandReg.exec(data)) != null) {
  12630. // var cmdStr = cmdResult[1];
  12631. // var cmdContent = cmdResult[2];
  12632. var cmdList = data.match(commandReg);
  12633. for (var l = 0; l < cmdList.length; l++) {
  12634. var cmdText = cmdList[l];
  12635. var cmdStr = cmdText.charAt(0);
  12636. var cmd; // String#split is faster a little bit than String#replace or RegExp#exec.
  12637. // var p = cmdContent.split(valueSplitReg);
  12638. // var pLen = 0;
  12639. // for (var i = 0; i < p.length; i++) {
  12640. // // '' and other invalid str => NaN
  12641. // var val = parseFloat(p[i]);
  12642. // !isNaN(val) && (p[pLen++] = val);
  12643. // }
  12644. var p = cmdText.match(numberReg) || [];
  12645. var pLen = p.length;
  12646. for (var i = 0; i < pLen; i++) {
  12647. p[i] = parseFloat(p[i]);
  12648. }
  12649. var off = 0;
  12650. while (off < pLen) {
  12651. var ctlPtx;
  12652. var ctlPty;
  12653. var rx;
  12654. var ry;
  12655. var psi;
  12656. var fa;
  12657. var fs;
  12658. var x1 = cpx;
  12659. var y1 = cpy; // convert l, H, h, V, and v to L
  12660. switch (cmdStr) {
  12661. case 'l':
  12662. cpx += p[off++];
  12663. cpy += p[off++];
  12664. cmd = CMD.L;
  12665. path.addData(cmd, cpx, cpy);
  12666. break;
  12667. case 'L':
  12668. cpx = p[off++];
  12669. cpy = p[off++];
  12670. cmd = CMD.L;
  12671. path.addData(cmd, cpx, cpy);
  12672. break;
  12673. case 'm':
  12674. cpx += p[off++];
  12675. cpy += p[off++];
  12676. cmd = CMD.M;
  12677. path.addData(cmd, cpx, cpy);
  12678. subpathX = cpx;
  12679. subpathY = cpy;
  12680. cmdStr = 'l';
  12681. break;
  12682. case 'M':
  12683. cpx = p[off++];
  12684. cpy = p[off++];
  12685. cmd = CMD.M;
  12686. path.addData(cmd, cpx, cpy);
  12687. subpathX = cpx;
  12688. subpathY = cpy;
  12689. cmdStr = 'L';
  12690. break;
  12691. case 'h':
  12692. cpx += p[off++];
  12693. cmd = CMD.L;
  12694. path.addData(cmd, cpx, cpy);
  12695. break;
  12696. case 'H':
  12697. cpx = p[off++];
  12698. cmd = CMD.L;
  12699. path.addData(cmd, cpx, cpy);
  12700. break;
  12701. case 'v':
  12702. cpy += p[off++];
  12703. cmd = CMD.L;
  12704. path.addData(cmd, cpx, cpy);
  12705. break;
  12706. case 'V':
  12707. cpy = p[off++];
  12708. cmd = CMD.L;
  12709. path.addData(cmd, cpx, cpy);
  12710. break;
  12711. case 'C':
  12712. cmd = CMD.C;
  12713. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12714. cpx = p[off - 2];
  12715. cpy = p[off - 1];
  12716. break;
  12717. case 'c':
  12718. cmd = CMD.C;
  12719. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12720. cpx += p[off - 2];
  12721. cpy += p[off - 1];
  12722. break;
  12723. case 'S':
  12724. ctlPtx = cpx;
  12725. ctlPty = cpy;
  12726. var len = path.len();
  12727. var pathData = path.data;
  12728. if (prevCmd === CMD.C) {
  12729. ctlPtx += cpx - pathData[len - 4];
  12730. ctlPty += cpy - pathData[len - 3];
  12731. }
  12732. cmd = CMD.C;
  12733. x1 = p[off++];
  12734. y1 = p[off++];
  12735. cpx = p[off++];
  12736. cpy = p[off++];
  12737. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12738. break;
  12739. case 's':
  12740. ctlPtx = cpx;
  12741. ctlPty = cpy;
  12742. var len = path.len();
  12743. var pathData = path.data;
  12744. if (prevCmd === CMD.C) {
  12745. ctlPtx += cpx - pathData[len - 4];
  12746. ctlPty += cpy - pathData[len - 3];
  12747. }
  12748. cmd = CMD.C;
  12749. x1 = cpx + p[off++];
  12750. y1 = cpy + p[off++];
  12751. cpx += p[off++];
  12752. cpy += p[off++];
  12753. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12754. break;
  12755. case 'Q':
  12756. x1 = p[off++];
  12757. y1 = p[off++];
  12758. cpx = p[off++];
  12759. cpy = p[off++];
  12760. cmd = CMD.Q;
  12761. path.addData(cmd, x1, y1, cpx, cpy);
  12762. break;
  12763. case 'q':
  12764. x1 = p[off++] + cpx;
  12765. y1 = p[off++] + cpy;
  12766. cpx += p[off++];
  12767. cpy += p[off++];
  12768. cmd = CMD.Q;
  12769. path.addData(cmd, x1, y1, cpx, cpy);
  12770. break;
  12771. case 'T':
  12772. ctlPtx = cpx;
  12773. ctlPty = cpy;
  12774. var len = path.len();
  12775. var pathData = path.data;
  12776. if (prevCmd === CMD.Q) {
  12777. ctlPtx += cpx - pathData[len - 4];
  12778. ctlPty += cpy - pathData[len - 3];
  12779. }
  12780. cpx = p[off++];
  12781. cpy = p[off++];
  12782. cmd = CMD.Q;
  12783. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12784. break;
  12785. case 't':
  12786. ctlPtx = cpx;
  12787. ctlPty = cpy;
  12788. var len = path.len();
  12789. var pathData = path.data;
  12790. if (prevCmd === CMD.Q) {
  12791. ctlPtx += cpx - pathData[len - 4];
  12792. ctlPty += cpy - pathData[len - 3];
  12793. }
  12794. cpx += p[off++];
  12795. cpy += p[off++];
  12796. cmd = CMD.Q;
  12797. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12798. break;
  12799. case 'A':
  12800. rx = p[off++];
  12801. ry = p[off++];
  12802. psi = p[off++];
  12803. fa = p[off++];
  12804. fs = p[off++];
  12805. x1 = cpx, y1 = cpy;
  12806. cpx = p[off++];
  12807. cpy = p[off++];
  12808. cmd = CMD.A;
  12809. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12810. break;
  12811. case 'a':
  12812. rx = p[off++];
  12813. ry = p[off++];
  12814. psi = p[off++];
  12815. fa = p[off++];
  12816. fs = p[off++];
  12817. x1 = cpx, y1 = cpy;
  12818. cpx += p[off++];
  12819. cpy += p[off++];
  12820. cmd = CMD.A;
  12821. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12822. break;
  12823. }
  12824. }
  12825. if (cmdStr === 'z' || cmdStr === 'Z') {
  12826. cmd = CMD.Z;
  12827. path.addData(cmd); // z may be in the middle of the path.
  12828. cpx = subpathX;
  12829. cpy = subpathY;
  12830. }
  12831. prevCmd = cmd;
  12832. }
  12833. path.toStatic();
  12834. return path;
  12835. } // TODO Optimize double memory cost problem
  12836. function createPathOptions(str, opts) {
  12837. var pathProxy = createPathProxyFromString(str);
  12838. opts = opts || {};
  12839. opts.buildPath = function (path) {
  12840. if (path.setData) {
  12841. path.setData(pathProxy.data); // Svg and vml renderer don't have context
  12842. var ctx = path.getContext();
  12843. if (ctx) {
  12844. path.rebuildPath(ctx);
  12845. }
  12846. } else {
  12847. var ctx = path;
  12848. pathProxy.rebuildPath(ctx);
  12849. }
  12850. };
  12851. opts.applyTransform = function (m) {
  12852. transformPath(pathProxy, m);
  12853. this.dirty(true);
  12854. };
  12855. return opts;
  12856. }
  12857. /**
  12858. * Create a Path object from path string data
  12859. * http://www.w3.org/TR/SVG/paths.html#PathData
  12860. * @param {Object} opts Other options
  12861. */
  12862. function createFromString(str, opts) {
  12863. return new Path(createPathOptions(str, opts));
  12864. }
  12865. /**
  12866. * Create a Path class from path string data
  12867. * @param {string} str
  12868. * @param {Object} opts Other options
  12869. */
  12870. function extendFromString(str, opts) {
  12871. return Path.extend(createPathOptions(str, opts));
  12872. }
  12873. /**
  12874. * Merge multiple paths
  12875. */
  12876. // TODO Apply transform
  12877. // TODO stroke dash
  12878. // TODO Optimize double memory cost problem
  12879. function mergePath$1(pathEls, opts) {
  12880. var pathList = [];
  12881. var len = pathEls.length;
  12882. for (var i = 0; i < len; i++) {
  12883. var pathEl = pathEls[i];
  12884. if (!pathEl.path) {
  12885. pathEl.createPathProxy();
  12886. }
  12887. if (pathEl.__dirtyPath) {
  12888. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12889. }
  12890. pathList.push(pathEl.path);
  12891. }
  12892. var pathBundle = new Path(opts); // Need path proxy.
  12893. pathBundle.createPathProxy();
  12894. pathBundle.buildPath = function (path) {
  12895. path.appendPath(pathList); // Svg and vml renderer don't have context
  12896. var ctx = path.getContext();
  12897. if (ctx) {
  12898. path.rebuildPath(ctx);
  12899. }
  12900. };
  12901. return pathBundle;
  12902. }
  12903. /**
  12904. * @alias zrender/graphic/Text
  12905. * @extends module:zrender/graphic/Displayable
  12906. * @constructor
  12907. * @param {Object} opts
  12908. */
  12909. var Text = function (opts) {
  12910. // jshint ignore:line
  12911. Displayable.call(this, opts);
  12912. };
  12913. Text.prototype = {
  12914. constructor: Text,
  12915. type: 'text',
  12916. brush: function (ctx, prevEl) {
  12917. var style = this.style; // Optimize, avoid normalize every time.
  12918. this.__dirty && normalizeTextStyle(style, true); // Use props with prefix 'text'.
  12919. style.fill = style.stroke = style.shadowBlur = style.shadowColor = style.shadowOffsetX = style.shadowOffsetY = null;
  12920. var text = style.text; // Convert to string
  12921. text != null && (text += ''); // Do not apply style.bind in Text node. Because the real bind job
  12922. // is in textHelper.renderText, and performance of text render should
  12923. // be considered.
  12924. // style.bind(ctx, this, prevEl);
  12925. if (!needDrawText(text, style)) {
  12926. // The current el.style is not applied
  12927. // and should not be used as cache.
  12928. ctx.__attrCachedBy = ContextCachedBy.NONE;
  12929. return;
  12930. }
  12931. this.setTransform(ctx);
  12932. renderText(this, ctx, text, style, null, prevEl);
  12933. this.restoreTransform(ctx);
  12934. },
  12935. getBoundingRect: function () {
  12936. var style = this.style; // Optimize, avoid normalize every time.
  12937. this.__dirty && normalizeTextStyle(style, true);
  12938. if (!this._rect) {
  12939. var text = style.text;
  12940. text != null ? text += '' : text = '';
  12941. var rect = getBoundingRect(style.text + '', style.font, style.textAlign, style.textVerticalAlign, style.textPadding, style.textLineHeight, style.rich);
  12942. rect.x += style.x || 0;
  12943. rect.y += style.y || 0;
  12944. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12945. var w = style.textStrokeWidth;
  12946. rect.x -= w / 2;
  12947. rect.y -= w / 2;
  12948. rect.width += w;
  12949. rect.height += w;
  12950. }
  12951. this._rect = rect;
  12952. }
  12953. return this._rect;
  12954. }
  12955. };
  12956. inherits(Text, Displayable);
  12957. /**
  12958. * 圆形
  12959. * @module zrender/shape/Circle
  12960. */
  12961. var Circle = Path.extend({
  12962. type: 'circle',
  12963. shape: {
  12964. cx: 0,
  12965. cy: 0,
  12966. r: 0
  12967. },
  12968. buildPath: function (ctx, shape, inBundle) {
  12969. // Better stroking in ShapeBundle
  12970. // Always do it may have performence issue ( fill may be 2x more cost)
  12971. if (inBundle) {
  12972. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12973. } // else {
  12974. // if (ctx.allocate && !ctx.data.length) {
  12975. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12976. // }
  12977. // }
  12978. // Better stroking in ShapeBundle
  12979. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12980. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12981. }
  12982. });
  12983. // where exception "unexpected call to method or property access"
  12984. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12985. // whose area size is zero is drawn and ctx.clip() is called and
  12986. // shadowBlur is set. See #4572, #3112, #5777.
  12987. // (e.g.,
  12988. // ctx.moveTo(10, 10);
  12989. // ctx.lineTo(20, 10);
  12990. // ctx.closePath();
  12991. // ctx.clip();
  12992. // ctx.shadowBlur = 10;
  12993. // ...
  12994. // ctx.fill();
  12995. // )
  12996. var shadowTemp = [['shadowBlur', 0], ['shadowColor', '#000'], ['shadowOffsetX', 0], ['shadowOffsetY', 0]];
  12997. var fixClipWithShadow = function (orignalBrush) {
  12998. // version string can be: '11.0'
  12999. return env$1.browser.ie && env$1.browser.version >= 11 ? function () {
  13000. var clipPaths = this.__clipPaths;
  13001. var style = this.style;
  13002. var modified;
  13003. if (clipPaths) {
  13004. for (var i = 0; i < clipPaths.length; i++) {
  13005. var clipPath = clipPaths[i];
  13006. var shape = clipPath && clipPath.shape;
  13007. var type = clipPath && clipPath.type;
  13008. if (shape && (type === 'sector' && shape.startAngle === shape.endAngle || type === 'rect' && (!shape.width || !shape.height))) {
  13009. for (var j = 0; j < shadowTemp.length; j++) {
  13010. // It is save to put shadowTemp static, because shadowTemp
  13011. // will be all modified each item brush called.
  13012. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13013. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13014. }
  13015. modified = true;
  13016. break;
  13017. }
  13018. }
  13019. }
  13020. orignalBrush.apply(this, arguments);
  13021. if (modified) {
  13022. for (var j = 0; j < shadowTemp.length; j++) {
  13023. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13024. }
  13025. }
  13026. } : orignalBrush;
  13027. };
  13028. /**
  13029. * 扇形
  13030. * @module zrender/graphic/shape/Sector
  13031. */
  13032. var Sector = Path.extend({
  13033. type: 'sector',
  13034. shape: {
  13035. cx: 0,
  13036. cy: 0,
  13037. r0: 0,
  13038. r: 0,
  13039. startAngle: 0,
  13040. endAngle: Math.PI * 2,
  13041. clockwise: true
  13042. },
  13043. brush: fixClipWithShadow(Path.prototype.brush),
  13044. buildPath: function (ctx, shape) {
  13045. var x = shape.cx;
  13046. var y = shape.cy;
  13047. var r0 = Math.max(shape.r0 || 0, 0);
  13048. var r = Math.max(shape.r, 0);
  13049. var startAngle = shape.startAngle;
  13050. var endAngle = shape.endAngle;
  13051. var clockwise = shape.clockwise;
  13052. var unitX = Math.cos(startAngle);
  13053. var unitY = Math.sin(startAngle);
  13054. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13055. ctx.lineTo(unitX * r + x, unitY * r + y);
  13056. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13057. ctx.lineTo(Math.cos(endAngle) * r0 + x, Math.sin(endAngle) * r0 + y);
  13058. if (r0 !== 0) {
  13059. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13060. }
  13061. ctx.closePath();
  13062. }
  13063. });
  13064. /**
  13065. * 圆环
  13066. * @module zrender/graphic/shape/Ring
  13067. */
  13068. var Ring = Path.extend({
  13069. type: 'ring',
  13070. shape: {
  13071. cx: 0,
  13072. cy: 0,
  13073. r: 0,
  13074. r0: 0
  13075. },
  13076. buildPath: function (ctx, shape) {
  13077. var x = shape.cx;
  13078. var y = shape.cy;
  13079. var PI2 = Math.PI * 2;
  13080. ctx.moveTo(x + shape.r, y);
  13081. ctx.arc(x, y, shape.r, 0, PI2, false);
  13082. ctx.moveTo(x + shape.r0, y);
  13083. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13084. }
  13085. });
  13086. /**
  13087. * Catmull-Rom spline 插值折线
  13088. * @module zrender/shape/util/smoothSpline
  13089. * @author pissang (https://www.github.com/pissang)
  13090. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13091. * errorrik (errorrik@gmail.com)
  13092. */
  13093. /**
  13094. * @inner
  13095. */
  13096. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13097. var v0 = (p2 - p0) * 0.5;
  13098. var v1 = (p3 - p1) * 0.5;
  13099. return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1;
  13100. }
  13101. /**
  13102. * @alias module:zrender/shape/util/smoothSpline
  13103. * @param {Array} points 线段顶点数组
  13104. * @param {boolean} isLoop
  13105. * @return {Array}
  13106. */
  13107. var smoothSpline = function (points, isLoop) {
  13108. var len$$1 = points.length;
  13109. var ret = [];
  13110. var distance$$1 = 0;
  13111. for (var i = 1; i < len$$1; i++) {
  13112. distance$$1 += distance(points[i - 1], points[i]);
  13113. }
  13114. var segs = distance$$1 / 2;
  13115. segs = segs < len$$1 ? len$$1 : segs;
  13116. for (var i = 0; i < segs; i++) {
  13117. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13118. var idx = Math.floor(pos);
  13119. var w = pos - idx;
  13120. var p0;
  13121. var p1 = points[idx % len$$1];
  13122. var p2;
  13123. var p3;
  13124. if (!isLoop) {
  13125. p0 = points[idx === 0 ? idx : idx - 1];
  13126. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13127. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13128. } else {
  13129. p0 = points[(idx - 1 + len$$1) % len$$1];
  13130. p2 = points[(idx + 1) % len$$1];
  13131. p3 = points[(idx + 2) % len$$1];
  13132. }
  13133. var w2 = w * w;
  13134. var w3 = w * w2;
  13135. ret.push([interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)]);
  13136. }
  13137. return ret;
  13138. };
  13139. /**
  13140. * 贝塞尔平滑曲线
  13141. * @module zrender/shape/util/smoothBezier
  13142. * @author pissang (https://www.github.com/pissang)
  13143. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13144. * errorrik (errorrik@gmail.com)
  13145. */
  13146. /**
  13147. * 贝塞尔平滑曲线
  13148. * @alias module:zrender/shape/util/smoothBezier
  13149. * @param {Array} points 线段顶点数组
  13150. * @param {number} smooth 平滑等级, 0-1
  13151. * @param {boolean} isLoop
  13152. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13153. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13154. * 整个折线的包围盒做一个并集用来约束控制点。
  13155. * @param {Array} 计算出来的控制点数组
  13156. */
  13157. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13158. var cps = [];
  13159. var v = [];
  13160. var v1 = [];
  13161. var v2 = [];
  13162. var prevPoint;
  13163. var nextPoint;
  13164. var min$$1;
  13165. var max$$1;
  13166. if (constraint) {
  13167. min$$1 = [Infinity, Infinity];
  13168. max$$1 = [-Infinity, -Infinity];
  13169. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13170. min(min$$1, min$$1, points[i]);
  13171. max(max$$1, max$$1, points[i]);
  13172. } // 与指定的包围盒做并集
  13173. min(min$$1, min$$1, constraint[0]);
  13174. max(max$$1, max$$1, constraint[1]);
  13175. }
  13176. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13177. var point = points[i];
  13178. if (isLoop) {
  13179. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13180. nextPoint = points[(i + 1) % len$$1];
  13181. } else {
  13182. if (i === 0 || i === len$$1 - 1) {
  13183. cps.push(clone$1(points[i]));
  13184. continue;
  13185. } else {
  13186. prevPoint = points[i - 1];
  13187. nextPoint = points[i + 1];
  13188. }
  13189. }
  13190. sub(v, nextPoint, prevPoint); // use degree to scale the handle length
  13191. scale(v, v, smooth);
  13192. var d0 = distance(point, prevPoint);
  13193. var d1 = distance(point, nextPoint);
  13194. var sum = d0 + d1;
  13195. if (sum !== 0) {
  13196. d0 /= sum;
  13197. d1 /= sum;
  13198. }
  13199. scale(v1, v, -d0);
  13200. scale(v2, v, d1);
  13201. var cp0 = add([], point, v1);
  13202. var cp1 = add([], point, v2);
  13203. if (constraint) {
  13204. max(cp0, cp0, min$$1);
  13205. min(cp0, cp0, max$$1);
  13206. max(cp1, cp1, min$$1);
  13207. min(cp1, cp1, max$$1);
  13208. }
  13209. cps.push(cp0);
  13210. cps.push(cp1);
  13211. }
  13212. if (isLoop) {
  13213. cps.push(cps.shift());
  13214. }
  13215. return cps;
  13216. };
  13217. function buildPath$1(ctx, shape, closePath) {
  13218. var points = shape.points;
  13219. var smooth = shape.smooth;
  13220. if (points && points.length >= 2) {
  13221. if (smooth && smooth !== 'spline') {
  13222. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13223. ctx.moveTo(points[0][0], points[0][1]);
  13224. var len = points.length;
  13225. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13226. var cp1 = controlPoints[i * 2];
  13227. var cp2 = controlPoints[i * 2 + 1];
  13228. var p = points[(i + 1) % len];
  13229. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13230. }
  13231. } else {
  13232. if (smooth === 'spline') {
  13233. points = smoothSpline(points, closePath);
  13234. }
  13235. ctx.moveTo(points[0][0], points[0][1]);
  13236. for (var i = 1, l = points.length; i < l; i++) {
  13237. ctx.lineTo(points[i][0], points[i][1]);
  13238. }
  13239. }
  13240. closePath && ctx.closePath();
  13241. }
  13242. }
  13243. /**
  13244. * 多边形
  13245. * @module zrender/shape/Polygon
  13246. */
  13247. var Polygon = Path.extend({
  13248. type: 'polygon',
  13249. shape: {
  13250. points: null,
  13251. smooth: false,
  13252. smoothConstraint: null
  13253. },
  13254. buildPath: function (ctx, shape) {
  13255. buildPath$1(ctx, shape, true);
  13256. }
  13257. });
  13258. /**
  13259. * @module zrender/graphic/shape/Polyline
  13260. */
  13261. var Polyline = Path.extend({
  13262. type: 'polyline',
  13263. shape: {
  13264. points: null,
  13265. smooth: false,
  13266. smoothConstraint: null
  13267. },
  13268. style: {
  13269. stroke: '#000',
  13270. fill: null
  13271. },
  13272. buildPath: function (ctx, shape) {
  13273. buildPath$1(ctx, shape, false);
  13274. }
  13275. });
  13276. /**
  13277. * Sub-pixel optimize for canvas rendering, prevent from blur
  13278. * when rendering a thin vertical/horizontal line.
  13279. */
  13280. var round = Math.round;
  13281. /**
  13282. * Sub pixel optimize line for canvas
  13283. *
  13284. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13285. * `outputShape` and `inputShape` can be the same object.
  13286. * `outputShape` object can be used repeatly, because all of
  13287. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13288. * @param {Object} [inputShape]
  13289. * @param {number} [inputShape.x1]
  13290. * @param {number} [inputShape.y1]
  13291. * @param {number} [inputShape.x2]
  13292. * @param {number} [inputShape.y2]
  13293. * @param {Object} [style]
  13294. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  13295. */
  13296. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13297. if (!inputShape) {
  13298. return;
  13299. }
  13300. var x1 = inputShape.x1;
  13301. var x2 = inputShape.x2;
  13302. var y1 = inputShape.y1;
  13303. var y2 = inputShape.y2;
  13304. outputShape.x1 = x1;
  13305. outputShape.x2 = x2;
  13306. outputShape.y1 = y1;
  13307. outputShape.y2 = y2;
  13308. var lineWidth = style && style.lineWidth;
  13309. if (!lineWidth) {
  13310. return;
  13311. }
  13312. if (round(x1 * 2) === round(x2 * 2)) {
  13313. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13314. }
  13315. if (round(y1 * 2) === round(y2 * 2)) {
  13316. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13317. }
  13318. }
  13319. /**
  13320. * Sub pixel optimize rect for canvas
  13321. *
  13322. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13323. * `outputShape` and `inputShape` can be the same object.
  13324. * `outputShape` object can be used repeatly, because all of
  13325. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13326. * @param {Object} [inputShape]
  13327. * @param {number} [inputShape.x]
  13328. * @param {number} [inputShape.y]
  13329. * @param {number} [inputShape.width]
  13330. * @param {number} [inputShape.height]
  13331. * @param {Object} [style]
  13332. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  13333. */
  13334. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13335. if (!inputShape) {
  13336. return;
  13337. }
  13338. var originX = inputShape.x;
  13339. var originY = inputShape.y;
  13340. var originWidth = inputShape.width;
  13341. var originHeight = inputShape.height;
  13342. outputShape.x = originX;
  13343. outputShape.y = originY;
  13344. outputShape.width = originWidth;
  13345. outputShape.height = originHeight;
  13346. var lineWidth = style && style.lineWidth;
  13347. if (!lineWidth) {
  13348. return;
  13349. }
  13350. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13351. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13352. outputShape.width = Math.max(subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  13353. outputShape.height = Math.max(subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  13354. }
  13355. /**
  13356. * Sub pixel optimize for canvas
  13357. *
  13358. * @param {number} position Coordinate, such as x, y
  13359. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  13360. * @param {boolean=} positiveOrNegative Default false (negative).
  13361. * @return {number} Optimized position.
  13362. */
  13363. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13364. if (!lineWidth) {
  13365. return position;
  13366. } // Assure that (position + lineWidth / 2) is near integer edge,
  13367. // otherwise line will be fuzzy in canvas.
  13368. var doubledPosition = round(position * 2);
  13369. return (doubledPosition + round(lineWidth)) % 2 === 0 ? doubledPosition / 2 : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13370. }
  13371. /**
  13372. * 矩形
  13373. * @module zrender/graphic/shape/Rect
  13374. */
  13375. var subPixelOptimizeOutputShape = {};
  13376. var Rect = Path.extend({
  13377. type: 'rect',
  13378. shape: {
  13379. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13380. // r缩写为1 相当于 [1, 1, 1, 1]
  13381. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13382. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13383. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13384. r: 0,
  13385. x: 0,
  13386. y: 0,
  13387. width: 0,
  13388. height: 0
  13389. },
  13390. buildPath: function (ctx, shape) {
  13391. var x;
  13392. var y;
  13393. var width;
  13394. var height;
  13395. if (this.subPixelOptimize) {
  13396. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13397. x = subPixelOptimizeOutputShape.x;
  13398. y = subPixelOptimizeOutputShape.y;
  13399. width = subPixelOptimizeOutputShape.width;
  13400. height = subPixelOptimizeOutputShape.height;
  13401. subPixelOptimizeOutputShape.r = shape.r;
  13402. shape = subPixelOptimizeOutputShape;
  13403. } else {
  13404. x = shape.x;
  13405. y = shape.y;
  13406. width = shape.width;
  13407. height = shape.height;
  13408. }
  13409. if (!shape.r) {
  13410. ctx.rect(x, y, width, height);
  13411. } else {
  13412. buildPath(ctx, shape);
  13413. }
  13414. ctx.closePath();
  13415. return;
  13416. }
  13417. });
  13418. /**
  13419. * 直线
  13420. * @module zrender/graphic/shape/Line
  13421. */
  13422. var subPixelOptimizeOutputShape$1 = {};
  13423. var Line = Path.extend({
  13424. type: 'line',
  13425. shape: {
  13426. // Start point
  13427. x1: 0,
  13428. y1: 0,
  13429. // End point
  13430. x2: 0,
  13431. y2: 0,
  13432. percent: 1
  13433. },
  13434. style: {
  13435. stroke: '#000',
  13436. fill: null
  13437. },
  13438. buildPath: function (ctx, shape) {
  13439. var x1;
  13440. var y1;
  13441. var x2;
  13442. var y2;
  13443. if (this.subPixelOptimize) {
  13444. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13445. x1 = subPixelOptimizeOutputShape$1.x1;
  13446. y1 = subPixelOptimizeOutputShape$1.y1;
  13447. x2 = subPixelOptimizeOutputShape$1.x2;
  13448. y2 = subPixelOptimizeOutputShape$1.y2;
  13449. } else {
  13450. x1 = shape.x1;
  13451. y1 = shape.y1;
  13452. x2 = shape.x2;
  13453. y2 = shape.y2;
  13454. }
  13455. var percent = shape.percent;
  13456. if (percent === 0) {
  13457. return;
  13458. }
  13459. ctx.moveTo(x1, y1);
  13460. if (percent < 1) {
  13461. x2 = x1 * (1 - percent) + x2 * percent;
  13462. y2 = y1 * (1 - percent) + y2 * percent;
  13463. }
  13464. ctx.lineTo(x2, y2);
  13465. },
  13466. /**
  13467. * Get point at percent
  13468. * @param {number} percent
  13469. * @return {Array.<number>}
  13470. */
  13471. pointAt: function (p) {
  13472. var shape = this.shape;
  13473. return [shape.x1 * (1 - p) + shape.x2 * p, shape.y1 * (1 - p) + shape.y2 * p];
  13474. }
  13475. });
  13476. /**
  13477. * 贝塞尔曲线
  13478. * @module zrender/shape/BezierCurve
  13479. */
  13480. var out = [];
  13481. function someVectorAt(shape, t, isTangent) {
  13482. var cpx2 = shape.cpx2;
  13483. var cpy2 = shape.cpy2;
  13484. if (cpx2 === null || cpy2 === null) {
  13485. return [(isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t), (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)];
  13486. } else {
  13487. return [(isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t), (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)];
  13488. }
  13489. }
  13490. var BezierCurve = Path.extend({
  13491. type: 'bezier-curve',
  13492. shape: {
  13493. x1: 0,
  13494. y1: 0,
  13495. x2: 0,
  13496. y2: 0,
  13497. cpx1: 0,
  13498. cpy1: 0,
  13499. // cpx2: 0,
  13500. // cpy2: 0
  13501. // Curve show percent, for animating
  13502. percent: 1
  13503. },
  13504. style: {
  13505. stroke: '#000',
  13506. fill: null
  13507. },
  13508. buildPath: function (ctx, shape) {
  13509. var x1 = shape.x1;
  13510. var y1 = shape.y1;
  13511. var x2 = shape.x2;
  13512. var y2 = shape.y2;
  13513. var cpx1 = shape.cpx1;
  13514. var cpy1 = shape.cpy1;
  13515. var cpx2 = shape.cpx2;
  13516. var cpy2 = shape.cpy2;
  13517. var percent = shape.percent;
  13518. if (percent === 0) {
  13519. return;
  13520. }
  13521. ctx.moveTo(x1, y1);
  13522. if (cpx2 == null || cpy2 == null) {
  13523. if (percent < 1) {
  13524. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13525. cpx1 = out[1];
  13526. x2 = out[2];
  13527. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13528. cpy1 = out[1];
  13529. y2 = out[2];
  13530. }
  13531. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13532. } else {
  13533. if (percent < 1) {
  13534. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13535. cpx1 = out[1];
  13536. cpx2 = out[2];
  13537. x2 = out[3];
  13538. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13539. cpy1 = out[1];
  13540. cpy2 = out[2];
  13541. y2 = out[3];
  13542. }
  13543. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13544. }
  13545. },
  13546. /**
  13547. * Get point at percent
  13548. * @param {number} t
  13549. * @return {Array.<number>}
  13550. */
  13551. pointAt: function (t) {
  13552. return someVectorAt(this.shape, t, false);
  13553. },
  13554. /**
  13555. * Get tangent at percent
  13556. * @param {number} t
  13557. * @return {Array.<number>}
  13558. */
  13559. tangentAt: function (t) {
  13560. var p = someVectorAt(this.shape, t, true);
  13561. return normalize(p, p);
  13562. }
  13563. });
  13564. /**
  13565. * 圆弧
  13566. * @module zrender/graphic/shape/Arc
  13567. */
  13568. var Arc = Path.extend({
  13569. type: 'arc',
  13570. shape: {
  13571. cx: 0,
  13572. cy: 0,
  13573. r: 0,
  13574. startAngle: 0,
  13575. endAngle: Math.PI * 2,
  13576. clockwise: true
  13577. },
  13578. style: {
  13579. stroke: '#000',
  13580. fill: null
  13581. },
  13582. buildPath: function (ctx, shape) {
  13583. var x = shape.cx;
  13584. var y = shape.cy;
  13585. var r = Math.max(shape.r, 0);
  13586. var startAngle = shape.startAngle;
  13587. var endAngle = shape.endAngle;
  13588. var clockwise = shape.clockwise;
  13589. var unitX = Math.cos(startAngle);
  13590. var unitY = Math.sin(startAngle);
  13591. ctx.moveTo(unitX * r + x, unitY * r + y);
  13592. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13593. }
  13594. });
  13595. // CompoundPath to improve performance
  13596. var CompoundPath = Path.extend({
  13597. type: 'compound',
  13598. shape: {
  13599. paths: null
  13600. },
  13601. _updatePathDirty: function () {
  13602. var dirtyPath = this.__dirtyPath;
  13603. var paths = this.shape.paths;
  13604. for (var i = 0; i < paths.length; i++) {
  13605. // Mark as dirty if any subpath is dirty
  13606. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13607. }
  13608. this.__dirtyPath = dirtyPath;
  13609. this.__dirty = this.__dirty || dirtyPath;
  13610. },
  13611. beforeBrush: function () {
  13612. this._updatePathDirty();
  13613. var paths = this.shape.paths || [];
  13614. var scale = this.getGlobalScale(); // Update path scale
  13615. for (var i = 0; i < paths.length; i++) {
  13616. if (!paths[i].path) {
  13617. paths[i].createPathProxy();
  13618. }
  13619. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13620. }
  13621. },
  13622. buildPath: function (ctx, shape) {
  13623. var paths = shape.paths || [];
  13624. for (var i = 0; i < paths.length; i++) {
  13625. paths[i].buildPath(ctx, paths[i].shape, true);
  13626. }
  13627. },
  13628. afterBrush: function () {
  13629. var paths = this.shape.paths || [];
  13630. for (var i = 0; i < paths.length; i++) {
  13631. paths[i].__dirtyPath = false;
  13632. }
  13633. },
  13634. getBoundingRect: function () {
  13635. this._updatePathDirty();
  13636. return Path.prototype.getBoundingRect.call(this);
  13637. }
  13638. });
  13639. /**
  13640. * @param {Array.<Object>} colorStops
  13641. */
  13642. var Gradient = function (colorStops) {
  13643. this.colorStops = colorStops || [];
  13644. };
  13645. Gradient.prototype = {
  13646. constructor: Gradient,
  13647. addColorStop: function (offset, color) {
  13648. this.colorStops.push({
  13649. offset: offset,
  13650. color: color
  13651. });
  13652. }
  13653. };
  13654. /**
  13655. * x, y, x2, y2 are all percent from 0 to 1
  13656. * @param {number} [x=0]
  13657. * @param {number} [y=0]
  13658. * @param {number} [x2=1]
  13659. * @param {number} [y2=0]
  13660. * @param {Array.<Object>} colorStops
  13661. * @param {boolean} [globalCoord=false]
  13662. */
  13663. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13664. // Should do nothing more in this constructor. Because gradient can be
  13665. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13666. // this constructor will not be called.
  13667. this.x = x == null ? 0 : x;
  13668. this.y = y == null ? 0 : y;
  13669. this.x2 = x2 == null ? 1 : x2;
  13670. this.y2 = y2 == null ? 0 : y2; // Can be cloned
  13671. this.type = 'linear'; // If use global coord
  13672. this.global = globalCoord || false;
  13673. Gradient.call(this, colorStops);
  13674. };
  13675. LinearGradient.prototype = {
  13676. constructor: LinearGradient
  13677. };
  13678. inherits(LinearGradient, Gradient);
  13679. /**
  13680. * x, y, r are all percent from 0 to 1
  13681. * @param {number} [x=0.5]
  13682. * @param {number} [y=0.5]
  13683. * @param {number} [r=0.5]
  13684. * @param {Array.<Object>} [colorStops]
  13685. * @param {boolean} [globalCoord=false]
  13686. */
  13687. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13688. // Should do nothing more in this constructor. Because gradient can be
  13689. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13690. // this constructor will not be called.
  13691. this.x = x == null ? 0.5 : x;
  13692. this.y = y == null ? 0.5 : y;
  13693. this.r = r == null ? 0.5 : r; // Can be cloned
  13694. this.type = 'radial'; // If use global coord
  13695. this.global = globalCoord || false;
  13696. Gradient.call(this, colorStops);
  13697. };
  13698. RadialGradient.prototype = {
  13699. constructor: RadialGradient
  13700. };
  13701. inherits(RadialGradient, Gradient);
  13702. /**
  13703. * Displayable for incremental rendering. It will be rendered in a separate layer
  13704. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  13705. * addDisplayables will render the added displayables incremetally.
  13706. *
  13707. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13708. */
  13709. function IncrementalDisplayble(opts) {
  13710. Displayable.call(this, opts);
  13711. this._displayables = [];
  13712. this._temporaryDisplayables = [];
  13713. this._cursor = 0;
  13714. this.notClear = true;
  13715. }
  13716. IncrementalDisplayble.prototype.incremental = true;
  13717. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13718. this._displayables = [];
  13719. this._temporaryDisplayables = [];
  13720. this._cursor = 0;
  13721. this.dirty();
  13722. this.notClear = false;
  13723. };
  13724. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13725. if (notPersistent) {
  13726. this._temporaryDisplayables.push(displayable);
  13727. } else {
  13728. this._displayables.push(displayable);
  13729. }
  13730. this.dirty();
  13731. };
  13732. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13733. notPersistent = notPersistent || false;
  13734. for (var i = 0; i < displayables.length; i++) {
  13735. this.addDisplayable(displayables[i], notPersistent);
  13736. }
  13737. };
  13738. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13739. for (var i = this._cursor; i < this._displayables.length; i++) {
  13740. cb && cb(this._displayables[i]);
  13741. }
  13742. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13743. cb && cb(this._temporaryDisplayables[i]);
  13744. }
  13745. };
  13746. IncrementalDisplayble.prototype.update = function () {
  13747. this.updateTransform();
  13748. for (var i = this._cursor; i < this._displayables.length; i++) {
  13749. var displayable = this._displayables[i]; // PENDING
  13750. displayable.parent = this;
  13751. displayable.update();
  13752. displayable.parent = null;
  13753. }
  13754. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13755. var displayable = this._temporaryDisplayables[i]; // PENDING
  13756. displayable.parent = this;
  13757. displayable.update();
  13758. displayable.parent = null;
  13759. }
  13760. };
  13761. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13762. // Render persistant displayables.
  13763. for (var i = this._cursor; i < this._displayables.length; i++) {
  13764. var displayable = this._displayables[i];
  13765. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13766. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13767. displayable.afterBrush && displayable.afterBrush(ctx);
  13768. }
  13769. this._cursor = i; // Render temporary displayables.
  13770. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13771. var displayable = this._temporaryDisplayables[i];
  13772. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13773. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13774. displayable.afterBrush && displayable.afterBrush(ctx);
  13775. }
  13776. this._temporaryDisplayables = [];
  13777. this.notClear = true;
  13778. };
  13779. var m = [];
  13780. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13781. if (!this._rect) {
  13782. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13783. for (var i = 0; i < this._displayables.length; i++) {
  13784. var displayable = this._displayables[i];
  13785. var childRect = displayable.getBoundingRect().clone();
  13786. if (displayable.needLocalTransform()) {
  13787. childRect.applyTransform(displayable.getLocalTransform(m));
  13788. }
  13789. rect.union(childRect);
  13790. }
  13791. this._rect = rect;
  13792. }
  13793. return this._rect;
  13794. };
  13795. IncrementalDisplayble.prototype.contain = function (x, y) {
  13796. var localPos = this.transformCoordToLocal(x, y);
  13797. var rect = this.getBoundingRect();
  13798. if (rect.contain(localPos[0], localPos[1])) {
  13799. for (var i = 0; i < this._displayables.length; i++) {
  13800. var displayable = this._displayables[i];
  13801. if (displayable.contain(x, y)) {
  13802. return true;
  13803. }
  13804. }
  13805. }
  13806. return false;
  13807. };
  13808. inherits(IncrementalDisplayble, Displayable);
  13809. /*
  13810. * Licensed to the Apache Software Foundation (ASF) under one
  13811. * or more contributor license agreements. See the NOTICE file
  13812. * distributed with this work for additional information
  13813. * regarding copyright ownership. The ASF licenses this file
  13814. * to you under the Apache License, Version 2.0 (the
  13815. * "License"); you may not use this file except in compliance
  13816. * with the License. You may obtain a copy of the License at
  13817. *
  13818. * http://www.apache.org/licenses/LICENSE-2.0
  13819. *
  13820. * Unless required by applicable law or agreed to in writing,
  13821. * software distributed under the License is distributed on an
  13822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13823. * KIND, either express or implied. See the License for the
  13824. * specific language governing permissions and limitations
  13825. * under the License.
  13826. */
  13827. var mathMax$1 = Math.max;
  13828. var mathMin$1 = Math.min;
  13829. var EMPTY_OBJ = {};
  13830. var Z2_EMPHASIS_LIFT = 1; // key: label model property nane, value: style property name.
  13831. var CACHED_LABEL_STYLE_PROPERTIES = {
  13832. color: 'textFill',
  13833. textBorderColor: 'textStroke',
  13834. textBorderWidth: 'textStrokeWidth'
  13835. };
  13836. var EMPHASIS = 'emphasis';
  13837. var NORMAL = 'normal'; // Reserve 0 as default.
  13838. var _highlightNextDigit = 1;
  13839. var _highlightKeyMap = {};
  13840. var _customShapeMap = {};
  13841. /**
  13842. * Extend shape with parameters
  13843. */
  13844. function extendShape(opts) {
  13845. return Path.extend(opts);
  13846. }
  13847. /**
  13848. * Extend path
  13849. */
  13850. function extendPath(pathData, opts) {
  13851. return extendFromString(pathData, opts);
  13852. }
  13853. /**
  13854. * Register a user defined shape.
  13855. * The shape class can be fetched by `getShapeClass`
  13856. * This method will overwrite the registered shapes, including
  13857. * the registered built-in shapes, if using the same `name`.
  13858. * The shape can be used in `custom series` and
  13859. * `graphic component` by declaring `{type: name}`.
  13860. *
  13861. * @param {string} name
  13862. * @param {Object} ShapeClass Can be generated by `extendShape`.
  13863. */
  13864. function registerShape(name, ShapeClass) {
  13865. _customShapeMap[name] = ShapeClass;
  13866. }
  13867. /**
  13868. * Find shape class registered by `registerShape`. Usually used in
  13869. * fetching user defined shape.
  13870. *
  13871. * [Caution]:
  13872. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13873. * to use user registered shapes.
  13874. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13875. * `registerShape` by default. That enables users to get both built-in
  13876. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13877. * the built-in shapes by using names like 'circle', 'rect' via calling
  13878. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13879. * in case that it is overwritten by users, except that some features, like
  13880. * `custom series`, `graphic component`, do it deliberately.
  13881. *
  13882. * (2) In the features like `custom series`, `graphic component`, the user input
  13883. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13884. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13885. * are reserved names, that is, if some user register a shape named `'image'`,
  13886. * the shape will not be used. If we intending to add some more reserved names
  13887. * in feature, that might bring break changes (disable some existing user shape
  13888. * names). But that case probably rearly happen. So we dont make more mechanism
  13889. * to resolve this issue here.
  13890. *
  13891. * @param {string} name
  13892. * @return {Object} The shape class. If not found, return nothing.
  13893. */
  13894. function getShapeClass(name) {
  13895. if (_customShapeMap.hasOwnProperty(name)) {
  13896. return _customShapeMap[name];
  13897. }
  13898. }
  13899. /**
  13900. * Create a path element from path data string
  13901. * @param {string} pathData
  13902. * @param {Object} opts
  13903. * @param {module:zrender/core/BoundingRect} rect
  13904. * @param {string} [layout=cover] 'center' or 'cover'
  13905. */
  13906. function makePath(pathData, opts, rect, layout) {
  13907. var path = createFromString(pathData, opts);
  13908. if (rect) {
  13909. if (layout === 'center') {
  13910. rect = centerGraphic(rect, path.getBoundingRect());
  13911. }
  13912. resizePath(path, rect);
  13913. }
  13914. return path;
  13915. }
  13916. /**
  13917. * Create a image element from image url
  13918. * @param {string} imageUrl image url
  13919. * @param {Object} opts options
  13920. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13921. * @param {string} [layout=cover] 'center' or 'cover'
  13922. */
  13923. function makeImage(imageUrl, rect, layout) {
  13924. var path = new ZImage({
  13925. style: {
  13926. image: imageUrl,
  13927. x: rect.x,
  13928. y: rect.y,
  13929. width: rect.width,
  13930. height: rect.height
  13931. },
  13932. onload: function (img) {
  13933. if (layout === 'center') {
  13934. var boundingRect = {
  13935. width: img.width,
  13936. height: img.height
  13937. };
  13938. path.setStyle(centerGraphic(rect, boundingRect));
  13939. }
  13940. }
  13941. });
  13942. return path;
  13943. }
  13944. /**
  13945. * Get position of centered element in bounding box.
  13946. *
  13947. * @param {Object} rect element local bounding box
  13948. * @param {Object} boundingRect constraint bounding box
  13949. * @return {Object} element position containing x, y, width, and height
  13950. */
  13951. function centerGraphic(rect, boundingRect) {
  13952. // Set rect to center, keep width / height ratio.
  13953. var aspect = boundingRect.width / boundingRect.height;
  13954. var width = rect.height * aspect;
  13955. var height;
  13956. if (width <= rect.width) {
  13957. height = rect.height;
  13958. } else {
  13959. width = rect.width;
  13960. height = width / aspect;
  13961. }
  13962. var cx = rect.x + rect.width / 2;
  13963. var cy = rect.y + rect.height / 2;
  13964. return {
  13965. x: cx - width / 2,
  13966. y: cy - height / 2,
  13967. width: width,
  13968. height: height
  13969. };
  13970. }
  13971. var mergePath = mergePath$1;
  13972. /**
  13973. * Resize a path to fit the rect
  13974. * @param {module:zrender/graphic/Path} path
  13975. * @param {Object} rect
  13976. */
  13977. function resizePath(path, rect) {
  13978. if (!path.applyTransform) {
  13979. return;
  13980. }
  13981. var pathRect = path.getBoundingRect();
  13982. var m = pathRect.calculateTransform(rect);
  13983. path.applyTransform(m);
  13984. }
  13985. /**
  13986. * Sub pixel optimize line for canvas
  13987. *
  13988. * @param {Object} param
  13989. * @param {Object} [param.shape]
  13990. * @param {number} [param.shape.x1]
  13991. * @param {number} [param.shape.y1]
  13992. * @param {number} [param.shape.x2]
  13993. * @param {number} [param.shape.y2]
  13994. * @param {Object} [param.style]
  13995. * @param {number} [param.style.lineWidth]
  13996. * @return {Object} Modified param
  13997. */
  13998. function subPixelOptimizeLine(param) {
  13999. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  14000. return param;
  14001. }
  14002. /**
  14003. * Sub pixel optimize rect for canvas
  14004. *
  14005. * @param {Object} param
  14006. * @param {Object} [param.shape]
  14007. * @param {number} [param.shape.x]
  14008. * @param {number} [param.shape.y]
  14009. * @param {number} [param.shape.width]
  14010. * @param {number} [param.shape.height]
  14011. * @param {Object} [param.style]
  14012. * @param {number} [param.style.lineWidth]
  14013. * @return {Object} Modified param
  14014. */
  14015. function subPixelOptimizeRect(param) {
  14016. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  14017. return param;
  14018. }
  14019. /**
  14020. * Sub pixel optimize for canvas
  14021. *
  14022. * @param {number} position Coordinate, such as x, y
  14023. * @param {number} lineWidth Should be nonnegative integer.
  14024. * @param {boolean=} positiveOrNegative Default false (negative).
  14025. * @return {number} Optimized position.
  14026. */
  14027. var subPixelOptimize = subPixelOptimize$1;
  14028. function hasFillOrStroke(fillOrStroke) {
  14029. return fillOrStroke != null && fillOrStroke !== 'none';
  14030. } // Most lifted color are duplicated.
  14031. var liftedColorMap = createHashMap();
  14032. var liftedColorCount = 0;
  14033. function liftColor(color) {
  14034. if (typeof color !== 'string') {
  14035. return color;
  14036. }
  14037. var liftedColor = liftedColorMap.get(color);
  14038. if (!liftedColor) {
  14039. liftedColor = lift(color, -0.1);
  14040. if (liftedColorCount < 10000) {
  14041. liftedColorMap.set(color, liftedColor);
  14042. liftedColorCount++;
  14043. }
  14044. }
  14045. return liftedColor;
  14046. }
  14047. function cacheElementStl(el) {
  14048. if (!el.__hoverStlDirty) {
  14049. return;
  14050. }
  14051. el.__hoverStlDirty = false;
  14052. var hoverStyle = el.__hoverStl;
  14053. if (!hoverStyle) {
  14054. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14055. return;
  14056. }
  14057. var normalStyle = el.__cachedNormalStl = {};
  14058. el.__cachedNormalZ2 = el.z2;
  14059. var elStyle = el.style;
  14060. for (var name in hoverStyle) {
  14061. // See comment in `singleEnterEmphasis`.
  14062. if (hoverStyle[name] != null) {
  14063. normalStyle[name] = elStyle[name];
  14064. }
  14065. } // Always cache fill and stroke to normalStyle for lifting color.
  14066. normalStyle.fill = elStyle.fill;
  14067. normalStyle.stroke = elStyle.stroke;
  14068. }
  14069. function singleEnterEmphasis(el) {
  14070. var hoverStl = el.__hoverStl;
  14071. if (!hoverStl || el.__highlighted) {
  14072. return;
  14073. }
  14074. var zr = el.__zr;
  14075. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  14076. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14077. if (el.isGroup || !zr && el.useHoverLayer) {
  14078. return;
  14079. }
  14080. var elTarget = el;
  14081. var targetStyle = el.style;
  14082. if (useHoverLayer) {
  14083. elTarget = zr.addHover(el);
  14084. targetStyle = elTarget.style;
  14085. }
  14086. rollbackDefaultTextStyle(targetStyle);
  14087. if (!useHoverLayer) {
  14088. cacheElementStl(elTarget);
  14089. } // styles can be:
  14090. // {
  14091. // label: {
  14092. // show: false,
  14093. // position: 'outside',
  14094. // fontSize: 18
  14095. // },
  14096. // emphasis: {
  14097. // label: {
  14098. // show: true
  14099. // }
  14100. // }
  14101. // },
  14102. // where properties of `emphasis` may not appear in `normal`. We previously use
  14103. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14104. // But consider rich text and setOption in merge mode, it is impossible to cover
  14105. // all properties in merge. So we use merge mode when setting style here.
  14106. // But we choose the merge strategy that only properties that is not `null/undefined`.
  14107. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  14108. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  14109. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  14110. // style any more in `emphasis`. Users can both set properties directly on normal and
  14111. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  14112. targetStyle.extendFrom(hoverStl);
  14113. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14114. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14115. applyDefaultTextStyle(targetStyle);
  14116. if (!useHoverLayer) {
  14117. el.dirty(false);
  14118. el.z2 += Z2_EMPHASIS_LIFT;
  14119. }
  14120. }
  14121. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14122. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14123. targetStyle[prop] = liftColor(targetStyle[prop]);
  14124. }
  14125. }
  14126. function singleEnterNormal(el) {
  14127. var highlighted = el.__highlighted;
  14128. if (!highlighted) {
  14129. return;
  14130. }
  14131. el.__highlighted = false;
  14132. if (el.isGroup) {
  14133. return;
  14134. }
  14135. if (highlighted === 'layer') {
  14136. el.__zr && el.__zr.removeHover(el);
  14137. } else {
  14138. var style = el.style;
  14139. var normalStl = el.__cachedNormalStl;
  14140. if (normalStl) {
  14141. rollbackDefaultTextStyle(style);
  14142. el.setStyle(normalStl);
  14143. applyDefaultTextStyle(style);
  14144. } // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14145. // when `el` is on emphasis state. So here by comparing with 1, we try
  14146. // hard to make the bug case rare.
  14147. var normalZ2 = el.__cachedNormalZ2;
  14148. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14149. el.z2 = normalZ2;
  14150. }
  14151. }
  14152. }
  14153. function traverseUpdate(el, updater, commonParam) {
  14154. // If root is group, also enter updater for `highDownOnUpdate`.
  14155. var fromState = NORMAL;
  14156. var toState = NORMAL;
  14157. var trigger; // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  14158. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  14159. updater(el, commonParam);
  14160. el.__highlighted && (toState = EMPHASIS, trigger = true);
  14161. el.isGroup && el.traverse(function (child) {
  14162. !child.isGroup && updater(child, commonParam);
  14163. });
  14164. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  14165. }
  14166. /**
  14167. * Set hover style (namely "emphasis style") of element, based on the current
  14168. * style of the given `el`.
  14169. * This method should be called after all of the normal styles have been adopted
  14170. * to the `el`. See the reason on `setHoverStyle`.
  14171. *
  14172. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14173. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  14174. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  14175. * Often used when item group has a label element and it's hoverStyle is different.
  14176. * @param {Object|boolean} [hoverStl] The specified hover style.
  14177. * If set as `false`, disable the hover style.
  14178. * Similarly, The `el.hoverStyle` can alse be set
  14179. * as `false` to disable the hover style.
  14180. * Otherwise, use the default hover style if not provided.
  14181. */
  14182. function setElementHoverStyle(el, hoverStl) {
  14183. // For performance consideration, it might be better to make the "hover style" only the
  14184. // difference properties from the "normal style", but not a entire copy of all styles.
  14185. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  14186. el.__hoverStlDirty = true; // FIXME
  14187. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14188. // It probably should be saved on `data` of series. Consider the cases:
  14189. // (1) A highlighted elements are moved out of the view port and re-enter
  14190. // again by dataZoom.
  14191. // (2) call `setOption` and replace elements totally when they are highlighted.
  14192. if (el.__highlighted) {
  14193. // Consider the case:
  14194. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14195. // should be adapted to the `el`. Notice here new "normal styles" should have
  14196. // been set outside and the cached "normal style" is out of date.
  14197. el.__cachedNormalStl = null; // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14198. // of this method. In most cases, `z2` is not set and hover style should be able
  14199. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14200. // `doSingleLeaveHover` for details.
  14201. singleEnterNormal(el);
  14202. singleEnterEmphasis(el);
  14203. }
  14204. }
  14205. function onElementMouseOver(e) {
  14206. !shouldSilent(this, e) // "emphasis" event highlight has higher priority than mouse highlight.
  14207. && !this.__highByOuter && traverseUpdate(this, singleEnterEmphasis);
  14208. }
  14209. function onElementMouseOut(e) {
  14210. !shouldSilent(this, e) // "emphasis" event highlight has higher priority than mouse highlight.
  14211. && !this.__highByOuter && traverseUpdate(this, singleEnterNormal);
  14212. }
  14213. function onElementEmphasisEvent(highlightDigit) {
  14214. this.__highByOuter |= 1 << (highlightDigit || 0);
  14215. traverseUpdate(this, singleEnterEmphasis);
  14216. }
  14217. function onElementNormalEvent(highlightDigit) {
  14218. !(this.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdate(this, singleEnterNormal);
  14219. }
  14220. function shouldSilent(el, e) {
  14221. return el.__highDownSilentOnTouch && e.zrByTouch;
  14222. }
  14223. /**
  14224. * Set hover style (namely "emphasis style") of element,
  14225. * based on the current style of the given `el`.
  14226. *
  14227. * (1)
  14228. * **CONSTRAINTS** for this method:
  14229. * <A> This method MUST be called after all of the normal styles having been adopted
  14230. * to the `el`.
  14231. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14232. * "normal style" having been set to the el.
  14233. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14234. * a default hover style).
  14235. *
  14236. * The reason: this method treat the current style of the `el` as the "normal style"
  14237. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14238. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14239. * logic, where the el should shift from the original emphasis style to the new
  14240. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14241. *
  14242. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14243. * not found a better solution yet to fit the backward compatibility, performance and
  14244. * the current programming style.
  14245. *
  14246. * (2)
  14247. * Call the method for a "root" element once. Do not call it for each descendants.
  14248. * If the descendants elemenets of a group has itself hover style different from the
  14249. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14250. * not call this method for them.
  14251. *
  14252. * (3) These input parameters can be set directly on `el`:
  14253. *
  14254. * @param {module:zrender/Element} el
  14255. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  14256. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  14257. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  14258. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14259. */
  14260. function setHoverStyle(el, hoverStyle) {
  14261. setAsHighDownDispatcher(el, true);
  14262. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  14263. }
  14264. /**
  14265. * @param {module:zrender/Element} el
  14266. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  14267. * Since `setHoverStyle` has the constraint that it must be called after
  14268. * all of the normal style updated, `highDownOnUpdate` is not needed to
  14269. * trigger if both `fromState` and `toState` is 'normal', and needed to
  14270. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  14271. * to sync outside style settings to "emphasis" state.
  14272. * @this {string} This dispatcher `el`.
  14273. * @param {string} fromState Can be "normal" or "emphasis".
  14274. * `fromState` might equal to `toState`,
  14275. * for example, when this method is called when `el` is
  14276. * on "emphasis" state.
  14277. * @param {string} toState Can be "normal" or "emphasis".
  14278. *
  14279. * FIXME
  14280. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  14281. * Because it is not a complete solution. The update
  14282. * listener should not have been mount in element,
  14283. * and the normal/emphasis state should not have
  14284. * mantained on elements.
  14285. *
  14286. * @param {boolean} [el.highDownSilentOnTouch=false]
  14287. * In touch device, mouseover event will be trigger on touchstart event
  14288. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14289. * conveniently use hoverStyle when tap on touch screen without additional
  14290. * code for compatibility.
  14291. * But if the chart/component has select feature, which usually also use
  14292. * hoverStyle, there might be conflict between 'select-highlight' and
  14293. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14294. * In this case, `highDownSilentOnTouch` should be used to disable
  14295. * hover-highlight on touch device.
  14296. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  14297. */
  14298. function setAsHighDownDispatcher(el, asDispatcher) {
  14299. var disable = asDispatcher === false; // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  14300. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  14301. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  14302. el.__highDownOnUpdate = el.highDownOnUpdate; // Simple optimize, since this method might be
  14303. // called for each elements of a group in some cases.
  14304. if (!disable || el.__highDownDispatcher) {
  14305. var method = disable ? 'off' : 'on'; // Duplicated function will be auto-ignored, see Eventful.js.
  14306. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut); // Emphasis, normal can be triggered manually by API or other components like hover link.
  14307. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent); // Also keep previous record.
  14308. el.__highByOuter = el.__highByOuter || 0;
  14309. el.__highDownDispatcher = !disable;
  14310. }
  14311. }
  14312. /**
  14313. * @param {module:zrender/src/Element} el
  14314. * @return {boolean}
  14315. */
  14316. function isHighDownDispatcher(el) {
  14317. return !!(el && el.__highDownDispatcher);
  14318. }
  14319. /**
  14320. * Support hightlight/downplay record on each elements.
  14321. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  14322. * user triggerred hightlight/downplay should not conflict.
  14323. * Only all of the highlightDigit cleared, return to normal.
  14324. * @param {string} highlightKey
  14325. * @return {number} highlightDigit
  14326. */
  14327. function getHighlightDigit(highlightKey) {
  14328. var highlightDigit = _highlightKeyMap[highlightKey];
  14329. if (highlightDigit == null && _highlightNextDigit <= 32) {
  14330. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  14331. }
  14332. return highlightDigit;
  14333. }
  14334. /**
  14335. * See more info in `setTextStyleCommon`.
  14336. * @param {Object|module:zrender/graphic/Style} normalStyle
  14337. * @param {Object} emphasisStyle
  14338. * @param {module:echarts/model/Model} normalModel
  14339. * @param {module:echarts/model/Model} emphasisModel
  14340. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14341. * @param {string|Function} [opt.defaultText]
  14342. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14343. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14344. * @param {number} [opt.labelDataIndex] Fetch text by
  14345. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14346. * @param {number} [opt.labelDimIndex] Fetch text by
  14347. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14348. * @param {string} [opt.labelProp] Fetch text by
  14349. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14350. * @param {Object} [normalSpecified]
  14351. * @param {Object} [emphasisSpecified]
  14352. */
  14353. function setLabelStyle(normalStyle, emphasisStyle, normalModel, emphasisModel, opt, normalSpecified, emphasisSpecified) {
  14354. opt = opt || EMPTY_OBJ;
  14355. var labelFetcher = opt.labelFetcher;
  14356. var labelDataIndex = opt.labelDataIndex;
  14357. var labelDimIndex = opt.labelDimIndex;
  14358. var labelProp = opt.labelProp; // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14359. // is not supported util someone requests.
  14360. var showNormal = normalModel.getShallow('show');
  14361. var showEmphasis = emphasisModel.getShallow('show'); // Consider performance, only fetch label when necessary.
  14362. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14363. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14364. var baseText;
  14365. if (showNormal || showEmphasis) {
  14366. if (labelFetcher) {
  14367. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, labelProp);
  14368. }
  14369. if (baseText == null) {
  14370. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14371. }
  14372. }
  14373. var normalStyleText = showNormal ? baseText : null;
  14374. var emphasisStyleText = showEmphasis ? retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex, labelProp) : null, baseText) : null; // Optimize: If style.text is null, text will not be drawn.
  14375. if (normalStyleText != null || emphasisStyleText != null) {
  14376. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14377. // values have to be set on `normalStyle`.
  14378. // If we set default values on `emphasisStyle`, consider case:
  14379. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14380. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14381. // Then the 'red' will not work on emphasis.
  14382. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14383. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14384. }
  14385. normalStyle.text = normalStyleText;
  14386. emphasisStyle.text = emphasisStyleText;
  14387. }
  14388. /**
  14389. * Modify label style manually.
  14390. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  14391. *
  14392. * @param {module:zrender/src/Element} el
  14393. * @param {Object} [normalStyleProps] optional
  14394. * @param {Object} [emphasisStyleProps] optional
  14395. */
  14396. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  14397. var elStyle = el.style;
  14398. if (normalStyleProps) {
  14399. rollbackDefaultTextStyle(elStyle);
  14400. el.setStyle(normalStyleProps);
  14401. applyDefaultTextStyle(elStyle);
  14402. }
  14403. elStyle = el.__hoverStl;
  14404. if (emphasisStyleProps && elStyle) {
  14405. rollbackDefaultTextStyle(elStyle);
  14406. extend(elStyle, emphasisStyleProps);
  14407. applyDefaultTextStyle(elStyle);
  14408. }
  14409. }
  14410. /**
  14411. * Set basic textStyle properties.
  14412. * See more info in `setTextStyleCommon`.
  14413. * @param {Object|module:zrender/graphic/Style} textStyle
  14414. * @param {module:echarts/model/Model} model
  14415. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14416. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14417. * @param {boolean} [isEmphasis]
  14418. */
  14419. function setTextStyle(textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis) {
  14420. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14421. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14422. return textStyle;
  14423. }
  14424. /**
  14425. * Set text option in the style.
  14426. * See more info in `setTextStyleCommon`.
  14427. * @deprecated
  14428. * @param {Object} textStyle
  14429. * @param {module:echarts/model/Model} labelModel
  14430. * @param {string|boolean} defaultColor Default text color.
  14431. * If set as false, it will be processed as a emphasis style.
  14432. */
  14433. function setText(textStyle, labelModel, defaultColor) {
  14434. var opt = {
  14435. isRectText: true
  14436. };
  14437. var isEmphasis;
  14438. if (defaultColor === false) {
  14439. isEmphasis = true;
  14440. } else {
  14441. // Support setting color as 'auto' to get visual color.
  14442. opt.autoColor = defaultColor;
  14443. }
  14444. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14445. }
  14446. /**
  14447. * The uniform entry of set text style, that is, retrieve style definitions
  14448. * from `model` and set to `textStyle` object.
  14449. *
  14450. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14451. * properties will be set. (Consider the states of normal and emphasis and
  14452. * default value can be adopted, merge would make the logic too complicated
  14453. * to manage.)
  14454. *
  14455. * The `textStyle` object can either be a plain object or an instance of
  14456. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14457. * After this mothod called, the `textStyle` object can then be used in
  14458. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14459. *
  14460. * Default value will be adopted and `insideRollbackOpt` will be created.
  14461. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14462. *
  14463. * opt: {
  14464. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14465. * isRectText: boolean,
  14466. * autoColor: string, specify a color when color is 'auto',
  14467. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14468. * If autoColor specified, it is used as default textFill.
  14469. * useInsideStyle:
  14470. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14471. * if `textFill` is not specified.
  14472. * `false`: Do not use inside style.
  14473. * `null/undefined`: use inside style if `isRectText` is true and
  14474. * `textFill` is not specified and textPosition contains `'inside'`.
  14475. * forceRich: boolean
  14476. * }
  14477. */
  14478. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14479. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14480. opt = opt || EMPTY_OBJ;
  14481. if (opt.isRectText) {
  14482. var textPosition;
  14483. if (opt.getTextPosition) {
  14484. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  14485. } else {
  14486. textPosition = textStyleModel.getShallow('position') || (isEmphasis ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14487. // in bar series, and magric type should be considered.
  14488. textPosition === 'outside' && (textPosition = 'top');
  14489. }
  14490. textStyle.textPosition = textPosition;
  14491. textStyle.textOffset = textStyleModel.getShallow('offset');
  14492. var labelRotate = textStyleModel.getShallow('rotate');
  14493. labelRotate != null && (labelRotate *= Math.PI / 180);
  14494. textStyle.textRotation = labelRotate;
  14495. textStyle.textDistance = retrieve2(textStyleModel.getShallow('distance'), isEmphasis ? null : 5);
  14496. }
  14497. var ecModel = textStyleModel.ecModel;
  14498. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14499. // {
  14500. // data: [{
  14501. // value: 12,
  14502. // label: {
  14503. // rich: {
  14504. // // no 'a' here but using parent 'a'.
  14505. // }
  14506. // }
  14507. // }],
  14508. // rich: {
  14509. // a: { ... }
  14510. // }
  14511. // }
  14512. var richItemNames = getRichItemNames(textStyleModel);
  14513. var richResult;
  14514. if (richItemNames) {
  14515. richResult = {};
  14516. for (var name in richItemNames) {
  14517. if (richItemNames.hasOwnProperty(name)) {
  14518. // Cascade is supported in rich.
  14519. var richTextStyle = textStyleModel.getModel(['rich', name]); // In rich, never `disableBox`.
  14520. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14521. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14522. // That might confuses users. So probably we should put `textStyleModel` as the
  14523. // root ancestor of the `richTextStyle`. But that would be a break change.
  14524. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14525. }
  14526. }
  14527. }
  14528. textStyle.rich = richResult;
  14529. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14530. if (opt.forceRich && !opt.textStyle) {
  14531. opt.textStyle = {};
  14532. }
  14533. return textStyle;
  14534. } // Consider case:
  14535. // {
  14536. // data: [{
  14537. // value: 12,
  14538. // label: {
  14539. // rich: {
  14540. // // no 'a' here but using parent 'a'.
  14541. // }
  14542. // }
  14543. // }],
  14544. // rich: {
  14545. // a: { ... }
  14546. // }
  14547. // }
  14548. function getRichItemNames(textStyleModel) {
  14549. // Use object to remove duplicated names.
  14550. var richItemNameMap;
  14551. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14552. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14553. if (rich) {
  14554. richItemNameMap = richItemNameMap || {};
  14555. for (var name in rich) {
  14556. if (rich.hasOwnProperty(name)) {
  14557. richItemNameMap[name] = 1;
  14558. }
  14559. }
  14560. }
  14561. textStyleModel = textStyleModel.parentModel;
  14562. }
  14563. return richItemNameMap;
  14564. }
  14565. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14566. // In merge mode, default value should not be given.
  14567. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14568. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt) || globalTextStyle.color;
  14569. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt) || globalTextStyle.textBorderColor;
  14570. textStyle.textStrokeWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14571. if (!isEmphasis) {
  14572. if (isBlock) {
  14573. textStyle.insideRollbackOpt = opt;
  14574. applyDefaultTextStyle(textStyle);
  14575. } // Set default finally.
  14576. if (textStyle.textFill == null) {
  14577. textStyle.textFill = opt.autoColor;
  14578. }
  14579. } // Do not use `getFont` here, because merge should be supported, where
  14580. // part of these properties may be changed in emphasis style, and the
  14581. // others should remain their original value got from normal style.
  14582. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14583. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14584. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14585. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14586. textStyle.textAlign = textStyleModel.getShallow('align');
  14587. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign') || textStyleModel.getShallow('baseline');
  14588. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14589. textStyle.textWidth = textStyleModel.getShallow('width');
  14590. textStyle.textHeight = textStyleModel.getShallow('height');
  14591. textStyle.textTag = textStyleModel.getShallow('tag');
  14592. if (!isBlock || !opt.disableBox) {
  14593. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14594. textStyle.textPadding = textStyleModel.getShallow('padding');
  14595. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14596. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14597. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14598. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14599. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14600. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14601. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14602. }
  14603. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor') || globalTextStyle.textShadowColor;
  14604. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur') || globalTextStyle.textShadowBlur;
  14605. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX') || globalTextStyle.textShadowOffsetX;
  14606. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY') || globalTextStyle.textShadowOffsetY;
  14607. }
  14608. function getAutoColor(color, opt) {
  14609. return color !== 'auto' ? color : opt && opt.autoColor ? opt.autoColor : null;
  14610. }
  14611. /**
  14612. * Give some default value to the input `textStyle` object, based on the current settings
  14613. * in this `textStyle` object.
  14614. *
  14615. * The Scenario:
  14616. * when text position is `inside` and `textFill` is not specified, we show
  14617. * text border by default for better view. But it should be considered that text position
  14618. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  14619. * restore the style.
  14620. *
  14621. * Usage (& NOTICE):
  14622. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  14623. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  14624. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  14625. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  14626. * does, `rollbackDefaultTextStyle` is not needed to be called).
  14627. */
  14628. function applyDefaultTextStyle(textStyle) {
  14629. var textPosition = textStyle.textPosition;
  14630. var opt = textStyle.insideRollbackOpt;
  14631. var insideRollback;
  14632. if (opt && textStyle.textFill == null) {
  14633. var autoColor = opt.autoColor;
  14634. var isRectText = opt.isRectText;
  14635. var useInsideStyle = opt.useInsideStyle;
  14636. var useInsideStyleCache = useInsideStyle !== false && (useInsideStyle === true || isRectText && textPosition // textPosition can be [10, 30]
  14637. && typeof textPosition === 'string' && textPosition.indexOf('inside') >= 0);
  14638. var useAutoColorCache = !useInsideStyleCache && autoColor != null; // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  14639. if (useInsideStyleCache || useAutoColorCache) {
  14640. insideRollback = {
  14641. textFill: textStyle.textFill,
  14642. textStroke: textStyle.textStroke,
  14643. textStrokeWidth: textStyle.textStrokeWidth
  14644. };
  14645. }
  14646. if (useInsideStyleCache) {
  14647. textStyle.textFill = '#fff'; // Consider text with #fff overflow its container.
  14648. if (textStyle.textStroke == null) {
  14649. textStyle.textStroke = autoColor;
  14650. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14651. }
  14652. }
  14653. if (useAutoColorCache) {
  14654. textStyle.textFill = autoColor;
  14655. }
  14656. } // Always set `insideRollback`, so that the previous one can be cleared.
  14657. textStyle.insideRollback = insideRollback;
  14658. }
  14659. /**
  14660. * Consider the case: in a scatter,
  14661. * label: {
  14662. * normal: {position: 'inside'},
  14663. * emphasis: {position: 'top'}
  14664. * }
  14665. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  14666. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  14667. * should be retured to 'autoColor', but not keep '#fff'.
  14668. */
  14669. function rollbackDefaultTextStyle(style) {
  14670. var insideRollback = style.insideRollback;
  14671. if (insideRollback) {
  14672. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  14673. style.textFill = insideRollback.textFill;
  14674. style.textStroke = insideRollback.textStroke;
  14675. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14676. style.insideRollback = null;
  14677. }
  14678. }
  14679. function getFont(opt, ecModel) {
  14680. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14681. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14682. 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(' '));
  14683. }
  14684. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14685. if (typeof dataIndex === 'function') {
  14686. cb = dataIndex;
  14687. dataIndex = null;
  14688. } // Do not check 'animation' property directly here. Consider this case:
  14689. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14690. // but its parent model (`seriesModel`) does.
  14691. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14692. if (animationEnabled) {
  14693. var postfix = isUpdate ? 'Update' : '';
  14694. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14695. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14696. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14697. if (typeof animationDelay === 'function') {
  14698. animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14699. }
  14700. if (typeof duration === 'function') {
  14701. duration = duration(dataIndex);
  14702. }
  14703. duration > 0 ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb) : (el.stopAnimation(), el.attr(props), cb && cb());
  14704. } else {
  14705. el.stopAnimation();
  14706. el.attr(props);
  14707. cb && cb();
  14708. }
  14709. }
  14710. /**
  14711. * Update graphic element properties with or without animation according to the
  14712. * configuration in series.
  14713. *
  14714. * Caution: this method will stop previous animation.
  14715. * So do not use this method to one element twice before
  14716. * animation starts, unless you know what you are doing.
  14717. *
  14718. * @param {module:zrender/Element} el
  14719. * @param {Object} props
  14720. * @param {module:echarts/model/Model} [animatableModel]
  14721. * @param {number} [dataIndex]
  14722. * @param {Function} [cb]
  14723. * @example
  14724. * graphic.updateProps(el, {
  14725. * position: [100, 100]
  14726. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14727. * // Or
  14728. * graphic.updateProps(el, {
  14729. * position: [100, 100]
  14730. * }, seriesModel, function () { console.log('Animation done!'); });
  14731. */
  14732. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14733. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14734. }
  14735. /**
  14736. * Init graphic element properties with or without animation according to the
  14737. * configuration in series.
  14738. *
  14739. * Caution: this method will stop previous animation.
  14740. * So do not use this method to one element twice before
  14741. * animation starts, unless you know what you are doing.
  14742. *
  14743. * @param {module:zrender/Element} el
  14744. * @param {Object} props
  14745. * @param {module:echarts/model/Model} [animatableModel]
  14746. * @param {number} [dataIndex]
  14747. * @param {Function} cb
  14748. */
  14749. function initProps(el, props, animatableModel, dataIndex, cb) {
  14750. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14751. }
  14752. /**
  14753. * Get transform matrix of target (param target),
  14754. * in coordinate of its ancestor (param ancestor)
  14755. *
  14756. * @param {module:zrender/mixin/Transformable} target
  14757. * @param {module:zrender/mixin/Transformable} [ancestor]
  14758. */
  14759. function getTransform(target, ancestor) {
  14760. var mat = identity([]);
  14761. while (target && target !== ancestor) {
  14762. mul$1(mat, target.getLocalTransform(), mat);
  14763. target = target.parent;
  14764. }
  14765. return mat;
  14766. }
  14767. /**
  14768. * Apply transform to an vertex.
  14769. * @param {Array.<number>} target [x, y]
  14770. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14771. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14772. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14773. * @param {boolean=} invert Whether use invert matrix.
  14774. * @return {Array.<number>} [x, y]
  14775. */
  14776. function applyTransform$1(target, transform, invert$$1) {
  14777. if (transform && !isArrayLike(transform)) {
  14778. transform = Transformable.getLocalTransform(transform);
  14779. }
  14780. if (invert$$1) {
  14781. transform = invert([], transform);
  14782. }
  14783. return applyTransform([], target, transform);
  14784. }
  14785. /**
  14786. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14787. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14788. * @param {boolean=} invert Whether use invert matrix.
  14789. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14790. */
  14791. function transformDirection(direction, transform, invert$$1) {
  14792. // Pick a base, ensure that transform result will not be (0, 0).
  14793. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14794. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14795. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14796. vertex = applyTransform$1(vertex, transform, invert$$1);
  14797. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14798. }
  14799. /**
  14800. * Apply group transition animation from g1 to g2.
  14801. * If no animatableModel, no animation.
  14802. */
  14803. function groupTransition(g1, g2, animatableModel, cb) {
  14804. if (!g1 || !g2) {
  14805. return;
  14806. }
  14807. function getElMap(g) {
  14808. var elMap = {};
  14809. g.traverse(function (el) {
  14810. if (!el.isGroup && el.anid) {
  14811. elMap[el.anid] = el;
  14812. }
  14813. });
  14814. return elMap;
  14815. }
  14816. function getAnimatableProps(el) {
  14817. var obj = {
  14818. position: clone$1(el.position),
  14819. rotation: el.rotation
  14820. };
  14821. if (el.shape) {
  14822. obj.shape = extend({}, el.shape);
  14823. }
  14824. return obj;
  14825. }
  14826. var elMap1 = getElMap(g1);
  14827. g2.traverse(function (el) {
  14828. if (!el.isGroup && el.anid) {
  14829. var oldEl = elMap1[el.anid];
  14830. if (oldEl) {
  14831. var newProp = getAnimatableProps(el);
  14832. el.attr(getAnimatableProps(oldEl));
  14833. updateProps(el, newProp, animatableModel, el.dataIndex);
  14834. } // else {
  14835. // if (el.previousProps) {
  14836. // graphic.updateProps
  14837. // }
  14838. // }
  14839. }
  14840. });
  14841. }
  14842. /**
  14843. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14844. * @param {Object} rect {x, y, width, height}
  14845. * @return {Array.<Array.<number>>} A new clipped points.
  14846. */
  14847. function clipPointsByRect(points, rect) {
  14848. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14849. // and when element have border.
  14850. return map(points, function (point) {
  14851. var x = point[0];
  14852. x = mathMax$1(x, rect.x);
  14853. x = mathMin$1(x, rect.x + rect.width);
  14854. var y = point[1];
  14855. y = mathMax$1(y, rect.y);
  14856. y = mathMin$1(y, rect.y + rect.height);
  14857. return [x, y];
  14858. });
  14859. }
  14860. /**
  14861. * @param {Object} targetRect {x, y, width, height}
  14862. * @param {Object} rect {x, y, width, height}
  14863. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14864. */
  14865. function clipRectByRect(targetRect, rect) {
  14866. var x = mathMax$1(targetRect.x, rect.x);
  14867. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14868. var y = mathMax$1(targetRect.y, rect.y);
  14869. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14870. // should be painted. So return undefined.
  14871. if (x2 >= x && y2 >= y) {
  14872. return {
  14873. x: x,
  14874. y: y,
  14875. width: x2 - x,
  14876. height: y2 - y
  14877. };
  14878. }
  14879. }
  14880. /**
  14881. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14882. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14883. * @param {Object} [rect] {x, y, width, height}
  14884. * @return {module:zrender/Element} Icon path or image element.
  14885. */
  14886. function createIcon(iconStr, opt, rect) {
  14887. opt = extend({
  14888. rectHover: true
  14889. }, opt);
  14890. var style = opt.style = {
  14891. strokeNoScale: true
  14892. };
  14893. rect = rect || {
  14894. x: -1,
  14895. y: -1,
  14896. width: 2,
  14897. height: 2
  14898. };
  14899. if (iconStr) {
  14900. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZImage(opt)) : makePath(iconStr.replace('path://', ''), opt, rect, 'center');
  14901. }
  14902. }
  14903. /**
  14904. * Return `true` if the given line (line `a`) and the given polygon
  14905. * are intersect.
  14906. * Note that we do not count colinear as intersect here because no
  14907. * requirement for that. We could do that if required in future.
  14908. *
  14909. * @param {number} a1x
  14910. * @param {number} a1y
  14911. * @param {number} a2x
  14912. * @param {number} a2y
  14913. * @param {Array.<Array.<number>>} points Points of the polygon.
  14914. * @return {boolean}
  14915. */
  14916. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14917. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14918. var p = points[i];
  14919. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14920. return true;
  14921. }
  14922. p2 = p;
  14923. }
  14924. }
  14925. /**
  14926. * Return `true` if the given two lines (line `a` and line `b`)
  14927. * are intersect.
  14928. * Note that we do not count colinear as intersect here because no
  14929. * requirement for that. We could do that if required in future.
  14930. *
  14931. * @param {number} a1x
  14932. * @param {number} a1y
  14933. * @param {number} a2x
  14934. * @param {number} a2y
  14935. * @param {number} b1x
  14936. * @param {number} b1y
  14937. * @param {number} b2x
  14938. * @param {number} b2y
  14939. * @return {boolean}
  14940. */
  14941. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14942. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14943. var mx = a2x - a1x;
  14944. var my = a2y - a1y;
  14945. var nx = b2x - b1x;
  14946. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14947. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14948. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14949. if (nearZero(nmCrossProduct)) {
  14950. return false;
  14951. } // `vec_m` and `vec_n` are intersect iff
  14952. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14953. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14954. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14955. var b1a1x = a1x - b1x;
  14956. var b1a1y = a1y - b1y;
  14957. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14958. if (q < 0 || q > 1) {
  14959. return false;
  14960. }
  14961. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14962. if (p < 0 || p > 1) {
  14963. return false;
  14964. }
  14965. return true;
  14966. }
  14967. /**
  14968. * Cross product of 2-dimension vector.
  14969. */
  14970. function crossProduct2d(x1, y1, x2, y2) {
  14971. return x1 * y2 - x2 * y1;
  14972. }
  14973. function nearZero(val) {
  14974. return val <= 1e-6 && val >= -1e-6;
  14975. } // Register built-in shapes. These shapes might be overwirtten
  14976. // by users, although we do not recommend that.
  14977. registerShape('circle', Circle);
  14978. registerShape('sector', Sector);
  14979. registerShape('ring', Ring);
  14980. registerShape('polygon', Polygon);
  14981. registerShape('polyline', Polyline);
  14982. registerShape('rect', Rect);
  14983. registerShape('line', Line);
  14984. registerShape('bezierCurve', BezierCurve);
  14985. registerShape('arc', Arc);
  14986. var graphic = (Object.freeze || Object)({
  14987. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  14988. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  14989. extendShape: extendShape,
  14990. extendPath: extendPath,
  14991. registerShape: registerShape,
  14992. getShapeClass: getShapeClass,
  14993. makePath: makePath,
  14994. makeImage: makeImage,
  14995. mergePath: mergePath,
  14996. resizePath: resizePath,
  14997. subPixelOptimizeLine: subPixelOptimizeLine,
  14998. subPixelOptimizeRect: subPixelOptimizeRect,
  14999. subPixelOptimize: subPixelOptimize,
  15000. setElementHoverStyle: setElementHoverStyle,
  15001. setHoverStyle: setHoverStyle,
  15002. setAsHighDownDispatcher: setAsHighDownDispatcher,
  15003. isHighDownDispatcher: isHighDownDispatcher,
  15004. getHighlightDigit: getHighlightDigit,
  15005. setLabelStyle: setLabelStyle,
  15006. modifyLabelStyle: modifyLabelStyle,
  15007. setTextStyle: setTextStyle,
  15008. setText: setText,
  15009. getFont: getFont,
  15010. updateProps: updateProps,
  15011. initProps: initProps,
  15012. getTransform: getTransform,
  15013. applyTransform: applyTransform$1,
  15014. transformDirection: transformDirection,
  15015. groupTransition: groupTransition,
  15016. clipPointsByRect: clipPointsByRect,
  15017. clipRectByRect: clipRectByRect,
  15018. createIcon: createIcon,
  15019. linePolygonIntersect: linePolygonIntersect,
  15020. lineLineIntersect: lineLineIntersect,
  15021. Group: Group,
  15022. Image: ZImage,
  15023. Text: Text,
  15024. Circle: Circle,
  15025. Sector: Sector,
  15026. Ring: Ring,
  15027. Polygon: Polygon,
  15028. Polyline: Polyline,
  15029. Rect: Rect,
  15030. Line: Line,
  15031. BezierCurve: BezierCurve,
  15032. Arc: Arc,
  15033. IncrementalDisplayable: IncrementalDisplayble,
  15034. CompoundPath: CompoundPath,
  15035. LinearGradient: LinearGradient,
  15036. RadialGradient: RadialGradient,
  15037. BoundingRect: BoundingRect
  15038. });
  15039. /*
  15040. * Licensed to the Apache Software Foundation (ASF) under one
  15041. * or more contributor license agreements. See the NOTICE file
  15042. * distributed with this work for additional information
  15043. * regarding copyright ownership. The ASF licenses this file
  15044. * to you under the Apache License, Version 2.0 (the
  15045. * "License"); you may not use this file except in compliance
  15046. * with the License. You may obtain a copy of the License at
  15047. *
  15048. * http://www.apache.org/licenses/LICENSE-2.0
  15049. *
  15050. * Unless required by applicable law or agreed to in writing,
  15051. * software distributed under the License is distributed on an
  15052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15053. * KIND, either express or implied. See the License for the
  15054. * specific language governing permissions and limitations
  15055. * under the License.
  15056. */
  15057. var PATH_COLOR = ['textStyle', 'color'];
  15058. var textStyleMixin = {
  15059. /**
  15060. * Get color property or get color from option.textStyle.color
  15061. * @param {boolean} [isEmphasis]
  15062. * @return {string}
  15063. */
  15064. getTextColor: function (isEmphasis) {
  15065. var ecModel = this.ecModel;
  15066. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15067. },
  15068. /**
  15069. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15070. * @return {string}
  15071. */
  15072. getFont: function () {
  15073. return getFont({
  15074. fontStyle: this.getShallow('fontStyle'),
  15075. fontWeight: this.getShallow('fontWeight'),
  15076. fontSize: this.getShallow('fontSize'),
  15077. fontFamily: this.getShallow('fontFamily')
  15078. }, this.ecModel);
  15079. },
  15080. getTextRect: function (text) {
  15081. return getBoundingRect(text, this.getFont(), this.getShallow('align'), this.getShallow('verticalAlign') || this.getShallow('baseline'), this.getShallow('padding'), this.getShallow('lineHeight'), this.getShallow('rich'), this.getShallow('truncateText'));
  15082. }
  15083. };
  15084. /*
  15085. * Licensed to the Apache Software Foundation (ASF) under one
  15086. * or more contributor license agreements. See the NOTICE file
  15087. * distributed with this work for additional information
  15088. * regarding copyright ownership. The ASF licenses this file
  15089. * to you under the Apache License, Version 2.0 (the
  15090. * "License"); you may not use this file except in compliance
  15091. * with the License. You may obtain a copy of the License at
  15092. *
  15093. * http://www.apache.org/licenses/LICENSE-2.0
  15094. *
  15095. * Unless required by applicable law or agreed to in writing,
  15096. * software distributed under the License is distributed on an
  15097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15098. * KIND, either express or implied. See the License for the
  15099. * specific language governing permissions and limitations
  15100. * under the License.
  15101. */
  15102. var getItemStyle = makeStyleMapper([['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['textPosition'], ['textAlign']]);
  15103. var itemStyleMixin = {
  15104. getItemStyle: function (excludes, includes) {
  15105. var style = getItemStyle(this, excludes, includes);
  15106. var lineDash = this.getBorderLineDash();
  15107. lineDash && (style.lineDash = lineDash);
  15108. return style;
  15109. },
  15110. getBorderLineDash: function () {
  15111. var lineType = this.get('borderType');
  15112. return lineType === 'solid' || lineType == null ? null : lineType === 'dashed' ? [5, 5] : [1, 1];
  15113. }
  15114. };
  15115. /*
  15116. * Licensed to the Apache Software Foundation (ASF) under one
  15117. * or more contributor license agreements. See the NOTICE file
  15118. * distributed with this work for additional information
  15119. * regarding copyright ownership. The ASF licenses this file
  15120. * to you under the Apache License, Version 2.0 (the
  15121. * "License"); you may not use this file except in compliance
  15122. * with the License. You may obtain a copy of the License at
  15123. *
  15124. * http://www.apache.org/licenses/LICENSE-2.0
  15125. *
  15126. * Unless required by applicable law or agreed to in writing,
  15127. * software distributed under the License is distributed on an
  15128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15129. * KIND, either express or implied. See the License for the
  15130. * specific language governing permissions and limitations
  15131. * under the License.
  15132. */
  15133. /**
  15134. * @module echarts/model/Model
  15135. */
  15136. var mixin$1 = mixin;
  15137. var inner = makeInner();
  15138. /**
  15139. * @alias module:echarts/model/Model
  15140. * @constructor
  15141. * @param {Object} [option]
  15142. * @param {module:echarts/model/Model} [parentModel]
  15143. * @param {module:echarts/model/Global} [ecModel]
  15144. */
  15145. function Model(option, parentModel, ecModel) {
  15146. /**
  15147. * @type {module:echarts/model/Model}
  15148. * @readOnly
  15149. */
  15150. this.parentModel = parentModel;
  15151. /**
  15152. * @type {module:echarts/model/Global}
  15153. * @readOnly
  15154. */
  15155. this.ecModel = ecModel;
  15156. /**
  15157. * @type {Object}
  15158. * @protected
  15159. */
  15160. this.option = option; // Simple optimization
  15161. // if (this.init) {
  15162. // if (arguments.length <= 4) {
  15163. // this.init(option, parentModel, ecModel, extraOpt);
  15164. // }
  15165. // else {
  15166. // this.init.apply(this, arguments);
  15167. // }
  15168. // }
  15169. }
  15170. Model.prototype = {
  15171. constructor: Model,
  15172. /**
  15173. * Model 的初始化函数
  15174. * @param {Object} option
  15175. */
  15176. init: null,
  15177. /**
  15178. * 从新的 Option merge
  15179. */
  15180. mergeOption: function (option) {
  15181. merge(this.option, option, true);
  15182. },
  15183. /**
  15184. * @param {string|Array.<string>} path
  15185. * @param {boolean} [ignoreParent=false]
  15186. * @return {*}
  15187. */
  15188. get: function (path, ignoreParent) {
  15189. if (path == null) {
  15190. return this.option;
  15191. }
  15192. return doGet(this.option, this.parsePath(path), !ignoreParent && getParent(this, path));
  15193. },
  15194. /**
  15195. * @param {string} key
  15196. * @param {boolean} [ignoreParent=false]
  15197. * @return {*}
  15198. */
  15199. getShallow: function (key, ignoreParent) {
  15200. var option = this.option;
  15201. var val = option == null ? option : option[key];
  15202. var parentModel = !ignoreParent && getParent(this, key);
  15203. if (val == null && parentModel) {
  15204. val = parentModel.getShallow(key);
  15205. }
  15206. return val;
  15207. },
  15208. /**
  15209. * @param {string|Array.<string>} [path]
  15210. * @param {module:echarts/model/Model} [parentModel]
  15211. * @return {module:echarts/model/Model}
  15212. */
  15213. getModel: function (path, parentModel) {
  15214. var obj = path == null ? this.option : doGet(this.option, path = this.parsePath(path));
  15215. var thisParentModel;
  15216. parentModel = parentModel || (thisParentModel = getParent(this, path)) && thisParentModel.getModel(path);
  15217. return new Model(obj, parentModel, this.ecModel);
  15218. },
  15219. /**
  15220. * If model has option
  15221. */
  15222. isEmpty: function () {
  15223. return this.option == null;
  15224. },
  15225. restoreData: function () {},
  15226. // Pending
  15227. clone: function () {
  15228. var Ctor = this.constructor;
  15229. return new Ctor(clone(this.option));
  15230. },
  15231. setReadOnly: function (properties) {// clazzUtil.setReadOnly(this, properties);
  15232. },
  15233. // If path is null/undefined, return null/undefined.
  15234. parsePath: function (path) {
  15235. if (typeof path === 'string') {
  15236. path = path.split('.');
  15237. }
  15238. return path;
  15239. },
  15240. /**
  15241. * @param {Function} getParentMethod
  15242. * param {Array.<string>|string} path
  15243. * return {module:echarts/model/Model}
  15244. */
  15245. customizeGetParent: function (getParentMethod) {
  15246. inner(this).getParent = getParentMethod;
  15247. },
  15248. isAnimationEnabled: function () {
  15249. if (!env$1.node) {
  15250. if (this.option.animation != null) {
  15251. return !!this.option.animation;
  15252. } else if (this.parentModel) {
  15253. return this.parentModel.isAnimationEnabled();
  15254. }
  15255. }
  15256. }
  15257. };
  15258. function doGet(obj, pathArr, parentModel) {
  15259. for (var i = 0; i < pathArr.length; i++) {
  15260. // Ignore empty
  15261. if (!pathArr[i]) {
  15262. continue;
  15263. } // obj could be number/string/... (like 0)
  15264. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15265. if (obj == null) {
  15266. break;
  15267. }
  15268. }
  15269. if (obj == null && parentModel) {
  15270. obj = parentModel.get(pathArr);
  15271. }
  15272. return obj;
  15273. } // `path` can be null/undefined
  15274. function getParent(model, path) {
  15275. var getParentMethod = inner(model).getParent;
  15276. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15277. } // Enable Model.extend.
  15278. enableClassExtend(Model);
  15279. enableClassCheck(Model);
  15280. mixin$1(Model, lineStyleMixin);
  15281. mixin$1(Model, areaStyleMixin);
  15282. mixin$1(Model, textStyleMixin);
  15283. mixin$1(Model, itemStyleMixin);
  15284. /*
  15285. * Licensed to the Apache Software Foundation (ASF) under one
  15286. * or more contributor license agreements. See the NOTICE file
  15287. * distributed with this work for additional information
  15288. * regarding copyright ownership. The ASF licenses this file
  15289. * to you under the Apache License, Version 2.0 (the
  15290. * "License"); you may not use this file except in compliance
  15291. * with the License. You may obtain a copy of the License at
  15292. *
  15293. * http://www.apache.org/licenses/LICENSE-2.0
  15294. *
  15295. * Unless required by applicable law or agreed to in writing,
  15296. * software distributed under the License is distributed on an
  15297. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15298. * KIND, either express or implied. See the License for the
  15299. * specific language governing permissions and limitations
  15300. * under the License.
  15301. */
  15302. var base = 0;
  15303. /**
  15304. * @public
  15305. * @param {string} type
  15306. * @return {string}
  15307. */
  15308. function getUID(type) {
  15309. // Considering the case of crossing js context,
  15310. // use Math.random to make id as unique as possible.
  15311. return [type || '', base++, Math.random().toFixed(5)].join('_');
  15312. }
  15313. /**
  15314. * @inner
  15315. */
  15316. function enableSubTypeDefaulter(entity) {
  15317. var subTypeDefaulters = {};
  15318. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15319. componentType = parseClassType$1(componentType);
  15320. subTypeDefaulters[componentType.main] = defaulter;
  15321. };
  15322. entity.determineSubType = function (componentType, option) {
  15323. var type = option.type;
  15324. if (!type) {
  15325. var componentTypeMain = parseClassType$1(componentType).main;
  15326. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15327. type = subTypeDefaulters[componentTypeMain](option);
  15328. }
  15329. }
  15330. return type;
  15331. };
  15332. return entity;
  15333. }
  15334. /**
  15335. * Topological travel on Activity Network (Activity On Vertices).
  15336. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15337. *
  15338. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15339. *
  15340. * If there is circle dependencey, Error will be thrown.
  15341. *
  15342. */
  15343. function enableTopologicalTravel(entity, dependencyGetter) {
  15344. /**
  15345. * @public
  15346. * @param {Array.<string>} targetNameList Target Component type list.
  15347. * Can be ['aa', 'bb', 'aa.xx']
  15348. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15349. * @param {Function} callback Params: componentType, dependencies.
  15350. * @param {Object} context Scope of callback.
  15351. */
  15352. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15353. if (!targetNameList.length) {
  15354. return;
  15355. }
  15356. var result = makeDepndencyGraph(fullNameList);
  15357. var graph = result.graph;
  15358. var stack = result.noEntryList;
  15359. var targetNameSet = {};
  15360. each$1(targetNameList, function (name) {
  15361. targetNameSet[name] = true;
  15362. });
  15363. while (stack.length) {
  15364. var currComponentType = stack.pop();
  15365. var currVertex = graph[currComponentType];
  15366. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15367. if (isInTargetNameSet) {
  15368. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15369. delete targetNameSet[currComponentType];
  15370. }
  15371. each$1(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15372. }
  15373. each$1(targetNameSet, function () {
  15374. throw new Error('Circle dependency may exists');
  15375. });
  15376. function removeEdge(succComponentType) {
  15377. graph[succComponentType].entryCount--;
  15378. if (graph[succComponentType].entryCount === 0) {
  15379. stack.push(succComponentType);
  15380. }
  15381. } // Consider this case: legend depends on series, and we call
  15382. // chart.setOption({series: [...]}), where only series is in option.
  15383. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15384. // not be called, but only sereis.mergeOption is called. Thus legend
  15385. // have no chance to update its local record about series (like which
  15386. // name of series is available in legend).
  15387. function removeEdgeAndAdd(succComponentType) {
  15388. targetNameSet[succComponentType] = true;
  15389. removeEdge(succComponentType);
  15390. }
  15391. };
  15392. /**
  15393. * DepndencyGraph: {Object}
  15394. * key: conponentType,
  15395. * value: {
  15396. * successor: [conponentTypes...],
  15397. * originalDeps: [conponentTypes...],
  15398. * entryCount: {number}
  15399. * }
  15400. */
  15401. function makeDepndencyGraph(fullNameList) {
  15402. var graph = {};
  15403. var noEntryList = [];
  15404. each$1(fullNameList, function (name) {
  15405. var thisItem = createDependencyGraphItem(graph, name);
  15406. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15407. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15408. thisItem.entryCount = availableDeps.length;
  15409. if (thisItem.entryCount === 0) {
  15410. noEntryList.push(name);
  15411. }
  15412. each$1(availableDeps, function (dependentName) {
  15413. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15414. thisItem.predecessor.push(dependentName);
  15415. }
  15416. var thatItem = createDependencyGraphItem(graph, dependentName);
  15417. if (indexOf(thatItem.successor, dependentName) < 0) {
  15418. thatItem.successor.push(name);
  15419. }
  15420. });
  15421. });
  15422. return {
  15423. graph: graph,
  15424. noEntryList: noEntryList
  15425. };
  15426. }
  15427. function createDependencyGraphItem(graph, name) {
  15428. if (!graph[name]) {
  15429. graph[name] = {
  15430. predecessor: [],
  15431. successor: []
  15432. };
  15433. }
  15434. return graph[name];
  15435. }
  15436. function getAvailableDependencies(originalDeps, fullNameList) {
  15437. var availableDeps = [];
  15438. each$1(originalDeps, function (dep) {
  15439. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15440. });
  15441. return availableDeps;
  15442. }
  15443. }
  15444. /*
  15445. * Licensed to the Apache Software Foundation (ASF) under one
  15446. * or more contributor license agreements. See the NOTICE file
  15447. * distributed with this work for additional information
  15448. * regarding copyright ownership. The ASF licenses this file
  15449. * to you under the Apache License, Version 2.0 (the
  15450. * "License"); you may not use this file except in compliance
  15451. * with the License. You may obtain a copy of the License at
  15452. *
  15453. * http://www.apache.org/licenses/LICENSE-2.0
  15454. *
  15455. * Unless required by applicable law or agreed to in writing,
  15456. * software distributed under the License is distributed on an
  15457. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15458. * KIND, either express or implied. See the License for the
  15459. * specific language governing permissions and limitations
  15460. * under the License.
  15461. */
  15462. /*
  15463. * A third-party license is embeded for some of the code in this file:
  15464. * The method "quantile" was copied from "d3.js".
  15465. * (See more details in the comment of the method below.)
  15466. * The use of the source code of this file is also subject to the terms
  15467. * and consitions of the license of "d3.js" (BSD-3Clause, see
  15468. * </licenses/LICENSE-d3>).
  15469. */
  15470. var RADIAN_EPSILON = 1e-4;
  15471. function _trim(str) {
  15472. return str.replace(/^\s+|\s+$/g, '');
  15473. }
  15474. /**
  15475. * Linear mapping a value from domain to range
  15476. * @memberOf module:echarts/util/number
  15477. * @param {(number|Array.<number>)} val
  15478. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15479. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15480. * @param {boolean} clamp
  15481. * @return {(number|Array.<number>}
  15482. */
  15483. function linearMap(val, domain, range, clamp) {
  15484. var subDomain = domain[1] - domain[0];
  15485. var subRange = range[1] - range[0];
  15486. if (subDomain === 0) {
  15487. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  15488. } // Avoid accuracy problem in edge, such as
  15489. // 146.39 - 62.83 === 83.55999999999999.
  15490. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15491. // It is a little verbose for efficiency considering this method
  15492. // is a hotspot.
  15493. if (clamp) {
  15494. if (subDomain > 0) {
  15495. if (val <= domain[0]) {
  15496. return range[0];
  15497. } else if (val >= domain[1]) {
  15498. return range[1];
  15499. }
  15500. } else {
  15501. if (val >= domain[0]) {
  15502. return range[0];
  15503. } else if (val <= domain[1]) {
  15504. return range[1];
  15505. }
  15506. }
  15507. } else {
  15508. if (val === domain[0]) {
  15509. return range[0];
  15510. }
  15511. if (val === domain[1]) {
  15512. return range[1];
  15513. }
  15514. }
  15515. return (val - domain[0]) / subDomain * subRange + range[0];
  15516. }
  15517. /**
  15518. * Convert a percent string to absolute number.
  15519. * Returns NaN if percent is not a valid string or number
  15520. * @memberOf module:echarts/util/number
  15521. * @param {string|number} percent
  15522. * @param {number} all
  15523. * @return {number}
  15524. */
  15525. function parsePercent$1(percent, all) {
  15526. switch (percent) {
  15527. case 'center':
  15528. case 'middle':
  15529. percent = '50%';
  15530. break;
  15531. case 'left':
  15532. case 'top':
  15533. percent = '0%';
  15534. break;
  15535. case 'right':
  15536. case 'bottom':
  15537. percent = '100%';
  15538. break;
  15539. }
  15540. if (typeof percent === 'string') {
  15541. if (_trim(percent).match(/%$/)) {
  15542. return parseFloat(percent) / 100 * all;
  15543. }
  15544. return parseFloat(percent);
  15545. }
  15546. return percent == null ? NaN : +percent;
  15547. }
  15548. /**
  15549. * (1) Fix rounding error of float numbers.
  15550. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15551. *
  15552. * @param {number} x
  15553. * @param {number} [precision]
  15554. * @param {boolean} [returnStr]
  15555. * @return {number|string}
  15556. */
  15557. function round$1(x, precision, returnStr) {
  15558. if (precision == null) {
  15559. precision = 10;
  15560. } // Avoid range error
  15561. precision = Math.min(Math.max(0, precision), 20);
  15562. x = (+x).toFixed(precision);
  15563. return returnStr ? x : +x;
  15564. }
  15565. /**
  15566. * asc sort arr.
  15567. * The input arr will be modified.
  15568. *
  15569. * @param {Array} arr
  15570. * @return {Array} The input arr.
  15571. */
  15572. function asc(arr) {
  15573. arr.sort(function (a, b) {
  15574. return a - b;
  15575. });
  15576. return arr;
  15577. }
  15578. /**
  15579. * Get precision
  15580. * @param {number} val
  15581. */
  15582. function getPrecision(val) {
  15583. val = +val;
  15584. if (isNaN(val)) {
  15585. return 0;
  15586. } // It is much faster than methods converting number to string as follows
  15587. // var tmp = val.toString();
  15588. // return tmp.length - 1 - tmp.indexOf('.');
  15589. // especially when precision is low
  15590. var e = 1;
  15591. var count = 0;
  15592. while (Math.round(val * e) / e !== val) {
  15593. e *= 10;
  15594. count++;
  15595. }
  15596. return count;
  15597. }
  15598. /**
  15599. * @param {string|number} val
  15600. * @return {number}
  15601. */
  15602. function getPrecisionSafe(val) {
  15603. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  15604. var eIndex = str.indexOf('e');
  15605. if (eIndex > 0) {
  15606. var precision = +str.slice(eIndex + 1);
  15607. return precision < 0 ? -precision : 0;
  15608. } else {
  15609. var dotIndex = str.indexOf('.');
  15610. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15611. }
  15612. }
  15613. /**
  15614. * Minimal dicernible data precisioin according to a single pixel.
  15615. *
  15616. * @param {Array.<number>} dataExtent
  15617. * @param {Array.<number>} pixelExtent
  15618. * @return {number} precision
  15619. */
  15620. function getPixelPrecision(dataExtent, pixelExtent) {
  15621. var log = Math.log;
  15622. var LN10 = Math.LN10;
  15623. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15624. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  15625. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15626. return !isFinite(precision) ? 20 : precision;
  15627. }
  15628. /**
  15629. * Get a data of given precision, assuring the sum of percentages
  15630. * in valueList is 1.
  15631. * The largest remainer method is used.
  15632. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15633. *
  15634. * @param {Array.<number>} valueList a list of all data
  15635. * @param {number} idx index of the data to be processed in valueList
  15636. * @param {number} precision integer number showing digits of precision
  15637. * @return {number} percent ranging from 0 to 100
  15638. */
  15639. function getPercentWithPrecision(valueList, idx, precision) {
  15640. if (!valueList[idx]) {
  15641. return 0;
  15642. }
  15643. var sum = reduce(valueList, function (acc, val) {
  15644. return acc + (isNaN(val) ? 0 : val);
  15645. }, 0);
  15646. if (sum === 0) {
  15647. return 0;
  15648. }
  15649. var digits = Math.pow(10, precision);
  15650. var votesPerQuota = map(valueList, function (val) {
  15651. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15652. });
  15653. var targetSeats = digits * 100;
  15654. var seats = map(votesPerQuota, function (votes) {
  15655. // Assign automatic seats.
  15656. return Math.floor(votes);
  15657. });
  15658. var currentSum = reduce(seats, function (acc, val) {
  15659. return acc + val;
  15660. }, 0);
  15661. var remainder = map(votesPerQuota, function (votes, idx) {
  15662. return votes - seats[idx];
  15663. }); // Has remainding votes.
  15664. while (currentSum < targetSeats) {
  15665. // Find next largest remainder.
  15666. var max = Number.NEGATIVE_INFINITY;
  15667. var maxId = null;
  15668. for (var i = 0, len = remainder.length; i < len; ++i) {
  15669. if (remainder[i] > max) {
  15670. max = remainder[i];
  15671. maxId = i;
  15672. }
  15673. } // Add a vote to max remainder.
  15674. ++seats[maxId];
  15675. remainder[maxId] = 0;
  15676. ++currentSum;
  15677. }
  15678. return seats[idx] / digits;
  15679. } // Number.MAX_SAFE_INTEGER, ie do not support.
  15680. var MAX_SAFE_INTEGER = 9007199254740991;
  15681. /**
  15682. * To 0 - 2 * PI, considering negative radian.
  15683. * @param {number} radian
  15684. * @return {number}
  15685. */
  15686. function remRadian(radian) {
  15687. var pi2 = Math.PI * 2;
  15688. return (radian % pi2 + pi2) % pi2;
  15689. }
  15690. /**
  15691. * @param {type} radian
  15692. * @return {boolean}
  15693. */
  15694. function isRadianAroundZero(val) {
  15695. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15696. }
  15697. /* eslint-disable */
  15698. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  15699. /* eslint-enable */
  15700. /**
  15701. * @param {string|Date|number} value These values can be accepted:
  15702. * + An instance of Date, represent a time in its own time zone.
  15703. * + Or string in a subset of ISO 8601, only including:
  15704. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15705. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15706. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15707. * all of which will be treated as local time if time zone is not specified
  15708. * (see <https://momentjs.com/>).
  15709. * + Or other string format, including (all of which will be treated as loacal time):
  15710. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15711. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15712. * + a timestamp, which represent a time in UTC.
  15713. * @return {Date} date
  15714. */
  15715. function parseDate(value) {
  15716. if (value instanceof Date) {
  15717. return value;
  15718. } else if (typeof value === 'string') {
  15719. // Different browsers parse date in different way, so we parse it manually.
  15720. // Some other issues:
  15721. // new Date('1970-01-01') is UTC,
  15722. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15723. // See issue #3623
  15724. var match = TIME_REG.exec(value);
  15725. if (!match) {
  15726. // return Invalid Date.
  15727. return new Date(NaN);
  15728. } // Use local time when no timezone offset specifed.
  15729. if (!match[8]) {
  15730. // match[n] can only be string or undefined.
  15731. // But take care of '12' + 1 => '121'.
  15732. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  15733. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15734. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15735. // For example, system timezone is set as "Time Zone: America/Toronto",
  15736. // then these code will get different result:
  15737. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15738. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15739. // So we should not use `new Date`, but use `Date.UTC`.
  15740. else {
  15741. var hour = +match[4] || 0;
  15742. if (match[8].toUpperCase() !== 'Z') {
  15743. hour -= match[8].slice(0, 3);
  15744. }
  15745. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  15746. }
  15747. } else if (value == null) {
  15748. return new Date(NaN);
  15749. }
  15750. return new Date(Math.round(value));
  15751. }
  15752. /**
  15753. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15754. *
  15755. * @param {number} val
  15756. * @return {number}
  15757. */
  15758. function quantity(val) {
  15759. return Math.pow(10, quantityExponent(val));
  15760. }
  15761. /**
  15762. * Exponent of the quantity of a number
  15763. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  15764. *
  15765. * @param {number} val non-negative value
  15766. * @return {number}
  15767. */
  15768. function quantityExponent(val) {
  15769. if (val === 0) {
  15770. return 0;
  15771. }
  15772. var exp = Math.floor(Math.log(val) / Math.LN10);
  15773. /**
  15774. * exp is expected to be the rounded-down result of the base-10 log of val.
  15775. * But due to the precision loss with Math.log(val), we need to restore it
  15776. * using 10^exp to make sure we can get val back from exp. #11249
  15777. */
  15778. if (val / Math.pow(10, exp) >= 10) {
  15779. exp++;
  15780. }
  15781. return exp;
  15782. }
  15783. /**
  15784. * find a “nice” number approximately equal to x. Round the number if round = true,
  15785. * take ceiling if round = false. The primary observation is that the “nicest”
  15786. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15787. *
  15788. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15789. *
  15790. * @param {number} val Non-negative value.
  15791. * @param {boolean} round
  15792. * @return {number}
  15793. */
  15794. function nice(val, round) {
  15795. var exponent = quantityExponent(val);
  15796. var exp10 = Math.pow(10, exponent);
  15797. var f = val / exp10; // 1 <= f < 10
  15798. var nf;
  15799. if (round) {
  15800. if (f < 1.5) {
  15801. nf = 1;
  15802. } else if (f < 2.5) {
  15803. nf = 2;
  15804. } else if (f < 4) {
  15805. nf = 3;
  15806. } else if (f < 7) {
  15807. nf = 5;
  15808. } else {
  15809. nf = 10;
  15810. }
  15811. } else {
  15812. if (f < 1) {
  15813. nf = 1;
  15814. } else if (f < 2) {
  15815. nf = 2;
  15816. } else if (f < 3) {
  15817. nf = 3;
  15818. } else if (f < 5) {
  15819. nf = 5;
  15820. } else {
  15821. nf = 10;
  15822. }
  15823. }
  15824. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15825. // 20 is the uppper bound of toFixed.
  15826. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15827. }
  15828. /**
  15829. * This code was copied from "d3.js"
  15830. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  15831. * See the license statement at the head of this file.
  15832. * @param {Array.<number>} ascArr
  15833. */
  15834. function quantile(ascArr, p) {
  15835. var H = (ascArr.length - 1) * p + 1;
  15836. var h = Math.floor(H);
  15837. var v = +ascArr[h - 1];
  15838. var e = H - h;
  15839. return e ? v + e * (ascArr[h] - v) : v;
  15840. }
  15841. /**
  15842. * Order intervals asc, and split them when overlap.
  15843. * expect(numberUtil.reformIntervals([
  15844. * {interval: [18, 62], close: [1, 1]},
  15845. * {interval: [-Infinity, -70], close: [0, 0]},
  15846. * {interval: [-70, -26], close: [1, 1]},
  15847. * {interval: [-26, 18], close: [1, 1]},
  15848. * {interval: [62, 150], close: [1, 1]},
  15849. * {interval: [106, 150], close: [1, 1]},
  15850. * {interval: [150, Infinity], close: [0, 0]}
  15851. * ])).toEqual([
  15852. * {interval: [-Infinity, -70], close: [0, 0]},
  15853. * {interval: [-70, -26], close: [1, 1]},
  15854. * {interval: [-26, 18], close: [0, 1]},
  15855. * {interval: [18, 62], close: [0, 1]},
  15856. * {interval: [62, 150], close: [0, 1]},
  15857. * {interval: [150, Infinity], close: [0, 0]}
  15858. * ]);
  15859. * @param {Array.<Object>} list, where `close` mean open or close
  15860. * of the interval, and Infinity can be used.
  15861. * @return {Array.<Object>} The origin list, which has been reformed.
  15862. */
  15863. function reformIntervals(list) {
  15864. list.sort(function (a, b) {
  15865. return littleThan(a, b, 0) ? -1 : 1;
  15866. });
  15867. var curr = -Infinity;
  15868. var currClose = 1;
  15869. for (var i = 0; i < list.length;) {
  15870. var interval = list[i].interval;
  15871. var close = list[i].close;
  15872. for (var lg = 0; lg < 2; lg++) {
  15873. if (interval[lg] <= curr) {
  15874. interval[lg] = curr;
  15875. close[lg] = !lg ? 1 - currClose : 1;
  15876. }
  15877. curr = interval[lg];
  15878. currClose = close[lg];
  15879. }
  15880. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15881. list.splice(i, 1);
  15882. } else {
  15883. i++;
  15884. }
  15885. }
  15886. return list;
  15887. function littleThan(a, b, lg) {
  15888. 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));
  15889. }
  15890. }
  15891. /**
  15892. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15893. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15894. * subtraction forces infinities to NaN
  15895. *
  15896. * @param {*} v
  15897. * @return {boolean}
  15898. */
  15899. function isNumeric(v) {
  15900. return v - parseFloat(v) >= 0;
  15901. }
  15902. var number = (Object.freeze || Object)({
  15903. linearMap: linearMap,
  15904. parsePercent: parsePercent$1,
  15905. round: round$1,
  15906. asc: asc,
  15907. getPrecision: getPrecision,
  15908. getPrecisionSafe: getPrecisionSafe,
  15909. getPixelPrecision: getPixelPrecision,
  15910. getPercentWithPrecision: getPercentWithPrecision,
  15911. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15912. remRadian: remRadian,
  15913. isRadianAroundZero: isRadianAroundZero,
  15914. parseDate: parseDate,
  15915. quantity: quantity,
  15916. quantityExponent: quantityExponent,
  15917. nice: nice,
  15918. quantile: quantile,
  15919. reformIntervals: reformIntervals,
  15920. isNumeric: isNumeric
  15921. });
  15922. /*
  15923. * Licensed to the Apache Software Foundation (ASF) under one
  15924. * or more contributor license agreements. See the NOTICE file
  15925. * distributed with this work for additional information
  15926. * regarding copyright ownership. The ASF licenses this file
  15927. * to you under the Apache License, Version 2.0 (the
  15928. * "License"); you may not use this file except in compliance
  15929. * with the License. You may obtain a copy of the License at
  15930. *
  15931. * http://www.apache.org/licenses/LICENSE-2.0
  15932. *
  15933. * Unless required by applicable law or agreed to in writing,
  15934. * software distributed under the License is distributed on an
  15935. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15936. * KIND, either express or implied. See the License for the
  15937. * specific language governing permissions and limitations
  15938. * under the License.
  15939. */
  15940. /**
  15941. * add commas after every three numbers
  15942. * @param {string|number} x
  15943. * @return {string}
  15944. */
  15945. function addCommas(x) {
  15946. if (isNaN(x)) {
  15947. return '-';
  15948. }
  15949. x = (x + '').split('.');
  15950. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (x.length > 1 ? '.' + x[1] : '');
  15951. }
  15952. /**
  15953. * @param {string} str
  15954. * @param {boolean} [upperCaseFirst=false]
  15955. * @return {string} str
  15956. */
  15957. function toCamelCase(str, upperCaseFirst) {
  15958. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15959. return group1.toUpperCase();
  15960. });
  15961. if (upperCaseFirst && str) {
  15962. str = str.charAt(0).toUpperCase() + str.slice(1);
  15963. }
  15964. return str;
  15965. }
  15966. var normalizeCssArray$1 = normalizeCssArray;
  15967. var replaceReg = /([&<>"'])/g;
  15968. var replaceMap = {
  15969. '&': '&amp;',
  15970. '<': '&lt;',
  15971. '>': '&gt;',
  15972. '"': '&quot;',
  15973. '\'': '&#39;'
  15974. };
  15975. function encodeHTML(source) {
  15976. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15977. return replaceMap[c];
  15978. });
  15979. }
  15980. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15981. var wrapVar = function (varName, seriesIdx) {
  15982. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15983. };
  15984. /**
  15985. * Template formatter
  15986. * @param {string} tpl
  15987. * @param {Array.<Object>|Object} paramsList
  15988. * @param {boolean} [encode=false]
  15989. * @return {string}
  15990. */
  15991. function formatTpl(tpl, paramsList, encode) {
  15992. if (!isArray(paramsList)) {
  15993. paramsList = [paramsList];
  15994. }
  15995. var seriesLen = paramsList.length;
  15996. if (!seriesLen) {
  15997. return '';
  15998. }
  15999. var $vars = paramsList[0].$vars || [];
  16000. for (var i = 0; i < $vars.length; i++) {
  16001. var alias = TPL_VAR_ALIAS[i];
  16002. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16003. }
  16004. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16005. for (var k = 0; k < $vars.length; k++) {
  16006. var val = paramsList[seriesIdx][$vars[k]];
  16007. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16008. }
  16009. }
  16010. return tpl;
  16011. }
  16012. /**
  16013. * simple Template formatter
  16014. *
  16015. * @param {string} tpl
  16016. * @param {Object} param
  16017. * @param {boolean} [encode=false]
  16018. * @return {string}
  16019. */
  16020. function formatTplSimple(tpl, param, encode) {
  16021. each$1(param, function (value, key) {
  16022. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  16023. });
  16024. return tpl;
  16025. }
  16026. /**
  16027. * @param {Object|string} [opt] If string, means color.
  16028. * @param {string} [opt.color]
  16029. * @param {string} [opt.extraCssText]
  16030. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16031. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16032. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16033. * @return {string}
  16034. */
  16035. function getTooltipMarker(opt, extraCssText) {
  16036. opt = isString(opt) ? {
  16037. color: opt,
  16038. extraCssText: extraCssText
  16039. } : opt || {};
  16040. var color = opt.color;
  16041. var type = opt.type;
  16042. var extraCssText = opt.extraCssText;
  16043. var renderMode = opt.renderMode || 'html';
  16044. var markerId = opt.markerId || 'X';
  16045. if (!color) {
  16046. return '';
  16047. }
  16048. if (renderMode === 'html') {
  16049. 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:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16050. } else {
  16051. // Space for rich element marker
  16052. return {
  16053. renderMode: renderMode,
  16054. content: '{marker' + markerId + '|} ',
  16055. style: {
  16056. color: color
  16057. }
  16058. };
  16059. }
  16060. }
  16061. function pad(str, len) {
  16062. str += '';
  16063. return '0000'.substr(0, len - str.length) + str;
  16064. }
  16065. /**
  16066. * ISO Date format
  16067. * @param {string} tpl
  16068. * @param {number} value
  16069. * @param {boolean} [isUTC=false] Default in local time.
  16070. * see `module:echarts/scale/Time`
  16071. * and `module:echarts/util/number#parseDate`.
  16072. * @inner
  16073. */
  16074. function formatTime(tpl, value, isUTC) {
  16075. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16076. tpl = 'MM-dd\nyyyy';
  16077. }
  16078. var date = parseDate(value);
  16079. var utc = isUTC ? 'UTC' : '';
  16080. var y = date['get' + utc + 'FullYear']();
  16081. var M = date['get' + utc + 'Month']() + 1;
  16082. var d = date['get' + utc + 'Date']();
  16083. var h = date['get' + utc + 'Hours']();
  16084. var m = date['get' + utc + 'Minutes']();
  16085. var s = date['get' + utc + 'Seconds']();
  16086. var S = date['get' + utc + 'Milliseconds']();
  16087. 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));
  16088. return tpl;
  16089. }
  16090. /**
  16091. * Capital first
  16092. * @param {string} str
  16093. * @return {string}
  16094. */
  16095. function capitalFirst(str) {
  16096. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16097. }
  16098. var truncateText$1 = truncateText;
  16099. /**
  16100. * @public
  16101. * @param {Object} opt
  16102. * @param {string} opt.text
  16103. * @param {string} opt.font
  16104. * @param {string} [opt.textAlign='left']
  16105. * @param {string} [opt.textVerticalAlign='top']
  16106. * @param {Array.<number>} [opt.textPadding]
  16107. * @param {number} [opt.textLineHeight]
  16108. * @param {Object} [opt.rich]
  16109. * @param {Object} [opt.truncate]
  16110. * @return {Object} {x, y, width, height, lineHeight}
  16111. */
  16112. function getTextBoundingRect(opt) {
  16113. return getBoundingRect(opt.text, opt.font, opt.textAlign, opt.textVerticalAlign, opt.textPadding, opt.textLineHeight, opt.rich, opt.truncate);
  16114. }
  16115. /**
  16116. * @deprecated
  16117. * the `textLineHeight` was added later.
  16118. * For backward compatiblility, put it as the last parameter.
  16119. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16120. */
  16121. function getTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight) {
  16122. return getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate);
  16123. }
  16124. /**
  16125. * open new tab
  16126. * @param {string} link url
  16127. * @param {string} target blank or self
  16128. */
  16129. function windowOpen(link, target) {
  16130. if (target === '_blank' || target === 'blank') {
  16131. var blank = window.open();
  16132. blank.opener = null;
  16133. blank.location = link;
  16134. } else {
  16135. window.open(link, target);
  16136. }
  16137. }
  16138. var format = (Object.freeze || Object)({
  16139. addCommas: addCommas,
  16140. toCamelCase: toCamelCase,
  16141. normalizeCssArray: normalizeCssArray$1,
  16142. encodeHTML: encodeHTML,
  16143. formatTpl: formatTpl,
  16144. formatTplSimple: formatTplSimple,
  16145. getTooltipMarker: getTooltipMarker,
  16146. formatTime: formatTime,
  16147. capitalFirst: capitalFirst,
  16148. truncateText: truncateText$1,
  16149. getTextBoundingRect: getTextBoundingRect,
  16150. getTextRect: getTextRect,
  16151. windowOpen: windowOpen
  16152. });
  16153. /*
  16154. * Licensed to the Apache Software Foundation (ASF) under one
  16155. * or more contributor license agreements. See the NOTICE file
  16156. * distributed with this work for additional information
  16157. * regarding copyright ownership. The ASF licenses this file
  16158. * to you under the Apache License, Version 2.0 (the
  16159. * "License"); you may not use this file except in compliance
  16160. * with the License. You may obtain a copy of the License at
  16161. *
  16162. * http://www.apache.org/licenses/LICENSE-2.0
  16163. *
  16164. * Unless required by applicable law or agreed to in writing,
  16165. * software distributed under the License is distributed on an
  16166. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16167. * KIND, either express or implied. See the License for the
  16168. * specific language governing permissions and limitations
  16169. * under the License.
  16170. */
  16171. // Layout helpers for each component positioning
  16172. var each$3 = each$1;
  16173. /**
  16174. * @public
  16175. */
  16176. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16177. /**
  16178. * @public
  16179. */
  16180. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16181. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16182. var x = 0;
  16183. var y = 0;
  16184. if (maxWidth == null) {
  16185. maxWidth = Infinity;
  16186. }
  16187. if (maxHeight == null) {
  16188. maxHeight = Infinity;
  16189. }
  16190. var currentLineMaxSize = 0;
  16191. group.eachChild(function (child, idx) {
  16192. var position = child.position;
  16193. var rect = child.getBoundingRect();
  16194. var nextChild = group.childAt(idx + 1);
  16195. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16196. var nextX;
  16197. var nextY;
  16198. if (orient === 'horizontal') {
  16199. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16200. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16201. // FIXME compare before adding gap?
  16202. if (nextX > maxWidth || child.newline) {
  16203. x = 0;
  16204. nextX = moveX;
  16205. y += currentLineMaxSize + gap;
  16206. currentLineMaxSize = rect.height;
  16207. } else {
  16208. // FIXME: consider rect.y is not `0`?
  16209. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16210. }
  16211. } else {
  16212. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16213. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16214. if (nextY > maxHeight || child.newline) {
  16215. x += currentLineMaxSize + gap;
  16216. y = 0;
  16217. nextY = moveY;
  16218. currentLineMaxSize = rect.width;
  16219. } else {
  16220. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16221. }
  16222. }
  16223. if (child.newline) {
  16224. return;
  16225. }
  16226. position[0] = x;
  16227. position[1] = y;
  16228. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16229. });
  16230. }
  16231. /**
  16232. * VBox or HBox layouting
  16233. * @param {string} orient
  16234. * @param {module:zrender/container/Group} group
  16235. * @param {number} gap
  16236. * @param {number} [width=Infinity]
  16237. * @param {number} [height=Infinity]
  16238. */
  16239. var box = boxLayout;
  16240. /**
  16241. * VBox layouting
  16242. * @param {module:zrender/container/Group} group
  16243. * @param {number} gap
  16244. * @param {number} [width=Infinity]
  16245. * @param {number} [height=Infinity]
  16246. */
  16247. var vbox = curry(boxLayout, 'vertical');
  16248. /**
  16249. * HBox layouting
  16250. * @param {module:zrender/container/Group} group
  16251. * @param {number} gap
  16252. * @param {number} [width=Infinity]
  16253. * @param {number} [height=Infinity]
  16254. */
  16255. var hbox = curry(boxLayout, 'horizontal');
  16256. /**
  16257. * If x or x2 is not specified or 'center' 'left' 'right',
  16258. * the width would be as long as possible.
  16259. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16260. * the height would be as long as possible.
  16261. *
  16262. * @param {Object} positionInfo
  16263. * @param {number|string} [positionInfo.x]
  16264. * @param {number|string} [positionInfo.y]
  16265. * @param {number|string} [positionInfo.x2]
  16266. * @param {number|string} [positionInfo.y2]
  16267. * @param {Object} containerRect {width, height}
  16268. * @param {string|number} margin
  16269. * @return {Object} {width, height}
  16270. */
  16271. /**
  16272. * Parse position info.
  16273. *
  16274. * @param {Object} positionInfo
  16275. * @param {number|string} [positionInfo.left]
  16276. * @param {number|string} [positionInfo.top]
  16277. * @param {number|string} [positionInfo.right]
  16278. * @param {number|string} [positionInfo.bottom]
  16279. * @param {number|string} [positionInfo.width]
  16280. * @param {number|string} [positionInfo.height]
  16281. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16282. * @param {Object} containerRect
  16283. * @param {string|number} [margin]
  16284. *
  16285. * @return {module:zrender/core/BoundingRect}
  16286. */
  16287. function getLayoutRect(positionInfo, containerRect, margin) {
  16288. margin = normalizeCssArray$1(margin || 0);
  16289. var containerWidth = containerRect.width;
  16290. var containerHeight = containerRect.height;
  16291. var left = parsePercent$1(positionInfo.left, containerWidth);
  16292. var top = parsePercent$1(positionInfo.top, containerHeight);
  16293. var right = parsePercent$1(positionInfo.right, containerWidth);
  16294. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16295. var width = parsePercent$1(positionInfo.width, containerWidth);
  16296. var height = parsePercent$1(positionInfo.height, containerHeight);
  16297. var verticalMargin = margin[2] + margin[0];
  16298. var horizontalMargin = margin[1] + margin[3];
  16299. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16300. if (isNaN(width)) {
  16301. width = containerWidth - right - horizontalMargin - left;
  16302. }
  16303. if (isNaN(height)) {
  16304. height = containerHeight - bottom - verticalMargin - top;
  16305. }
  16306. if (aspect != null) {
  16307. // If width and height are not given
  16308. // 1. Graph should not exceeds the container
  16309. // 2. Aspect must be keeped
  16310. // 3. Graph should take the space as more as possible
  16311. // FIXME
  16312. // Margin is not considered, because there is no case that both
  16313. // using margin and aspect so far.
  16314. if (isNaN(width) && isNaN(height)) {
  16315. if (aspect > containerWidth / containerHeight) {
  16316. width = containerWidth * 0.8;
  16317. } else {
  16318. height = containerHeight * 0.8;
  16319. }
  16320. } // Calculate width or height with given aspect
  16321. if (isNaN(width)) {
  16322. width = aspect * height;
  16323. }
  16324. if (isNaN(height)) {
  16325. height = width / aspect;
  16326. }
  16327. } // If left is not specified, calculate left from right and width
  16328. if (isNaN(left)) {
  16329. left = containerWidth - right - width - horizontalMargin;
  16330. }
  16331. if (isNaN(top)) {
  16332. top = containerHeight - bottom - height - verticalMargin;
  16333. } // Align left and top
  16334. switch (positionInfo.left || positionInfo.right) {
  16335. case 'center':
  16336. left = containerWidth / 2 - width / 2 - margin[3];
  16337. break;
  16338. case 'right':
  16339. left = containerWidth - width - horizontalMargin;
  16340. break;
  16341. }
  16342. switch (positionInfo.top || positionInfo.bottom) {
  16343. case 'middle':
  16344. case 'center':
  16345. top = containerHeight / 2 - height / 2 - margin[0];
  16346. break;
  16347. case 'bottom':
  16348. top = containerHeight - height - verticalMargin;
  16349. break;
  16350. } // If something is wrong and left, top, width, height are calculated as NaN
  16351. left = left || 0;
  16352. top = top || 0;
  16353. if (isNaN(width)) {
  16354. // Width may be NaN if only one value is given except width
  16355. width = containerWidth - horizontalMargin - left - (right || 0);
  16356. }
  16357. if (isNaN(height)) {
  16358. // Height may be NaN if only one value is given except height
  16359. height = containerHeight - verticalMargin - top - (bottom || 0);
  16360. }
  16361. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16362. rect.margin = margin;
  16363. return rect;
  16364. }
  16365. /**
  16366. * Position a zr element in viewport
  16367. * Group position is specified by either
  16368. * {left, top}, {right, bottom}
  16369. * If all properties exists, right and bottom will be igonred.
  16370. *
  16371. * Logic:
  16372. * 1. Scale (against origin point in parent coord)
  16373. * 2. Rotate (against origin point in parent coord)
  16374. * 3. Traslate (with el.position by this method)
  16375. * So this method only fixes the last step 'Traslate', which does not affect
  16376. * scaling and rotating.
  16377. *
  16378. * If be called repeatly with the same input el, the same result will be gotten.
  16379. *
  16380. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16381. * @param {Object} positionInfo
  16382. * @param {number|string} [positionInfo.left]
  16383. * @param {number|string} [positionInfo.top]
  16384. * @param {number|string} [positionInfo.right]
  16385. * @param {number|string} [positionInfo.bottom]
  16386. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16387. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16388. * @param {Object} containerRect
  16389. * @param {string|number} margin
  16390. * @param {Object} [opt]
  16391. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16392. * @param {Array.<number>} [opt.boundingMode='all']
  16393. * Specify how to calculate boundingRect when locating.
  16394. * 'all': Position the boundingRect that is transformed and uioned
  16395. * both itself and its descendants.
  16396. * This mode simplies confine the elements in the bounding
  16397. * of their container (e.g., using 'right: 0').
  16398. * 'raw': Position the boundingRect that is not transformed and only itself.
  16399. * This mode is useful when you want a element can overflow its
  16400. * container. (Consider a rotated circle needs to be located in a corner.)
  16401. * In this mode positionInfo.width/height can only be number.
  16402. */
  16403. /**
  16404. * @param {Object} option Contains some of the properties in HV_NAMES.
  16405. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16406. */
  16407. /**
  16408. * Consider Case:
  16409. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16410. * through setOption or media query, using normal zrUtil.merge will cause
  16411. * {right: 0} does not take effect.
  16412. *
  16413. * @example
  16414. * ComponentModel.extend({
  16415. * init: function () {
  16416. * ...
  16417. * var inputPositionParams = layout.getLayoutParams(option);
  16418. * this.mergeOption(inputPositionParams);
  16419. * },
  16420. * mergeOption: function (newOption) {
  16421. * newOption && zrUtil.merge(thisOption, newOption, true);
  16422. * layout.mergeLayoutParam(thisOption, newOption);
  16423. * }
  16424. * });
  16425. *
  16426. * @param {Object} targetOption
  16427. * @param {Object} newOption
  16428. * @param {Object|string} [opt]
  16429. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16430. * that width (or height) should not be calculated by left and right (or top and bottom).
  16431. */
  16432. function mergeLayoutParam(targetOption, newOption, opt) {
  16433. !isObject$1(opt) && (opt = {});
  16434. var ignoreSize = opt.ignoreSize;
  16435. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16436. var hResult = merge$$1(HV_NAMES[0], 0);
  16437. var vResult = merge$$1(HV_NAMES[1], 1);
  16438. copy(HV_NAMES[0], targetOption, hResult);
  16439. copy(HV_NAMES[1], targetOption, vResult);
  16440. function merge$$1(names, hvIdx) {
  16441. var newParams = {};
  16442. var newValueCount = 0;
  16443. var merged = {};
  16444. var mergedValueCount = 0;
  16445. var enoughParamNumber = 2;
  16446. each$3(names, function (name) {
  16447. merged[name] = targetOption[name];
  16448. });
  16449. each$3(names, function (name) {
  16450. // Consider case: newOption.width is null, which is
  16451. // set by user for removing width setting.
  16452. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16453. hasValue(newParams, name) && newValueCount++;
  16454. hasValue(merged, name) && mergedValueCount++;
  16455. });
  16456. if (ignoreSize[hvIdx]) {
  16457. // Only one of left/right is premitted to exist.
  16458. if (hasValue(newOption, names[1])) {
  16459. merged[names[2]] = null;
  16460. } else if (hasValue(newOption, names[2])) {
  16461. merged[names[1]] = null;
  16462. }
  16463. return merged;
  16464. } // Case: newOption: {width: ..., right: ...},
  16465. // or targetOption: {right: ...} and newOption: {width: ...},
  16466. // There is no conflict when merged only has params count
  16467. // little than enoughParamNumber.
  16468. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16469. return merged;
  16470. } // Case: newOption: {width: ..., right: ...},
  16471. // Than we can make sure user only want those two, and ignore
  16472. // all origin params in targetOption.
  16473. else if (newValueCount >= enoughParamNumber) {
  16474. return newParams;
  16475. } else {
  16476. // Chose another param from targetOption by priority.
  16477. for (var i = 0; i < names.length; i++) {
  16478. var name = names[i];
  16479. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16480. newParams[name] = targetOption[name];
  16481. break;
  16482. }
  16483. }
  16484. return newParams;
  16485. }
  16486. }
  16487. function hasProp(obj, name) {
  16488. return obj.hasOwnProperty(name);
  16489. }
  16490. function hasValue(obj, name) {
  16491. return obj[name] != null && obj[name] !== 'auto';
  16492. }
  16493. function copy(names, target, source) {
  16494. each$3(names, function (name) {
  16495. target[name] = source[name];
  16496. });
  16497. }
  16498. }
  16499. /**
  16500. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16501. * @param {Object} source
  16502. * @return {Object} Result contains those props.
  16503. */
  16504. function getLayoutParams(source) {
  16505. return copyLayoutParams({}, source);
  16506. }
  16507. /**
  16508. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16509. * @param {Object} source
  16510. * @return {Object} Result contains those props.
  16511. */
  16512. function copyLayoutParams(target, source) {
  16513. source && target && each$3(LOCATION_PARAMS, function (name) {
  16514. source.hasOwnProperty(name) && (target[name] = source[name]);
  16515. });
  16516. return target;
  16517. }
  16518. /*
  16519. * Licensed to the Apache Software Foundation (ASF) under one
  16520. * or more contributor license agreements. See the NOTICE file
  16521. * distributed with this work for additional information
  16522. * regarding copyright ownership. The ASF licenses this file
  16523. * to you under the Apache License, Version 2.0 (the
  16524. * "License"); you may not use this file except in compliance
  16525. * with the License. You may obtain a copy of the License at
  16526. *
  16527. * http://www.apache.org/licenses/LICENSE-2.0
  16528. *
  16529. * Unless required by applicable law or agreed to in writing,
  16530. * software distributed under the License is distributed on an
  16531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16532. * KIND, either express or implied. See the License for the
  16533. * specific language governing permissions and limitations
  16534. * under the License.
  16535. */
  16536. var boxLayoutMixin = {
  16537. getBoxLayoutParams: function () {
  16538. return {
  16539. left: this.get('left'),
  16540. top: this.get('top'),
  16541. right: this.get('right'),
  16542. bottom: this.get('bottom'),
  16543. width: this.get('width'),
  16544. height: this.get('height')
  16545. };
  16546. }
  16547. };
  16548. /*
  16549. * Licensed to the Apache Software Foundation (ASF) under one
  16550. * or more contributor license agreements. See the NOTICE file
  16551. * distributed with this work for additional information
  16552. * regarding copyright ownership. The ASF licenses this file
  16553. * to you under the Apache License, Version 2.0 (the
  16554. * "License"); you may not use this file except in compliance
  16555. * with the License. You may obtain a copy of the License at
  16556. *
  16557. * http://www.apache.org/licenses/LICENSE-2.0
  16558. *
  16559. * Unless required by applicable law or agreed to in writing,
  16560. * software distributed under the License is distributed on an
  16561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16562. * KIND, either express or implied. See the License for the
  16563. * specific language governing permissions and limitations
  16564. * under the License.
  16565. */
  16566. /**
  16567. * Component model
  16568. *
  16569. * @module echarts/model/Component
  16570. */
  16571. var inner$1 = makeInner();
  16572. /**
  16573. * @alias module:echarts/model/Component
  16574. * @constructor
  16575. * @param {Object} option
  16576. * @param {module:echarts/model/Model} parentModel
  16577. * @param {module:echarts/model/Model} ecModel
  16578. */
  16579. var ComponentModel = Model.extend({
  16580. type: 'component',
  16581. /**
  16582. * @readOnly
  16583. * @type {string}
  16584. */
  16585. id: '',
  16586. /**
  16587. * Because simplified concept is probably better, series.name (or component.name)
  16588. * has been having too many resposibilities:
  16589. * (1) Generating id (which requires name in option should not be modified).
  16590. * (2) As an index to mapping series when merging option or calling API (a name
  16591. * can refer to more then one components, which is convinient is some case).
  16592. * (3) Display.
  16593. * @readOnly
  16594. */
  16595. name: '',
  16596. /**
  16597. * @readOnly
  16598. * @type {string}
  16599. */
  16600. mainType: '',
  16601. /**
  16602. * @readOnly
  16603. * @type {string}
  16604. */
  16605. subType: '',
  16606. /**
  16607. * @readOnly
  16608. * @type {number}
  16609. */
  16610. componentIndex: 0,
  16611. /**
  16612. * @type {Object}
  16613. * @protected
  16614. */
  16615. defaultOption: null,
  16616. /**
  16617. * @type {module:echarts/model/Global}
  16618. * @readOnly
  16619. */
  16620. ecModel: null,
  16621. /**
  16622. * key: componentType
  16623. * value: Component model list, can not be null.
  16624. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16625. * @readOnly
  16626. */
  16627. dependentModels: [],
  16628. /**
  16629. * @type {string}
  16630. * @readOnly
  16631. */
  16632. uid: null,
  16633. /**
  16634. * Support merge layout params.
  16635. * Only support 'box' now (left/right/top/bottom/width/height).
  16636. * @type {string|Object} Object can be {ignoreSize: true}
  16637. * @readOnly
  16638. */
  16639. layoutMode: null,
  16640. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16641. Model.call(this, option, parentModel, ecModel, extraOpt);
  16642. this.uid = getUID('ec_cpt_model');
  16643. },
  16644. init: function (option, parentModel, ecModel, extraOpt) {
  16645. this.mergeDefaultAndTheme(option, ecModel);
  16646. },
  16647. mergeDefaultAndTheme: function (option, ecModel) {
  16648. var layoutMode = this.layoutMode;
  16649. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16650. var themeModel = ecModel.getTheme();
  16651. merge(option, themeModel.get(this.mainType));
  16652. merge(option, this.getDefaultOption());
  16653. if (layoutMode) {
  16654. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16655. }
  16656. },
  16657. mergeOption: function (option, extraOpt) {
  16658. merge(this.option, option, true);
  16659. var layoutMode = this.layoutMode;
  16660. if (layoutMode) {
  16661. mergeLayoutParam(this.option, option, layoutMode);
  16662. }
  16663. },
  16664. // Hooker after init or mergeOption
  16665. optionUpdated: function (newCptOption, isInit) {},
  16666. getDefaultOption: function () {
  16667. var fields = inner$1(this);
  16668. if (!fields.defaultOption) {
  16669. var optList = [];
  16670. var Class = this.constructor;
  16671. while (Class) {
  16672. var opt = Class.prototype.defaultOption;
  16673. opt && optList.push(opt);
  16674. Class = Class.superClass;
  16675. }
  16676. var defaultOption = {};
  16677. for (var i = optList.length - 1; i >= 0; i--) {
  16678. defaultOption = merge(defaultOption, optList[i], true);
  16679. }
  16680. fields.defaultOption = defaultOption;
  16681. }
  16682. return fields.defaultOption;
  16683. },
  16684. getReferringComponents: function (mainType) {
  16685. return this.ecModel.queryComponents({
  16686. mainType: mainType,
  16687. index: this.get(mainType + 'Index', true),
  16688. id: this.get(mainType + 'Id', true)
  16689. });
  16690. }
  16691. }); // Reset ComponentModel.extend, add preConstruct.
  16692. // clazzUtil.enableClassExtend(
  16693. // ComponentModel,
  16694. // function (option, parentModel, ecModel, extraOpt) {
  16695. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16696. // zrUtil.extend(this, extraOpt);
  16697. // this.uid = componentUtil.getUID('componentModel');
  16698. // // this.setReadOnly([
  16699. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16700. // // 'dependentModels', 'componentIndex'
  16701. // // ]);
  16702. // }
  16703. // );
  16704. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16705. enableClassManagement(ComponentModel, {
  16706. registerWhenExtend: true
  16707. });
  16708. enableSubTypeDefaulter(ComponentModel); // Add capability of ComponentModel.topologicalTravel.
  16709. enableTopologicalTravel(ComponentModel, getDependencies);
  16710. function getDependencies(componentType) {
  16711. var deps = [];
  16712. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16713. deps = deps.concat(Clazz.prototype.dependencies || []);
  16714. }); // Ensure main type.
  16715. deps = map(deps, function (type) {
  16716. return parseClassType$1(type).main;
  16717. }); // Hack dataset for convenience.
  16718. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16719. deps.unshift('dataset');
  16720. }
  16721. return deps;
  16722. }
  16723. mixin(ComponentModel, boxLayoutMixin);
  16724. /*
  16725. * Licensed to the Apache Software Foundation (ASF) under one
  16726. * or more contributor license agreements. See the NOTICE file
  16727. * distributed with this work for additional information
  16728. * regarding copyright ownership. The ASF licenses this file
  16729. * to you under the Apache License, Version 2.0 (the
  16730. * "License"); you may not use this file except in compliance
  16731. * with the License. You may obtain a copy of the License at
  16732. *
  16733. * http://www.apache.org/licenses/LICENSE-2.0
  16734. *
  16735. * Unless required by applicable law or agreed to in writing,
  16736. * software distributed under the License is distributed on an
  16737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16738. * KIND, either express or implied. See the License for the
  16739. * specific language governing permissions and limitations
  16740. * under the License.
  16741. */
  16742. var platform = ''; // Navigator not exists in node
  16743. if (typeof navigator !== 'undefined') {
  16744. platform = navigator.platform || '';
  16745. }
  16746. var globalDefault = {
  16747. // backgroundColor: 'rgba(0,0,0,0)',
  16748. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16749. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16750. // Light colors:
  16751. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16752. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16753. // Dark colors:
  16754. color: ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'],
  16755. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16756. // If xAxis and yAxis declared, grid is created by default.
  16757. // grid: {},
  16758. textStyle: {
  16759. // color: '#000',
  16760. // decoration: 'none',
  16761. // PENDING
  16762. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16763. // fontFamily: 'Arial, Verdana, sans-serif',
  16764. fontSize: 12,
  16765. fontStyle: 'normal',
  16766. fontWeight: 'normal'
  16767. },
  16768. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16769. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16770. // Default is source-over
  16771. blendMode: null,
  16772. animation: 'auto',
  16773. animationDuration: 1000,
  16774. animationDurationUpdate: 300,
  16775. animationEasing: 'exponentialOut',
  16776. animationEasingUpdate: 'cubicOut',
  16777. animationThreshold: 2000,
  16778. // Configuration for progressive/incremental rendering
  16779. progressiveThreshold: 3000,
  16780. progressive: 400,
  16781. // Threshold of if use single hover layer to optimize.
  16782. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16783. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16784. // which is unexpected.
  16785. // see example <echarts/test/heatmap-large.html>.
  16786. hoverLayerThreshold: 3000,
  16787. // See: module:echarts/scale/Time
  16788. useUTC: false
  16789. };
  16790. /*
  16791. * Licensed to the Apache Software Foundation (ASF) under one
  16792. * or more contributor license agreements. See the NOTICE file
  16793. * distributed with this work for additional information
  16794. * regarding copyright ownership. The ASF licenses this file
  16795. * to you under the Apache License, Version 2.0 (the
  16796. * "License"); you may not use this file except in compliance
  16797. * with the License. You may obtain a copy of the License at
  16798. *
  16799. * http://www.apache.org/licenses/LICENSE-2.0
  16800. *
  16801. * Unless required by applicable law or agreed to in writing,
  16802. * software distributed under the License is distributed on an
  16803. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16804. * KIND, either express or implied. See the License for the
  16805. * specific language governing permissions and limitations
  16806. * under the License.
  16807. */
  16808. var inner$2 = makeInner();
  16809. function getNearestColorPalette(colors, requestColorNum) {
  16810. var paletteNum = colors.length; // TODO colors must be in order
  16811. for (var i = 0; i < paletteNum; i++) {
  16812. if (colors[i].length > requestColorNum) {
  16813. return colors[i];
  16814. }
  16815. }
  16816. return colors[paletteNum - 1];
  16817. }
  16818. var colorPaletteMixin = {
  16819. clearColorPalette: function () {
  16820. inner$2(this).colorIdx = 0;
  16821. inner$2(this).colorNameMap = {};
  16822. },
  16823. /**
  16824. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16825. * twise with the same parameters will get different result.
  16826. * @param {Object} [scope=this]
  16827. * @param {Object} [requestColorNum]
  16828. * @return {string} color string.
  16829. */
  16830. getColorFromPalette: function (name, scope, requestColorNum) {
  16831. scope = scope || this;
  16832. var scopeFields = inner$2(scope);
  16833. var colorIdx = scopeFields.colorIdx || 0;
  16834. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16835. if (colorNameMap.hasOwnProperty(name)) {
  16836. return colorNameMap[name];
  16837. }
  16838. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16839. var layeredColorPalette = this.get('colorLayer', true);
  16840. var colorPalette = requestColorNum == null || !layeredColorPalette ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum); // In case can't find in layered color palette.
  16841. colorPalette = colorPalette || defaultColorPalette;
  16842. if (!colorPalette || !colorPalette.length) {
  16843. return;
  16844. }
  16845. var color = colorPalette[colorIdx];
  16846. if (name) {
  16847. colorNameMap[name] = color;
  16848. }
  16849. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16850. return color;
  16851. }
  16852. };
  16853. /*
  16854. * Licensed to the Apache Software Foundation (ASF) under one
  16855. * or more contributor license agreements. See the NOTICE file
  16856. * distributed with this work for additional information
  16857. * regarding copyright ownership. The ASF licenses this file
  16858. * to you under the Apache License, Version 2.0 (the
  16859. * "License"); you may not use this file except in compliance
  16860. * with the License. You may obtain a copy of the License at
  16861. *
  16862. * http://www.apache.org/licenses/LICENSE-2.0
  16863. *
  16864. * Unless required by applicable law or agreed to in writing,
  16865. * software distributed under the License is distributed on an
  16866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16867. * KIND, either express or implied. See the License for the
  16868. * specific language governing permissions and limitations
  16869. * under the License.
  16870. */
  16871. // Avoid typo.
  16872. var SOURCE_FORMAT_ORIGINAL = 'original';
  16873. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16874. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16875. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16876. var SOURCE_FORMAT_UNKNOWN = 'unknown'; // ??? CHANGE A NAME
  16877. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16878. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16879. var SERIES_LAYOUT_BY_ROW = 'row';
  16880. /*
  16881. * Licensed to the Apache Software Foundation (ASF) under one
  16882. * or more contributor license agreements. See the NOTICE file
  16883. * distributed with this work for additional information
  16884. * regarding copyright ownership. The ASF licenses this file
  16885. * to you under the Apache License, Version 2.0 (the
  16886. * "License"); you may not use this file except in compliance
  16887. * with the License. You may obtain a copy of the License at
  16888. *
  16889. * http://www.apache.org/licenses/LICENSE-2.0
  16890. *
  16891. * Unless required by applicable law or agreed to in writing,
  16892. * software distributed under the License is distributed on an
  16893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16894. * KIND, either express or implied. See the License for the
  16895. * specific language governing permissions and limitations
  16896. * under the License.
  16897. */
  16898. /**
  16899. * [sourceFormat]
  16900. *
  16901. * + "original":
  16902. * This format is only used in series.data, where
  16903. * itemStyle can be specified in data item.
  16904. *
  16905. * + "arrayRows":
  16906. * [
  16907. * ['product', 'score', 'amount'],
  16908. * ['Matcha Latte', 89.3, 95.8],
  16909. * ['Milk Tea', 92.1, 89.4],
  16910. * ['Cheese Cocoa', 94.4, 91.2],
  16911. * ['Walnut Brownie', 85.4, 76.9]
  16912. * ]
  16913. *
  16914. * + "objectRows":
  16915. * [
  16916. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16917. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16918. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16919. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16920. * ]
  16921. *
  16922. * + "keyedColumns":
  16923. * {
  16924. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16925. * 'count': [823, 235, 1042, 988],
  16926. * 'score': [95.8, 81.4, 91.2, 76.9]
  16927. * }
  16928. *
  16929. * + "typedArray"
  16930. *
  16931. * + "unknown"
  16932. */
  16933. /**
  16934. * @constructor
  16935. * @param {Object} fields
  16936. * @param {string} fields.sourceFormat
  16937. * @param {Array|Object} fields.fromDataset
  16938. * @param {Array|Object} [fields.data]
  16939. * @param {string} [seriesLayoutBy='column']
  16940. * @param {Array.<Object|string>} [dimensionsDefine]
  16941. * @param {Objet|HashMap} [encodeDefine]
  16942. * @param {number} [startIndex=0]
  16943. * @param {number} [dimensionsDetectCount]
  16944. */
  16945. function Source(fields) {
  16946. /**
  16947. * @type {boolean}
  16948. */
  16949. this.fromDataset = fields.fromDataset;
  16950. /**
  16951. * Not null/undefined.
  16952. * @type {Array|Object}
  16953. */
  16954. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  16955. /**
  16956. * See also "detectSourceFormat".
  16957. * Not null/undefined.
  16958. * @type {string}
  16959. */
  16960. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16961. /**
  16962. * 'row' or 'column'
  16963. * Not null/undefined.
  16964. * @type {string} seriesLayoutBy
  16965. */
  16966. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16967. /**
  16968. * dimensions definition in option.
  16969. * can be null/undefined.
  16970. * @type {Array.<Object|string>}
  16971. */
  16972. this.dimensionsDefine = fields.dimensionsDefine;
  16973. /**
  16974. * encode definition in option.
  16975. * can be null/undefined.
  16976. * @type {Objet|HashMap}
  16977. */
  16978. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16979. /**
  16980. * Not null/undefined, uint.
  16981. * @type {number}
  16982. */
  16983. this.startIndex = fields.startIndex || 0;
  16984. /**
  16985. * Can be null/undefined (when unknown), uint.
  16986. * @type {number}
  16987. */
  16988. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16989. }
  16990. /**
  16991. * Wrap original series data for some compatibility cases.
  16992. */
  16993. Source.seriesDataToSource = function (data) {
  16994. return new Source({
  16995. data: data,
  16996. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL,
  16997. fromDataset: false
  16998. });
  16999. };
  17000. enableClassCheck(Source);
  17001. /*
  17002. * Licensed to the Apache Software Foundation (ASF) under one
  17003. * or more contributor license agreements. See the NOTICE file
  17004. * distributed with this work for additional information
  17005. * regarding copyright ownership. The ASF licenses this file
  17006. * to you under the Apache License, Version 2.0 (the
  17007. * "License"); you may not use this file except in compliance
  17008. * with the License. You may obtain a copy of the License at
  17009. *
  17010. * http://www.apache.org/licenses/LICENSE-2.0
  17011. *
  17012. * Unless required by applicable law or agreed to in writing,
  17013. * software distributed under the License is distributed on an
  17014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17015. * KIND, either express or implied. See the License for the
  17016. * specific language governing permissions and limitations
  17017. * under the License.
  17018. */
  17019. var BE_ORDINAL = {
  17020. Must: 1,
  17021. // Encounter string but not '-' and not number-like.
  17022. Might: 2,
  17023. // Encounter string but number-like.
  17024. Not: 3 // Other cases
  17025. };
  17026. var inner$3 = makeInner();
  17027. /**
  17028. * @see {module:echarts/data/Source}
  17029. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17030. * @return {string} sourceFormat
  17031. */
  17032. function detectSourceFormat(datasetModel) {
  17033. var data = datasetModel.option.source;
  17034. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17035. if (isTypedArray(data)) {
  17036. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17037. } else if (isArray(data)) {
  17038. // FIXME Whether tolerate null in top level array?
  17039. if (data.length === 0) {
  17040. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17041. }
  17042. for (var i = 0, len = data.length; i < len; i++) {
  17043. var item = data[i];
  17044. if (item == null) {
  17045. continue;
  17046. } else if (isArray(item)) {
  17047. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17048. break;
  17049. } else if (isObject$1(item)) {
  17050. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17051. break;
  17052. }
  17053. }
  17054. } else if (isObject$1(data)) {
  17055. for (var key in data) {
  17056. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17057. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17058. break;
  17059. }
  17060. }
  17061. } else if (data != null) {
  17062. throw new Error('Invalid data');
  17063. }
  17064. inner$3(datasetModel).sourceFormat = sourceFormat;
  17065. }
  17066. /**
  17067. * [Scenarios]:
  17068. * (1) Provide source data directly:
  17069. * series: {
  17070. * encode: {...},
  17071. * dimensions: [...]
  17072. * seriesLayoutBy: 'row',
  17073. * data: [[...]]
  17074. * }
  17075. * (2) Refer to datasetModel.
  17076. * series: [{
  17077. * encode: {...}
  17078. * // Ignore datasetIndex means `datasetIndex: 0`
  17079. * // and the dimensions defination in dataset is used
  17080. * }, {
  17081. * encode: {...},
  17082. * seriesLayoutBy: 'column',
  17083. * datasetIndex: 1
  17084. * }]
  17085. *
  17086. * Get data from series itself or datset.
  17087. * @return {module:echarts/data/Source} source
  17088. */
  17089. function getSource(seriesModel) {
  17090. return inner$3(seriesModel).source;
  17091. }
  17092. /**
  17093. * MUST be called before mergeOption of all series.
  17094. * @param {module:echarts/model/Global} ecModel
  17095. */
  17096. function resetSourceDefaulter(ecModel) {
  17097. // `datasetMap` is used to make default encode.
  17098. inner$3(ecModel).datasetMap = createHashMap();
  17099. }
  17100. /**
  17101. * [Caution]:
  17102. * MUST be called after series option merged and
  17103. * before "series.getInitailData()" called.
  17104. *
  17105. * [The rule of making default encode]:
  17106. * Category axis (if exists) alway map to the first dimension.
  17107. * Each other axis occupies a subsequent dimension.
  17108. *
  17109. * [Why make default encode]:
  17110. * Simplify the typing of encode in option, avoiding the case like that:
  17111. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17112. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17113. *
  17114. * @param {module:echarts/model/Series} seriesModel
  17115. */
  17116. function prepareSource(seriesModel) {
  17117. var seriesOption = seriesModel.option;
  17118. var data = seriesOption.data;
  17119. var sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17120. var fromDataset = false;
  17121. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17122. var sourceHeader = seriesOption.sourceHeader;
  17123. var dimensionsDefine = seriesOption.dimensions;
  17124. var datasetModel = getDatasetModel(seriesModel);
  17125. if (datasetModel) {
  17126. var datasetOption = datasetModel.option;
  17127. data = datasetOption.source;
  17128. sourceFormat = inner$3(datasetModel).sourceFormat;
  17129. fromDataset = true; // These settings from series has higher priority.
  17130. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17131. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17132. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17133. }
  17134. var completeResult = completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine);
  17135. inner$3(seriesModel).source = new Source({
  17136. data: data,
  17137. fromDataset: fromDataset,
  17138. seriesLayoutBy: seriesLayoutBy,
  17139. sourceFormat: sourceFormat,
  17140. dimensionsDefine: completeResult.dimensionsDefine,
  17141. startIndex: completeResult.startIndex,
  17142. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17143. // Note: dataset option does not have `encode`.
  17144. encodeDefine: seriesOption.encode
  17145. });
  17146. } // return {startIndex, dimensionsDefine, dimensionsCount}
  17147. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17148. if (!data) {
  17149. return {
  17150. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)
  17151. };
  17152. }
  17153. var dimensionsDetectCount;
  17154. var startIndex;
  17155. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17156. // Rule: Most of the first line are string: it is header.
  17157. // Caution: consider a line with 5 string and 1 number,
  17158. // it still can not be sure it is a head, because the
  17159. // 5 string may be 5 values of category columns.
  17160. if (sourceHeader === 'auto' || sourceHeader == null) {
  17161. arrayRowsTravelFirst(function (val) {
  17162. // '-' is regarded as null/undefined.
  17163. if (val != null && val !== '-') {
  17164. if (isString(val)) {
  17165. startIndex == null && (startIndex = 1);
  17166. } else {
  17167. startIndex = 0;
  17168. }
  17169. } // 10 is an experience number, avoid long loop.
  17170. }, seriesLayoutBy, data, 10);
  17171. } else {
  17172. startIndex = sourceHeader ? 1 : 0;
  17173. }
  17174. if (!dimensionsDefine && startIndex === 1) {
  17175. dimensionsDefine = [];
  17176. arrayRowsTravelFirst(function (val, index) {
  17177. dimensionsDefine[index] = val != null ? val : '';
  17178. }, seriesLayoutBy, data);
  17179. }
  17180. dimensionsDetectCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? data.length : data[0] ? data[0].length : null;
  17181. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17182. if (!dimensionsDefine) {
  17183. dimensionsDefine = objectRowsCollectDimensions(data);
  17184. }
  17185. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17186. if (!dimensionsDefine) {
  17187. dimensionsDefine = [];
  17188. each$1(data, function (colArr, key) {
  17189. dimensionsDefine.push(key);
  17190. });
  17191. }
  17192. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17193. var value0 = getDataItemValue(data[0]);
  17194. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17195. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {}
  17196. return {
  17197. startIndex: startIndex,
  17198. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17199. dimensionsDetectCount: dimensionsDetectCount
  17200. };
  17201. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17202. // which is reasonable. But dimension name is duplicated.
  17203. // Returns undefined or an array contains only object without null/undefiend or string.
  17204. function normalizeDimensionsDefine(dimensionsDefine) {
  17205. if (!dimensionsDefine) {
  17206. // The meaning of null/undefined is different from empty array.
  17207. return;
  17208. }
  17209. var nameMap = createHashMap();
  17210. return map(dimensionsDefine, function (item, index) {
  17211. item = extend({}, isObject$1(item) ? item : {
  17212. name: item
  17213. }); // User can set null in dimensions.
  17214. // We dont auto specify name, othewise a given name may
  17215. // cause it be refered unexpectedly.
  17216. if (item.name == null) {
  17217. return item;
  17218. } // Also consider number form like 2012.
  17219. item.name += ''; // User may also specify displayName.
  17220. // displayName will always exists except user not
  17221. // specified or dim name is not specified or detected.
  17222. // (A auto generated dim name will not be used as
  17223. // displayName).
  17224. if (item.displayName == null) {
  17225. item.displayName = item.name;
  17226. }
  17227. var exist = nameMap.get(item.name);
  17228. if (!exist) {
  17229. nameMap.set(item.name, {
  17230. count: 1
  17231. });
  17232. } else {
  17233. item.name += '-' + exist.count++;
  17234. }
  17235. return item;
  17236. });
  17237. }
  17238. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17239. maxLoop == null && (maxLoop = Infinity);
  17240. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17241. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17242. cb(data[i] ? data[i][0] : null, i);
  17243. }
  17244. } else {
  17245. var value0 = data[0] || [];
  17246. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17247. cb(value0[i], i);
  17248. }
  17249. }
  17250. }
  17251. function objectRowsCollectDimensions(data) {
  17252. var firstIndex = 0;
  17253. var obj;
  17254. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17255. if (obj) {
  17256. var dimensions = [];
  17257. each$1(obj, function (value, key) {
  17258. dimensions.push(key);
  17259. });
  17260. return dimensions;
  17261. }
  17262. }
  17263. /**
  17264. * [The strategy of the arrengment of data dimensions for dataset]:
  17265. * "value way": all axes are non-category axes. So series one by one take
  17266. * several (the number is coordSysDims.length) dimensions from dataset.
  17267. * The result of data arrengment of data dimensions like:
  17268. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17269. * "category way": at least one axis is category axis. So the the first data
  17270. * dimension is always mapped to the first category axis and shared by
  17271. * all of the series. The other data dimensions are taken by series like
  17272. * "value way" does.
  17273. * The result of data arrengment of data dimensions like:
  17274. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17275. *
  17276. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  17277. * @param {module:model/Series} seriesModel
  17278. * @param {module:data/Source} source
  17279. * @return {Object} encode Never be `null/undefined`.
  17280. */
  17281. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17282. var encode = {};
  17283. var datasetModel = getDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17284. if (!datasetModel || !coordDimensions) {
  17285. return encode;
  17286. }
  17287. var encodeItemName = [];
  17288. var encodeSeriesName = [];
  17289. var ecModel = seriesModel.ecModel;
  17290. var datasetMap = inner$3(ecModel).datasetMap;
  17291. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17292. var baseCategoryDimIndex;
  17293. var categoryWayValueDimStart;
  17294. coordDimensions = coordDimensions.slice();
  17295. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17296. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {
  17297. name: coordDimInfo
  17298. });
  17299. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17300. baseCategoryDimIndex = coordDimIdx;
  17301. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  17302. }
  17303. encode[coordDimInfo.name] = [];
  17304. });
  17305. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17306. categoryWayDim: categoryWayValueDimStart,
  17307. valueWayDim: 0
  17308. }); // TODO
  17309. // Auto detect first time axis and do arrangement.
  17310. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17311. var coordDimName = coordDimInfo.name;
  17312. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  17313. if (baseCategoryDimIndex == null) {
  17314. var start = datasetRecord.valueWayDim;
  17315. pushDim(encode[coordDimName], start, count);
  17316. pushDim(encodeSeriesName, start, count);
  17317. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  17318. // especially when encode x y specified.
  17319. // consider: when mutiple series share one dimension
  17320. // category axis, series name should better use
  17321. // the other dimsion name. On the other hand, use
  17322. // both dimensions name.
  17323. } // In category way, the first category axis.
  17324. else if (baseCategoryDimIndex === coordDimIdx) {
  17325. pushDim(encode[coordDimName], 0, count);
  17326. pushDim(encodeItemName, 0, count);
  17327. } // In category way, the other axis.
  17328. else {
  17329. var start = datasetRecord.categoryWayDim;
  17330. pushDim(encode[coordDimName], start, count);
  17331. pushDim(encodeSeriesName, start, count);
  17332. datasetRecord.categoryWayDim += count;
  17333. }
  17334. });
  17335. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17336. for (var i = 0; i < idxCount; i++) {
  17337. dimIdxArr.push(idxFrom + i);
  17338. }
  17339. }
  17340. function getDataDimCountOnCoordDim(coordDimInfo) {
  17341. var dimsDef = coordDimInfo.dimsDef;
  17342. return dimsDef ? dimsDef.length : 1;
  17343. }
  17344. encodeItemName.length && (encode.itemName = encodeItemName);
  17345. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17346. return encode;
  17347. }
  17348. /**
  17349. * Work for data like [{name: ..., value: ...}, ...].
  17350. *
  17351. * @param {module:model/Series} seriesModel
  17352. * @param {module:data/Source} source
  17353. * @return {Object} encode Never be `null/undefined`.
  17354. */
  17355. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17356. var encode = {};
  17357. var datasetModel = getDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17358. if (!datasetModel) {
  17359. return encode;
  17360. }
  17361. var sourceFormat = source.sourceFormat;
  17362. var dimensionsDefine = source.dimensionsDefine;
  17363. var potentialNameDimIndex;
  17364. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17365. each$1(dimensionsDefine, function (dim, idx) {
  17366. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17367. potentialNameDimIndex = idx;
  17368. }
  17369. });
  17370. } // idxResult: {v, n}.
  17371. var idxResult = function () {
  17372. var idxRes0 = {};
  17373. var idxRes1 = {};
  17374. var guessRecords = []; // 5 is an experience value.
  17375. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17376. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17377. guessRecords.push(guessResult);
  17378. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17379. // and then find a name dim with the priority:
  17380. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17381. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17382. idxRes0.v = i;
  17383. }
  17384. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17385. idxRes0.n = i;
  17386. }
  17387. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17388. return idxRes0;
  17389. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17390. // find the first BE_ORDINAL.Might as the value dim,
  17391. // and then find a name dim with the priority:
  17392. // "other dim" > "the value dim itself".
  17393. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17394. // treated as number.
  17395. if (!isPureNumber) {
  17396. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17397. idxRes1.v = i;
  17398. }
  17399. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17400. idxRes1.n = i;
  17401. }
  17402. }
  17403. }
  17404. function fulfilled(idxResult) {
  17405. return idxResult.v != null && idxResult.n != null;
  17406. }
  17407. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17408. }();
  17409. if (idxResult) {
  17410. encode.value = idxResult.v; // `potentialNameDimIndex` has highest priority.
  17411. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  17412. // So we dont set encodeLabel here.
  17413. encode.itemName = [nameDimIndex];
  17414. encode.seriesName = [nameDimIndex];
  17415. }
  17416. return encode;
  17417. }
  17418. /**
  17419. * If return null/undefined, indicate that should not use datasetModel.
  17420. */
  17421. function getDatasetModel(seriesModel) {
  17422. var option = seriesModel.option; // Caution: consider the scenario:
  17423. // A dataset is declared and a series is not expected to use the dataset,
  17424. // and at the beginning `setOption({series: { noData })` (just prepare other
  17425. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17426. // the user should set an empty array to avoid that dataset is used by default.
  17427. var thisData = option.data;
  17428. if (!thisData) {
  17429. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17430. }
  17431. }
  17432. /**
  17433. * The rule should not be complex, otherwise user might not
  17434. * be able to known where the data is wrong.
  17435. * The code is ugly, but how to make it neat?
  17436. *
  17437. * @param {module:echars/data/Source} source
  17438. * @param {number} dimIndex
  17439. * @return {BE_ORDINAL} guess result.
  17440. */
  17441. function guessOrdinal(source, dimIndex) {
  17442. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17443. } // dimIndex may be overflow source data.
  17444. // return {BE_ORDINAL}
  17445. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17446. var result; // Experience value.
  17447. var maxLoop = 5;
  17448. if (isTypedArray(data)) {
  17449. return BE_ORDINAL.Not;
  17450. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17451. // always exists in source.
  17452. var dimName;
  17453. var dimType;
  17454. if (dimensionsDefine) {
  17455. var dimDefItem = dimensionsDefine[dimIndex];
  17456. if (isObject$1(dimDefItem)) {
  17457. dimName = dimDefItem.name;
  17458. dimType = dimDefItem.type;
  17459. } else if (isString(dimDefItem)) {
  17460. dimName = dimDefItem;
  17461. }
  17462. }
  17463. if (dimType != null) {
  17464. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17465. }
  17466. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17467. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17468. var sample = data[dimIndex];
  17469. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17470. if ((result = detectValue(sample[startIndex + i])) != null) {
  17471. return result;
  17472. }
  17473. }
  17474. } else {
  17475. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17476. var row = data[startIndex + i];
  17477. if (row && (result = detectValue(row[dimIndex])) != null) {
  17478. return result;
  17479. }
  17480. }
  17481. }
  17482. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17483. if (!dimName) {
  17484. return BE_ORDINAL.Not;
  17485. }
  17486. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17487. var item = data[i];
  17488. if (item && (result = detectValue(item[dimName])) != null) {
  17489. return result;
  17490. }
  17491. }
  17492. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17493. if (!dimName) {
  17494. return BE_ORDINAL.Not;
  17495. }
  17496. var sample = data[dimName];
  17497. if (!sample || isTypedArray(sample)) {
  17498. return BE_ORDINAL.Not;
  17499. }
  17500. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17501. if ((result = detectValue(sample[i])) != null) {
  17502. return result;
  17503. }
  17504. }
  17505. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17506. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17507. var item = data[i];
  17508. var val = getDataItemValue(item);
  17509. if (!isArray(val)) {
  17510. return BE_ORDINAL.Not;
  17511. }
  17512. if ((result = detectValue(val[dimIndex])) != null) {
  17513. return result;
  17514. }
  17515. }
  17516. }
  17517. function detectValue(val) {
  17518. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17519. // `isFinit('')` get `true`.
  17520. if (val != null && isFinite(val) && val !== '') {
  17521. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17522. } else if (beStr && val !== '-') {
  17523. return BE_ORDINAL.Must;
  17524. }
  17525. }
  17526. return BE_ORDINAL.Not;
  17527. }
  17528. /*
  17529. * Licensed to the Apache Software Foundation (ASF) under one
  17530. * or more contributor license agreements. See the NOTICE file
  17531. * distributed with this work for additional information
  17532. * regarding copyright ownership. The ASF licenses this file
  17533. * to you under the Apache License, Version 2.0 (the
  17534. * "License"); you may not use this file except in compliance
  17535. * with the License. You may obtain a copy of the License at
  17536. *
  17537. * http://www.apache.org/licenses/LICENSE-2.0
  17538. *
  17539. * Unless required by applicable law or agreed to in writing,
  17540. * software distributed under the License is distributed on an
  17541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17542. * KIND, either express or implied. See the License for the
  17543. * specific language governing permissions and limitations
  17544. * under the License.
  17545. */
  17546. /**
  17547. * ECharts global model
  17548. *
  17549. * @module {echarts/model/Global}
  17550. */
  17551. /**
  17552. * Caution: If the mechanism should be changed some day, these cases
  17553. * should be considered:
  17554. *
  17555. * (1) In `merge option` mode, if using the same option to call `setOption`
  17556. * many times, the result should be the same (try our best to ensure that).
  17557. * (2) In `merge option` mode, if a component has no id/name specified, it
  17558. * will be merged by index, and the result sequence of the components is
  17559. * consistent to the original sequence.
  17560. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17561. * `mergeOption` in module:echarts/model/OptionManager.
  17562. */
  17563. var OPTION_INNER_KEY = '\0_ec_inner';
  17564. /**
  17565. * @alias module:echarts/model/Global
  17566. *
  17567. * @param {Object} option
  17568. * @param {module:echarts/model/Model} parentModel
  17569. * @param {Object} theme
  17570. */
  17571. var GlobalModel = Model.extend({
  17572. init: function (option, parentModel, theme, optionManager) {
  17573. theme = theme || {};
  17574. this.option = null; // Mark as not initialized.
  17575. /**
  17576. * @type {module:echarts/model/Model}
  17577. * @private
  17578. */
  17579. this._theme = new Model(theme);
  17580. /**
  17581. * @type {module:echarts/model/OptionManager}
  17582. */
  17583. this._optionManager = optionManager;
  17584. },
  17585. setOption: function (option, optionPreprocessorFuncs) {
  17586. assert$1(!(OPTION_INNER_KEY in option), 'please use chart.getOption()');
  17587. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17588. this.resetOption(null);
  17589. },
  17590. /**
  17591. * @param {string} type null/undefined: reset all.
  17592. * 'recreate': force recreate all.
  17593. * 'timeline': only reset timeline option
  17594. * 'media': only reset media query option
  17595. * @return {boolean} Whether option changed.
  17596. */
  17597. resetOption: function (type) {
  17598. var optionChanged = false;
  17599. var optionManager = this._optionManager;
  17600. if (!type || type === 'recreate') {
  17601. var baseOption = optionManager.mountOption(type === 'recreate');
  17602. if (!this.option || type === 'recreate') {
  17603. initBase.call(this, baseOption);
  17604. } else {
  17605. this.restoreData();
  17606. this.mergeOption(baseOption);
  17607. }
  17608. optionChanged = true;
  17609. }
  17610. if (type === 'timeline' || type === 'media') {
  17611. this.restoreData();
  17612. }
  17613. if (!type || type === 'recreate' || type === 'timeline') {
  17614. var timelineOption = optionManager.getTimelineOption(this);
  17615. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17616. }
  17617. if (!type || type === 'recreate' || type === 'media') {
  17618. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17619. if (mediaOptions.length) {
  17620. each$1(mediaOptions, function (mediaOption) {
  17621. this.mergeOption(mediaOption, optionChanged = true);
  17622. }, this);
  17623. }
  17624. }
  17625. return optionChanged;
  17626. },
  17627. /**
  17628. * @protected
  17629. */
  17630. mergeOption: function (newOption) {
  17631. var option = this.option;
  17632. var componentsMap = this._componentsMap;
  17633. var newCptTypes = [];
  17634. resetSourceDefaulter(this); // If no component class, merge directly.
  17635. // For example: color, animaiton options, etc.
  17636. each$1(newOption, function (componentOption, mainType) {
  17637. if (componentOption == null) {
  17638. return;
  17639. }
  17640. if (!ComponentModel.hasClass(mainType)) {
  17641. // globalSettingTask.dirty();
  17642. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17643. } else if (mainType) {
  17644. newCptTypes.push(mainType);
  17645. }
  17646. });
  17647. ComponentModel.topologicalTravel(newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17648. function visitComponent(mainType, dependencies) {
  17649. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17650. var mapResult = mappingToExists(componentsMap.get(mainType), newCptOptionList);
  17651. makeIdAndName(mapResult); // Set mainType and complete subType.
  17652. each$1(mapResult, function (item, index) {
  17653. var opt = item.option;
  17654. if (isObject$1(opt)) {
  17655. item.keyInfo.mainType = mainType;
  17656. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17657. }
  17658. });
  17659. var dependentModels = getComponentsByTypes(componentsMap, dependencies);
  17660. option[mainType] = [];
  17661. componentsMap.set(mainType, []);
  17662. each$1(mapResult, function (resultItem, index) {
  17663. var componentModel = resultItem.exist;
  17664. var newCptOption = resultItem.option;
  17665. assert$1(isObject$1(newCptOption) || componentModel, 'Empty component definition'); // Consider where is no new option and should be merged using {},
  17666. // see removeEdgeAndAdd in topologicalTravel and
  17667. // ComponentModel.getAllClassMainTypes.
  17668. if (!newCptOption) {
  17669. componentModel.mergeOption({}, this);
  17670. componentModel.optionUpdated({}, false);
  17671. } else {
  17672. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, true);
  17673. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17674. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17675. componentModel.mergeOption(newCptOption, this);
  17676. componentModel.optionUpdated(newCptOption, false);
  17677. } else {
  17678. // PENDING Global as parent ?
  17679. var extraOpt = extend({
  17680. dependentModels: dependentModels,
  17681. componentIndex: index
  17682. }, resultItem.keyInfo);
  17683. componentModel = new ComponentModelClass(newCptOption, this, this, extraOpt);
  17684. extend(componentModel, extraOpt);
  17685. componentModel.init(newCptOption, this, this, extraOpt); // Call optionUpdated after init.
  17686. // newCptOption has been used as componentModel.option
  17687. // and may be merged with theme and default, so pass null
  17688. // to avoid confusion.
  17689. componentModel.optionUpdated(null, true);
  17690. }
  17691. }
  17692. componentsMap.get(mainType)[index] = componentModel;
  17693. option[mainType][index] = componentModel.option;
  17694. }, this); // Backup series for filtering.
  17695. if (mainType === 'series') {
  17696. createSeriesIndices(this, componentsMap.get('series'));
  17697. }
  17698. }
  17699. this._seriesIndicesMap = createHashMap(this._seriesIndices = this._seriesIndices || []);
  17700. },
  17701. /**
  17702. * Get option for output (cloned option and inner info removed)
  17703. * @public
  17704. * @return {Object}
  17705. */
  17706. getOption: function () {
  17707. var option = clone(this.option);
  17708. each$1(option, function (opts, mainType) {
  17709. if (ComponentModel.hasClass(mainType)) {
  17710. var opts = normalizeToArray(opts);
  17711. for (var i = opts.length - 1; i >= 0; i--) {
  17712. // Remove options with inner id.
  17713. if (isIdInner(opts[i])) {
  17714. opts.splice(i, 1);
  17715. }
  17716. }
  17717. option[mainType] = opts;
  17718. }
  17719. });
  17720. delete option[OPTION_INNER_KEY];
  17721. return option;
  17722. },
  17723. /**
  17724. * @return {module:echarts/model/Model}
  17725. */
  17726. getTheme: function () {
  17727. return this._theme;
  17728. },
  17729. /**
  17730. * @param {string} mainType
  17731. * @param {number} [idx=0]
  17732. * @return {module:echarts/model/Component}
  17733. */
  17734. getComponent: function (mainType, idx) {
  17735. var list = this._componentsMap.get(mainType);
  17736. if (list) {
  17737. return list[idx || 0];
  17738. }
  17739. },
  17740. /**
  17741. * If none of index and id and name used, return all components with mainType.
  17742. * @param {Object} condition
  17743. * @param {string} condition.mainType
  17744. * @param {string} [condition.subType] If ignore, only query by mainType
  17745. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17746. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17747. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17748. * @return {Array.<module:echarts/model/Component>}
  17749. */
  17750. queryComponents: function (condition) {
  17751. var mainType = condition.mainType;
  17752. if (!mainType) {
  17753. return [];
  17754. }
  17755. var index = condition.index;
  17756. var id = condition.id;
  17757. var name = condition.name;
  17758. var cpts = this._componentsMap.get(mainType);
  17759. if (!cpts || !cpts.length) {
  17760. return [];
  17761. }
  17762. var result;
  17763. if (index != null) {
  17764. if (!isArray(index)) {
  17765. index = [index];
  17766. }
  17767. result = filter(map(index, function (idx) {
  17768. return cpts[idx];
  17769. }), function (val) {
  17770. return !!val;
  17771. });
  17772. } else if (id != null) {
  17773. var isIdArray = isArray(id);
  17774. result = filter(cpts, function (cpt) {
  17775. return isIdArray && indexOf(id, cpt.id) >= 0 || !isIdArray && cpt.id === id;
  17776. });
  17777. } else if (name != null) {
  17778. var isNameArray = isArray(name);
  17779. result = filter(cpts, function (cpt) {
  17780. return isNameArray && indexOf(name, cpt.name) >= 0 || !isNameArray && cpt.name === name;
  17781. });
  17782. } else {
  17783. // Return all components with mainType
  17784. result = cpts.slice();
  17785. }
  17786. return filterBySubType(result, condition);
  17787. },
  17788. /**
  17789. * The interface is different from queryComponents,
  17790. * which is convenient for inner usage.
  17791. *
  17792. * @usage
  17793. * var result = findComponents(
  17794. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17795. * );
  17796. * var result = findComponents(
  17797. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17798. * );
  17799. * var result = findComponents(
  17800. * {mainType: 'series',
  17801. * filter: function (model, index) {...}}
  17802. * );
  17803. * // result like [component0, componnet1, ...]
  17804. *
  17805. * @param {Object} condition
  17806. * @param {string} condition.mainType Mandatory.
  17807. * @param {string} [condition.subType] Optional.
  17808. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17809. * where xxx is mainType.
  17810. * If query attribute is null/undefined or has no index/id/name,
  17811. * do not filtering by query conditions, which is convenient for
  17812. * no-payload situations or when target of action is global.
  17813. * @param {Function} [condition.filter] parameter: component, return boolean.
  17814. * @return {Array.<module:echarts/model/Component>}
  17815. */
  17816. findComponents: function (condition) {
  17817. var query = condition.query;
  17818. var mainType = condition.mainType;
  17819. var queryCond = getQueryCond(query);
  17820. var result = queryCond ? this.queryComponents(queryCond) : this._componentsMap.get(mainType);
  17821. return doFilter(filterBySubType(result, condition));
  17822. function getQueryCond(q) {
  17823. var indexAttr = mainType + 'Index';
  17824. var idAttr = mainType + 'Id';
  17825. var nameAttr = mainType + 'Name';
  17826. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17827. mainType: mainType,
  17828. // subType will be filtered finally.
  17829. index: q[indexAttr],
  17830. id: q[idAttr],
  17831. name: q[nameAttr]
  17832. } : null;
  17833. }
  17834. function doFilter(res) {
  17835. return condition.filter ? filter(res, condition.filter) : res;
  17836. }
  17837. },
  17838. /**
  17839. * @usage
  17840. * eachComponent('legend', function (legendModel, index) {
  17841. * ...
  17842. * });
  17843. * eachComponent(function (componentType, model, index) {
  17844. * // componentType does not include subType
  17845. * // (componentType is 'xxx' but not 'xxx.aa')
  17846. * });
  17847. * eachComponent(
  17848. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17849. * function (model, index) {...}
  17850. * );
  17851. * eachComponent(
  17852. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17853. * function (model, index) {...}
  17854. * );
  17855. *
  17856. * @param {string|Object=} mainType When mainType is object, the definition
  17857. * is the same as the method 'findComponents'.
  17858. * @param {Function} cb
  17859. * @param {*} context
  17860. */
  17861. eachComponent: function (mainType, cb, context) {
  17862. var componentsMap = this._componentsMap;
  17863. if (typeof mainType === 'function') {
  17864. context = cb;
  17865. cb = mainType;
  17866. componentsMap.each(function (components, componentType) {
  17867. each$1(components, function (component, index) {
  17868. cb.call(context, componentType, component, index);
  17869. });
  17870. });
  17871. } else if (isString(mainType)) {
  17872. each$1(componentsMap.get(mainType), cb, context);
  17873. } else if (isObject$1(mainType)) {
  17874. var queryResult = this.findComponents(mainType);
  17875. each$1(queryResult, cb, context);
  17876. }
  17877. },
  17878. /**
  17879. * @param {string} name
  17880. * @return {Array.<module:echarts/model/Series>}
  17881. */
  17882. getSeriesByName: function (name) {
  17883. var series = this._componentsMap.get('series');
  17884. return filter(series, function (oneSeries) {
  17885. return oneSeries.name === name;
  17886. });
  17887. },
  17888. /**
  17889. * @param {number} seriesIndex
  17890. * @return {module:echarts/model/Series}
  17891. */
  17892. getSeriesByIndex: function (seriesIndex) {
  17893. return this._componentsMap.get('series')[seriesIndex];
  17894. },
  17895. /**
  17896. * Get series list before filtered by type.
  17897. * FIXME: rename to getRawSeriesByType?
  17898. *
  17899. * @param {string} subType
  17900. * @return {Array.<module:echarts/model/Series>}
  17901. */
  17902. getSeriesByType: function (subType) {
  17903. var series = this._componentsMap.get('series');
  17904. return filter(series, function (oneSeries) {
  17905. return oneSeries.subType === subType;
  17906. });
  17907. },
  17908. /**
  17909. * @return {Array.<module:echarts/model/Series>}
  17910. */
  17911. getSeries: function () {
  17912. return this._componentsMap.get('series').slice();
  17913. },
  17914. /**
  17915. * @return {number}
  17916. */
  17917. getSeriesCount: function () {
  17918. return this._componentsMap.get('series').length;
  17919. },
  17920. /**
  17921. * After filtering, series may be different
  17922. * frome raw series.
  17923. *
  17924. * @param {Function} cb
  17925. * @param {*} context
  17926. */
  17927. eachSeries: function (cb, context) {
  17928. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17929. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17930. cb.call(context, series, rawSeriesIndex);
  17931. }, this);
  17932. },
  17933. /**
  17934. * Iterate raw series before filtered.
  17935. *
  17936. * @param {Function} cb
  17937. * @param {*} context
  17938. */
  17939. eachRawSeries: function (cb, context) {
  17940. each$1(this._componentsMap.get('series'), cb, context);
  17941. },
  17942. /**
  17943. * After filtering, series may be different.
  17944. * frome raw series.
  17945. *
  17946. * @param {string} subType.
  17947. * @param {Function} cb
  17948. * @param {*} context
  17949. */
  17950. eachSeriesByType: function (subType, cb, context) {
  17951. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17952. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17953. if (series.subType === subType) {
  17954. cb.call(context, series, rawSeriesIndex);
  17955. }
  17956. }, this);
  17957. },
  17958. /**
  17959. * Iterate raw series before filtered of given type.
  17960. *
  17961. * @parma {string} subType
  17962. * @param {Function} cb
  17963. * @param {*} context
  17964. */
  17965. eachRawSeriesByType: function (subType, cb, context) {
  17966. return each$1(this.getSeriesByType(subType), cb, context);
  17967. },
  17968. /**
  17969. * @param {module:echarts/model/Series} seriesModel
  17970. */
  17971. isSeriesFiltered: function (seriesModel) {
  17972. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17973. },
  17974. /**
  17975. * @return {Array.<number>}
  17976. */
  17977. getCurrentSeriesIndices: function () {
  17978. return (this._seriesIndices || []).slice();
  17979. },
  17980. /**
  17981. * @param {Function} cb
  17982. * @param {*} context
  17983. */
  17984. filterSeries: function (cb, context) {
  17985. var filteredSeries = filter(this._componentsMap.get('series'), cb, context);
  17986. createSeriesIndices(this, filteredSeries);
  17987. },
  17988. restoreData: function (payload) {
  17989. var componentsMap = this._componentsMap;
  17990. createSeriesIndices(this, componentsMap.get('series'));
  17991. var componentTypes = [];
  17992. componentsMap.each(function (components, componentType) {
  17993. componentTypes.push(componentType);
  17994. });
  17995. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType, dependencies) {
  17996. each$1(componentsMap.get(componentType), function (component) {
  17997. (componentType !== 'series' || !isNotTargetSeries(component, payload)) && component.restoreData();
  17998. });
  17999. });
  18000. }
  18001. });
  18002. function isNotTargetSeries(seriesModel, payload) {
  18003. if (payload) {
  18004. var index = payload.seiresIndex;
  18005. var id = payload.seriesId;
  18006. var name = payload.seriesName;
  18007. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name != null && seriesModel.name !== name;
  18008. }
  18009. }
  18010. /**
  18011. * @inner
  18012. */
  18013. function mergeTheme(option, theme) {
  18014. // PENDING
  18015. // NOT use `colorLayer` in theme if option has `color`
  18016. var notMergeColorLayer = option.color && !option.colorLayer;
  18017. each$1(theme, function (themeItem, name) {
  18018. if (name === 'colorLayer' && notMergeColorLayer) {
  18019. return;
  18020. } // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18021. if (!ComponentModel.hasClass(name)) {
  18022. if (typeof themeItem === 'object') {
  18023. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  18024. } else {
  18025. if (option[name] == null) {
  18026. option[name] = themeItem;
  18027. }
  18028. }
  18029. }
  18030. });
  18031. }
  18032. function initBase(baseOption) {
  18033. baseOption = baseOption; // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18034. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18035. this.option = {};
  18036. this.option[OPTION_INNER_KEY] = 1;
  18037. /**
  18038. * Init with series: [], in case of calling findSeries method
  18039. * before series initialized.
  18040. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18041. * @private
  18042. */
  18043. this._componentsMap = createHashMap({
  18044. series: []
  18045. });
  18046. /**
  18047. * Mapping between filtered series list and raw series list.
  18048. * key: filtered series indices, value: raw series indices.
  18049. * @type {Array.<nubmer>}
  18050. * @private
  18051. */
  18052. this._seriesIndices;
  18053. this._seriesIndicesMap;
  18054. mergeTheme(baseOption, this._theme.option); // TODO Needs clone when merging to the unexisted property
  18055. merge(baseOption, globalDefault, false);
  18056. this.mergeOption(baseOption);
  18057. }
  18058. /**
  18059. * @inner
  18060. * @param {Array.<string>|string} types model types
  18061. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18062. */
  18063. function getComponentsByTypes(componentsMap, types) {
  18064. if (!isArray(types)) {
  18065. types = types ? [types] : [];
  18066. }
  18067. var ret = {};
  18068. each$1(types, function (type) {
  18069. ret[type] = (componentsMap.get(type) || []).slice();
  18070. });
  18071. return ret;
  18072. }
  18073. /**
  18074. * @inner
  18075. */
  18076. function determineSubType(mainType, newCptOption, existComponent) {
  18077. var subType = newCptOption.type ? newCptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  18078. : ComponentModel.determineSubType(mainType, newCptOption); // tooltip, markline, markpoint may always has no subType
  18079. return subType;
  18080. }
  18081. /**
  18082. * @inner
  18083. */
  18084. function createSeriesIndices(ecModel, seriesModels) {
  18085. ecModel._seriesIndicesMap = createHashMap(ecModel._seriesIndices = map(seriesModels, function (series) {
  18086. return series.componentIndex;
  18087. }) || []);
  18088. }
  18089. /**
  18090. * @inner
  18091. */
  18092. function filterBySubType(components, condition) {
  18093. // Using hasOwnProperty for restrict. Consider
  18094. // subType is undefined in user payload.
  18095. return condition.hasOwnProperty('subType') ? filter(components, function (cpt) {
  18096. return cpt.subType === condition.subType;
  18097. }) : components;
  18098. }
  18099. mixin(GlobalModel, colorPaletteMixin);
  18100. /*
  18101. * Licensed to the Apache Software Foundation (ASF) under one
  18102. * or more contributor license agreements. See the NOTICE file
  18103. * distributed with this work for additional information
  18104. * regarding copyright ownership. The ASF licenses this file
  18105. * to you under the Apache License, Version 2.0 (the
  18106. * "License"); you may not use this file except in compliance
  18107. * with the License. You may obtain a copy of the License at
  18108. *
  18109. * http://www.apache.org/licenses/LICENSE-2.0
  18110. *
  18111. * Unless required by applicable law or agreed to in writing,
  18112. * software distributed under the License is distributed on an
  18113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18114. * KIND, either express or implied. See the License for the
  18115. * specific language governing permissions and limitations
  18116. * under the License.
  18117. */
  18118. var echartsAPIList = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption', 'getViewOfComponentModel', 'getViewOfSeriesModel']; // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18119. function ExtensionAPI(chartInstance) {
  18120. each$1(echartsAPIList, function (name) {
  18121. this[name] = bind(chartInstance[name], chartInstance);
  18122. }, this);
  18123. }
  18124. /*
  18125. * Licensed to the Apache Software Foundation (ASF) under one
  18126. * or more contributor license agreements. See the NOTICE file
  18127. * distributed with this work for additional information
  18128. * regarding copyright ownership. The ASF licenses this file
  18129. * to you under the Apache License, Version 2.0 (the
  18130. * "License"); you may not use this file except in compliance
  18131. * with the License. You may obtain a copy of the License at
  18132. *
  18133. * http://www.apache.org/licenses/LICENSE-2.0
  18134. *
  18135. * Unless required by applicable law or agreed to in writing,
  18136. * software distributed under the License is distributed on an
  18137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18138. * KIND, either express or implied. See the License for the
  18139. * specific language governing permissions and limitations
  18140. * under the License.
  18141. */
  18142. var coordinateSystemCreators = {};
  18143. function CoordinateSystemManager() {
  18144. this._coordinateSystems = [];
  18145. }
  18146. CoordinateSystemManager.prototype = {
  18147. constructor: CoordinateSystemManager,
  18148. create: function (ecModel, api) {
  18149. var coordinateSystems = [];
  18150. each$1(coordinateSystemCreators, function (creater, type) {
  18151. var list = creater.create(ecModel, api);
  18152. coordinateSystems = coordinateSystems.concat(list || []);
  18153. });
  18154. this._coordinateSystems = coordinateSystems;
  18155. },
  18156. update: function (ecModel, api) {
  18157. each$1(this._coordinateSystems, function (coordSys) {
  18158. coordSys.update && coordSys.update(ecModel, api);
  18159. });
  18160. },
  18161. getCoordinateSystems: function () {
  18162. return this._coordinateSystems.slice();
  18163. }
  18164. };
  18165. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18166. coordinateSystemCreators[type] = coordinateSystemCreator;
  18167. };
  18168. CoordinateSystemManager.get = function (type) {
  18169. return coordinateSystemCreators[type];
  18170. };
  18171. /*
  18172. * Licensed to the Apache Software Foundation (ASF) under one
  18173. * or more contributor license agreements. See the NOTICE file
  18174. * distributed with this work for additional information
  18175. * regarding copyright ownership. The ASF licenses this file
  18176. * to you under the Apache License, Version 2.0 (the
  18177. * "License"); you may not use this file except in compliance
  18178. * with the License. You may obtain a copy of the License at
  18179. *
  18180. * http://www.apache.org/licenses/LICENSE-2.0
  18181. *
  18182. * Unless required by applicable law or agreed to in writing,
  18183. * software distributed under the License is distributed on an
  18184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18185. * KIND, either express or implied. See the License for the
  18186. * specific language governing permissions and limitations
  18187. * under the License.
  18188. */
  18189. /**
  18190. * ECharts option manager
  18191. *
  18192. * @module {echarts/model/OptionManager}
  18193. */
  18194. var each$4 = each$1;
  18195. var clone$3 = clone;
  18196. var map$1 = map;
  18197. var merge$1 = merge;
  18198. var QUERY_REG = /^(min|max)?(.+)$/;
  18199. /**
  18200. * TERM EXPLANATIONS:
  18201. *
  18202. * [option]:
  18203. *
  18204. * An object that contains definitions of components. For example:
  18205. * var option = {
  18206. * title: {...},
  18207. * legend: {...},
  18208. * visualMap: {...},
  18209. * series: [
  18210. * {data: [...]},
  18211. * {data: [...]},
  18212. * ...
  18213. * ]
  18214. * };
  18215. *
  18216. * [rawOption]:
  18217. *
  18218. * An object input to echarts.setOption. 'rawOption' may be an
  18219. * 'option', or may be an object contains multi-options. For example:
  18220. * var option = {
  18221. * baseOption: {
  18222. * title: {...},
  18223. * legend: {...},
  18224. * series: [
  18225. * {data: [...]},
  18226. * {data: [...]},
  18227. * ...
  18228. * ]
  18229. * },
  18230. * timeline: {...},
  18231. * options: [
  18232. * {title: {...}, series: {data: [...]}},
  18233. * {title: {...}, series: {data: [...]}},
  18234. * ...
  18235. * ],
  18236. * media: [
  18237. * {
  18238. * query: {maxWidth: 320},
  18239. * option: {series: {x: 20}, visualMap: {show: false}}
  18240. * },
  18241. * {
  18242. * query: {minWidth: 320, maxWidth: 720},
  18243. * option: {series: {x: 500}, visualMap: {show: true}}
  18244. * },
  18245. * {
  18246. * option: {series: {x: 1200}, visualMap: {show: true}}
  18247. * }
  18248. * ]
  18249. * };
  18250. *
  18251. * @alias module:echarts/model/OptionManager
  18252. * @param {module:echarts/ExtensionAPI} api
  18253. */
  18254. function OptionManager(api) {
  18255. /**
  18256. * @private
  18257. * @type {module:echarts/ExtensionAPI}
  18258. */
  18259. this._api = api;
  18260. /**
  18261. * @private
  18262. * @type {Array.<number>}
  18263. */
  18264. this._timelineOptions = [];
  18265. /**
  18266. * @private
  18267. * @type {Array.<Object>}
  18268. */
  18269. this._mediaList = [];
  18270. /**
  18271. * @private
  18272. * @type {Object}
  18273. */
  18274. this._mediaDefault;
  18275. /**
  18276. * -1, means default.
  18277. * empty means no media.
  18278. * @private
  18279. * @type {Array.<number>}
  18280. */
  18281. this._currentMediaIndices = [];
  18282. /**
  18283. * @private
  18284. * @type {Object}
  18285. */
  18286. this._optionBackup;
  18287. /**
  18288. * @private
  18289. * @type {Object}
  18290. */
  18291. this._newBaseOption;
  18292. } // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18293. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18294. // rawOption cloned and backuped when timeline changed, which does no
  18295. // good to performance. What's more, that both timeline and setOption
  18296. // method supply 'notMerge' brings complex and some problems.
  18297. // Consider this case:
  18298. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18299. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18300. OptionManager.prototype = {
  18301. constructor: OptionManager,
  18302. /**
  18303. * @public
  18304. * @param {Object} rawOption Raw option.
  18305. * @param {module:echarts/model/Global} ecModel
  18306. * @param {Array.<Function>} optionPreprocessorFuncs
  18307. * @return {Object} Init option
  18308. */
  18309. setOption: function (rawOption, optionPreprocessorFuncs) {
  18310. if (rawOption) {
  18311. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18312. each$1(normalizeToArray(rawOption.series), function (series) {
  18313. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18314. });
  18315. } // Caution: some series modify option data, if do not clone,
  18316. // it should ensure that the repeat modify correctly
  18317. // (create a new object when modify itself).
  18318. rawOption = clone$3(rawOption); // FIXME
  18319. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18320. var oldOptionBackup = this._optionBackup;
  18321. var newParsedOption = parseRawOption.call(this, rawOption, optionPreprocessorFuncs, !oldOptionBackup);
  18322. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  18323. if (oldOptionBackup) {
  18324. // Only baseOption can be merged.
  18325. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption); // For simplicity, timeline options and media options do not support merge,
  18326. // that is, if you `setOption` twice and both has timeline options, the latter
  18327. // timeline opitons will not be merged to the formers, but just substitude them.
  18328. if (newParsedOption.timelineOptions.length) {
  18329. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18330. }
  18331. if (newParsedOption.mediaList.length) {
  18332. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18333. }
  18334. if (newParsedOption.mediaDefault) {
  18335. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18336. }
  18337. } else {
  18338. this._optionBackup = newParsedOption;
  18339. }
  18340. },
  18341. /**
  18342. * @param {boolean} isRecreate
  18343. * @return {Object}
  18344. */
  18345. mountOption: function (isRecreate) {
  18346. var optionBackup = this._optionBackup; // TODO
  18347. // 如果没有reset功能则不clone。
  18348. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18349. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18350. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18351. this._currentMediaIndices = [];
  18352. return clone$3(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  18353. // called, and is merged into every new option by inner method `mergeOption`
  18354. // each time `setOption` called, can be only used in `isRecreate`, because
  18355. // its reliability is under suspicion. In other cases option merge is
  18356. // performed by `model.mergeOption`.
  18357. ? optionBackup.baseOption : this._newBaseOption);
  18358. },
  18359. /**
  18360. * @param {module:echarts/model/Global} ecModel
  18361. * @return {Object}
  18362. */
  18363. getTimelineOption: function (ecModel) {
  18364. var option;
  18365. var timelineOptions = this._timelineOptions;
  18366. if (timelineOptions.length) {
  18367. // getTimelineOption can only be called after ecModel inited,
  18368. // so we can get currentIndex from timelineModel.
  18369. var timelineModel = ecModel.getComponent('timeline');
  18370. if (timelineModel) {
  18371. option = clone$3(timelineOptions[timelineModel.getCurrentIndex()], true);
  18372. }
  18373. }
  18374. return option;
  18375. },
  18376. /**
  18377. * @param {module:echarts/model/Global} ecModel
  18378. * @return {Array.<Object>}
  18379. */
  18380. getMediaOption: function (ecModel) {
  18381. var ecWidth = this._api.getWidth();
  18382. var ecHeight = this._api.getHeight();
  18383. var mediaList = this._mediaList;
  18384. var mediaDefault = this._mediaDefault;
  18385. var indices = [];
  18386. var result = []; // No media defined.
  18387. if (!mediaList.length && !mediaDefault) {
  18388. return result;
  18389. } // Multi media may be applied, the latter defined media has higher priority.
  18390. for (var i = 0, len = mediaList.length; i < len; i++) {
  18391. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18392. indices.push(i);
  18393. }
  18394. } // FIXME
  18395. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18396. if (!indices.length && mediaDefault) {
  18397. indices = [-1];
  18398. }
  18399. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18400. result = map$1(indices, function (index) {
  18401. return clone$3(index === -1 ? mediaDefault.option : mediaList[index].option);
  18402. });
  18403. } // Otherwise return nothing.
  18404. this._currentMediaIndices = indices;
  18405. return result;
  18406. }
  18407. };
  18408. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18409. var timelineOptions = [];
  18410. var mediaList = [];
  18411. var mediaDefault;
  18412. var baseOption; // Compatible with ec2.
  18413. var timelineOpt = rawOption.timeline;
  18414. if (rawOption.baseOption) {
  18415. baseOption = rawOption.baseOption;
  18416. } // For timeline
  18417. if (timelineOpt || rawOption.options) {
  18418. baseOption = baseOption || {};
  18419. timelineOptions = (rawOption.options || []).slice();
  18420. } // For media query
  18421. if (rawOption.media) {
  18422. baseOption = baseOption || {};
  18423. var media = rawOption.media;
  18424. each$4(media, function (singleMedia) {
  18425. if (singleMedia && singleMedia.option) {
  18426. if (singleMedia.query) {
  18427. mediaList.push(singleMedia);
  18428. } else if (!mediaDefault) {
  18429. // Use the first media default.
  18430. mediaDefault = singleMedia;
  18431. }
  18432. }
  18433. });
  18434. } // For normal option
  18435. if (!baseOption) {
  18436. baseOption = rawOption;
  18437. } // Set timelineOpt to baseOption in ec3,
  18438. // which is convenient for merge option.
  18439. if (!baseOption.timeline) {
  18440. baseOption.timeline = timelineOpt;
  18441. } // Preprocess.
  18442. each$4([baseOption].concat(timelineOptions).concat(map(mediaList, function (media) {
  18443. return media.option;
  18444. })), function (option) {
  18445. each$4(optionPreprocessorFuncs, function (preProcess) {
  18446. preProcess(option, isNew);
  18447. });
  18448. });
  18449. return {
  18450. baseOption: baseOption,
  18451. timelineOptions: timelineOptions,
  18452. mediaDefault: mediaDefault,
  18453. mediaList: mediaList
  18454. };
  18455. }
  18456. /**
  18457. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18458. * Support: width, height, aspectRatio
  18459. * Can use max or min as prefix.
  18460. */
  18461. function applyMediaQuery(query, ecWidth, ecHeight) {
  18462. var realMap = {
  18463. width: ecWidth,
  18464. height: ecHeight,
  18465. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18466. };
  18467. var applicatable = true;
  18468. each$1(query, function (value, attr) {
  18469. var matched = attr.match(QUERY_REG);
  18470. if (!matched || !matched[1] || !matched[2]) {
  18471. return;
  18472. }
  18473. var operator = matched[1];
  18474. var realAttr = matched[2].toLowerCase();
  18475. if (!compare(realMap[realAttr], value, operator)) {
  18476. applicatable = false;
  18477. }
  18478. });
  18479. return applicatable;
  18480. }
  18481. function compare(real, expect, operator) {
  18482. if (operator === 'min') {
  18483. return real >= expect;
  18484. } else if (operator === 'max') {
  18485. return real <= expect;
  18486. } else {
  18487. // Equals
  18488. return real === expect;
  18489. }
  18490. }
  18491. function indicesEquals(indices1, indices2) {
  18492. // indices is always order by asc and has only finite number.
  18493. return indices1.join(',') === indices2.join(',');
  18494. }
  18495. /**
  18496. * Consider case:
  18497. * `chart.setOption(opt1);`
  18498. * Then user do some interaction like dataZoom, dataView changing.
  18499. * `chart.setOption(opt2);`
  18500. * Then user press 'reset button' in toolbox.
  18501. *
  18502. * After doing that all of the interaction effects should be reset, the
  18503. * chart should be the same as the result of invoke
  18504. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18505. *
  18506. * Although it is not able ensure that
  18507. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18508. * `chart.setOption(merge(opt1, opt2));` exactly,
  18509. * this might be the only simple way to implement that feature.
  18510. *
  18511. * MEMO: We've considered some other approaches:
  18512. * 1. Each model handle its self restoration but not uniform treatment.
  18513. * (Too complex in logic and error-prone)
  18514. * 2. Use a shadow ecModel. (Performace expensive)
  18515. */
  18516. function mergeOption(oldOption, newOption) {
  18517. newOption = newOption || {};
  18518. each$4(newOption, function (newCptOpt, mainType) {
  18519. if (newCptOpt == null) {
  18520. return;
  18521. }
  18522. var oldCptOpt = oldOption[mainType];
  18523. if (!ComponentModel.hasClass(mainType)) {
  18524. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18525. } else {
  18526. newCptOpt = normalizeToArray(newCptOpt);
  18527. oldCptOpt = normalizeToArray(oldCptOpt);
  18528. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18529. oldOption[mainType] = map$1(mapResult, function (item) {
  18530. return item.option && item.exist ? merge$1(item.exist, item.option, true) : item.exist || item.option;
  18531. });
  18532. }
  18533. });
  18534. }
  18535. /*
  18536. * Licensed to the Apache Software Foundation (ASF) under one
  18537. * or more contributor license agreements. See the NOTICE file
  18538. * distributed with this work for additional information
  18539. * regarding copyright ownership. The ASF licenses this file
  18540. * to you under the Apache License, Version 2.0 (the
  18541. * "License"); you may not use this file except in compliance
  18542. * with the License. You may obtain a copy of the License at
  18543. *
  18544. * http://www.apache.org/licenses/LICENSE-2.0
  18545. *
  18546. * Unless required by applicable law or agreed to in writing,
  18547. * software distributed under the License is distributed on an
  18548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18549. * KIND, either express or implied. See the License for the
  18550. * specific language governing permissions and limitations
  18551. * under the License.
  18552. */
  18553. var each$5 = each$1;
  18554. var isObject$3 = isObject$1;
  18555. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18556. function compatEC2ItemStyle(opt) {
  18557. var itemStyleOpt = opt && opt.itemStyle;
  18558. if (!itemStyleOpt) {
  18559. return;
  18560. }
  18561. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18562. var styleName = POSSIBLE_STYLES[i];
  18563. var normalItemStyleOpt = itemStyleOpt.normal;
  18564. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18565. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18566. opt[styleName] = opt[styleName] || {};
  18567. if (!opt[styleName].normal) {
  18568. opt[styleName].normal = normalItemStyleOpt[styleName];
  18569. } else {
  18570. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18571. }
  18572. normalItemStyleOpt[styleName] = null;
  18573. }
  18574. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18575. opt[styleName] = opt[styleName] || {};
  18576. if (!opt[styleName].emphasis) {
  18577. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18578. } else {
  18579. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18580. }
  18581. emphasisItemStyleOpt[styleName] = null;
  18582. }
  18583. }
  18584. }
  18585. function convertNormalEmphasis(opt, optType, useExtend) {
  18586. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18587. var normalOpt = opt[optType].normal;
  18588. var emphasisOpt = opt[optType].emphasis;
  18589. if (normalOpt) {
  18590. // Timeline controlStyle has other properties besides normal and emphasis
  18591. if (useExtend) {
  18592. opt[optType].normal = opt[optType].emphasis = null;
  18593. defaults(opt[optType], normalOpt);
  18594. } else {
  18595. opt[optType] = normalOpt;
  18596. }
  18597. }
  18598. if (emphasisOpt) {
  18599. opt.emphasis = opt.emphasis || {};
  18600. opt.emphasis[optType] = emphasisOpt;
  18601. }
  18602. }
  18603. }
  18604. function removeEC3NormalStatus(opt) {
  18605. convertNormalEmphasis(opt, 'itemStyle');
  18606. convertNormalEmphasis(opt, 'lineStyle');
  18607. convertNormalEmphasis(opt, 'areaStyle');
  18608. convertNormalEmphasis(opt, 'label');
  18609. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18610. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18611. convertNormalEmphasis(opt, 'edgeLabel');
  18612. }
  18613. function compatTextStyle(opt, propName) {
  18614. // Check whether is not object (string\null\undefined ...)
  18615. var labelOptSingle = isObject$3(opt) && opt[propName];
  18616. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18617. if (textStyle) {
  18618. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18619. var propName = TEXT_STYLE_OPTIONS[i];
  18620. if (textStyle.hasOwnProperty(propName)) {
  18621. labelOptSingle[propName] = textStyle[propName];
  18622. }
  18623. }
  18624. }
  18625. }
  18626. function compatEC3CommonStyles(opt) {
  18627. if (opt) {
  18628. removeEC3NormalStatus(opt);
  18629. compatTextStyle(opt, 'label');
  18630. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18631. }
  18632. }
  18633. function processSeries(seriesOpt) {
  18634. if (!isObject$3(seriesOpt)) {
  18635. return;
  18636. }
  18637. compatEC2ItemStyle(seriesOpt);
  18638. removeEC3NormalStatus(seriesOpt);
  18639. compatTextStyle(seriesOpt, 'label'); // treemap
  18640. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18641. compatTextStyle(seriesOpt, 'edgeLabel');
  18642. if (seriesOpt.emphasis) {
  18643. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18644. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18645. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18646. }
  18647. var markPoint = seriesOpt.markPoint;
  18648. if (markPoint) {
  18649. compatEC2ItemStyle(markPoint);
  18650. compatEC3CommonStyles(markPoint);
  18651. }
  18652. var markLine = seriesOpt.markLine;
  18653. if (markLine) {
  18654. compatEC2ItemStyle(markLine);
  18655. compatEC3CommonStyles(markLine);
  18656. }
  18657. var markArea = seriesOpt.markArea;
  18658. if (markArea) {
  18659. compatEC3CommonStyles(markArea);
  18660. }
  18661. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18662. // then the backward compat based on option type will not be performed.
  18663. if (seriesOpt.type === 'graph') {
  18664. data = data || seriesOpt.nodes;
  18665. var edgeData = seriesOpt.links || seriesOpt.edges;
  18666. if (edgeData && !isTypedArray(edgeData)) {
  18667. for (var i = 0; i < edgeData.length; i++) {
  18668. compatEC3CommonStyles(edgeData[i]);
  18669. }
  18670. }
  18671. each$1(seriesOpt.categories, function (opt) {
  18672. removeEC3NormalStatus(opt);
  18673. });
  18674. }
  18675. if (data && !isTypedArray(data)) {
  18676. for (var i = 0; i < data.length; i++) {
  18677. compatEC3CommonStyles(data[i]);
  18678. }
  18679. } // mark point data
  18680. var markPoint = seriesOpt.markPoint;
  18681. if (markPoint && markPoint.data) {
  18682. var mpData = markPoint.data;
  18683. for (var i = 0; i < mpData.length; i++) {
  18684. compatEC3CommonStyles(mpData[i]);
  18685. }
  18686. } // mark line data
  18687. var markLine = seriesOpt.markLine;
  18688. if (markLine && markLine.data) {
  18689. var mlData = markLine.data;
  18690. for (var i = 0; i < mlData.length; i++) {
  18691. if (isArray(mlData[i])) {
  18692. compatEC3CommonStyles(mlData[i][0]);
  18693. compatEC3CommonStyles(mlData[i][1]);
  18694. } else {
  18695. compatEC3CommonStyles(mlData[i]);
  18696. }
  18697. }
  18698. } // Series
  18699. if (seriesOpt.type === 'gauge') {
  18700. compatTextStyle(seriesOpt, 'axisLabel');
  18701. compatTextStyle(seriesOpt, 'title');
  18702. compatTextStyle(seriesOpt, 'detail');
  18703. } else if (seriesOpt.type === 'treemap') {
  18704. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18705. each$1(seriesOpt.levels, function (opt) {
  18706. removeEC3NormalStatus(opt);
  18707. });
  18708. } else if (seriesOpt.type === 'tree') {
  18709. removeEC3NormalStatus(seriesOpt.leaves);
  18710. } // sunburst starts from ec4, so it does not need to compat levels.
  18711. }
  18712. function toArr(o) {
  18713. return isArray(o) ? o : o ? [o] : [];
  18714. }
  18715. function toObj(o) {
  18716. return (isArray(o) ? o[0] : o) || {};
  18717. }
  18718. var compatStyle = function (option, isTheme) {
  18719. each$5(toArr(option.series), function (seriesOpt) {
  18720. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18721. });
  18722. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18723. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18724. each$5(axes, function (axisName) {
  18725. each$5(toArr(option[axisName]), function (axisOpt) {
  18726. if (axisOpt) {
  18727. compatTextStyle(axisOpt, 'axisLabel');
  18728. compatTextStyle(axisOpt.axisPointer, 'label');
  18729. }
  18730. });
  18731. });
  18732. each$5(toArr(option.parallel), function (parallelOpt) {
  18733. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18734. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18735. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18736. });
  18737. each$5(toArr(option.calendar), function (calendarOpt) {
  18738. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18739. compatTextStyle(calendarOpt, 'dayLabel');
  18740. compatTextStyle(calendarOpt, 'monthLabel');
  18741. compatTextStyle(calendarOpt, 'yearLabel');
  18742. }); // radar.name.textStyle
  18743. each$5(toArr(option.radar), function (radarOpt) {
  18744. compatTextStyle(radarOpt, 'name');
  18745. });
  18746. each$5(toArr(option.geo), function (geoOpt) {
  18747. if (isObject$3(geoOpt)) {
  18748. compatEC3CommonStyles(geoOpt);
  18749. each$5(toArr(geoOpt.regions), function (regionObj) {
  18750. compatEC3CommonStyles(regionObj);
  18751. });
  18752. }
  18753. });
  18754. each$5(toArr(option.timeline), function (timelineOpt) {
  18755. compatEC3CommonStyles(timelineOpt);
  18756. convertNormalEmphasis(timelineOpt, 'label');
  18757. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18758. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18759. var data = timelineOpt.data;
  18760. isArray(data) && each$1(data, function (item) {
  18761. if (isObject$1(item)) {
  18762. convertNormalEmphasis(item, 'label');
  18763. convertNormalEmphasis(item, 'itemStyle');
  18764. }
  18765. });
  18766. });
  18767. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18768. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18769. each$5(toolboxOpt.feature, function (featureOpt) {
  18770. convertNormalEmphasis(featureOpt, 'iconStyle');
  18771. });
  18772. });
  18773. compatTextStyle(toObj(option.axisPointer), 'label');
  18774. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18775. };
  18776. /*
  18777. * Licensed to the Apache Software Foundation (ASF) under one
  18778. * or more contributor license agreements. See the NOTICE file
  18779. * distributed with this work for additional information
  18780. * regarding copyright ownership. The ASF licenses this file
  18781. * to you under the Apache License, Version 2.0 (the
  18782. * "License"); you may not use this file except in compliance
  18783. * with the License. You may obtain a copy of the License at
  18784. *
  18785. * http://www.apache.org/licenses/LICENSE-2.0
  18786. *
  18787. * Unless required by applicable law or agreed to in writing,
  18788. * software distributed under the License is distributed on an
  18789. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18790. * KIND, either express or implied. See the License for the
  18791. * specific language governing permissions and limitations
  18792. * under the License.
  18793. */
  18794. // Compatitable with 2.0
  18795. function get(opt, path) {
  18796. path = path.split(',');
  18797. var obj = opt;
  18798. for (var i = 0; i < path.length; i++) {
  18799. obj = obj && obj[path[i]];
  18800. if (obj == null) {
  18801. break;
  18802. }
  18803. }
  18804. return obj;
  18805. }
  18806. function set$1(opt, path, val, overwrite) {
  18807. path = path.split(',');
  18808. var obj = opt;
  18809. var key;
  18810. for (var i = 0; i < path.length - 1; i++) {
  18811. key = path[i];
  18812. if (obj[key] == null) {
  18813. obj[key] = {};
  18814. }
  18815. obj = obj[key];
  18816. }
  18817. if (overwrite || obj[path[i]] == null) {
  18818. obj[path[i]] = val;
  18819. }
  18820. }
  18821. function compatLayoutProperties(option) {
  18822. each$1(LAYOUT_PROPERTIES, function (prop) {
  18823. if (prop[0] in option && !(prop[1] in option)) {
  18824. option[prop[1]] = option[prop[0]];
  18825. }
  18826. });
  18827. }
  18828. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18829. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18830. var backwardCompat = function (option, isTheme) {
  18831. compatStyle(option, isTheme); // Make sure series array for model initialization.
  18832. option.series = normalizeToArray(option.series);
  18833. each$1(option.series, function (seriesOpt) {
  18834. if (!isObject$1(seriesOpt)) {
  18835. return;
  18836. }
  18837. var seriesType = seriesOpt.type;
  18838. if (seriesType === 'line') {
  18839. if (seriesOpt.clipOverflow != null) {
  18840. seriesOpt.clip = seriesOpt.clipOverflow;
  18841. }
  18842. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18843. if (seriesOpt.clockWise != null) {
  18844. seriesOpt.clockwise = seriesOpt.clockWise;
  18845. }
  18846. } else if (seriesType === 'gauge') {
  18847. var pointerColor = get(seriesOpt, 'pointer.color');
  18848. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18849. }
  18850. compatLayoutProperties(seriesOpt);
  18851. }); // dataRange has changed to visualMap
  18852. if (option.dataRange) {
  18853. option.visualMap = option.dataRange;
  18854. }
  18855. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18856. var options = option[componentName];
  18857. if (options) {
  18858. if (!isArray(options)) {
  18859. options = [options];
  18860. }
  18861. each$1(options, function (option) {
  18862. compatLayoutProperties(option);
  18863. });
  18864. }
  18865. });
  18866. };
  18867. /*
  18868. * Licensed to the Apache Software Foundation (ASF) under one
  18869. * or more contributor license agreements. See the NOTICE file
  18870. * distributed with this work for additional information
  18871. * regarding copyright ownership. The ASF licenses this file
  18872. * to you under the Apache License, Version 2.0 (the
  18873. * "License"); you may not use this file except in compliance
  18874. * with the License. You may obtain a copy of the License at
  18875. *
  18876. * http://www.apache.org/licenses/LICENSE-2.0
  18877. *
  18878. * Unless required by applicable law or agreed to in writing,
  18879. * software distributed under the License is distributed on an
  18880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18881. * KIND, either express or implied. See the License for the
  18882. * specific language governing permissions and limitations
  18883. * under the License.
  18884. */
  18885. // data processing stage is blocked in stream.
  18886. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18887. // (2) Only register once when import repeatly.
  18888. // Should be executed after series filtered and before stack calculation.
  18889. var dataStack = function (ecModel) {
  18890. var stackInfoMap = createHashMap();
  18891. ecModel.eachSeries(function (seriesModel) {
  18892. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18893. if (stack) {
  18894. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18895. var data = seriesModel.getData();
  18896. var stackInfo = {
  18897. // Used for calculate axis extent automatically.
  18898. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18899. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18900. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18901. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18902. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18903. data: data,
  18904. seriesModel: seriesModel
  18905. }; // If stacked on axis that do not support data stack.
  18906. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18907. return;
  18908. }
  18909. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18910. stackInfoList.push(stackInfo);
  18911. }
  18912. });
  18913. stackInfoMap.each(calculateStack);
  18914. };
  18915. function calculateStack(stackInfoList) {
  18916. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  18917. var resultVal = [];
  18918. var resultNaN = [NaN, NaN];
  18919. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18920. var targetData = targetStackInfo.data;
  18921. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  18922. // depending on legend selection.
  18923. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18924. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18925. // should also be NaN, to draw a appropriate belt area.
  18926. if (isNaN(sum)) {
  18927. return resultNaN;
  18928. }
  18929. var byValue;
  18930. var stackedDataRawIndex;
  18931. if (isStackedByIndex) {
  18932. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18933. } else {
  18934. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18935. } // If stackOver is NaN, chart view will render point on value start.
  18936. var stackedOver = NaN;
  18937. for (var j = idxInStack - 1; j >= 0; j--) {
  18938. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18939. if (!isStackedByIndex) {
  18940. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18941. }
  18942. if (stackedDataRawIndex >= 0) {
  18943. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18944. if (sum >= 0 && val > 0 || // Positive stack
  18945. sum <= 0 && val < 0 // Negative stack
  18946. ) {
  18947. sum += val;
  18948. stackedOver = val;
  18949. break;
  18950. }
  18951. }
  18952. }
  18953. resultVal[0] = sum;
  18954. resultVal[1] = stackedOver;
  18955. return resultVal;
  18956. });
  18957. targetData.hostModel.setData(newData); // Update for consequent calculation
  18958. targetStackInfo.data = newData;
  18959. });
  18960. }
  18961. /*
  18962. * Licensed to the Apache Software Foundation (ASF) under one
  18963. * or more contributor license agreements. See the NOTICE file
  18964. * distributed with this work for additional information
  18965. * regarding copyright ownership. The ASF licenses this file
  18966. * to you under the Apache License, Version 2.0 (the
  18967. * "License"); you may not use this file except in compliance
  18968. * with the License. You may obtain a copy of the License at
  18969. *
  18970. * http://www.apache.org/licenses/LICENSE-2.0
  18971. *
  18972. * Unless required by applicable law or agreed to in writing,
  18973. * software distributed under the License is distributed on an
  18974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18975. * KIND, either express or implied. See the License for the
  18976. * specific language governing permissions and limitations
  18977. * under the License.
  18978. */
  18979. // TODO
  18980. // ??? refactor? check the outer usage of data provider.
  18981. // merge with defaultDimValueGetter?
  18982. /**
  18983. * If normal array used, mutable chunk size is supported.
  18984. * If typed array used, chunk size must be fixed.
  18985. */
  18986. function DefaultDataProvider(source, dimSize) {
  18987. if (!Source.isInstance(source)) {
  18988. source = Source.seriesDataToSource(source);
  18989. }
  18990. this._source = source;
  18991. var data = this._data = source.data;
  18992. var sourceFormat = source.sourceFormat; // Typed array. TODO IE10+?
  18993. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18994. this._offset = 0;
  18995. this._dimSize = dimSize;
  18996. this._data = data;
  18997. }
  18998. var methods = providerMethods[sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + source.seriesLayoutBy : sourceFormat];
  18999. extend(this, methods);
  19000. }
  19001. var providerProto = DefaultDataProvider.prototype; // If data is pure without style configuration
  19002. providerProto.pure = false; // If data is persistent and will not be released after use.
  19003. providerProto.persistent = true; // ???! FIXME legacy data provider do not has method getSource
  19004. providerProto.getSource = function () {
  19005. return this._source;
  19006. };
  19007. var providerMethods = {
  19008. 'arrayRows_column': {
  19009. pure: true,
  19010. count: function () {
  19011. return Math.max(0, this._data.length - this._source.startIndex);
  19012. },
  19013. getItem: function (idx) {
  19014. return this._data[idx + this._source.startIndex];
  19015. },
  19016. appendData: appendDataSimply
  19017. },
  19018. 'arrayRows_row': {
  19019. pure: true,
  19020. count: function () {
  19021. var row = this._data[0];
  19022. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19023. },
  19024. getItem: function (idx) {
  19025. idx += this._source.startIndex;
  19026. var item = [];
  19027. var data = this._data;
  19028. for (var i = 0; i < data.length; i++) {
  19029. var row = data[i];
  19030. item.push(row ? row[idx] : null);
  19031. }
  19032. return item;
  19033. },
  19034. appendData: function () {
  19035. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19036. }
  19037. },
  19038. 'objectRows': {
  19039. pure: true,
  19040. count: countSimply,
  19041. getItem: getItemSimply,
  19042. appendData: appendDataSimply
  19043. },
  19044. 'keyedColumns': {
  19045. pure: true,
  19046. count: function () {
  19047. var dimName = this._source.dimensionsDefine[0].name;
  19048. var col = this._data[dimName];
  19049. return col ? col.length : 0;
  19050. },
  19051. getItem: function (idx) {
  19052. var item = [];
  19053. var dims = this._source.dimensionsDefine;
  19054. for (var i = 0; i < dims.length; i++) {
  19055. var col = this._data[dims[i].name];
  19056. item.push(col ? col[idx] : null);
  19057. }
  19058. return item;
  19059. },
  19060. appendData: function (newData) {
  19061. var data = this._data;
  19062. each$1(newData, function (newCol, key) {
  19063. var oldCol = data[key] || (data[key] = []);
  19064. for (var i = 0; i < (newCol || []).length; i++) {
  19065. oldCol.push(newCol[i]);
  19066. }
  19067. });
  19068. }
  19069. },
  19070. 'original': {
  19071. count: countSimply,
  19072. getItem: getItemSimply,
  19073. appendData: appendDataSimply
  19074. },
  19075. 'typedArray': {
  19076. persistent: false,
  19077. pure: true,
  19078. count: function () {
  19079. return this._data ? this._data.length / this._dimSize : 0;
  19080. },
  19081. getItem: function (idx, out) {
  19082. idx = idx - this._offset;
  19083. out = out || [];
  19084. var offset = this._dimSize * idx;
  19085. for (var i = 0; i < this._dimSize; i++) {
  19086. out[i] = this._data[offset + i];
  19087. }
  19088. return out;
  19089. },
  19090. appendData: function (newData) {
  19091. this._data = newData;
  19092. },
  19093. // Clean self if data is already used.
  19094. clean: function () {
  19095. // PENDING
  19096. this._offset += this.count();
  19097. this._data = null;
  19098. }
  19099. }
  19100. };
  19101. function countSimply() {
  19102. return this._data.length;
  19103. }
  19104. function getItemSimply(idx) {
  19105. return this._data[idx];
  19106. }
  19107. function appendDataSimply(newData) {
  19108. for (var i = 0; i < newData.length; i++) {
  19109. this._data.push(newData[i]);
  19110. }
  19111. }
  19112. var rawValueGetters = {
  19113. arrayRows: getRawValueSimply,
  19114. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19115. return dimIndex != null ? dataItem[dimName] : dataItem;
  19116. },
  19117. keyedColumns: getRawValueSimply,
  19118. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19119. // FIXME
  19120. // In some case (markpoint in geo (geo-map.html)), dataItem
  19121. // is {coord: [...]}
  19122. var value = getDataItemValue(dataItem);
  19123. return dimIndex == null || !(value instanceof Array) ? value : value[dimIndex];
  19124. },
  19125. typedArray: getRawValueSimply
  19126. };
  19127. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19128. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19129. }
  19130. var defaultDimValueGetters = {
  19131. arrayRows: getDimValueSimply,
  19132. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19133. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19134. },
  19135. keyedColumns: getDimValueSimply,
  19136. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19137. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19138. // If dataItem is an plain object with no value field, the var `value`
  19139. // will be assigned with the object, but it will be tread correctly
  19140. // in the `convertDataValue`.
  19141. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 }
  19142. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19143. this.hasItemOption = true;
  19144. }
  19145. return converDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  19146. : value, this._dimensionInfos[dimName]);
  19147. },
  19148. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19149. return dataItem[dimIndex];
  19150. }
  19151. };
  19152. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19153. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19154. }
  19155. /**
  19156. * This helper method convert value in data.
  19157. * @param {string|number|Date} value
  19158. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19159. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19160. */
  19161. function converDataValue(value, dimInfo) {
  19162. // Performance sensitive.
  19163. var dimType = dimInfo && dimInfo.type;
  19164. if (dimType === 'ordinal') {
  19165. // If given value is a category string
  19166. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19167. return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value;
  19168. }
  19169. if (dimType === 'time' // spead up when using timestamp
  19170. && typeof value !== 'number' && value != null && value !== '-') {
  19171. value = +parseDate(value);
  19172. } // dimType defaults 'number'.
  19173. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19174. // parse to NaN.
  19175. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19176. // If object, also parse to NaN
  19177. : +value;
  19178. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19179. // Consider persistent.
  19180. // Caution: why use raw value to display on label or tooltip?
  19181. // A reason is to avoid format. For example time value we do not know
  19182. // how to format is expected. More over, if stack is used, calculated
  19183. // value may be 0.91000000001, which have brings trouble to display.
  19184. // TODO: consider how to treat null/undefined/NaN when display?
  19185. /**
  19186. * @param {module:echarts/data/List} data
  19187. * @param {number} dataIndex
  19188. * @param {string|number} [dim] dimName or dimIndex
  19189. * @return {Array.<number>|string|number} can be null/undefined.
  19190. */
  19191. function retrieveRawValue(data, dataIndex, dim) {
  19192. if (!data) {
  19193. return;
  19194. } // Consider data may be not persistent.
  19195. var dataItem = data.getRawDataItem(dataIndex);
  19196. if (dataItem == null) {
  19197. return;
  19198. }
  19199. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19200. var dimName;
  19201. var dimIndex;
  19202. var dimInfo = data.getDimensionInfo(dim);
  19203. if (dimInfo) {
  19204. dimName = dimInfo.name;
  19205. dimIndex = dimInfo.index;
  19206. }
  19207. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19208. }
  19209. /**
  19210. * Compatible with some cases (in pie, map) like:
  19211. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19212. * where only sourceFormat is 'original' and 'objectRows' supported.
  19213. *
  19214. * ??? TODO
  19215. * Supported detail options in data item when using 'arrayRows'.
  19216. *
  19217. * @param {module:echarts/data/List} data
  19218. * @param {number} dataIndex
  19219. * @param {string} attr like 'selected'
  19220. */
  19221. function retrieveRawAttr(data, dataIndex, attr) {
  19222. if (!data) {
  19223. return;
  19224. }
  19225. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19226. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  19227. return;
  19228. }
  19229. var dataItem = data.getRawDataItem(dataIndex);
  19230. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19231. dataItem = null;
  19232. }
  19233. if (dataItem) {
  19234. return dataItem[attr];
  19235. }
  19236. }
  19237. /*
  19238. * Licensed to the Apache Software Foundation (ASF) under one
  19239. * or more contributor license agreements. See the NOTICE file
  19240. * distributed with this work for additional information
  19241. * regarding copyright ownership. The ASF licenses this file
  19242. * to you under the Apache License, Version 2.0 (the
  19243. * "License"); you may not use this file except in compliance
  19244. * with the License. You may obtain a copy of the License at
  19245. *
  19246. * http://www.apache.org/licenses/LICENSE-2.0
  19247. *
  19248. * Unless required by applicable law or agreed to in writing,
  19249. * software distributed under the License is distributed on an
  19250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19251. * KIND, either express or implied. See the License for the
  19252. * specific language governing permissions and limitations
  19253. * under the License.
  19254. */
  19255. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g; // PENDING A little ugly
  19256. var dataFormatMixin = {
  19257. /**
  19258. * Get params for formatter
  19259. * @param {number} dataIndex
  19260. * @param {string} [dataType]
  19261. * @return {Object}
  19262. */
  19263. getDataParams: function (dataIndex, dataType) {
  19264. var data = this.getData(dataType);
  19265. var rawValue = this.getRawValue(dataIndex, dataType);
  19266. var rawDataIndex = data.getRawIndex(dataIndex);
  19267. var name = data.getName(dataIndex);
  19268. var itemOpt = data.getRawDataItem(dataIndex);
  19269. var color = data.getItemVisual(dataIndex, 'color');
  19270. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  19271. var tooltipModel = this.ecModel.getComponent('tooltip');
  19272. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  19273. var renderMode = getTooltipRenderMode(renderModeOption);
  19274. var mainType = this.mainType;
  19275. var isSeries = mainType === 'series';
  19276. var userOutput = data.userOutput;
  19277. return {
  19278. componentType: mainType,
  19279. componentSubType: this.subType,
  19280. componentIndex: this.componentIndex,
  19281. seriesType: isSeries ? this.subType : null,
  19282. seriesIndex: this.seriesIndex,
  19283. seriesId: isSeries ? this.id : null,
  19284. seriesName: isSeries ? this.name : null,
  19285. name: name,
  19286. dataIndex: rawDataIndex,
  19287. data: itemOpt,
  19288. dataType: dataType,
  19289. value: rawValue,
  19290. color: color,
  19291. borderColor: borderColor,
  19292. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  19293. encode: userOutput ? userOutput.encode : null,
  19294. marker: getTooltipMarker({
  19295. color: color,
  19296. renderMode: renderMode
  19297. }),
  19298. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19299. $vars: ['seriesName', 'name', 'value']
  19300. };
  19301. },
  19302. /**
  19303. * Format label
  19304. * @param {number} dataIndex
  19305. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19306. * @param {string} [dataType]
  19307. * @param {number} [dimIndex] Only used in some chart that
  19308. * use formatter in different dimensions, like radar.
  19309. * @param {string} [labelProp='label']
  19310. * @return {string} If not formatter, return null/undefined
  19311. */
  19312. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19313. status = status || 'normal';
  19314. var data = this.getData(dataType);
  19315. var itemModel = data.getItemModel(dataIndex);
  19316. var params = this.getDataParams(dataIndex, dataType);
  19317. if (dimIndex != null && params.value instanceof Array) {
  19318. params.value = params.value[dimIndex];
  19319. }
  19320. var formatter = itemModel.get(status === 'normal' ? [labelProp || 'label', 'formatter'] : [status, labelProp || 'label', 'formatter']);
  19321. if (typeof formatter === 'function') {
  19322. params.status = status;
  19323. params.dimensionIndex = dimIndex;
  19324. return formatter(params);
  19325. } else if (typeof formatter === 'string') {
  19326. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19327. // Do not support '}' in dim name util have to.
  19328. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19329. var len = dim.length;
  19330. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19331. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19332. }
  19333. return retrieveRawValue(data, dataIndex, dim);
  19334. });
  19335. }
  19336. },
  19337. /**
  19338. * Get raw value in option
  19339. * @param {number} idx
  19340. * @param {string} [dataType]
  19341. * @return {Array|number|string}
  19342. */
  19343. getRawValue: function (idx, dataType) {
  19344. return retrieveRawValue(this.getData(dataType), idx);
  19345. },
  19346. /**
  19347. * Should be implemented.
  19348. * @param {number} dataIndex
  19349. * @param {boolean} [multipleSeries=false]
  19350. * @param {number} [dataType]
  19351. * @return {string} tooltip string
  19352. */
  19353. formatTooltip: function () {// Empty function
  19354. }
  19355. };
  19356. /*
  19357. * Licensed to the Apache Software Foundation (ASF) under one
  19358. * or more contributor license agreements. See the NOTICE file
  19359. * distributed with this work for additional information
  19360. * regarding copyright ownership. The ASF licenses this file
  19361. * to you under the Apache License, Version 2.0 (the
  19362. * "License"); you may not use this file except in compliance
  19363. * with the License. You may obtain a copy of the License at
  19364. *
  19365. * http://www.apache.org/licenses/LICENSE-2.0
  19366. *
  19367. * Unless required by applicable law or agreed to in writing,
  19368. * software distributed under the License is distributed on an
  19369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19370. * KIND, either express or implied. See the License for the
  19371. * specific language governing permissions and limitations
  19372. * under the License.
  19373. */
  19374. /**
  19375. * @param {Object} define
  19376. * @return See the return of `createTask`.
  19377. */
  19378. function createTask(define) {
  19379. return new Task(define);
  19380. }
  19381. /**
  19382. * @constructor
  19383. * @param {Object} define
  19384. * @param {Function} define.reset Custom reset
  19385. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19386. * @param {Function} [define.count] count is used to determin data task.
  19387. * @param {Function} [define.onDirty] count is used to determin data task.
  19388. */
  19389. function Task(define) {
  19390. define = define || {};
  19391. this._reset = define.reset;
  19392. this._plan = define.plan;
  19393. this._count = define.count;
  19394. this._onDirty = define.onDirty;
  19395. this._dirty = true; // Context must be specified implicitly, to
  19396. // avoid miss update context when model changed.
  19397. this.context;
  19398. }
  19399. var taskProto = Task.prototype;
  19400. /**
  19401. * @param {Object} performArgs
  19402. * @param {number} [performArgs.step] Specified step.
  19403. * @param {number} [performArgs.skip] Skip customer perform call.
  19404. * @param {number} [performArgs.modBy] Sampling window size.
  19405. * @param {number} [performArgs.modDataCount] Sampling count.
  19406. */
  19407. taskProto.perform = function (performArgs) {
  19408. var upTask = this._upstream;
  19409. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19410. // Pull data. Must pull data each time, because context.data
  19411. // may be updated by Series.setData.
  19412. if (this._dirty && upTask) {
  19413. var context = this.context;
  19414. context.data = context.outputData = upTask.context.outputData;
  19415. }
  19416. if (this.__pipeline) {
  19417. this.__pipeline.currentTask = this;
  19418. }
  19419. var planResult;
  19420. if (this._plan && !skip) {
  19421. planResult = this._plan(this.context);
  19422. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19423. // elements uniformed distributed when progress, especially when moving or zooming.
  19424. var lastModBy = normalizeModBy(this._modBy);
  19425. var lastModDataCount = this._modDataCount || 0;
  19426. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19427. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19428. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19429. planResult = 'reset';
  19430. }
  19431. function normalizeModBy(val) {
  19432. !(val >= 1) && (val = 1); // jshint ignore:line
  19433. return val;
  19434. }
  19435. var forceFirstProgress;
  19436. if (this._dirty || planResult === 'reset') {
  19437. this._dirty = false;
  19438. forceFirstProgress = reset(this, skip);
  19439. }
  19440. this._modBy = modBy;
  19441. this._modDataCount = modDataCount;
  19442. var step = performArgs && performArgs.step;
  19443. if (upTask) {
  19444. this._dueEnd = upTask._outputDueEnd;
  19445. } // DataTask or overallTask
  19446. else {
  19447. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19448. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19449. // If no progress, pass index from upstream to downstream each time plan called.
  19450. if (this._progress) {
  19451. var start = this._dueIndex;
  19452. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19453. if (!skip && (forceFirstProgress || start < end)) {
  19454. var progress = this._progress;
  19455. if (isArray(progress)) {
  19456. for (var i = 0; i < progress.length; i++) {
  19457. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19458. }
  19459. } else {
  19460. doProgress(this, progress, start, end, modBy, modDataCount);
  19461. }
  19462. }
  19463. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19464. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19465. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19466. this._outputDueEnd = outputDueEnd;
  19467. } else {
  19468. // (1) Some overall task has no progress.
  19469. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19470. // This should always be performed so it can be passed to downstream.
  19471. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19472. }
  19473. return this.unfinished();
  19474. };
  19475. var iterator = function () {
  19476. var end;
  19477. var current;
  19478. var modBy;
  19479. var modDataCount;
  19480. var winCount;
  19481. var it = {
  19482. reset: function (s, e, sStep, sCount) {
  19483. current = s;
  19484. end = e;
  19485. modBy = sStep;
  19486. modDataCount = sCount;
  19487. winCount = Math.ceil(modDataCount / modBy);
  19488. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19489. }
  19490. };
  19491. return it;
  19492. function sequentialNext() {
  19493. return current < end ? current++ : null;
  19494. }
  19495. function modNext() {
  19496. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19497. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19498. // Use normal linear rendering mode.
  19499. : current;
  19500. current++;
  19501. return result;
  19502. }
  19503. }();
  19504. taskProto.dirty = function () {
  19505. this._dirty = true;
  19506. this._onDirty && this._onDirty(this.context);
  19507. };
  19508. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19509. iterator.reset(start, end, modBy, modDataCount);
  19510. taskIns._callingProgress = progress;
  19511. taskIns._callingProgress({
  19512. start: start,
  19513. end: end,
  19514. count: end - start,
  19515. next: iterator.next
  19516. }, taskIns.context);
  19517. }
  19518. function reset(taskIns, skip) {
  19519. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19520. taskIns._settedOutputEnd = null;
  19521. var progress;
  19522. var forceFirstProgress;
  19523. if (!skip && taskIns._reset) {
  19524. progress = taskIns._reset(taskIns.context);
  19525. if (progress && progress.progress) {
  19526. forceFirstProgress = progress.forceFirstProgress;
  19527. progress = progress.progress;
  19528. } // To simplify no progress checking, array must has item.
  19529. if (isArray(progress) && !progress.length) {
  19530. progress = null;
  19531. }
  19532. }
  19533. taskIns._progress = progress;
  19534. taskIns._modBy = taskIns._modDataCount = null;
  19535. var downstream = taskIns._downstream;
  19536. downstream && downstream.dirty();
  19537. return forceFirstProgress;
  19538. }
  19539. /**
  19540. * @return {boolean}
  19541. */
  19542. taskProto.unfinished = function () {
  19543. return this._progress && this._dueIndex < this._dueEnd;
  19544. };
  19545. /**
  19546. * @param {Object} downTask The downstream task.
  19547. * @return {Object} The downstream task.
  19548. */
  19549. taskProto.pipe = function (downTask) {
  19550. // If already downstream, do not dirty downTask.
  19551. if (this._downstream !== downTask || this._dirty) {
  19552. this._downstream = downTask;
  19553. downTask._upstream = this;
  19554. downTask.dirty();
  19555. }
  19556. };
  19557. taskProto.dispose = function () {
  19558. if (this._disposed) {
  19559. return;
  19560. }
  19561. this._upstream && (this._upstream._downstream = null);
  19562. this._downstream && (this._downstream._upstream = null);
  19563. this._dirty = false;
  19564. this._disposed = true;
  19565. };
  19566. taskProto.getUpstream = function () {
  19567. return this._upstream;
  19568. };
  19569. taskProto.getDownstream = function () {
  19570. return this._downstream;
  19571. };
  19572. taskProto.setOutputEnd = function (end) {
  19573. // This only happend in dataTask, dataZoom, map, currently.
  19574. // where dataZoom do not set end each time, but only set
  19575. // when reset. So we should record the setted end, in case
  19576. // that the stub of dataZoom perform again and earse the
  19577. // setted end by upstream.
  19578. this._outputDueEnd = this._settedOutputEnd = end;
  19579. }; ///////////////////////////////////////////////////////////
  19580. // For stream debug (Should be commented out after used!)
  19581. // Usage: printTask(this, 'begin');
  19582. // Usage: printTask(this, null, {someExtraProp});
  19583. // function printTask(task, prefix, extra) {
  19584. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19585. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19586. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19587. // var props = [];
  19588. // if (task.__pipeline) {
  19589. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19590. // props.push({text: 'idx', value: val});
  19591. // } else {
  19592. // var stubCount = 0;
  19593. // task.agentStubMap.each(() => stubCount++);
  19594. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19595. // }
  19596. // props.push({text: 'uid', value: task.uidDebug});
  19597. // if (task.__pipeline) {
  19598. // props.push({text: 'pid', value: task.__pipeline.id});
  19599. // task.agent && props.push(
  19600. // {text: 'stubFor', value: task.agent.uidDebug}
  19601. // );
  19602. // }
  19603. // props.push(
  19604. // {text: 'dirty', value: task._dirty},
  19605. // {text: 'dueIndex', value: task._dueIndex},
  19606. // {text: 'dueEnd', value: task._dueEnd},
  19607. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19608. // );
  19609. // if (extra) {
  19610. // Object.keys(extra).forEach(key => {
  19611. // props.push({text: key, value: extra[key]});
  19612. // });
  19613. // }
  19614. // var args = ['color: blue'];
  19615. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19616. // args.push('color: black', 'color: red'),
  19617. // `${item.text}: %c${item.value}`
  19618. // )).join('%c, ');
  19619. // console.log.apply(console, [msg].concat(args));
  19620. // // console.log(this);
  19621. // }
  19622. /*
  19623. * Licensed to the Apache Software Foundation (ASF) under one
  19624. * or more contributor license agreements. See the NOTICE file
  19625. * distributed with this work for additional information
  19626. * regarding copyright ownership. The ASF licenses this file
  19627. * to you under the Apache License, Version 2.0 (the
  19628. * "License"); you may not use this file except in compliance
  19629. * with the License. You may obtain a copy of the License at
  19630. *
  19631. * http://www.apache.org/licenses/LICENSE-2.0
  19632. *
  19633. * Unless required by applicable law or agreed to in writing,
  19634. * software distributed under the License is distributed on an
  19635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19636. * KIND, either express or implied. See the License for the
  19637. * specific language governing permissions and limitations
  19638. * under the License.
  19639. */
  19640. var inner$4 = makeInner();
  19641. var SeriesModel = ComponentModel.extend({
  19642. type: 'series.__base__',
  19643. /**
  19644. * @readOnly
  19645. */
  19646. seriesIndex: 0,
  19647. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19648. coordinateSystem: null,
  19649. /**
  19650. * @type {Object}
  19651. * @protected
  19652. */
  19653. defaultOption: null,
  19654. /**
  19655. * legend visual provider to the legend component
  19656. * @type {Object}
  19657. */
  19658. // PENDING
  19659. legendVisualProvider: null,
  19660. /**
  19661. * Access path of color for visual
  19662. */
  19663. visualColorAccessPath: 'itemStyle.color',
  19664. /**
  19665. * Access path of borderColor for visual
  19666. */
  19667. visualBorderColorAccessPath: 'itemStyle.borderColor',
  19668. /**
  19669. * Support merge layout params.
  19670. * Only support 'box' now (left/right/top/bottom/width/height).
  19671. * @type {string|Object} Object can be {ignoreSize: true}
  19672. * @readOnly
  19673. */
  19674. layoutMode: null,
  19675. init: function (option, parentModel, ecModel, extraOpt) {
  19676. /**
  19677. * @type {number}
  19678. * @readOnly
  19679. */
  19680. this.seriesIndex = this.componentIndex;
  19681. this.dataTask = createTask({
  19682. count: dataTaskCount,
  19683. reset: dataTaskReset
  19684. });
  19685. this.dataTask.context = {
  19686. model: this
  19687. };
  19688. this.mergeDefaultAndTheme(option, ecModel);
  19689. prepareSource(this);
  19690. var data = this.getInitialData(option, ecModel);
  19691. wrapData(data, this);
  19692. this.dataTask.context.data = data;
  19693. /**
  19694. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19695. * @private
  19696. */
  19697. inner$4(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  19698. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19699. // cause data.graph.data !== data when using
  19700. // module:echarts/data/Graph or module:echarts/data/Tree.
  19701. // See module:echarts/data/helper/linkList
  19702. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19703. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19704. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19705. // Call `seriesModel.getRawData()` instead.
  19706. // this.restoreData();
  19707. autoSeriesName(this);
  19708. },
  19709. /**
  19710. * Util for merge default and theme to option
  19711. * @param {Object} option
  19712. * @param {module:echarts/model/Global} ecModel
  19713. */
  19714. mergeDefaultAndTheme: function (option, ecModel) {
  19715. var layoutMode = this.layoutMode;
  19716. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  19717. // But if name duplicate between series subType
  19718. // (for example: parallel) add component mainType,
  19719. // add suffix 'Series'.
  19720. var themeSubType = this.subType;
  19721. if (ComponentModel.hasClass(themeSubType)) {
  19722. themeSubType += 'Series';
  19723. }
  19724. merge(option, ecModel.getTheme().get(this.subType));
  19725. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  19726. defaultEmphasis(option, 'label', ['show']);
  19727. this.fillDataTextStyle(option.data);
  19728. if (layoutMode) {
  19729. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19730. }
  19731. },
  19732. mergeOption: function (newSeriesOption, ecModel) {
  19733. // this.settingTask.dirty();
  19734. newSeriesOption = merge(this.option, newSeriesOption, true);
  19735. this.fillDataTextStyle(newSeriesOption.data);
  19736. var layoutMode = this.layoutMode;
  19737. if (layoutMode) {
  19738. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19739. }
  19740. prepareSource(this);
  19741. var data = this.getInitialData(newSeriesOption, ecModel);
  19742. wrapData(data, this);
  19743. this.dataTask.dirty();
  19744. this.dataTask.context.data = data;
  19745. inner$4(this).dataBeforeProcessed = data;
  19746. autoSeriesName(this);
  19747. },
  19748. fillDataTextStyle: function (data) {
  19749. // Default data label emphasis `show`
  19750. // FIXME Tree structure data ?
  19751. // FIXME Performance ?
  19752. if (data && !isTypedArray(data)) {
  19753. var props = ['show'];
  19754. for (var i = 0; i < data.length; i++) {
  19755. if (data[i] && data[i].label) {
  19756. defaultEmphasis(data[i], 'label', props);
  19757. }
  19758. }
  19759. }
  19760. },
  19761. /**
  19762. * Init a data structure from data related option in series
  19763. * Must be overwritten
  19764. */
  19765. getInitialData: function () {},
  19766. /**
  19767. * Append data to list
  19768. * @param {Object} params
  19769. * @param {Array|TypedArray} params.data
  19770. */
  19771. appendData: function (params) {
  19772. // FIXME ???
  19773. // (1) If data from dataset, forbidden append.
  19774. // (2) support append data of dataset.
  19775. var data = this.getRawData();
  19776. data.appendData(params.data);
  19777. },
  19778. /**
  19779. * Consider some method like `filter`, `map` need make new data,
  19780. * We should make sure that `seriesModel.getData()` get correct
  19781. * data in the stream procedure. So we fetch data from upstream
  19782. * each time `task.perform` called.
  19783. * @param {string} [dataType]
  19784. * @return {module:echarts/data/List}
  19785. */
  19786. getData: function (dataType) {
  19787. var task = getCurrentTask(this);
  19788. if (task) {
  19789. var data = task.context.data;
  19790. return dataType == null ? data : data.getLinkedData(dataType);
  19791. } else {
  19792. // When series is not alive (that may happen when click toolbox
  19793. // restore or setOption with not merge mode), series data may
  19794. // be still need to judge animation or something when graphic
  19795. // elements want to know whether fade out.
  19796. return inner$4(this).data;
  19797. }
  19798. },
  19799. /**
  19800. * @param {module:echarts/data/List} data
  19801. */
  19802. setData: function (data) {
  19803. var task = getCurrentTask(this);
  19804. if (task) {
  19805. var context = task.context; // Consider case: filter, data sample.
  19806. if (context.data !== data && task.modifyOutputEnd) {
  19807. task.setOutputEnd(data.count());
  19808. }
  19809. context.outputData = data; // Caution: setData should update context.data,
  19810. // Because getData may be called multiply in a
  19811. // single stage and expect to get the data just
  19812. // set. (For example, AxisProxy, x y both call
  19813. // getData and setDate sequentially).
  19814. // So the context.data should be fetched from
  19815. // upstream each time when a stage starts to be
  19816. // performed.
  19817. if (task !== this.dataTask) {
  19818. context.data = data;
  19819. }
  19820. }
  19821. inner$4(this).data = data;
  19822. },
  19823. /**
  19824. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19825. * @return {module:echarts/data/Source} source
  19826. */
  19827. getSource: function () {
  19828. return getSource(this);
  19829. },
  19830. /**
  19831. * Get data before processed
  19832. * @return {module:echarts/data/List}
  19833. */
  19834. getRawData: function () {
  19835. return inner$4(this).dataBeforeProcessed;
  19836. },
  19837. /**
  19838. * Get base axis if has coordinate system and has axis.
  19839. * By default use coordSys.getBaseAxis();
  19840. * Can be overrided for some chart.
  19841. * @return {type} description
  19842. */
  19843. getBaseAxis: function () {
  19844. var coordSys = this.coordinateSystem;
  19845. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19846. },
  19847. // FIXME
  19848. /**
  19849. * Default tooltip formatter
  19850. *
  19851. * @param {number} dataIndex
  19852. * @param {boolean} [multipleSeries=false]
  19853. * @param {number} [dataType]
  19854. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  19855. * 'html' is used for rendering tooltip in extra DOM form, and the result
  19856. * string is used as DOM HTML content.
  19857. * 'richText' is used for rendering tooltip in rich text form, for those where
  19858. * DOM operation is not supported.
  19859. * @return {Object} formatted tooltip with `html` and `markers`
  19860. */
  19861. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  19862. var series = this;
  19863. renderMode = renderMode || 'html';
  19864. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  19865. var isRichText = renderMode === 'richText';
  19866. var markers = {};
  19867. var markerId = 0;
  19868. function formatArrayValue(value) {
  19869. // ??? TODO refactor these logic.
  19870. // check: category-no-encode-has-axis-data in dataset.html
  19871. var vertially = reduce(value, function (vertially, val, idx) {
  19872. var dimItem = data.getDimensionInfo(idx);
  19873. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19874. }, 0);
  19875. var result = [];
  19876. tooltipDims.length ? each$1(tooltipDims, function (dim) {
  19877. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19878. }) // By default, all dims is used on tooltip.
  19879. : each$1(value, setEachItem);
  19880. function setEachItem(val, dim) {
  19881. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  19882. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19883. return;
  19884. }
  19885. var dimType = dimInfo.type;
  19886. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  19887. var dimHead = getTooltipMarker({
  19888. color: color,
  19889. type: 'subItem',
  19890. renderMode: renderMode,
  19891. markerId: markName
  19892. });
  19893. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  19894. var valStr = (vertially ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': ' : '') + // FIXME should not format time for raw data?
  19895. encodeHTML(dimType === 'ordinal' ? val + '' : dimType === 'time' ? multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val) : addCommas(val));
  19896. valStr && result.push(valStr);
  19897. if (isRichText) {
  19898. markers[markName] = color;
  19899. ++markerId;
  19900. }
  19901. }
  19902. var newLine = vertially ? isRichText ? '\n' : '<br/>' : '';
  19903. var content = newLine + result.join(newLine || ', ');
  19904. return {
  19905. renderMode: renderMode,
  19906. content: content,
  19907. style: markers
  19908. };
  19909. }
  19910. function formatSingleValue(val) {
  19911. // return encodeHTML(addCommas(val));
  19912. return {
  19913. renderMode: renderMode,
  19914. content: encodeHTML(addCommas(val)),
  19915. style: markers
  19916. };
  19917. }
  19918. var data = this.getData();
  19919. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19920. var tooltipDimLen = tooltipDims.length;
  19921. var value = this.getRawValue(dataIndex);
  19922. var isValueArr = isArray(value);
  19923. var color = data.getItemVisual(dataIndex, 'color');
  19924. if (isObject$1(color) && color.colorStops) {
  19925. color = (color.colorStops[0] || {}).color;
  19926. }
  19927. color = color || 'transparent'; // Complicated rule for pretty tooltip.
  19928. var formattedValue = tooltipDimLen > 1 || isValueArr && !tooltipDimLen ? formatArrayValue(value) : tooltipDimLen ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0])) : formatSingleValue(isValueArr ? value[0] : value);
  19929. var content = formattedValue.content;
  19930. var markName = series.seriesIndex + 'at' + markerId;
  19931. var colorEl = getTooltipMarker({
  19932. color: color,
  19933. type: 'item',
  19934. renderMode: renderMode,
  19935. markerId: markName
  19936. });
  19937. markers[markName] = color;
  19938. ++markerId;
  19939. var name = data.getName(dataIndex);
  19940. var seriesName = this.name;
  19941. if (!isNameSpecified(this)) {
  19942. seriesName = '';
  19943. }
  19944. seriesName = seriesName ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ') : '';
  19945. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  19946. var html = !multipleSeries ? seriesName + colorStr + (name ? encodeHTML(name) + ': ' + content : content) : colorStr + seriesName + content;
  19947. return {
  19948. html: html,
  19949. markers: markers
  19950. };
  19951. },
  19952. /**
  19953. * @return {boolean}
  19954. */
  19955. isAnimationEnabled: function () {
  19956. if (env$1.node) {
  19957. return false;
  19958. }
  19959. var animationEnabled = this.getShallow('animation');
  19960. if (animationEnabled) {
  19961. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19962. animationEnabled = false;
  19963. }
  19964. }
  19965. return animationEnabled;
  19966. },
  19967. restoreData: function () {
  19968. this.dataTask.dirty();
  19969. },
  19970. getColorFromPalette: function (name, scope, requestColorNum) {
  19971. var ecModel = this.ecModel; // PENDING
  19972. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19973. if (!color) {
  19974. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19975. }
  19976. return color;
  19977. },
  19978. /**
  19979. * Use `data.mapDimension(coordDim, true)` instead.
  19980. * @deprecated
  19981. */
  19982. coordDimToDataDim: function (coordDim) {
  19983. return this.getRawData().mapDimension(coordDim, true);
  19984. },
  19985. /**
  19986. * Get progressive rendering count each step
  19987. * @return {number}
  19988. */
  19989. getProgressive: function () {
  19990. return this.get('progressive');
  19991. },
  19992. /**
  19993. * Get progressive rendering count each step
  19994. * @return {number}
  19995. */
  19996. getProgressiveThreshold: function () {
  19997. return this.get('progressiveThreshold');
  19998. },
  19999. /**
  20000. * Get data indices for show tooltip content. See tooltip.
  20001. * @abstract
  20002. * @param {Array.<string>|string} dim
  20003. * @param {Array.<number>} value
  20004. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20005. * @return {Object} {dataIndices, nestestValue}.
  20006. */
  20007. getAxisTooltipData: null,
  20008. /**
  20009. * See tooltip.
  20010. * @abstract
  20011. * @param {number} dataIndex
  20012. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20013. */
  20014. getTooltipPosition: null,
  20015. /**
  20016. * @see {module:echarts/stream/Scheduler}
  20017. */
  20018. pipeTask: null,
  20019. /**
  20020. * Convinient for override in extended class.
  20021. * @protected
  20022. * @type {Function}
  20023. */
  20024. preventIncremental: null,
  20025. /**
  20026. * @public
  20027. * @readOnly
  20028. * @type {Object}
  20029. */
  20030. pipelineContext: null
  20031. });
  20032. mixin(SeriesModel, dataFormatMixin);
  20033. mixin(SeriesModel, colorPaletteMixin);
  20034. /**
  20035. * MUST be called after `prepareSource` called
  20036. * Here we need to make auto series, especially for auto legend. But we
  20037. * do not modify series.name in option to avoid side effects.
  20038. */
  20039. function autoSeriesName(seriesModel) {
  20040. // User specified name has higher priority, otherwise it may cause
  20041. // series can not be queried unexpectedly.
  20042. var name = seriesModel.name;
  20043. if (!isNameSpecified(seriesModel)) {
  20044. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20045. }
  20046. }
  20047. function getSeriesAutoName(seriesModel) {
  20048. var data = seriesModel.getRawData();
  20049. var dataDims = data.mapDimension('seriesName', true);
  20050. var nameArr = [];
  20051. each$1(dataDims, function (dataDim) {
  20052. var dimInfo = data.getDimensionInfo(dataDim);
  20053. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20054. });
  20055. return nameArr.join(' ');
  20056. }
  20057. function dataTaskCount(context) {
  20058. return context.model.getRawData().count();
  20059. }
  20060. function dataTaskReset(context) {
  20061. var seriesModel = context.model;
  20062. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20063. return dataTaskProgress;
  20064. }
  20065. function dataTaskProgress(param, context) {
  20066. // Avoid repead cloneShallow when data just created in reset.
  20067. if (context.outputData && param.end > context.outputData.count()) {
  20068. context.model.getRawData().cloneShallow(context.outputData);
  20069. }
  20070. } // TODO refactor
  20071. function wrapData(data, seriesModel) {
  20072. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20073. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20074. });
  20075. }
  20076. function onDataSelfChange(seriesModel) {
  20077. var task = getCurrentTask(seriesModel);
  20078. if (task) {
  20079. // Consider case: filter, selectRange
  20080. task.setOutputEnd(this.count());
  20081. }
  20082. }
  20083. function getCurrentTask(seriesModel) {
  20084. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20085. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20086. if (pipeline) {
  20087. // When pipline finished, the currrentTask keep the last
  20088. // task (renderTask).
  20089. var task = pipeline.currentTask;
  20090. if (task) {
  20091. var agentStubMap = task.agentStubMap;
  20092. if (agentStubMap) {
  20093. task = agentStubMap.get(seriesModel.uid);
  20094. }
  20095. }
  20096. return task;
  20097. }
  20098. }
  20099. /*
  20100. * Licensed to the Apache Software Foundation (ASF) under one
  20101. * or more contributor license agreements. See the NOTICE file
  20102. * distributed with this work for additional information
  20103. * regarding copyright ownership. The ASF licenses this file
  20104. * to you under the Apache License, Version 2.0 (the
  20105. * "License"); you may not use this file except in compliance
  20106. * with the License. You may obtain a copy of the License at
  20107. *
  20108. * http://www.apache.org/licenses/LICENSE-2.0
  20109. *
  20110. * Unless required by applicable law or agreed to in writing,
  20111. * software distributed under the License is distributed on an
  20112. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20113. * KIND, either express or implied. See the License for the
  20114. * specific language governing permissions and limitations
  20115. * under the License.
  20116. */
  20117. var Component$1 = function () {
  20118. /**
  20119. * @type {module:zrender/container/Group}
  20120. * @readOnly
  20121. */
  20122. this.group = new Group();
  20123. /**
  20124. * @type {string}
  20125. * @readOnly
  20126. */
  20127. this.uid = getUID('viewComponent');
  20128. };
  20129. Component$1.prototype = {
  20130. constructor: Component$1,
  20131. init: function (ecModel, api) {},
  20132. render: function (componentModel, ecModel, api, payload) {},
  20133. dispose: function () {},
  20134. /**
  20135. * @param {string} eventType
  20136. * @param {Object} query
  20137. * @param {module:zrender/Element} targetEl
  20138. * @param {Object} packedEvent
  20139. * @return {boolen} Pass only when return `true`.
  20140. */
  20141. filterForExposedEvent: null
  20142. };
  20143. var componentProto = Component$1.prototype;
  20144. componentProto.updateView = componentProto.updateLayout = componentProto.updateVisual = function (seriesModel, ecModel, api, payload) {// Do nothing;
  20145. }; // Enable Component.extend.
  20146. enableClassExtend(Component$1); // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20147. enableClassManagement(Component$1, {
  20148. registerWhenExtend: true
  20149. });
  20150. /*
  20151. * Licensed to the Apache Software Foundation (ASF) under one
  20152. * or more contributor license agreements. See the NOTICE file
  20153. * distributed with this work for additional information
  20154. * regarding copyright ownership. The ASF licenses this file
  20155. * to you under the Apache License, Version 2.0 (the
  20156. * "License"); you may not use this file except in compliance
  20157. * with the License. You may obtain a copy of the License at
  20158. *
  20159. * http://www.apache.org/licenses/LICENSE-2.0
  20160. *
  20161. * Unless required by applicable law or agreed to in writing,
  20162. * software distributed under the License is distributed on an
  20163. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20164. * KIND, either express or implied. See the License for the
  20165. * specific language governing permissions and limitations
  20166. * under the License.
  20167. */
  20168. /**
  20169. * @return {string} If large mode changed, return string 'reset';
  20170. */
  20171. var createRenderPlanner = function () {
  20172. var inner = makeInner();
  20173. return function (seriesModel) {
  20174. var fields = inner(seriesModel);
  20175. var pipelineContext = seriesModel.pipelineContext;
  20176. var originalLarge = fields.large;
  20177. var originalProgressive = fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  20178. // exists. See #11611 . Probably we need to modify this structure, see the comment
  20179. // on `performRawSeries` in `Schedular.js`.
  20180. var large = fields.large = pipelineContext && pipelineContext.large;
  20181. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  20182. return !!(originalLarge ^ large || originalProgressive ^ progressive) && 'reset';
  20183. };
  20184. };
  20185. /*
  20186. * Licensed to the Apache Software Foundation (ASF) under one
  20187. * or more contributor license agreements. See the NOTICE file
  20188. * distributed with this work for additional information
  20189. * regarding copyright ownership. The ASF licenses this file
  20190. * to you under the Apache License, Version 2.0 (the
  20191. * "License"); you may not use this file except in compliance
  20192. * with the License. You may obtain a copy of the License at
  20193. *
  20194. * http://www.apache.org/licenses/LICENSE-2.0
  20195. *
  20196. * Unless required by applicable law or agreed to in writing,
  20197. * software distributed under the License is distributed on an
  20198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20199. * KIND, either express or implied. See the License for the
  20200. * specific language governing permissions and limitations
  20201. * under the License.
  20202. */
  20203. var inner$5 = makeInner();
  20204. var renderPlanner = createRenderPlanner();
  20205. function Chart() {
  20206. /**
  20207. * @type {module:zrender/container/Group}
  20208. * @readOnly
  20209. */
  20210. this.group = new Group();
  20211. /**
  20212. * @type {string}
  20213. * @readOnly
  20214. */
  20215. this.uid = getUID('viewChart');
  20216. this.renderTask = createTask({
  20217. plan: renderTaskPlan,
  20218. reset: renderTaskReset
  20219. });
  20220. this.renderTask.context = {
  20221. view: this
  20222. };
  20223. }
  20224. Chart.prototype = {
  20225. type: 'chart',
  20226. /**
  20227. * Init the chart.
  20228. * @param {module:echarts/model/Global} ecModel
  20229. * @param {module:echarts/ExtensionAPI} api
  20230. */
  20231. init: function (ecModel, api) {},
  20232. /**
  20233. * Render the chart.
  20234. * @param {module:echarts/model/Series} seriesModel
  20235. * @param {module:echarts/model/Global} ecModel
  20236. * @param {module:echarts/ExtensionAPI} api
  20237. * @param {Object} payload
  20238. */
  20239. render: function (seriesModel, ecModel, api, payload) {},
  20240. /**
  20241. * Highlight series or specified data item.
  20242. * @param {module:echarts/model/Series} seriesModel
  20243. * @param {module:echarts/model/Global} ecModel
  20244. * @param {module:echarts/ExtensionAPI} api
  20245. * @param {Object} payload
  20246. */
  20247. highlight: function (seriesModel, ecModel, api, payload) {
  20248. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20249. },
  20250. /**
  20251. * Downplay series or specified data item.
  20252. * @param {module:echarts/model/Series} seriesModel
  20253. * @param {module:echarts/model/Global} ecModel
  20254. * @param {module:echarts/ExtensionAPI} api
  20255. * @param {Object} payload
  20256. */
  20257. downplay: function (seriesModel, ecModel, api, payload) {
  20258. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20259. },
  20260. /**
  20261. * Remove self.
  20262. * @param {module:echarts/model/Global} ecModel
  20263. * @param {module:echarts/ExtensionAPI} api
  20264. */
  20265. remove: function (ecModel, api) {
  20266. this.group.removeAll();
  20267. },
  20268. /**
  20269. * Dispose self.
  20270. * @param {module:echarts/model/Global} ecModel
  20271. * @param {module:echarts/ExtensionAPI} api
  20272. */
  20273. dispose: function () {},
  20274. /**
  20275. * Rendering preparation in progressive mode.
  20276. * @param {module:echarts/model/Series} seriesModel
  20277. * @param {module:echarts/model/Global} ecModel
  20278. * @param {module:echarts/ExtensionAPI} api
  20279. * @param {Object} payload
  20280. */
  20281. incrementalPrepareRender: null,
  20282. /**
  20283. * Render in progressive mode.
  20284. * @param {Object} params See taskParams in `stream/task.js`
  20285. * @param {module:echarts/model/Series} seriesModel
  20286. * @param {module:echarts/model/Global} ecModel
  20287. * @param {module:echarts/ExtensionAPI} api
  20288. * @param {Object} payload
  20289. */
  20290. incrementalRender: null,
  20291. /**
  20292. * Update transform directly.
  20293. * @param {module:echarts/model/Series} seriesModel
  20294. * @param {module:echarts/model/Global} ecModel
  20295. * @param {module:echarts/ExtensionAPI} api
  20296. * @param {Object} payload
  20297. * @return {Object} {update: true}
  20298. */
  20299. updateTransform: null,
  20300. /**
  20301. * The view contains the given point.
  20302. * @interface
  20303. * @param {Array.<number>} point
  20304. * @return {boolean}
  20305. */
  20306. // containPoint: function () {}
  20307. /**
  20308. * @param {string} eventType
  20309. * @param {Object} query
  20310. * @param {module:zrender/Element} targetEl
  20311. * @param {Object} packedEvent
  20312. * @return {boolen} Pass only when return `true`.
  20313. */
  20314. filterForExposedEvent: null
  20315. };
  20316. var chartProto = Chart.prototype;
  20317. chartProto.updateView = chartProto.updateLayout = chartProto.updateVisual = function (seriesModel, ecModel, api, payload) {
  20318. this.render(seriesModel, ecModel, api, payload);
  20319. };
  20320. /**
  20321. * Set state of single element
  20322. * @param {module:zrender/Element} el
  20323. * @param {string} state 'normal'|'emphasis'
  20324. * @param {number} highlightDigit
  20325. */
  20326. function elSetState(el, state, highlightDigit) {
  20327. if (el) {
  20328. el.trigger(state, highlightDigit);
  20329. if (el.isGroup // Simple optimize.
  20330. && !isHighDownDispatcher(el)) {
  20331. for (var i = 0, len = el.childCount(); i < len; i++) {
  20332. elSetState(el.childAt(i), state, highlightDigit);
  20333. }
  20334. }
  20335. }
  20336. }
  20337. /**
  20338. * @param {module:echarts/data/List} data
  20339. * @param {Object} payload
  20340. * @param {string} state 'normal'|'emphasis'
  20341. */
  20342. function toggleHighlight(data, payload, state) {
  20343. var dataIndex = queryDataIndex(data, payload);
  20344. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  20345. if (dataIndex != null) {
  20346. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20347. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  20348. });
  20349. } else {
  20350. data.eachItemGraphicEl(function (el) {
  20351. elSetState(el, state, highlightDigit);
  20352. });
  20353. }
  20354. } // Enable Chart.extend.
  20355. enableClassExtend(Chart, ['dispose']); // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20356. enableClassManagement(Chart, {
  20357. registerWhenExtend: true
  20358. });
  20359. Chart.markUpdateMethod = function (payload, methodName) {
  20360. inner$5(payload).updateMethod = methodName;
  20361. };
  20362. function renderTaskPlan(context) {
  20363. return renderPlanner(context.model);
  20364. }
  20365. function renderTaskReset(context) {
  20366. var seriesModel = context.model;
  20367. var ecModel = context.ecModel;
  20368. var api = context.api;
  20369. var payload = context.payload; // ???! remove updateView updateVisual
  20370. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20371. var view = context.view;
  20372. var updateMethod = payload && inner$5(payload).updateMethod;
  20373. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  20374. // is less than progressive threshold.
  20375. : 'render';
  20376. if (methodName !== 'render') {
  20377. view[methodName](seriesModel, ecModel, api, payload);
  20378. }
  20379. return progressMethodMap[methodName];
  20380. }
  20381. var progressMethodMap = {
  20382. incrementalPrepareRender: {
  20383. progress: function (params, context) {
  20384. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  20385. }
  20386. },
  20387. render: {
  20388. // Put view.render in `progress` to support appendData. But in this case
  20389. // view.render should not be called in reset, otherwise it will be called
  20390. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20391. // in any cases.
  20392. forceFirstProgress: true,
  20393. progress: function (params, context) {
  20394. context.view.render(context.model, context.ecModel, context.api, context.payload);
  20395. }
  20396. }
  20397. };
  20398. /*
  20399. * Licensed to the Apache Software Foundation (ASF) under one
  20400. * or more contributor license agreements. See the NOTICE file
  20401. * distributed with this work for additional information
  20402. * regarding copyright ownership. The ASF licenses this file
  20403. * to you under the Apache License, Version 2.0 (the
  20404. * "License"); you may not use this file except in compliance
  20405. * with the License. You may obtain a copy of the License at
  20406. *
  20407. * http://www.apache.org/licenses/LICENSE-2.0
  20408. *
  20409. * Unless required by applicable law or agreed to in writing,
  20410. * software distributed under the License is distributed on an
  20411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20412. * KIND, either express or implied. See the License for the
  20413. * specific language governing permissions and limitations
  20414. * under the License.
  20415. */
  20416. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20417. var RATE = '\0__throttleRate';
  20418. var THROTTLE_TYPE = '\0__throttleType';
  20419. /**
  20420. * @public
  20421. * @param {(Function)} fn
  20422. * @param {number} [delay=0] Unit: ms.
  20423. * @param {boolean} [debounce=false]
  20424. * true: If call interval less than `delay`, only the last call works.
  20425. * false: If call interval less than `delay, call works on fixed rate.
  20426. * @return {(Function)} throttled fn.
  20427. */
  20428. function throttle(fn, delay, debounce) {
  20429. var currCall;
  20430. var lastCall = 0;
  20431. var lastExec = 0;
  20432. var timer = null;
  20433. var diff;
  20434. var scope;
  20435. var args;
  20436. var debounceNextCall;
  20437. delay = delay || 0;
  20438. function exec() {
  20439. lastExec = new Date().getTime();
  20440. timer = null;
  20441. fn.apply(scope, args || []);
  20442. }
  20443. var cb = function () {
  20444. currCall = new Date().getTime();
  20445. scope = this;
  20446. args = arguments;
  20447. var thisDelay = debounceNextCall || delay;
  20448. var thisDebounce = debounceNextCall || debounce;
  20449. debounceNextCall = null;
  20450. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20451. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  20452. // than a new call of `cb`, that is, preserving the command order. Consider
  20453. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20454. // happens, either the `exec` is called dierectly, or the call is delayed.
  20455. // But the delayed call should never be later than next call of `cb`. Under
  20456. // this assurance, we can simply update view state each time `dispatchAction`
  20457. // triggered by user roaming, but not need to add extra code to avoid the
  20458. // state being "rolled-back".
  20459. if (thisDebounce) {
  20460. timer = setTimeout(exec, thisDelay);
  20461. } else {
  20462. if (diff >= 0) {
  20463. exec();
  20464. } else {
  20465. timer = setTimeout(exec, -diff);
  20466. }
  20467. }
  20468. lastCall = currCall;
  20469. };
  20470. /**
  20471. * Clear throttle.
  20472. * @public
  20473. */
  20474. cb.clear = function () {
  20475. if (timer) {
  20476. clearTimeout(timer);
  20477. timer = null;
  20478. }
  20479. };
  20480. /**
  20481. * Enable debounce once.
  20482. */
  20483. cb.debounceNextCall = function (debounceDelay) {
  20484. debounceNextCall = debounceDelay;
  20485. };
  20486. return cb;
  20487. }
  20488. /**
  20489. * Create throttle method or update throttle rate.
  20490. *
  20491. * @example
  20492. * ComponentView.prototype.render = function () {
  20493. * ...
  20494. * throttle.createOrUpdate(
  20495. * this,
  20496. * '_dispatchAction',
  20497. * this.model.get('throttle'),
  20498. * 'fixRate'
  20499. * );
  20500. * };
  20501. * ComponentView.prototype.remove = function () {
  20502. * throttle.clear(this, '_dispatchAction');
  20503. * };
  20504. * ComponentView.prototype.dispose = function () {
  20505. * throttle.clear(this, '_dispatchAction');
  20506. * };
  20507. *
  20508. * @public
  20509. * @param {Object} obj
  20510. * @param {string} fnAttr
  20511. * @param {number} [rate]
  20512. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20513. * @return {Function} throttled function.
  20514. */
  20515. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20516. var fn = obj[fnAttr];
  20517. if (!fn) {
  20518. return;
  20519. }
  20520. var originFn = fn[ORIGIN_METHOD] || fn;
  20521. var lastThrottleType = fn[THROTTLE_TYPE];
  20522. var lastRate = fn[RATE];
  20523. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20524. if (rate == null || !throttleType) {
  20525. return obj[fnAttr] = originFn;
  20526. }
  20527. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  20528. fn[ORIGIN_METHOD] = originFn;
  20529. fn[THROTTLE_TYPE] = throttleType;
  20530. fn[RATE] = rate;
  20531. }
  20532. return fn;
  20533. }
  20534. /**
  20535. * Clear throttle. Example see throttle.createOrUpdate.
  20536. *
  20537. * @public
  20538. * @param {Object} obj
  20539. * @param {string} fnAttr
  20540. */
  20541. /*
  20542. * Licensed to the Apache Software Foundation (ASF) under one
  20543. * or more contributor license agreements. See the NOTICE file
  20544. * distributed with this work for additional information
  20545. * regarding copyright ownership. The ASF licenses this file
  20546. * to you under the Apache License, Version 2.0 (the
  20547. * "License"); you may not use this file except in compliance
  20548. * with the License. You may obtain a copy of the License at
  20549. *
  20550. * http://www.apache.org/licenses/LICENSE-2.0
  20551. *
  20552. * Unless required by applicable law or agreed to in writing,
  20553. * software distributed under the License is distributed on an
  20554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20555. * KIND, either express or implied. See the License for the
  20556. * specific language governing permissions and limitations
  20557. * under the License.
  20558. */
  20559. var seriesColor = {
  20560. createOnAllSeries: true,
  20561. performRawSeries: true,
  20562. reset: function (seriesModel, ecModel) {
  20563. var data = seriesModel.getData();
  20564. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.'); // Set in itemStyle
  20565. var color = seriesModel.get(colorAccessPath);
  20566. var colorCallback = isFunction$1(color) && !(color instanceof Gradient) ? color : null; // Default color
  20567. if (!color || colorCallback) {
  20568. color = seriesModel.getColorFromPalette( // TODO series count changed.
  20569. seriesModel.name, null, ecModel.getSeriesCount());
  20570. }
  20571. data.setVisual('color', color);
  20572. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  20573. var borderColor = seriesModel.get(borderColorAccessPath);
  20574. data.setVisual('borderColor', borderColor); // Only visible series has each data be visual encoded
  20575. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20576. if (colorCallback) {
  20577. data.each(function (idx) {
  20578. data.setItemVisual(idx, 'color', colorCallback(seriesModel.getDataParams(idx)));
  20579. });
  20580. } // itemStyle in each data item
  20581. var dataEach = function (data, idx) {
  20582. var itemModel = data.getItemModel(idx);
  20583. var color = itemModel.get(colorAccessPath, true);
  20584. var borderColor = itemModel.get(borderColorAccessPath, true);
  20585. if (color != null) {
  20586. data.setItemVisual(idx, 'color', color);
  20587. }
  20588. if (borderColor != null) {
  20589. data.setItemVisual(idx, 'borderColor', borderColor);
  20590. }
  20591. };
  20592. return {
  20593. dataEach: data.hasItemOption ? dataEach : null
  20594. };
  20595. }
  20596. }
  20597. };
  20598. /*
  20599. * Licensed to the Apache Software Foundation (ASF) under one
  20600. * or more contributor license agreements. See the NOTICE file
  20601. * distributed with this work for additional information
  20602. * regarding copyright ownership. The ASF licenses this file
  20603. * to you under the Apache License, Version 2.0 (the
  20604. * "License"); you may not use this file except in compliance
  20605. * with the License. You may obtain a copy of the License at
  20606. *
  20607. * http://www.apache.org/licenses/LICENSE-2.0
  20608. *
  20609. * Unless required by applicable law or agreed to in writing,
  20610. * software distributed under the License is distributed on an
  20611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20612. * KIND, either express or implied. See the License for the
  20613. * specific language governing permissions and limitations
  20614. * under the License.
  20615. */
  20616. /**
  20617. * Language: (Simplified) Chinese.
  20618. */
  20619. var lang = {
  20620. legend: {
  20621. selector: {
  20622. all: '全选',
  20623. inverse: '反选'
  20624. }
  20625. },
  20626. toolbox: {
  20627. brush: {
  20628. title: {
  20629. rect: '矩形选择',
  20630. polygon: '圈选',
  20631. lineX: '横向选择',
  20632. lineY: '纵向选择',
  20633. keep: '保持选择',
  20634. clear: '清除选择'
  20635. }
  20636. },
  20637. dataView: {
  20638. title: '数据视图',
  20639. lang: ['数据视图', '关闭', '刷新']
  20640. },
  20641. dataZoom: {
  20642. title: {
  20643. zoom: '区域缩放',
  20644. back: '区域缩放还原'
  20645. }
  20646. },
  20647. magicType: {
  20648. title: {
  20649. line: '切换为折线图',
  20650. bar: '切换为柱状图',
  20651. stack: '切换为堆叠',
  20652. tiled: '切换为平铺'
  20653. }
  20654. },
  20655. restore: {
  20656. title: '还原'
  20657. },
  20658. saveAsImage: {
  20659. title: '保存为图片',
  20660. lang: ['右键另存为图片']
  20661. }
  20662. },
  20663. series: {
  20664. typeNames: {
  20665. pie: '饼图',
  20666. bar: '柱状图',
  20667. line: '折线图',
  20668. scatter: '散点图',
  20669. effectScatter: '涟漪散点图',
  20670. radar: '雷达图',
  20671. tree: '树图',
  20672. treemap: '矩形树图',
  20673. boxplot: '箱型图',
  20674. candlestick: 'K线图',
  20675. k: 'K线图',
  20676. heatmap: '热力图',
  20677. map: '地图',
  20678. parallel: '平行坐标图',
  20679. lines: '线图',
  20680. graph: '关系图',
  20681. sankey: '桑基图',
  20682. funnel: '漏斗图',
  20683. gauge: '仪表盘图',
  20684. pictorialBar: '象形柱图',
  20685. themeRiver: '主题河流图',
  20686. sunburst: '旭日图'
  20687. }
  20688. },
  20689. aria: {
  20690. general: {
  20691. withTitle: '这是一个关于“{title}”的图表。',
  20692. withoutTitle: '这是一个图表,'
  20693. },
  20694. series: {
  20695. single: {
  20696. prefix: '',
  20697. withName: '图表类型是{seriesType},表示{seriesName}。',
  20698. withoutName: '图表类型是{seriesType}。'
  20699. },
  20700. multiple: {
  20701. prefix: '它由{seriesCount}个图表系列组成。',
  20702. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20703. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20704. separator: {
  20705. middle: ';',
  20706. end: '。'
  20707. }
  20708. }
  20709. },
  20710. data: {
  20711. allData: '其数据是——',
  20712. partialData: '其中,前{displayCnt}项是——',
  20713. withName: '{name}的数据是{value}',
  20714. withoutName: '{value}',
  20715. separator: {
  20716. middle: ',',
  20717. end: ''
  20718. }
  20719. }
  20720. }
  20721. };
  20722. /*
  20723. * Licensed to the Apache Software Foundation (ASF) under one
  20724. * or more contributor license agreements. See the NOTICE file
  20725. * distributed with this work for additional information
  20726. * regarding copyright ownership. The ASF licenses this file
  20727. * to you under the Apache License, Version 2.0 (the
  20728. * "License"); you may not use this file except in compliance
  20729. * with the License. You may obtain a copy of the License at
  20730. *
  20731. * http://www.apache.org/licenses/LICENSE-2.0
  20732. *
  20733. * Unless required by applicable law or agreed to in writing,
  20734. * software distributed under the License is distributed on an
  20735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20736. * KIND, either express or implied. See the License for the
  20737. * specific language governing permissions and limitations
  20738. * under the License.
  20739. */
  20740. var aria = function (dom, ecModel) {
  20741. var ariaModel = ecModel.getModel('aria');
  20742. if (!ariaModel.get('show')) {
  20743. return;
  20744. } else if (ariaModel.get('description')) {
  20745. dom.setAttribute('aria-label', ariaModel.get('description'));
  20746. return;
  20747. }
  20748. var seriesCnt = 0;
  20749. ecModel.eachSeries(function (seriesModel, idx) {
  20750. ++seriesCnt;
  20751. }, this);
  20752. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20753. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20754. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20755. var ariaLabel;
  20756. if (seriesCnt < 1) {
  20757. // No series, no aria label
  20758. return;
  20759. } else {
  20760. var title = getTitle();
  20761. if (title) {
  20762. ariaLabel = replace(getConfig('general.withTitle'), {
  20763. title: title
  20764. });
  20765. } else {
  20766. ariaLabel = getConfig('general.withoutTitle');
  20767. }
  20768. var seriesLabels = [];
  20769. var prefix = seriesCnt > 1 ? 'series.multiple.prefix' : 'series.single.prefix';
  20770. ariaLabel += replace(getConfig(prefix), {
  20771. seriesCount: seriesCnt
  20772. });
  20773. ecModel.eachSeries(function (seriesModel, idx) {
  20774. if (idx < displaySeriesCnt) {
  20775. var seriesLabel;
  20776. var seriesName = seriesModel.get('name');
  20777. var seriesTpl = 'series.' + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20778. seriesLabel = getConfig(seriesName ? seriesTpl + 'withName' : seriesTpl + 'withoutName');
  20779. seriesLabel = replace(seriesLabel, {
  20780. seriesId: seriesModel.seriesIndex,
  20781. seriesName: seriesModel.get('name'),
  20782. seriesType: getSeriesTypeName(seriesModel.subType)
  20783. });
  20784. var data = seriesModel.getData();
  20785. window.data = data;
  20786. if (data.count() > maxDataCnt) {
  20787. // Show part of data
  20788. seriesLabel += replace(getConfig('data.partialData'), {
  20789. displayCnt: maxDataCnt
  20790. });
  20791. } else {
  20792. seriesLabel += getConfig('data.allData');
  20793. }
  20794. var dataLabels = [];
  20795. for (var i = 0; i < data.count(); i++) {
  20796. if (i < maxDataCnt) {
  20797. var name = data.getName(i);
  20798. var value = retrieveRawValue(data, i);
  20799. dataLabels.push(replace(name ? getConfig('data.withName') : getConfig('data.withoutName'), {
  20800. name: name,
  20801. value: value
  20802. }));
  20803. }
  20804. }
  20805. seriesLabel += dataLabels.join(getConfig('data.separator.middle')) + getConfig('data.separator.end');
  20806. seriesLabels.push(seriesLabel);
  20807. }
  20808. });
  20809. ariaLabel += seriesLabels.join(getConfig('series.multiple.separator.middle')) + getConfig('series.multiple.separator.end');
  20810. dom.setAttribute('aria-label', ariaLabel);
  20811. }
  20812. function replace(str, keyValues) {
  20813. if (typeof str !== 'string') {
  20814. return str;
  20815. }
  20816. var result = str;
  20817. each$1(keyValues, function (value, key) {
  20818. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  20819. });
  20820. return result;
  20821. }
  20822. function getConfig(path) {
  20823. var userConfig = ariaModel.get(path);
  20824. if (userConfig == null) {
  20825. var pathArr = path.split('.');
  20826. var result = lang.aria;
  20827. for (var i = 0; i < pathArr.length; ++i) {
  20828. result = result[pathArr[i]];
  20829. }
  20830. return result;
  20831. } else {
  20832. return userConfig;
  20833. }
  20834. }
  20835. function getTitle() {
  20836. var title = ecModel.getModel('title').option;
  20837. if (title && title.length) {
  20838. title = title[0];
  20839. }
  20840. return title && title.text;
  20841. }
  20842. function getSeriesTypeName(type) {
  20843. return lang.series.typeNames[type] || '自定义图';
  20844. }
  20845. };
  20846. /*
  20847. * Licensed to the Apache Software Foundation (ASF) under one
  20848. * or more contributor license agreements. See the NOTICE file
  20849. * distributed with this work for additional information
  20850. * regarding copyright ownership. The ASF licenses this file
  20851. * to you under the Apache License, Version 2.0 (the
  20852. * "License"); you may not use this file except in compliance
  20853. * with the License. You may obtain a copy of the License at
  20854. *
  20855. * http://www.apache.org/licenses/LICENSE-2.0
  20856. *
  20857. * Unless required by applicable law or agreed to in writing,
  20858. * software distributed under the License is distributed on an
  20859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20860. * KIND, either express or implied. See the License for the
  20861. * specific language governing permissions and limitations
  20862. * under the License.
  20863. */
  20864. var PI$1 = Math.PI;
  20865. /**
  20866. * @param {module:echarts/ExtensionAPI} api
  20867. * @param {Object} [opts]
  20868. * @param {string} [opts.text]
  20869. * @param {string} [opts.color]
  20870. * @param {string} [opts.textColor]
  20871. * @return {module:zrender/Element}
  20872. */
  20873. var loadingDefault = function (api, opts) {
  20874. opts = opts || {};
  20875. defaults(opts, {
  20876. text: 'loading',
  20877. textColor: '#000',
  20878. fontSize: '12px',
  20879. maskColor: 'rgba(255, 255, 255, 0.8)',
  20880. showSpinner: true,
  20881. color: '#c23531',
  20882. spinnerRadius: 10,
  20883. lineWidth: 5,
  20884. zlevel: 0
  20885. });
  20886. var group = new Group();
  20887. var mask = new Rect({
  20888. style: {
  20889. fill: opts.maskColor
  20890. },
  20891. zlevel: opts.zlevel,
  20892. z: 10000
  20893. });
  20894. group.add(mask);
  20895. var font = opts.fontSize + ' sans-serif';
  20896. var labelRect = new Rect({
  20897. style: {
  20898. fill: 'none',
  20899. text: opts.text,
  20900. font: font,
  20901. textPosition: 'right',
  20902. textDistance: 10,
  20903. textFill: opts.textColor
  20904. },
  20905. zlevel: opts.zlevel,
  20906. z: 10001
  20907. });
  20908. group.add(labelRect);
  20909. if (opts.showSpinner) {
  20910. var arc = new Arc({
  20911. shape: {
  20912. startAngle: -PI$1 / 2,
  20913. endAngle: -PI$1 / 2 + 0.1,
  20914. r: opts.spinnerRadius
  20915. },
  20916. style: {
  20917. stroke: opts.color,
  20918. lineCap: 'round',
  20919. lineWidth: opts.lineWidth
  20920. },
  20921. zlevel: opts.zlevel,
  20922. z: 10001
  20923. });
  20924. arc.animateShape(true).when(1000, {
  20925. endAngle: PI$1 * 3 / 2
  20926. }).start('circularInOut');
  20927. arc.animateShape(true).when(1000, {
  20928. startAngle: PI$1 * 3 / 2
  20929. }).delay(300).start('circularInOut');
  20930. group.add(arc);
  20931. } // Inject resize
  20932. group.resize = function () {
  20933. var textWidth = getWidth(opts.text, font);
  20934. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  20935. // textDistance needs to be calculated when both animation and text exist
  20936. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 // only show the text
  20937. - (opts.showSpinner ? 0 : textWidth / 2);
  20938. var cy = api.getHeight() / 2;
  20939. opts.showSpinner && arc.setShape({
  20940. cx: cx,
  20941. cy: cy
  20942. });
  20943. labelRect.setShape({
  20944. x: cx - r,
  20945. y: cy - r,
  20946. width: r * 2,
  20947. height: r * 2
  20948. });
  20949. mask.setShape({
  20950. x: 0,
  20951. y: 0,
  20952. width: api.getWidth(),
  20953. height: api.getHeight()
  20954. });
  20955. };
  20956. group.resize();
  20957. return group;
  20958. };
  20959. /*
  20960. * Licensed to the Apache Software Foundation (ASF) under one
  20961. * or more contributor license agreements. See the NOTICE file
  20962. * distributed with this work for additional information
  20963. * regarding copyright ownership. The ASF licenses this file
  20964. * to you under the Apache License, Version 2.0 (the
  20965. * "License"); you may not use this file except in compliance
  20966. * with the License. You may obtain a copy of the License at
  20967. *
  20968. * http://www.apache.org/licenses/LICENSE-2.0
  20969. *
  20970. * Unless required by applicable law or agreed to in writing,
  20971. * software distributed under the License is distributed on an
  20972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20973. * KIND, either express or implied. See the License for the
  20974. * specific language governing permissions and limitations
  20975. * under the License.
  20976. */
  20977. /**
  20978. * @module echarts/stream/Scheduler
  20979. */
  20980. /**
  20981. * @constructor
  20982. */
  20983. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20984. this.ecInstance = ecInstance;
  20985. this.api = api;
  20986. this.unfinished; // Fix current processors in case that in some rear cases that
  20987. // processors might be registered after echarts instance created.
  20988. // Register processors incrementally for a echarts instance is
  20989. // not supported by this stream architecture.
  20990. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20991. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  20992. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  20993. /**
  20994. * @private
  20995. * @type {
  20996. * [handlerUID: string]: {
  20997. * seriesTaskMap?: {
  20998. * [seriesUID: string]: Task
  20999. * },
  21000. * overallTask?: Task
  21001. * }
  21002. * }
  21003. */
  21004. this._stageTaskMap = createHashMap();
  21005. }
  21006. var proto = Scheduler.prototype;
  21007. /**
  21008. * @param {module:echarts/model/Global} ecModel
  21009. * @param {Object} payload
  21010. */
  21011. proto.restoreData = function (ecModel, payload) {
  21012. // TODO: Only restroe needed series and components, but not all components.
  21013. // Currently `restoreData` of all of the series and component will be called.
  21014. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21015. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21016. // and some components like coordinate system, axes, dataZoom, visualMap only
  21017. // need their target series refresh.
  21018. // (1) If we are implementing this feature some day, we should consider these cases:
  21019. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21020. // on the settings of `dataZoom`), it should be re-performed if the component
  21021. // is modified by `setOption`.
  21022. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21023. // it should be re-performed when the result array of `getTargetSeries` changed.
  21024. // We use `dependencies` to cover these issues.
  21025. // (3) How to update target series when coordinate system related components modified.
  21026. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21027. // and this case all of the tasks will be set as dirty.
  21028. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  21029. // depends on all of the series.
  21030. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21031. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21032. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21033. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21034. // probably cause state chaos (consider `dataZoomProcessor`).
  21035. this._stageTaskMap.each(function (taskRecord) {
  21036. var overallTask = taskRecord.overallTask;
  21037. overallTask && overallTask.dirty();
  21038. });
  21039. }; // If seriesModel provided, incremental threshold is check by series data.
  21040. proto.getPerformArgs = function (task, isBlock) {
  21041. // For overall task
  21042. if (!task.__pipeline) {
  21043. return;
  21044. }
  21045. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21046. var pCtx = pipeline.context;
  21047. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  21048. var step = incremental ? pipeline.step : null;
  21049. var modDataCount = pCtx && pCtx.modDataCount;
  21050. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21051. return {
  21052. step: step,
  21053. modBy: modBy,
  21054. modDataCount: modDataCount
  21055. };
  21056. };
  21057. proto.getPipeline = function (pipelineId) {
  21058. return this._pipelineMap.get(pipelineId);
  21059. };
  21060. /**
  21061. * Current, progressive rendering starts from visual and layout.
  21062. * Always detect render mode in the same stage, avoiding that incorrect
  21063. * detection caused by data filtering.
  21064. * Caution:
  21065. * `updateStreamModes` use `seriesModel.getData()`.
  21066. */
  21067. proto.updateStreamModes = function (seriesModel, view) {
  21068. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21069. var data = seriesModel.getData();
  21070. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  21071. // animation frame. Note that some types of series do not provide
  21072. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21073. // use the term `incremental` but not `progressive` to describe the
  21074. // case that `chart.appendData`.
  21075. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  21076. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21077. // see `test/candlestick-large3.html`
  21078. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21079. seriesModel.pipelineContext = pipeline.context = {
  21080. progressiveRender: progressiveRender,
  21081. modDataCount: modDataCount,
  21082. large: large
  21083. };
  21084. };
  21085. proto.restorePipelines = function (ecModel) {
  21086. var scheduler = this;
  21087. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21088. ecModel.eachSeries(function (seriesModel) {
  21089. var progressive = seriesModel.getProgressive();
  21090. var pipelineId = seriesModel.uid;
  21091. pipelineMap.set(pipelineId, {
  21092. id: pipelineId,
  21093. head: null,
  21094. tail: null,
  21095. threshold: seriesModel.getProgressiveThreshold(),
  21096. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21097. blockIndex: -1,
  21098. step: Math.round(progressive || 700),
  21099. count: 0
  21100. });
  21101. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21102. });
  21103. };
  21104. proto.prepareStageTasks = function () {
  21105. var stageTaskMap = this._stageTaskMap;
  21106. var ecModel = this.ecInstance.getModel();
  21107. var api = this.api;
  21108. each$1(this._allHandlers, function (handler) {
  21109. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21110. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21111. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21112. }, this);
  21113. };
  21114. proto.prepareView = function (view, model, ecModel, api) {
  21115. var renderTask = view.renderTask;
  21116. var context = renderTask.context;
  21117. context.model = model;
  21118. context.ecModel = ecModel;
  21119. context.api = api;
  21120. renderTask.__block = !view.incrementalPrepareRender;
  21121. pipe(this, model, renderTask);
  21122. };
  21123. proto.performDataProcessorTasks = function (ecModel, payload) {
  21124. // If we do not use `block` here, it should be considered when to update modes.
  21125. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {
  21126. block: true
  21127. });
  21128. }; // opt
  21129. // opt.visualType: 'visual' or 'layout'
  21130. // opt.setDirty
  21131. proto.performVisualTasks = function (ecModel, payload, opt) {
  21132. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21133. };
  21134. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21135. opt = opt || {};
  21136. var unfinished;
  21137. each$1(stageHandlers, function (stageHandler, idx) {
  21138. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21139. return;
  21140. }
  21141. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21142. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21143. var overallTask = stageHandlerRecord.overallTask;
  21144. if (overallTask) {
  21145. var overallNeedDirty;
  21146. var agentStubMap = overallTask.agentStubMap;
  21147. agentStubMap.each(function (stub) {
  21148. if (needSetDirty(opt, stub)) {
  21149. stub.dirty();
  21150. overallNeedDirty = true;
  21151. }
  21152. });
  21153. overallNeedDirty && overallTask.dirty();
  21154. updatePayload(overallTask, payload);
  21155. var performArgs = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  21156. // then execute the overall task. And stub will call seriesModel.setData,
  21157. // which ensures that in the overallTask seriesModel.getData() will not
  21158. // return incorrect data.
  21159. agentStubMap.each(function (stub) {
  21160. stub.perform(performArgs);
  21161. });
  21162. unfinished |= overallTask.perform(performArgs);
  21163. } else if (seriesTaskMap) {
  21164. seriesTaskMap.each(function (task, pipelineId) {
  21165. if (needSetDirty(opt, task)) {
  21166. task.dirty();
  21167. }
  21168. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  21169. // if intending to decalare `performRawSeries` in handlers, only
  21170. // stream-independent (specifically, data item independent) operations can be
  21171. // performed. Because is a series is filtered, most of the tasks will not
  21172. // be performed. A stream-dependent operation probably cause wrong biz logic.
  21173. // Perhaps we should not provide a separate callback for this case instead
  21174. // of providing the config `performRawSeries`. The stream-dependent operaions
  21175. // and stream-independent operations should better not be mixed.
  21176. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  21177. updatePayload(task, payload);
  21178. unfinished |= task.perform(performArgs);
  21179. });
  21180. }
  21181. });
  21182. function needSetDirty(opt, task) {
  21183. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21184. }
  21185. scheduler.unfinished |= unfinished;
  21186. }
  21187. proto.performSeriesTasks = function (ecModel) {
  21188. var unfinished;
  21189. ecModel.eachSeries(function (seriesModel) {
  21190. // Progress to the end for dataInit and dataRestore.
  21191. unfinished |= seriesModel.dataTask.perform();
  21192. });
  21193. this.unfinished |= unfinished;
  21194. };
  21195. proto.plan = function () {
  21196. // Travel pipelines, check block.
  21197. this._pipelineMap.each(function (pipeline) {
  21198. var task = pipeline.tail;
  21199. do {
  21200. if (task.__block) {
  21201. pipeline.blockIndex = task.__idxInPipeline;
  21202. break;
  21203. }
  21204. task = task.getUpstream();
  21205. } while (task);
  21206. });
  21207. };
  21208. var updatePayload = proto.updatePayload = function (task, payload) {
  21209. payload !== 'remain' && (task.context.payload = payload);
  21210. };
  21211. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21212. var seriesTaskMap = stageHandlerRecord.seriesTaskMap || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21213. var seriesType = stageHandler.seriesType;
  21214. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21215. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21216. // it works but it may cause other irrelevant charts blocked.
  21217. if (stageHandler.createOnAllSeries) {
  21218. ecModel.eachRawSeries(create);
  21219. } else if (seriesType) {
  21220. ecModel.eachRawSeriesByType(seriesType, create);
  21221. } else if (getTargetSeries) {
  21222. getTargetSeries(ecModel, api).each(create);
  21223. }
  21224. function create(seriesModel) {
  21225. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  21226. // Reuse original task instance.
  21227. var task = seriesTaskMap.get(pipelineId) || seriesTaskMap.set(pipelineId, createTask({
  21228. plan: seriesTaskPlan,
  21229. reset: seriesTaskReset,
  21230. count: seriesTaskCount
  21231. }));
  21232. task.context = {
  21233. model: seriesModel,
  21234. ecModel: ecModel,
  21235. api: api,
  21236. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21237. plan: stageHandler.plan,
  21238. reset: stageHandler.reset,
  21239. scheduler: scheduler
  21240. };
  21241. pipe(scheduler, seriesModel, task);
  21242. } // Clear unused series tasks.
  21243. var pipelineMap = scheduler._pipelineMap;
  21244. seriesTaskMap.each(function (task, pipelineId) {
  21245. if (!pipelineMap.get(pipelineId)) {
  21246. task.dispose();
  21247. seriesTaskMap.removeKey(pipelineId);
  21248. }
  21249. });
  21250. }
  21251. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21252. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  21253. || createTask({
  21254. reset: overallTaskReset
  21255. });
  21256. overallTask.context = {
  21257. ecModel: ecModel,
  21258. api: api,
  21259. overallReset: stageHandler.overallReset,
  21260. scheduler: scheduler
  21261. }; // Reuse orignal stubs.
  21262. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21263. var seriesType = stageHandler.seriesType;
  21264. var getTargetSeries = stageHandler.getTargetSeries;
  21265. var overallProgress = true;
  21266. var modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add
  21267. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21268. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21269. // we set the pipeline block.
  21270. if (seriesType) {
  21271. ecModel.eachRawSeriesByType(seriesType, createStub);
  21272. } else if (getTargetSeries) {
  21273. getTargetSeries(ecModel, api).each(createStub);
  21274. } // Otherwise, (usually it is legancy case), the overall task will only be
  21275. // executed when upstream dirty. Otherwise the progressive rendering of all
  21276. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21277. // dirty info from upsteam.
  21278. else {
  21279. overallProgress = false;
  21280. each$1(ecModel.getSeries(), createStub);
  21281. }
  21282. function createStub(seriesModel) {
  21283. var pipelineId = seriesModel.uid;
  21284. var stub = agentStubMap.get(pipelineId);
  21285. if (!stub) {
  21286. stub = agentStubMap.set(pipelineId, createTask({
  21287. reset: stubReset,
  21288. onDirty: stubOnDirty
  21289. })); // When the result of `getTargetSeries` changed, the overallTask
  21290. // should be set as dirty and re-performed.
  21291. overallTask.dirty();
  21292. }
  21293. stub.context = {
  21294. model: seriesModel,
  21295. overallProgress: overallProgress,
  21296. modifyOutputEnd: modifyOutputEnd
  21297. };
  21298. stub.agent = overallTask;
  21299. stub.__block = overallProgress;
  21300. pipe(scheduler, seriesModel, stub);
  21301. } // Clear unused stubs.
  21302. var pipelineMap = scheduler._pipelineMap;
  21303. agentStubMap.each(function (stub, pipelineId) {
  21304. if (!pipelineMap.get(pipelineId)) {
  21305. stub.dispose(); // When the result of `getTargetSeries` changed, the overallTask
  21306. // should be set as dirty and re-performed.
  21307. overallTask.dirty();
  21308. agentStubMap.removeKey(pipelineId);
  21309. }
  21310. });
  21311. }
  21312. function overallTaskReset(context) {
  21313. context.overallReset(context.ecModel, context.api, context.payload);
  21314. }
  21315. function stubReset(context, upstreamContext) {
  21316. return context.overallProgress && stubProgress;
  21317. }
  21318. function stubProgress() {
  21319. this.agent.dirty();
  21320. this.getDownstream().dirty();
  21321. }
  21322. function stubOnDirty() {
  21323. this.agent && this.agent.dirty();
  21324. }
  21325. function seriesTaskPlan(context) {
  21326. return context.plan && context.plan(context.model, context.ecModel, context.api, context.payload);
  21327. }
  21328. function seriesTaskReset(context) {
  21329. if (context.useClearVisual) {
  21330. context.data.clearAllVisual();
  21331. }
  21332. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  21333. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  21334. return makeSeriesTaskProgress(idx);
  21335. }) : singleSeriesTaskProgress;
  21336. }
  21337. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21338. function makeSeriesTaskProgress(resetDefineIdx) {
  21339. return function (params, context) {
  21340. var data = context.data;
  21341. var resetDefine = context.resetDefines[resetDefineIdx];
  21342. if (resetDefine && resetDefine.dataEach) {
  21343. for (var i = params.start; i < params.end; i++) {
  21344. resetDefine.dataEach(data, i);
  21345. }
  21346. } else if (resetDefine && resetDefine.progress) {
  21347. resetDefine.progress(params, data);
  21348. }
  21349. };
  21350. }
  21351. function seriesTaskCount(context) {
  21352. return context.data.count();
  21353. }
  21354. function pipe(scheduler, seriesModel, task) {
  21355. var pipelineId = seriesModel.uid;
  21356. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21357. !pipeline.head && (pipeline.head = task);
  21358. pipeline.tail && pipeline.tail.pipe(task);
  21359. pipeline.tail = task;
  21360. task.__idxInPipeline = pipeline.count++;
  21361. task.__pipeline = pipeline;
  21362. }
  21363. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21364. if (isFunction$1(stageHandler)) {
  21365. stageHandler = {
  21366. overallReset: stageHandler,
  21367. seriesType: detectSeriseType(stageHandler)
  21368. };
  21369. }
  21370. stageHandler.uid = getUID('stageHandler');
  21371. visualType && (stageHandler.visualType = visualType);
  21372. return stageHandler;
  21373. };
  21374. /**
  21375. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21376. * To ensure that they can work normally, they should work in block mode, that is,
  21377. * they should not be started util the previous tasks finished. So they cause the
  21378. * progressive rendering disabled. We try to detect the series type, to narrow down
  21379. * the block range to only the series type they concern, but not all series.
  21380. */
  21381. function detectSeriseType(legacyFunc) {
  21382. seriesType = null;
  21383. try {
  21384. // Assume there is no async when calling `eachSeriesByType`.
  21385. legacyFunc(ecModelMock, apiMock);
  21386. } catch (e) {}
  21387. return seriesType;
  21388. }
  21389. var ecModelMock = {};
  21390. var apiMock = {};
  21391. var seriesType;
  21392. mockMethods(ecModelMock, GlobalModel);
  21393. mockMethods(apiMock, ExtensionAPI);
  21394. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21395. seriesType = type;
  21396. };
  21397. ecModelMock.eachComponent = function (cond) {
  21398. if (cond.mainType === 'series' && cond.subType) {
  21399. seriesType = cond.subType;
  21400. }
  21401. };
  21402. function mockMethods(target, Clz) {
  21403. /* eslint-disable */
  21404. for (var name in Clz.prototype) {
  21405. // Do not use hasOwnProperty
  21406. target[name] = noop;
  21407. }
  21408. /* eslint-enable */
  21409. }
  21410. /*
  21411. * Licensed to the Apache Software Foundation (ASF) under one
  21412. * or more contributor license agreements. See the NOTICE file
  21413. * distributed with this work for additional information
  21414. * regarding copyright ownership. The ASF licenses this file
  21415. * to you under the Apache License, Version 2.0 (the
  21416. * "License"); you may not use this file except in compliance
  21417. * with the License. You may obtain a copy of the License at
  21418. *
  21419. * http://www.apache.org/licenses/LICENSE-2.0
  21420. *
  21421. * Unless required by applicable law or agreed to in writing,
  21422. * software distributed under the License is distributed on an
  21423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21424. * KIND, either express or implied. See the License for the
  21425. * specific language governing permissions and limitations
  21426. * under the License.
  21427. */
  21428. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21429. var lightTheme = {
  21430. color: colorAll,
  21431. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  21432. };
  21433. /*
  21434. * Licensed to the Apache Software Foundation (ASF) under one
  21435. * or more contributor license agreements. See the NOTICE file
  21436. * distributed with this work for additional information
  21437. * regarding copyright ownership. The ASF licenses this file
  21438. * to you under the Apache License, Version 2.0 (the
  21439. * "License"); you may not use this file except in compliance
  21440. * with the License. You may obtain a copy of the License at
  21441. *
  21442. * http://www.apache.org/licenses/LICENSE-2.0
  21443. *
  21444. * Unless required by applicable law or agreed to in writing,
  21445. * software distributed under the License is distributed on an
  21446. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21447. * KIND, either express or implied. See the License for the
  21448. * specific language governing permissions and limitations
  21449. * under the License.
  21450. */
  21451. var contrastColor = '#eee';
  21452. var axisCommon = function () {
  21453. return {
  21454. axisLine: {
  21455. lineStyle: {
  21456. color: contrastColor
  21457. }
  21458. },
  21459. axisTick: {
  21460. lineStyle: {
  21461. color: contrastColor
  21462. }
  21463. },
  21464. axisLabel: {
  21465. textStyle: {
  21466. color: contrastColor
  21467. }
  21468. },
  21469. splitLine: {
  21470. lineStyle: {
  21471. type: 'dashed',
  21472. color: '#aaa'
  21473. }
  21474. },
  21475. splitArea: {
  21476. areaStyle: {
  21477. color: contrastColor
  21478. }
  21479. }
  21480. };
  21481. };
  21482. var colorPalette = ['#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53', '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'];
  21483. var theme = {
  21484. color: colorPalette,
  21485. backgroundColor: '#333',
  21486. tooltip: {
  21487. axisPointer: {
  21488. lineStyle: {
  21489. color: contrastColor
  21490. },
  21491. crossStyle: {
  21492. color: contrastColor
  21493. },
  21494. label: {
  21495. color: '#000'
  21496. }
  21497. }
  21498. },
  21499. legend: {
  21500. textStyle: {
  21501. color: contrastColor
  21502. }
  21503. },
  21504. textStyle: {
  21505. color: contrastColor
  21506. },
  21507. title: {
  21508. textStyle: {
  21509. color: contrastColor
  21510. }
  21511. },
  21512. toolbox: {
  21513. iconStyle: {
  21514. normal: {
  21515. borderColor: contrastColor
  21516. }
  21517. }
  21518. },
  21519. dataZoom: {
  21520. textStyle: {
  21521. color: contrastColor
  21522. }
  21523. },
  21524. visualMap: {
  21525. textStyle: {
  21526. color: contrastColor
  21527. }
  21528. },
  21529. timeline: {
  21530. lineStyle: {
  21531. color: contrastColor
  21532. },
  21533. itemStyle: {
  21534. normal: {
  21535. color: colorPalette[1]
  21536. }
  21537. },
  21538. label: {
  21539. normal: {
  21540. textStyle: {
  21541. color: contrastColor
  21542. }
  21543. }
  21544. },
  21545. controlStyle: {
  21546. normal: {
  21547. color: contrastColor,
  21548. borderColor: contrastColor
  21549. }
  21550. }
  21551. },
  21552. timeAxis: axisCommon(),
  21553. logAxis: axisCommon(),
  21554. valueAxis: axisCommon(),
  21555. categoryAxis: axisCommon(),
  21556. line: {
  21557. symbol: 'circle'
  21558. },
  21559. graph: {
  21560. color: colorPalette
  21561. },
  21562. gauge: {
  21563. title: {
  21564. textStyle: {
  21565. color: contrastColor
  21566. }
  21567. }
  21568. },
  21569. candlestick: {
  21570. itemStyle: {
  21571. normal: {
  21572. color: '#FD1050',
  21573. color0: '#0CF49B',
  21574. borderColor: '#FD1050',
  21575. borderColor0: '#0CF49B'
  21576. }
  21577. }
  21578. }
  21579. };
  21580. theme.categoryAxis.splitLine.show = false;
  21581. /*
  21582. * Licensed to the Apache Software Foundation (ASF) under one
  21583. * or more contributor license agreements. See the NOTICE file
  21584. * distributed with this work for additional information
  21585. * regarding copyright ownership. The ASF licenses this file
  21586. * to you under the Apache License, Version 2.0 (the
  21587. * "License"); you may not use this file except in compliance
  21588. * with the License. You may obtain a copy of the License at
  21589. *
  21590. * http://www.apache.org/licenses/LICENSE-2.0
  21591. *
  21592. * Unless required by applicable law or agreed to in writing,
  21593. * software distributed under the License is distributed on an
  21594. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21595. * KIND, either express or implied. See the License for the
  21596. * specific language governing permissions and limitations
  21597. * under the License.
  21598. */
  21599. /**
  21600. * This module is imported by echarts directly.
  21601. *
  21602. * Notice:
  21603. * Always keep this file exists for backward compatibility.
  21604. * Because before 4.1.0, dataset is an optional component,
  21605. * some users may import this module manually.
  21606. */
  21607. ComponentModel.extend({
  21608. type: 'dataset',
  21609. /**
  21610. * @protected
  21611. */
  21612. defaultOption: {
  21613. // 'row', 'column'
  21614. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21615. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21616. sourceHeader: null,
  21617. dimensions: null,
  21618. source: null
  21619. },
  21620. optionUpdated: function () {
  21621. detectSourceFormat(this);
  21622. }
  21623. });
  21624. Component$1.extend({
  21625. type: 'dataset'
  21626. });
  21627. /**
  21628. * 椭圆形状
  21629. * @module zrender/graphic/shape/Ellipse
  21630. */
  21631. var Ellipse = Path.extend({
  21632. type: 'ellipse',
  21633. shape: {
  21634. cx: 0,
  21635. cy: 0,
  21636. rx: 0,
  21637. ry: 0
  21638. },
  21639. buildPath: function (ctx, shape) {
  21640. var k = 0.5522848;
  21641. var x = shape.cx;
  21642. var y = shape.cy;
  21643. var a = shape.rx;
  21644. var b = shape.ry;
  21645. var ox = a * k; // 水平控制点偏移量
  21646. var oy = b * k; // 垂直控制点偏移量
  21647. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  21648. ctx.moveTo(x - a, y);
  21649. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  21650. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  21651. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  21652. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  21653. ctx.closePath();
  21654. }
  21655. });
  21656. // import Pattern from '../graphic/Pattern';
  21657. var DILIMITER_REG = /[\s,]+/;
  21658. /**
  21659. * For big svg string, this method might be time consuming.
  21660. *
  21661. * @param {string} svg xml string
  21662. * @return {Object} xml root.
  21663. */
  21664. function parseXML(svg) {
  21665. if (isString(svg)) {
  21666. var parser = new DOMParser();
  21667. svg = parser.parseFromString(svg, 'text/xml');
  21668. } // Document node. If using $.get, doc node may be input.
  21669. if (svg.nodeType === 9) {
  21670. svg = svg.firstChild;
  21671. } // nodeName of <!DOCTYPE svg> is also 'svg'.
  21672. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  21673. svg = svg.nextSibling;
  21674. }
  21675. return svg;
  21676. }
  21677. function SVGParser() {
  21678. this._defs = {};
  21679. this._root = null;
  21680. this._isDefine = false;
  21681. this._isText = false;
  21682. }
  21683. SVGParser.prototype.parse = function (xml, opt) {
  21684. opt = opt || {};
  21685. var svg = parseXML(xml);
  21686. if (!svg) {
  21687. throw new Error('Illegal svg');
  21688. }
  21689. var root = new Group();
  21690. this._root = root; // parse view port
  21691. var viewBox = svg.getAttribute('viewBox') || ''; // If width/height not specified, means "100%" of `opt.width/height`.
  21692. // TODO: Other percent value not supported yet.
  21693. var width = parseFloat(svg.getAttribute('width') || opt.width);
  21694. var height = parseFloat(svg.getAttribute('height') || opt.height); // If width/height not specified, set as null for output.
  21695. isNaN(width) && (width = null);
  21696. isNaN(height) && (height = null); // Apply inline style on svg element.
  21697. parseAttributes(svg, root, null, true);
  21698. var child = svg.firstChild;
  21699. while (child) {
  21700. this._parseNode(child, root);
  21701. child = child.nextSibling;
  21702. }
  21703. var viewBoxRect;
  21704. var viewBoxTransform;
  21705. if (viewBox) {
  21706. var viewBoxArr = trim(viewBox).split(DILIMITER_REG); // Some invalid case like viewBox: 'none'.
  21707. if (viewBoxArr.length >= 4) {
  21708. viewBoxRect = {
  21709. x: parseFloat(viewBoxArr[0] || 0),
  21710. y: parseFloat(viewBoxArr[1] || 0),
  21711. width: parseFloat(viewBoxArr[2]),
  21712. height: parseFloat(viewBoxArr[3])
  21713. };
  21714. }
  21715. }
  21716. if (viewBoxRect && width != null && height != null) {
  21717. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  21718. if (!opt.ignoreViewBox) {
  21719. // If set transform on the output group, it probably bring trouble when
  21720. // some users only intend to show the clipped content inside the viewBox,
  21721. // but not intend to transform the output group. So we keep the output
  21722. // group no transform. If the user intend to use the viewBox as a
  21723. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  21724. // manually according to the viewBox info in the output of this method.
  21725. var elRoot = root;
  21726. root = new Group();
  21727. root.add(elRoot);
  21728. elRoot.scale = viewBoxTransform.scale.slice();
  21729. elRoot.position = viewBoxTransform.position.slice();
  21730. }
  21731. } // Some shapes might be overflow the viewport, which should be
  21732. // clipped despite whether the viewBox is used, as the SVG does.
  21733. if (!opt.ignoreRootClip && width != null && height != null) {
  21734. root.setClipPath(new Rect({
  21735. shape: {
  21736. x: 0,
  21737. y: 0,
  21738. width: width,
  21739. height: height
  21740. }
  21741. }));
  21742. } // Set width/height on group just for output the viewport size.
  21743. return {
  21744. root: root,
  21745. width: width,
  21746. height: height,
  21747. viewBoxRect: viewBoxRect,
  21748. viewBoxTransform: viewBoxTransform
  21749. };
  21750. };
  21751. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  21752. var nodeName = xmlNode.nodeName.toLowerCase(); // TODO
  21753. // support <style>...</style> in svg, where nodeName is 'style',
  21754. // CSS classes is defined globally wherever the style tags are declared.
  21755. if (nodeName === 'defs') {
  21756. // define flag
  21757. this._isDefine = true;
  21758. } else if (nodeName === 'text') {
  21759. this._isText = true;
  21760. }
  21761. var el;
  21762. if (this._isDefine) {
  21763. var parser = defineParsers[nodeName];
  21764. if (parser) {
  21765. var def = parser.call(this, xmlNode);
  21766. var id = xmlNode.getAttribute('id');
  21767. if (id) {
  21768. this._defs[id] = def;
  21769. }
  21770. }
  21771. } else {
  21772. var parser = nodeParsers[nodeName];
  21773. if (parser) {
  21774. el = parser.call(this, xmlNode, parentGroup);
  21775. parentGroup.add(el);
  21776. }
  21777. }
  21778. var child = xmlNode.firstChild;
  21779. while (child) {
  21780. if (child.nodeType === 1) {
  21781. this._parseNode(child, el);
  21782. } // Is text
  21783. if (child.nodeType === 3 && this._isText) {
  21784. this._parseText(child, el);
  21785. }
  21786. child = child.nextSibling;
  21787. } // Quit define
  21788. if (nodeName === 'defs') {
  21789. this._isDefine = false;
  21790. } else if (nodeName === 'text') {
  21791. this._isText = false;
  21792. }
  21793. };
  21794. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  21795. if (xmlNode.nodeType === 1) {
  21796. var dx = xmlNode.getAttribute('dx') || 0;
  21797. var dy = xmlNode.getAttribute('dy') || 0;
  21798. this._textX += parseFloat(dx);
  21799. this._textY += parseFloat(dy);
  21800. }
  21801. var text = new Text({
  21802. style: {
  21803. text: xmlNode.textContent,
  21804. transformText: true
  21805. },
  21806. position: [this._textX || 0, this._textY || 0]
  21807. });
  21808. inheritStyle(parentGroup, text);
  21809. parseAttributes(xmlNode, text, this._defs);
  21810. var fontSize = text.style.fontSize;
  21811. if (fontSize && fontSize < 9) {
  21812. // PENDING
  21813. text.style.fontSize = 9;
  21814. text.scale = text.scale || [1, 1];
  21815. text.scale[0] *= fontSize / 9;
  21816. text.scale[1] *= fontSize / 9;
  21817. }
  21818. var rect = text.getBoundingRect();
  21819. this._textX += rect.width;
  21820. parentGroup.add(text);
  21821. return text;
  21822. };
  21823. var nodeParsers = {
  21824. 'g': function (xmlNode, parentGroup) {
  21825. var g = new Group();
  21826. inheritStyle(parentGroup, g);
  21827. parseAttributes(xmlNode, g, this._defs);
  21828. return g;
  21829. },
  21830. 'rect': function (xmlNode, parentGroup) {
  21831. var rect = new Rect();
  21832. inheritStyle(parentGroup, rect);
  21833. parseAttributes(xmlNode, rect, this._defs);
  21834. rect.setShape({
  21835. x: parseFloat(xmlNode.getAttribute('x') || 0),
  21836. y: parseFloat(xmlNode.getAttribute('y') || 0),
  21837. width: parseFloat(xmlNode.getAttribute('width') || 0),
  21838. height: parseFloat(xmlNode.getAttribute('height') || 0)
  21839. }); // console.log(xmlNode.getAttribute('transform'));
  21840. // console.log(rect.transform);
  21841. return rect;
  21842. },
  21843. 'circle': function (xmlNode, parentGroup) {
  21844. var circle = new Circle();
  21845. inheritStyle(parentGroup, circle);
  21846. parseAttributes(xmlNode, circle, this._defs);
  21847. circle.setShape({
  21848. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  21849. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  21850. r: parseFloat(xmlNode.getAttribute('r') || 0)
  21851. });
  21852. return circle;
  21853. },
  21854. 'line': function (xmlNode, parentGroup) {
  21855. var line = new Line();
  21856. inheritStyle(parentGroup, line);
  21857. parseAttributes(xmlNode, line, this._defs);
  21858. line.setShape({
  21859. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  21860. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  21861. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  21862. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  21863. });
  21864. return line;
  21865. },
  21866. 'ellipse': function (xmlNode, parentGroup) {
  21867. var ellipse = new Ellipse();
  21868. inheritStyle(parentGroup, ellipse);
  21869. parseAttributes(xmlNode, ellipse, this._defs);
  21870. ellipse.setShape({
  21871. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  21872. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  21873. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  21874. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  21875. });
  21876. return ellipse;
  21877. },
  21878. 'polygon': function (xmlNode, parentGroup) {
  21879. var points = xmlNode.getAttribute('points');
  21880. if (points) {
  21881. points = parsePoints(points);
  21882. }
  21883. var polygon = new Polygon({
  21884. shape: {
  21885. points: points || []
  21886. }
  21887. });
  21888. inheritStyle(parentGroup, polygon);
  21889. parseAttributes(xmlNode, polygon, this._defs);
  21890. return polygon;
  21891. },
  21892. 'polyline': function (xmlNode, parentGroup) {
  21893. var path = new Path();
  21894. inheritStyle(parentGroup, path);
  21895. parseAttributes(xmlNode, path, this._defs);
  21896. var points = xmlNode.getAttribute('points');
  21897. if (points) {
  21898. points = parsePoints(points);
  21899. }
  21900. var polyline = new Polyline({
  21901. shape: {
  21902. points: points || []
  21903. }
  21904. });
  21905. return polyline;
  21906. },
  21907. 'image': function (xmlNode, parentGroup) {
  21908. var img = new ZImage();
  21909. inheritStyle(parentGroup, img);
  21910. parseAttributes(xmlNode, img, this._defs);
  21911. img.setStyle({
  21912. image: xmlNode.getAttribute('xlink:href'),
  21913. x: xmlNode.getAttribute('x'),
  21914. y: xmlNode.getAttribute('y'),
  21915. width: xmlNode.getAttribute('width'),
  21916. height: xmlNode.getAttribute('height')
  21917. });
  21918. return img;
  21919. },
  21920. 'text': function (xmlNode, parentGroup) {
  21921. var x = xmlNode.getAttribute('x') || 0;
  21922. var y = xmlNode.getAttribute('y') || 0;
  21923. var dx = xmlNode.getAttribute('dx') || 0;
  21924. var dy = xmlNode.getAttribute('dy') || 0;
  21925. this._textX = parseFloat(x) + parseFloat(dx);
  21926. this._textY = parseFloat(y) + parseFloat(dy);
  21927. var g = new Group();
  21928. inheritStyle(parentGroup, g);
  21929. parseAttributes(xmlNode, g, this._defs);
  21930. return g;
  21931. },
  21932. 'tspan': function (xmlNode, parentGroup) {
  21933. var x = xmlNode.getAttribute('x');
  21934. var y = xmlNode.getAttribute('y');
  21935. if (x != null) {
  21936. // new offset x
  21937. this._textX = parseFloat(x);
  21938. }
  21939. if (y != null) {
  21940. // new offset y
  21941. this._textY = parseFloat(y);
  21942. }
  21943. var dx = xmlNode.getAttribute('dx') || 0;
  21944. var dy = xmlNode.getAttribute('dy') || 0;
  21945. var g = new Group();
  21946. inheritStyle(parentGroup, g);
  21947. parseAttributes(xmlNode, g, this._defs);
  21948. this._textX += dx;
  21949. this._textY += dy;
  21950. return g;
  21951. },
  21952. 'path': function (xmlNode, parentGroup) {
  21953. // TODO svg fill rule
  21954. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  21955. // path.style.globalCompositeOperation = 'xor';
  21956. var d = xmlNode.getAttribute('d') || ''; // Performance sensitive.
  21957. var path = createFromString(d);
  21958. inheritStyle(parentGroup, path);
  21959. parseAttributes(xmlNode, path, this._defs);
  21960. return path;
  21961. }
  21962. };
  21963. var defineParsers = {
  21964. 'lineargradient': function (xmlNode) {
  21965. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  21966. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  21967. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  21968. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  21969. var gradient = new LinearGradient(x1, y1, x2, y2);
  21970. _parseGradientColorStops(xmlNode, gradient);
  21971. return gradient;
  21972. },
  21973. 'radialgradient': function (xmlNode) {}
  21974. };
  21975. function _parseGradientColorStops(xmlNode, gradient) {
  21976. var stop = xmlNode.firstChild;
  21977. while (stop) {
  21978. if (stop.nodeType === 1) {
  21979. var offset = stop.getAttribute('offset');
  21980. if (offset.indexOf('%') > 0) {
  21981. // percentage
  21982. offset = parseInt(offset, 10) / 100;
  21983. } else if (offset) {
  21984. // number from 0 to 1
  21985. offset = parseFloat(offset);
  21986. } else {
  21987. offset = 0;
  21988. }
  21989. var stopColor = stop.getAttribute('stop-color') || '#000000';
  21990. gradient.addColorStop(offset, stopColor);
  21991. }
  21992. stop = stop.nextSibling;
  21993. }
  21994. }
  21995. function inheritStyle(parent, child) {
  21996. if (parent && parent.__inheritedStyle) {
  21997. if (!child.__inheritedStyle) {
  21998. child.__inheritedStyle = {};
  21999. }
  22000. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  22001. }
  22002. }
  22003. function parsePoints(pointsString) {
  22004. var list = trim(pointsString).split(DILIMITER_REG);
  22005. var points = [];
  22006. for (var i = 0; i < list.length; i += 2) {
  22007. var x = parseFloat(list[i]);
  22008. var y = parseFloat(list[i + 1]);
  22009. points.push([x, y]);
  22010. }
  22011. return points;
  22012. }
  22013. var attributesMap = {
  22014. 'fill': 'fill',
  22015. 'stroke': 'stroke',
  22016. 'stroke-width': 'lineWidth',
  22017. 'opacity': 'opacity',
  22018. 'fill-opacity': 'fillOpacity',
  22019. 'stroke-opacity': 'strokeOpacity',
  22020. 'stroke-dasharray': 'lineDash',
  22021. 'stroke-dashoffset': 'lineDashOffset',
  22022. 'stroke-linecap': 'lineCap',
  22023. 'stroke-linejoin': 'lineJoin',
  22024. 'stroke-miterlimit': 'miterLimit',
  22025. 'font-family': 'fontFamily',
  22026. 'font-size': 'fontSize',
  22027. 'font-style': 'fontStyle',
  22028. 'font-weight': 'fontWeight',
  22029. 'text-align': 'textAlign',
  22030. 'alignment-baseline': 'textBaseline'
  22031. };
  22032. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  22033. var zrStyle = el.__inheritedStyle || {};
  22034. var isTextEl = el.type === 'text'; // TODO Shadow
  22035. if (xmlNode.nodeType === 1) {
  22036. parseTransformAttribute(xmlNode, el);
  22037. extend(zrStyle, parseStyleAttribute(xmlNode));
  22038. if (!onlyInlineStyle) {
  22039. for (var svgAttrName in attributesMap) {
  22040. if (attributesMap.hasOwnProperty(svgAttrName)) {
  22041. var attrValue = xmlNode.getAttribute(svgAttrName);
  22042. if (attrValue != null) {
  22043. zrStyle[attributesMap[svgAttrName]] = attrValue;
  22044. }
  22045. }
  22046. }
  22047. }
  22048. }
  22049. var elFillProp = isTextEl ? 'textFill' : 'fill';
  22050. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  22051. el.style = el.style || new Style();
  22052. var elStyle = el.style;
  22053. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  22054. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  22055. each$1(['lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'], function (propName) {
  22056. var elPropName = propName === 'lineWidth' && isTextEl ? 'textStrokeWidth' : propName;
  22057. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  22058. });
  22059. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  22060. zrStyle.textBaseline = 'alphabetic';
  22061. }
  22062. if (zrStyle.textBaseline === 'alphabetic') {
  22063. zrStyle.textBaseline = 'bottom';
  22064. }
  22065. if (zrStyle.textAlign === 'start') {
  22066. zrStyle.textAlign = 'left';
  22067. }
  22068. if (zrStyle.textAlign === 'end') {
  22069. zrStyle.textAlign = 'right';
  22070. }
  22071. each$1(['lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'], function (propName) {
  22072. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  22073. });
  22074. if (zrStyle.lineDash) {
  22075. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  22076. }
  22077. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  22078. // enable stroke
  22079. el[elStrokeProp] = true;
  22080. }
  22081. el.__inheritedStyle = zrStyle;
  22082. }
  22083. var urlRegex = /url\(\s*#(.*?)\)/;
  22084. function getPaint(str, defs) {
  22085. // if (str === 'none') {
  22086. // return;
  22087. // }
  22088. var urlMatch = defs && str && str.match(urlRegex);
  22089. if (urlMatch) {
  22090. var url = trim(urlMatch[1]);
  22091. var def = defs[url];
  22092. return def;
  22093. }
  22094. return str;
  22095. }
  22096. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  22097. function parseTransformAttribute(xmlNode, node) {
  22098. var transform = xmlNode.getAttribute('transform');
  22099. if (transform) {
  22100. transform = transform.replace(/,/g, ' ');
  22101. var m = null;
  22102. var transformOps = [];
  22103. transform.replace(transformRegex, function (str, type, value) {
  22104. transformOps.push(type, value);
  22105. });
  22106. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  22107. var value = transformOps[i];
  22108. var type = transformOps[i - 1];
  22109. m = m || create$1();
  22110. switch (type) {
  22111. case 'translate':
  22112. value = trim(value).split(DILIMITER_REG);
  22113. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  22114. break;
  22115. case 'scale':
  22116. value = trim(value).split(DILIMITER_REG);
  22117. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  22118. break;
  22119. case 'rotate':
  22120. value = trim(value).split(DILIMITER_REG);
  22121. rotate(m, m, parseFloat(value[0]));
  22122. break;
  22123. case 'skew':
  22124. value = trim(value).split(DILIMITER_REG);
  22125. console.warn('Skew transform is not supported yet');
  22126. break;
  22127. case 'matrix':
  22128. var value = trim(value).split(DILIMITER_REG);
  22129. m[0] = parseFloat(value[0]);
  22130. m[1] = parseFloat(value[1]);
  22131. m[2] = parseFloat(value[2]);
  22132. m[3] = parseFloat(value[3]);
  22133. m[4] = parseFloat(value[4]);
  22134. m[5] = parseFloat(value[5]);
  22135. break;
  22136. }
  22137. }
  22138. node.setLocalTransform(m);
  22139. }
  22140. } // Value may contain space.
  22141. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  22142. function parseStyleAttribute(xmlNode) {
  22143. var style = xmlNode.getAttribute('style');
  22144. var result = {};
  22145. if (!style) {
  22146. return result;
  22147. }
  22148. var styleList = {};
  22149. styleRegex.lastIndex = 0;
  22150. var styleRegResult;
  22151. while ((styleRegResult = styleRegex.exec(style)) != null) {
  22152. styleList[styleRegResult[1]] = styleRegResult[2];
  22153. }
  22154. for (var svgAttrName in attributesMap) {
  22155. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  22156. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  22157. }
  22158. }
  22159. return result;
  22160. }
  22161. /**
  22162. * @param {Array.<number>} viewBoxRect
  22163. * @param {number} width
  22164. * @param {number} height
  22165. * @return {Object} {scale, position}
  22166. */
  22167. function makeViewBoxTransform(viewBoxRect, width, height) {
  22168. var scaleX = width / viewBoxRect.width;
  22169. var scaleY = height / viewBoxRect.height;
  22170. var scale = Math.min(scaleX, scaleY); // preserveAspectRatio 'xMidYMid'
  22171. var viewBoxScale = [scale, scale];
  22172. var viewBoxPosition = [-(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2, -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2];
  22173. return {
  22174. scale: viewBoxScale,
  22175. position: viewBoxPosition
  22176. };
  22177. }
  22178. /**
  22179. * @param {string|XMLElement} xml
  22180. * @param {Object} [opt]
  22181. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  22182. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  22183. * @param {boolean} [opt.ignoreViewBox]
  22184. * @param {boolean} [opt.ignoreRootClip]
  22185. * @return {Object} result:
  22186. * {
  22187. * root: Group, The root of the the result tree of zrender shapes,
  22188. * width: number, the viewport width of the SVG,
  22189. * height: number, the viewport height of the SVG,
  22190. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  22191. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  22192. * }
  22193. */
  22194. /*
  22195. * Licensed to the Apache Software Foundation (ASF) under one
  22196. * or more contributor license agreements. See the NOTICE file
  22197. * distributed with this work for additional information
  22198. * regarding copyright ownership. The ASF licenses this file
  22199. * to you under the Apache License, Version 2.0 (the
  22200. * "License"); you may not use this file except in compliance
  22201. * with the License. You may obtain a copy of the License at
  22202. *
  22203. * http://www.apache.org/licenses/LICENSE-2.0
  22204. *
  22205. * Unless required by applicable law or agreed to in writing,
  22206. * software distributed under the License is distributed on an
  22207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22208. * KIND, either express or implied. See the License for the
  22209. * specific language governing permissions and limitations
  22210. * under the License.
  22211. */
  22212. var storage = createHashMap(); // For minimize the code size of common echarts package,
  22213. // do not put too much logic in this module.
  22214. var mapDataStorage = {
  22215. // The format of record: see `echarts.registerMap`.
  22216. // Compatible with previous `echarts.registerMap`.
  22217. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  22218. var records;
  22219. if (isArray(rawGeoJson)) {
  22220. records = rawGeoJson;
  22221. } else if (rawGeoJson.svg) {
  22222. records = [{
  22223. type: 'svg',
  22224. source: rawGeoJson.svg,
  22225. specialAreas: rawGeoJson.specialAreas
  22226. }];
  22227. } else {
  22228. // Backward compatibility.
  22229. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  22230. rawSpecialAreas = rawGeoJson.specialAreas;
  22231. rawGeoJson = rawGeoJson.geoJson;
  22232. }
  22233. records = [{
  22234. type: 'geoJSON',
  22235. source: rawGeoJson,
  22236. specialAreas: rawSpecialAreas
  22237. }];
  22238. }
  22239. each$1(records, function (record) {
  22240. var type = record.type;
  22241. type === 'geoJson' && (type = record.type = 'geoJSON');
  22242. var parse = parsers[type];
  22243. parse(record);
  22244. });
  22245. return storage.set(mapName, records);
  22246. },
  22247. retrieveMap: function (mapName) {
  22248. return storage.get(mapName);
  22249. }
  22250. };
  22251. var parsers = {
  22252. geoJSON: function (record) {
  22253. var source = record.source;
  22254. record.geoJSON = !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  22255. },
  22256. // Only perform parse to XML object here, which might be time
  22257. // consiming for large SVG.
  22258. // Although convert XML to zrender element is also time consiming,
  22259. // if we do it here, the clone of zrender elements has to be
  22260. // required. So we do it once for each geo instance, util real
  22261. // performance issues call for optimizing it.
  22262. svg: function (record) {
  22263. record.svgXML = parseXML(record.source);
  22264. }
  22265. };
  22266. /*
  22267. * Licensed to the Apache Software Foundation (ASF) under one
  22268. * or more contributor license agreements. See the NOTICE file
  22269. * distributed with this work for additional information
  22270. * regarding copyright ownership. The ASF licenses this file
  22271. * to you under the Apache License, Version 2.0 (the
  22272. * "License"); you may not use this file except in compliance
  22273. * with the License. You may obtain a copy of the License at
  22274. *
  22275. * http://www.apache.org/licenses/LICENSE-2.0
  22276. *
  22277. * Unless required by applicable law or agreed to in writing,
  22278. * software distributed under the License is distributed on an
  22279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22280. * KIND, either express or implied. See the License for the
  22281. * specific language governing permissions and limitations
  22282. * under the License.
  22283. */
  22284. var assert = assert$1;
  22285. var each = each$1;
  22286. var isFunction = isFunction$1;
  22287. var isObject = isObject$1;
  22288. var parseClassType = ComponentModel.parseClassType;
  22289. var version = '4.8.0';
  22290. var dependencies = {
  22291. zrender: '4.3.1'
  22292. };
  22293. var TEST_FRAME_REMAIN_TIME = 1;
  22294. var PRIORITY_PROCESSOR_FILTER = 1000;
  22295. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  22296. var PRIORITY_PROCESSOR_DATASTACK = 900;
  22297. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  22298. var PRIORITY_VISUAL_LAYOUT = 1000;
  22299. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  22300. var PRIORITY_VISUAL_GLOBAL = 2000;
  22301. var PRIORITY_VISUAL_CHART = 3000;
  22302. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  22303. var PRIORITY_VISUAL_COMPONENT = 4000; // FIXME
  22304. // necessary?
  22305. var PRIORITY_VISUAL_BRUSH = 5000;
  22306. var PRIORITY = {
  22307. PROCESSOR: {
  22308. FILTER: PRIORITY_PROCESSOR_FILTER,
  22309. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  22310. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  22311. },
  22312. VISUAL: {
  22313. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  22314. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  22315. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  22316. CHART: PRIORITY_VISUAL_CHART,
  22317. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  22318. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  22319. BRUSH: PRIORITY_VISUAL_BRUSH
  22320. }
  22321. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  22322. // where they must not be invoked nestedly, except the only case: invoke
  22323. // dispatchAction with updateMethod "none" in main process.
  22324. // This flag is used to carry out this rule.
  22325. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  22326. var IN_MAIN_PROCESS = '__flagInMainProcess';
  22327. var OPTION_UPDATED = '__optionUpdated';
  22328. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  22329. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  22330. return function (eventName, handler, context) {
  22331. if (!ignoreDisposed && this._disposed) {
  22332. return;
  22333. } // Event name is all lowercase
  22334. eventName = eventName && eventName.toLowerCase();
  22335. Eventful.prototype[method].call(this, eventName, handler, context);
  22336. };
  22337. }
  22338. /**
  22339. * @module echarts~MessageCenter
  22340. */
  22341. function MessageCenter() {
  22342. Eventful.call(this);
  22343. }
  22344. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  22345. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  22346. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  22347. mixin(MessageCenter, Eventful);
  22348. /**
  22349. * @module echarts~ECharts
  22350. */
  22351. function ECharts(dom, theme$$1, opts) {
  22352. opts = opts || {}; // Get theme by name
  22353. if (typeof theme$$1 === 'string') {
  22354. theme$$1 = themeStorage[theme$$1];
  22355. }
  22356. /**
  22357. * @type {string}
  22358. */
  22359. this.id;
  22360. /**
  22361. * Group id
  22362. * @type {string}
  22363. */
  22364. this.group;
  22365. /**
  22366. * @type {HTMLElement}
  22367. * @private
  22368. */
  22369. this._dom = dom;
  22370. var defaultRenderer = 'canvas';
  22371. /**
  22372. * @type {module:zrender/ZRender}
  22373. * @private
  22374. */
  22375. var zr = this._zr = init$1(dom, {
  22376. renderer: opts.renderer || defaultRenderer,
  22377. devicePixelRatio: opts.devicePixelRatio,
  22378. width: opts.width,
  22379. height: opts.height
  22380. });
  22381. /**
  22382. * Expect 60 fps.
  22383. * @type {Function}
  22384. * @private
  22385. */
  22386. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  22387. var theme$$1 = clone(theme$$1);
  22388. theme$$1 && backwardCompat(theme$$1, true);
  22389. /**
  22390. * @type {Object}
  22391. * @private
  22392. */
  22393. this._theme = theme$$1;
  22394. /**
  22395. * @type {Array.<module:echarts/view/Chart>}
  22396. * @private
  22397. */
  22398. this._chartsViews = [];
  22399. /**
  22400. * @type {Object.<string, module:echarts/view/Chart>}
  22401. * @private
  22402. */
  22403. this._chartsMap = {};
  22404. /**
  22405. * @type {Array.<module:echarts/view/Component>}
  22406. * @private
  22407. */
  22408. this._componentsViews = [];
  22409. /**
  22410. * @type {Object.<string, module:echarts/view/Component>}
  22411. * @private
  22412. */
  22413. this._componentsMap = {};
  22414. /**
  22415. * @type {module:echarts/CoordinateSystem}
  22416. * @private
  22417. */
  22418. this._coordSysMgr = new CoordinateSystemManager();
  22419. /**
  22420. * @type {module:echarts/ExtensionAPI}
  22421. * @private
  22422. */
  22423. var api = this._api = createExtensionAPI(this); // Sort on demand
  22424. function prioritySortFunc(a, b) {
  22425. return a.__prio - b.__prio;
  22426. }
  22427. sort(visualFuncs, prioritySortFunc);
  22428. sort(dataProcessorFuncs, prioritySortFunc);
  22429. /**
  22430. * @type {module:echarts/stream/Scheduler}
  22431. */
  22432. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22433. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  22434. /**
  22435. * @type {module:echarts~MessageCenter}
  22436. * @private
  22437. */
  22438. this._messageCenter = new MessageCenter(); // Init mouse events
  22439. this._initEvents(); // In case some people write `window.onresize = chart.resize`
  22440. this.resize = bind(this.resize, this); // Can't dispatch action during rendering procedure
  22441. this._pendingActions = [];
  22442. zr.animation.on('frame', this._onframe, this);
  22443. bindRenderedEvent(zr, this); // ECharts instance can be used as value.
  22444. setAsPrimitive(this);
  22445. }
  22446. var echartsProto = ECharts.prototype;
  22447. echartsProto._onframe = function () {
  22448. if (this._disposed) {
  22449. return;
  22450. }
  22451. var scheduler = this._scheduler; // Lazy update
  22452. if (this[OPTION_UPDATED]) {
  22453. var silent = this[OPTION_UPDATED].silent;
  22454. this[IN_MAIN_PROCESS] = true;
  22455. prepare(this);
  22456. updateMethods.update.call(this);
  22457. this[IN_MAIN_PROCESS] = false;
  22458. this[OPTION_UPDATED] = false;
  22459. flushPendingActions.call(this, silent);
  22460. triggerUpdatedEvent.call(this, silent);
  22461. } // Avoid do both lazy update and progress in one frame.
  22462. else if (scheduler.unfinished) {
  22463. // Stream progress.
  22464. var remainTime = TEST_FRAME_REMAIN_TIME;
  22465. var ecModel = this._model;
  22466. var api = this._api;
  22467. scheduler.unfinished = false;
  22468. do {
  22469. var startTime = +new Date();
  22470. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  22471. scheduler.performDataProcessorTasks(ecModel);
  22472. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  22473. // each frame is not a good user experience. So we follow the rule that
  22474. // the extent of the coordinate system is determin in the first frame (the
  22475. // frame is executed immedietely after task reset.
  22476. // this._coordSysMgr.update(ecModel, api);
  22477. // console.log('--- ec frame visual ---', remainTime);
  22478. scheduler.performVisualTasks(ecModel);
  22479. renderSeries(this, this._model, api, 'remain');
  22480. remainTime -= +new Date() - startTime;
  22481. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  22482. if (!scheduler.unfinished) {
  22483. this._zr.flush();
  22484. } // Else, zr flushing be ensue within the same frame,
  22485. // because zr flushing is after onframe event.
  22486. }
  22487. };
  22488. /**
  22489. * @return {HTMLElement}
  22490. */
  22491. echartsProto.getDom = function () {
  22492. return this._dom;
  22493. };
  22494. /**
  22495. * @return {module:zrender~ZRender}
  22496. */
  22497. echartsProto.getZr = function () {
  22498. return this._zr;
  22499. };
  22500. /**
  22501. * Usage:
  22502. * chart.setOption(option, notMerge, lazyUpdate);
  22503. * chart.setOption(option, {
  22504. * notMerge: ...,
  22505. * lazyUpdate: ...,
  22506. * silent: ...
  22507. * });
  22508. *
  22509. * @param {Object} option
  22510. * @param {Object|boolean} [opts] opts or notMerge.
  22511. * @param {boolean} [opts.notMerge=false]
  22512. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22513. */
  22514. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  22515. if (this._disposed) {
  22516. return;
  22517. }
  22518. var silent;
  22519. if (isObject(notMerge)) {
  22520. lazyUpdate = notMerge.lazyUpdate;
  22521. silent = notMerge.silent;
  22522. notMerge = notMerge.notMerge;
  22523. }
  22524. this[IN_MAIN_PROCESS] = true;
  22525. if (!this._model || notMerge) {
  22526. var optionManager = new OptionManager(this._api);
  22527. var theme$$1 = this._theme;
  22528. var ecModel = this._model = new GlobalModel();
  22529. ecModel.scheduler = this._scheduler;
  22530. ecModel.init(null, null, theme$$1, optionManager);
  22531. }
  22532. this._model.setOption(option, optionPreprocessorFuncs);
  22533. if (lazyUpdate) {
  22534. this[OPTION_UPDATED] = {
  22535. silent: silent
  22536. };
  22537. this[IN_MAIN_PROCESS] = false;
  22538. } else {
  22539. prepare(this);
  22540. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  22541. // fetched after `setOption`.
  22542. this._zr.flush();
  22543. this[OPTION_UPDATED] = false;
  22544. this[IN_MAIN_PROCESS] = false;
  22545. flushPendingActions.call(this, silent);
  22546. triggerUpdatedEvent.call(this, silent);
  22547. }
  22548. };
  22549. /**
  22550. * @DEPRECATED
  22551. */
  22552. echartsProto.setTheme = function () {
  22553. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22554. };
  22555. /**
  22556. * @return {module:echarts/model/Global}
  22557. */
  22558. echartsProto.getModel = function () {
  22559. return this._model;
  22560. };
  22561. /**
  22562. * @return {Object}
  22563. */
  22564. echartsProto.getOption = function () {
  22565. return this._model && this._model.getOption();
  22566. };
  22567. /**
  22568. * @return {number}
  22569. */
  22570. echartsProto.getWidth = function () {
  22571. return this._zr.getWidth();
  22572. };
  22573. /**
  22574. * @return {number}
  22575. */
  22576. echartsProto.getHeight = function () {
  22577. return this._zr.getHeight();
  22578. };
  22579. /**
  22580. * @return {number}
  22581. */
  22582. echartsProto.getDevicePixelRatio = function () {
  22583. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  22584. };
  22585. /**
  22586. * Get canvas which has all thing rendered
  22587. * @param {Object} opts
  22588. * @param {string} [opts.backgroundColor]
  22589. * @return {string}
  22590. */
  22591. echartsProto.getRenderedCanvas = function (opts) {
  22592. if (!env$1.canvasSupported) {
  22593. return;
  22594. }
  22595. opts = opts || {};
  22596. opts.pixelRatio = opts.pixelRatio || 1;
  22597. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  22598. var zr = this._zr; // var list = zr.storage.getDisplayList();
  22599. // Stop animations
  22600. // Never works before in init animation, so remove it.
  22601. // zrUtil.each(list, function (el) {
  22602. // el.stopAnimation(true);
  22603. // });
  22604. return zr.painter.getRenderedCanvas(opts);
  22605. };
  22606. /**
  22607. * Get svg data url
  22608. * @return {string}
  22609. */
  22610. echartsProto.getSvgDataURL = function () {
  22611. if (!env$1.svgSupported) {
  22612. return;
  22613. }
  22614. var zr = this._zr;
  22615. var list = zr.storage.getDisplayList(); // Stop animations
  22616. each$1(list, function (el) {
  22617. el.stopAnimation(true);
  22618. });
  22619. return zr.painter.toDataURL();
  22620. };
  22621. /**
  22622. * @return {string}
  22623. * @param {Object} opts
  22624. * @param {string} [opts.type='png']
  22625. * @param {string} [opts.pixelRatio=1]
  22626. * @param {string} [opts.backgroundColor]
  22627. * @param {string} [opts.excludeComponents]
  22628. */
  22629. echartsProto.getDataURL = function (opts) {
  22630. if (this._disposed) {
  22631. return;
  22632. }
  22633. opts = opts || {};
  22634. var excludeComponents = opts.excludeComponents;
  22635. var ecModel = this._model;
  22636. var excludesComponentViews = [];
  22637. var self = this;
  22638. each(excludeComponents, function (componentType) {
  22639. ecModel.eachComponent({
  22640. mainType: componentType
  22641. }, function (component) {
  22642. var view = self._componentsMap[component.__viewId];
  22643. if (!view.group.ignore) {
  22644. excludesComponentViews.push(view);
  22645. view.group.ignore = true;
  22646. }
  22647. });
  22648. });
  22649. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  22650. each(excludesComponentViews, function (view) {
  22651. view.group.ignore = false;
  22652. });
  22653. return url;
  22654. };
  22655. /**
  22656. * @return {string}
  22657. * @param {Object} opts
  22658. * @param {string} [opts.type='png']
  22659. * @param {string} [opts.pixelRatio=1]
  22660. * @param {string} [opts.backgroundColor]
  22661. */
  22662. echartsProto.getConnectedDataURL = function (opts) {
  22663. if (this._disposed) {
  22664. return;
  22665. }
  22666. if (!env$1.canvasSupported) {
  22667. return;
  22668. }
  22669. var isSvg = opts.type === 'svg';
  22670. var groupId = this.group;
  22671. var mathMin = Math.min;
  22672. var mathMax = Math.max;
  22673. var MAX_NUMBER = Infinity;
  22674. if (connectedGroups[groupId]) {
  22675. var left = MAX_NUMBER;
  22676. var top = MAX_NUMBER;
  22677. var right = -MAX_NUMBER;
  22678. var bottom = -MAX_NUMBER;
  22679. var canvasList = [];
  22680. var dpr = opts && opts.pixelRatio || 1;
  22681. each$1(instances, function (chart, id) {
  22682. if (chart.group === groupId) {
  22683. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  22684. var boundingRect = chart.getDom().getBoundingClientRect();
  22685. left = mathMin(boundingRect.left, left);
  22686. top = mathMin(boundingRect.top, top);
  22687. right = mathMax(boundingRect.right, right);
  22688. bottom = mathMax(boundingRect.bottom, bottom);
  22689. canvasList.push({
  22690. dom: canvas,
  22691. left: boundingRect.left,
  22692. top: boundingRect.top
  22693. });
  22694. }
  22695. });
  22696. left *= dpr;
  22697. top *= dpr;
  22698. right *= dpr;
  22699. bottom *= dpr;
  22700. var width = right - left;
  22701. var height = bottom - top;
  22702. var targetCanvas = createCanvas();
  22703. var zr = init$1(targetCanvas, {
  22704. renderer: isSvg ? 'svg' : 'canvas'
  22705. });
  22706. zr.resize({
  22707. width: width,
  22708. height: height
  22709. });
  22710. if (isSvg) {
  22711. var content = '';
  22712. each(canvasList, function (item) {
  22713. var x = item.left - left;
  22714. var y = item.top - top;
  22715. content += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  22716. });
  22717. zr.painter.getSvgRoot().innerHTML = content;
  22718. if (opts.connectedBackgroundColor) {
  22719. zr.painter.setBackgroundColor(opts.connectedBackgroundColor);
  22720. }
  22721. zr.refreshImmediately();
  22722. return zr.painter.toDataURL();
  22723. } else {
  22724. // Background between the charts
  22725. if (opts.connectedBackgroundColor) {
  22726. zr.add(new Rect({
  22727. shape: {
  22728. x: 0,
  22729. y: 0,
  22730. width: width,
  22731. height: height
  22732. },
  22733. style: {
  22734. fill: opts.connectedBackgroundColor
  22735. }
  22736. }));
  22737. }
  22738. each(canvasList, function (item) {
  22739. var img = new ZImage({
  22740. style: {
  22741. x: item.left * dpr - left,
  22742. y: item.top * dpr - top,
  22743. image: item.dom
  22744. }
  22745. });
  22746. zr.add(img);
  22747. });
  22748. zr.refreshImmediately();
  22749. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  22750. }
  22751. } else {
  22752. return this.getDataURL(opts);
  22753. }
  22754. };
  22755. /**
  22756. * Convert from logical coordinate system to pixel coordinate system.
  22757. * See CoordinateSystem#convertToPixel.
  22758. * @param {string|Object} finder
  22759. * If string, e.g., 'geo', means {geoIndex: 0}.
  22760. * If Object, could contain some of these properties below:
  22761. * {
  22762. * seriesIndex / seriesId / seriesName,
  22763. * geoIndex / geoId, geoName,
  22764. * bmapIndex / bmapId / bmapName,
  22765. * xAxisIndex / xAxisId / xAxisName,
  22766. * yAxisIndex / yAxisId / yAxisName,
  22767. * gridIndex / gridId / gridName,
  22768. * ... (can be extended)
  22769. * }
  22770. * @param {Array|number} value
  22771. * @return {Array|number} result
  22772. */
  22773. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  22774. /**
  22775. * Convert from pixel coordinate system to logical coordinate system.
  22776. * See CoordinateSystem#convertFromPixel.
  22777. * @param {string|Object} finder
  22778. * If string, e.g., 'geo', means {geoIndex: 0}.
  22779. * If Object, could contain some of these properties below:
  22780. * {
  22781. * seriesIndex / seriesId / seriesName,
  22782. * geoIndex / geoId / geoName,
  22783. * bmapIndex / bmapId / bmapName,
  22784. * xAxisIndex / xAxisId / xAxisName,
  22785. * yAxisIndex / yAxisId / yAxisName
  22786. * gridIndex / gridId / gridName,
  22787. * ... (can be extended)
  22788. * }
  22789. * @param {Array|number} value
  22790. * @return {Array|number} result
  22791. */
  22792. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  22793. function doConvertPixel(methodName, finder, value) {
  22794. if (this._disposed) {
  22795. return;
  22796. }
  22797. var ecModel = this._model;
  22798. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  22799. var result;
  22800. finder = parseFinder(ecModel, finder);
  22801. for (var i = 0; i < coordSysList.length; i++) {
  22802. var coordSys = coordSysList[i];
  22803. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, finder, value)) != null) {
  22804. return result;
  22805. }
  22806. }
  22807. }
  22808. /**
  22809. * Is the specified coordinate systems or components contain the given pixel point.
  22810. * @param {string|Object} finder
  22811. * If string, e.g., 'geo', means {geoIndex: 0}.
  22812. * If Object, could contain some of these properties below:
  22813. * {
  22814. * seriesIndex / seriesId / seriesName,
  22815. * geoIndex / geoId / geoName,
  22816. * bmapIndex / bmapId / bmapName,
  22817. * xAxisIndex / xAxisId / xAxisName,
  22818. * yAxisIndex / yAxisId / yAxisName,
  22819. * gridIndex / gridId / gridName,
  22820. * ... (can be extended)
  22821. * }
  22822. * @param {Array|number} value
  22823. * @return {boolean} result
  22824. */
  22825. echartsProto.containPixel = function (finder, value) {
  22826. if (this._disposed) {
  22827. return;
  22828. }
  22829. var ecModel = this._model;
  22830. var result;
  22831. finder = parseFinder(ecModel, finder);
  22832. each$1(finder, function (models, key) {
  22833. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  22834. var coordSys = model.coordinateSystem;
  22835. if (coordSys && coordSys.containPoint) {
  22836. result |= !!coordSys.containPoint(value);
  22837. } else if (key === 'seriesModels') {
  22838. var view = this._chartsMap[model.__viewId];
  22839. if (view && view.containPoint) {
  22840. result |= view.containPoint(value, model);
  22841. } else {}
  22842. } else {}
  22843. }, this);
  22844. }, this);
  22845. return !!result;
  22846. };
  22847. /**
  22848. * Get visual from series or data.
  22849. * @param {string|Object} finder
  22850. * If string, e.g., 'series', means {seriesIndex: 0}.
  22851. * If Object, could contain some of these properties below:
  22852. * {
  22853. * seriesIndex / seriesId / seriesName,
  22854. * dataIndex / dataIndexInside
  22855. * }
  22856. * If dataIndex is not specified, series visual will be fetched,
  22857. * but not data item visual.
  22858. * If all of seriesIndex, seriesId, seriesName are not specified,
  22859. * visual will be fetched from first series.
  22860. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  22861. */
  22862. echartsProto.getVisual = function (finder, visualType) {
  22863. var ecModel = this._model;
  22864. finder = parseFinder(ecModel, finder, {
  22865. defaultMainType: 'series'
  22866. });
  22867. var seriesModel = finder.seriesModel;
  22868. var data = seriesModel.getData();
  22869. var dataIndexInside = finder.hasOwnProperty('dataIndexInside') ? finder.dataIndexInside : finder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(finder.dataIndex) : null;
  22870. return dataIndexInside != null ? data.getItemVisual(dataIndexInside, visualType) : data.getVisual(visualType);
  22871. };
  22872. /**
  22873. * Get view of corresponding component model
  22874. * @param {module:echarts/model/Component} componentModel
  22875. * @return {module:echarts/view/Component}
  22876. */
  22877. echartsProto.getViewOfComponentModel = function (componentModel) {
  22878. return this._componentsMap[componentModel.__viewId];
  22879. };
  22880. /**
  22881. * Get view of corresponding series model
  22882. * @param {module:echarts/model/Series} seriesModel
  22883. * @return {module:echarts/view/Chart}
  22884. */
  22885. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  22886. return this._chartsMap[seriesModel.__viewId];
  22887. };
  22888. var updateMethods = {
  22889. prepareAndUpdate: function (payload) {
  22890. prepare(this);
  22891. updateMethods.update.call(this, payload);
  22892. },
  22893. /**
  22894. * @param {Object} payload
  22895. * @private
  22896. */
  22897. update: function (payload) {
  22898. // console.profile && console.profile('update');
  22899. var ecModel = this._model;
  22900. var api = this._api;
  22901. var zr = this._zr;
  22902. var coordSysMgr = this._coordSysMgr;
  22903. var scheduler = this._scheduler; // update before setOption
  22904. if (!ecModel) {
  22905. return;
  22906. }
  22907. scheduler.restoreData(ecModel, payload);
  22908. scheduler.performSeriesTasks(ecModel); // TODO
  22909. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  22910. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  22911. // Create new coordinate system each update
  22912. // In LineView may save the old coordinate system and use it to get the orignal point
  22913. coordSysMgr.create(ecModel, api);
  22914. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  22915. // stream modes after data processing, where the filtered data is used to
  22916. // deteming whether use progressive rendering.
  22917. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  22918. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  22919. // the drawback is the full coord info can not be fetched. Fortunately this full
  22920. // coord is not requied in stream mode updater currently.
  22921. coordSysMgr.update(ecModel, api);
  22922. clearColorPalette(ecModel);
  22923. scheduler.performVisualTasks(ecModel, payload);
  22924. render(this, ecModel, api, payload); // Set background
  22925. var backgroundColor = ecModel.get('backgroundColor') || 'transparent'; // In IE8
  22926. if (!env$1.canvasSupported) {
  22927. var colorArr = parse(backgroundColor);
  22928. backgroundColor = stringify(colorArr, 'rgb');
  22929. if (colorArr[3] === 0) {
  22930. backgroundColor = 'transparent';
  22931. }
  22932. } else {
  22933. zr.setBackgroundColor(backgroundColor);
  22934. }
  22935. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  22936. },
  22937. /**
  22938. * @param {Object} payload
  22939. * @private
  22940. */
  22941. updateTransform: function (payload) {
  22942. var ecModel = this._model;
  22943. var ecIns = this;
  22944. var api = this._api; // update before setOption
  22945. if (!ecModel) {
  22946. return;
  22947. } // ChartView.markUpdateMethod(payload, 'updateTransform');
  22948. var componentDirtyList = [];
  22949. ecModel.eachComponent(function (componentType, componentModel) {
  22950. var componentView = ecIns.getViewOfComponentModel(componentModel);
  22951. if (componentView && componentView.__alive) {
  22952. if (componentView.updateTransform) {
  22953. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  22954. result && result.update && componentDirtyList.push(componentView);
  22955. } else {
  22956. componentDirtyList.push(componentView);
  22957. }
  22958. }
  22959. });
  22960. var seriesDirtyMap = createHashMap();
  22961. ecModel.eachSeries(function (seriesModel) {
  22962. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22963. if (chartView.updateTransform) {
  22964. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  22965. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  22966. } else {
  22967. seriesDirtyMap.set(seriesModel.uid, 1);
  22968. }
  22969. });
  22970. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22971. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22972. this._scheduler.performVisualTasks(ecModel, payload, {
  22973. setDirty: true,
  22974. dirtyMap: seriesDirtyMap
  22975. }); // Currently, not call render of components. Geo render cost a lot.
  22976. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  22977. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  22978. performPostUpdateFuncs(ecModel, this._api);
  22979. },
  22980. /**
  22981. * @param {Object} payload
  22982. * @private
  22983. */
  22984. updateView: function (payload) {
  22985. var ecModel = this._model; // update before setOption
  22986. if (!ecModel) {
  22987. return;
  22988. }
  22989. Chart.markUpdateMethod(payload, 'updateView');
  22990. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22991. this._scheduler.performVisualTasks(ecModel, payload, {
  22992. setDirty: true
  22993. });
  22994. render(this, this._model, this._api, payload);
  22995. performPostUpdateFuncs(ecModel, this._api);
  22996. },
  22997. /**
  22998. * @param {Object} payload
  22999. * @private
  23000. */
  23001. updateVisual: function (payload) {
  23002. updateMethods.update.call(this, payload); // var ecModel = this._model;
  23003. // // update before setOption
  23004. // if (!ecModel) {
  23005. // return;
  23006. // }
  23007. // ChartView.markUpdateMethod(payload, 'updateVisual');
  23008. // clearColorPalette(ecModel);
  23009. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23010. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  23011. // render(this, this._model, this._api, payload);
  23012. // performPostUpdateFuncs(ecModel, this._api);
  23013. },
  23014. /**
  23015. * @param {Object} payload
  23016. * @private
  23017. */
  23018. updateLayout: function (payload) {
  23019. updateMethods.update.call(this, payload); // var ecModel = this._model;
  23020. // // update before setOption
  23021. // if (!ecModel) {
  23022. // return;
  23023. // }
  23024. // ChartView.markUpdateMethod(payload, 'updateLayout');
  23025. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23026. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23027. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23028. // render(this, this._model, this._api, payload);
  23029. // performPostUpdateFuncs(ecModel, this._api);
  23030. }
  23031. };
  23032. function prepare(ecIns) {
  23033. var ecModel = ecIns._model;
  23034. var scheduler = ecIns._scheduler;
  23035. scheduler.restorePipelines(ecModel);
  23036. scheduler.prepareStageTasks();
  23037. prepareView(ecIns, 'component', ecModel, scheduler);
  23038. prepareView(ecIns, 'chart', ecModel, scheduler);
  23039. scheduler.plan();
  23040. }
  23041. /**
  23042. * @private
  23043. */
  23044. function updateDirectly(ecIns, method, payload, mainType, subType) {
  23045. var ecModel = ecIns._model; // broadcast
  23046. if (!mainType) {
  23047. // FIXME
  23048. // Chart will not be update directly here, except set dirty.
  23049. // But there is no such scenario now.
  23050. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  23051. return;
  23052. }
  23053. var query = {};
  23054. query[mainType + 'Id'] = payload[mainType + 'Id'];
  23055. query[mainType + 'Index'] = payload[mainType + 'Index'];
  23056. query[mainType + 'Name'] = payload[mainType + 'Name'];
  23057. var condition = {
  23058. mainType: mainType,
  23059. query: query
  23060. };
  23061. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  23062. var excludeSeriesId = payload.excludeSeriesId;
  23063. if (excludeSeriesId != null) {
  23064. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  23065. } // If dispatchAction before setOption, do nothing.
  23066. ecModel && ecModel.eachComponent(condition, function (model) {
  23067. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  23068. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  23069. }
  23070. }, ecIns);
  23071. function callView(view) {
  23072. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  23073. }
  23074. }
  23075. /**
  23076. * Resize the chart
  23077. * @param {Object} opts
  23078. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  23079. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  23080. * @param {boolean} [opts.silent=false]
  23081. */
  23082. echartsProto.resize = function (opts) {
  23083. if (this._disposed) {
  23084. return;
  23085. }
  23086. this._zr.resize(opts);
  23087. var ecModel = this._model; // Resize loading effect
  23088. this._loadingFX && this._loadingFX.resize();
  23089. if (!ecModel) {
  23090. return;
  23091. }
  23092. var optionChanged = ecModel.resetOption('media');
  23093. var silent = opts && opts.silent;
  23094. this[IN_MAIN_PROCESS] = true;
  23095. optionChanged && prepare(this);
  23096. updateMethods.update.call(this);
  23097. this[IN_MAIN_PROCESS] = false;
  23098. flushPendingActions.call(this, silent);
  23099. triggerUpdatedEvent.call(this, silent);
  23100. };
  23101. function updateStreamModes(ecIns, ecModel) {
  23102. var chartsMap = ecIns._chartsMap;
  23103. var scheduler = ecIns._scheduler;
  23104. ecModel.eachSeries(function (seriesModel) {
  23105. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  23106. });
  23107. }
  23108. /**
  23109. * Show loading effect
  23110. * @param {string} [name='default']
  23111. * @param {Object} [cfg]
  23112. */
  23113. echartsProto.showLoading = function (name, cfg) {
  23114. if (this._disposed) {
  23115. return;
  23116. }
  23117. if (isObject(name)) {
  23118. cfg = name;
  23119. name = '';
  23120. }
  23121. name = name || 'default';
  23122. this.hideLoading();
  23123. if (!loadingEffects[name]) {
  23124. return;
  23125. }
  23126. var el = loadingEffects[name](this._api, cfg);
  23127. var zr = this._zr;
  23128. this._loadingFX = el;
  23129. zr.add(el);
  23130. };
  23131. /**
  23132. * Hide loading effect
  23133. */
  23134. echartsProto.hideLoading = function () {
  23135. if (this._disposed) {
  23136. return;
  23137. }
  23138. this._loadingFX && this._zr.remove(this._loadingFX);
  23139. this._loadingFX = null;
  23140. };
  23141. /**
  23142. * @param {Object} eventObj
  23143. * @return {Object}
  23144. */
  23145. echartsProto.makeActionFromEvent = function (eventObj) {
  23146. var payload = extend({}, eventObj);
  23147. payload.type = eventActionMap[eventObj.type];
  23148. return payload;
  23149. };
  23150. /**
  23151. * @pubilc
  23152. * @param {Object} payload
  23153. * @param {string} [payload.type] Action type
  23154. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  23155. * @param {boolean} [opt.silent=false] Whether trigger events.
  23156. * @param {boolean} [opt.flush=undefined]
  23157. * true: Flush immediately, and then pixel in canvas can be fetched
  23158. * immediately. Caution: it might affect performance.
  23159. * false: Not flush.
  23160. * undefined: Auto decide whether perform flush.
  23161. */
  23162. echartsProto.dispatchAction = function (payload, opt) {
  23163. if (this._disposed) {
  23164. return;
  23165. }
  23166. if (!isObject(opt)) {
  23167. opt = {
  23168. silent: !!opt
  23169. };
  23170. }
  23171. if (!actions[payload.type]) {
  23172. return;
  23173. } // Avoid dispatch action before setOption. Especially in `connect`.
  23174. if (!this._model) {
  23175. return;
  23176. } // May dispatchAction in rendering procedure
  23177. if (this[IN_MAIN_PROCESS]) {
  23178. this._pendingActions.push(payload);
  23179. return;
  23180. }
  23181. doDispatchAction.call(this, payload, opt.silent);
  23182. if (opt.flush) {
  23183. this._zr.flush(true);
  23184. } else if (opt.flush !== false && env$1.browser.weChat) {
  23185. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  23186. // hang when sliding page (on touch event), which cause that zr does not
  23187. // refresh util user interaction finished, which is not expected.
  23188. // But `dispatchAction` may be called too frequently when pan on touch
  23189. // screen, which impacts performance if do not throttle them.
  23190. this._throttledZrFlush();
  23191. }
  23192. flushPendingActions.call(this, opt.silent);
  23193. triggerUpdatedEvent.call(this, opt.silent);
  23194. };
  23195. function doDispatchAction(payload, silent) {
  23196. var payloadType = payload.type;
  23197. var escapeConnect = payload.escapeConnect;
  23198. var actionWrap = actions[payloadType];
  23199. var actionInfo = actionWrap.actionInfo;
  23200. var cptType = (actionInfo.update || 'update').split(':');
  23201. var updateMethod = cptType.pop();
  23202. cptType = cptType[0] != null && parseClassType(cptType[0]);
  23203. this[IN_MAIN_PROCESS] = true;
  23204. var payloads = [payload];
  23205. var batched = false; // Batch action
  23206. if (payload.batch) {
  23207. batched = true;
  23208. payloads = map(payload.batch, function (item) {
  23209. item = defaults(extend({}, item), payload);
  23210. item.batch = null;
  23211. return item;
  23212. });
  23213. }
  23214. var eventObjBatch = [];
  23215. var eventObj;
  23216. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  23217. each(payloads, function (batchItem) {
  23218. // Action can specify the event by return it.
  23219. eventObj = actionWrap.action(batchItem, this._model, this._api); // Emit event outside
  23220. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  23221. eventObj.type = actionInfo.event || eventObj.type;
  23222. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  23223. if (isHighDown) {
  23224. // method, payload, mainType, subType
  23225. updateDirectly(this, updateMethod, batchItem, 'series');
  23226. } else if (cptType) {
  23227. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  23228. }
  23229. }, this);
  23230. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  23231. // Still dirty
  23232. if (this[OPTION_UPDATED]) {
  23233. // FIXME Pass payload ?
  23234. prepare(this);
  23235. updateMethods.update.call(this, payload);
  23236. this[OPTION_UPDATED] = false;
  23237. } else {
  23238. updateMethods[updateMethod].call(this, payload);
  23239. }
  23240. } // Follow the rule of action batch
  23241. if (batched) {
  23242. eventObj = {
  23243. type: actionInfo.event || payloadType,
  23244. escapeConnect: escapeConnect,
  23245. batch: eventObjBatch
  23246. };
  23247. } else {
  23248. eventObj = eventObjBatch[0];
  23249. }
  23250. this[IN_MAIN_PROCESS] = false;
  23251. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  23252. }
  23253. function flushPendingActions(silent) {
  23254. var pendingActions = this._pendingActions;
  23255. while (pendingActions.length) {
  23256. var payload = pendingActions.shift();
  23257. doDispatchAction.call(this, payload, silent);
  23258. }
  23259. }
  23260. function triggerUpdatedEvent(silent) {
  23261. !silent && this.trigger('updated');
  23262. }
  23263. /**
  23264. * Event `rendered` is triggered when zr
  23265. * rendered. It is useful for realtime
  23266. * snapshot (reflect animation).
  23267. *
  23268. * Event `finished` is triggered when:
  23269. * (1) zrender rendering finished.
  23270. * (2) initial animation finished.
  23271. * (3) progressive rendering finished.
  23272. * (4) no pending action.
  23273. * (5) no delayed setOption needs to be processed.
  23274. */
  23275. function bindRenderedEvent(zr, ecIns) {
  23276. zr.on('rendered', function () {
  23277. ecIns.trigger('rendered'); // The `finished` event should not be triggered repeatly,
  23278. // so it should only be triggered when rendering indeed happend
  23279. // in zrender. (Consider the case that dipatchAction is keep
  23280. // triggering when mouse move).
  23281. if ( // Although zr is dirty if initial animation is not finished
  23282. // and this checking is called on frame, we also check
  23283. // animation finished for robustness.
  23284. zr.animation.isFinished() && !ecIns[OPTION_UPDATED] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  23285. ecIns.trigger('finished');
  23286. }
  23287. });
  23288. }
  23289. /**
  23290. * @param {Object} params
  23291. * @param {number} params.seriesIndex
  23292. * @param {Array|TypedArray} params.data
  23293. */
  23294. echartsProto.appendData = function (params) {
  23295. if (this._disposed) {
  23296. return;
  23297. }
  23298. var seriesIndex = params.seriesIndex;
  23299. var ecModel = this.getModel();
  23300. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  23301. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  23302. // system, util some scenario require that. In the expected usage of
  23303. // `appendData`, the initial extent of coordinate system should better
  23304. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  23305. // the extent changed while `appendData`, the location of the painted
  23306. // graphic elements have to be changed, which make the usage of
  23307. // `appendData` meaningless.
  23308. this._scheduler.unfinished = true;
  23309. };
  23310. /**
  23311. * Register event
  23312. * @method
  23313. */
  23314. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  23315. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  23316. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  23317. /**
  23318. * Prepare view instances of charts and components
  23319. * @param {module:echarts/model/Global} ecModel
  23320. * @private
  23321. */
  23322. function prepareView(ecIns, type, ecModel, scheduler) {
  23323. var isComponent = type === 'component';
  23324. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  23325. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  23326. var zr = ecIns._zr;
  23327. var api = ecIns._api;
  23328. for (var i = 0; i < viewList.length; i++) {
  23329. viewList[i].__alive = false;
  23330. }
  23331. isComponent ? ecModel.eachComponent(function (componentType, model) {
  23332. componentType !== 'series' && doPrepare(model);
  23333. }) : ecModel.eachSeries(doPrepare);
  23334. function doPrepare(model) {
  23335. // Consider: id same and type changed.
  23336. var viewId = '_ec_' + model.id + '_' + model.type;
  23337. var view = viewMap[viewId];
  23338. if (!view) {
  23339. var classType = parseClassType(model.type);
  23340. var Clazz = isComponent ? Component$1.getClass(classType.main, classType.sub) : Chart.getClass(classType.sub);
  23341. view = new Clazz();
  23342. view.init(ecModel, api);
  23343. viewMap[viewId] = view;
  23344. viewList.push(view);
  23345. zr.add(view.group);
  23346. }
  23347. model.__viewId = view.__id = viewId;
  23348. view.__alive = true;
  23349. view.__model = model;
  23350. view.group.__ecComponentInfo = {
  23351. mainType: model.mainType,
  23352. index: model.componentIndex
  23353. };
  23354. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23355. }
  23356. for (var i = 0; i < viewList.length;) {
  23357. var view = viewList[i];
  23358. if (!view.__alive) {
  23359. !isComponent && view.renderTask.dispose();
  23360. zr.remove(view.group);
  23361. view.dispose(ecModel, api);
  23362. viewList.splice(i, 1);
  23363. delete viewMap[view.__id];
  23364. view.__id = view.group.__ecComponentInfo = null;
  23365. } else {
  23366. i++;
  23367. }
  23368. }
  23369. } // /**
  23370. // * Encode visual infomation from data after data processing
  23371. // *
  23372. // * @param {module:echarts/model/Global} ecModel
  23373. // * @param {object} layout
  23374. // * @param {boolean} [layoutFilter] `true`: only layout,
  23375. // * `false`: only not layout,
  23376. // * `null`/`undefined`: all.
  23377. // * @param {string} taskBaseTag
  23378. // * @private
  23379. // */
  23380. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23381. // each(visualFuncs, function (visual, index) {
  23382. // var isLayout = visual.isLayout;
  23383. // if (layoutFilter == null
  23384. // || (layoutFilter === false && !isLayout)
  23385. // || (layoutFilter === true && isLayout)
  23386. // ) {
  23387. // visual.func(ecModel, api, payload);
  23388. // }
  23389. // });
  23390. // }
  23391. function clearColorPalette(ecModel) {
  23392. ecModel.clearColorPalette();
  23393. ecModel.eachSeries(function (seriesModel) {
  23394. seriesModel.clearColorPalette();
  23395. });
  23396. }
  23397. function render(ecIns, ecModel, api, payload) {
  23398. renderComponents(ecIns, ecModel, api, payload);
  23399. each(ecIns._chartsViews, function (chart) {
  23400. chart.__alive = false;
  23401. });
  23402. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  23403. each(ecIns._chartsViews, function (chart) {
  23404. if (!chart.__alive) {
  23405. chart.remove(ecModel, api);
  23406. }
  23407. });
  23408. }
  23409. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23410. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23411. var componentModel = componentView.__model;
  23412. componentView.render(componentModel, ecModel, api, payload);
  23413. updateZ(componentModel, componentView);
  23414. });
  23415. }
  23416. /**
  23417. * Render each chart and component
  23418. * @private
  23419. */
  23420. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23421. // Render all charts
  23422. var scheduler = ecIns._scheduler;
  23423. var unfinished;
  23424. ecModel.eachSeries(function (seriesModel) {
  23425. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23426. chartView.__alive = true;
  23427. var renderTask = chartView.renderTask;
  23428. scheduler.updatePayload(renderTask, payload);
  23429. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23430. renderTask.dirty();
  23431. }
  23432. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23433. chartView.group.silent = !!seriesModel.get('silent');
  23434. updateZ(seriesModel, chartView);
  23435. updateBlend(seriesModel, chartView);
  23436. });
  23437. scheduler.unfinished |= unfinished; // If use hover layer
  23438. updateHoverLayerStatus(ecIns, ecModel); // Add aria
  23439. aria(ecIns._zr.dom, ecModel);
  23440. }
  23441. function performPostUpdateFuncs(ecModel, api) {
  23442. each(postUpdateFuncs, function (func) {
  23443. func(ecModel, api);
  23444. });
  23445. }
  23446. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  23447. /**
  23448. * @private
  23449. */
  23450. echartsProto._initEvents = function () {
  23451. each(MOUSE_EVENT_NAMES, function (eveName) {
  23452. var handler = function (e) {
  23453. var ecModel = this.getModel();
  23454. var el = e.target;
  23455. var params;
  23456. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  23457. if (isGlobalOut) {
  23458. params = {};
  23459. } else if (el && el.dataIndex != null) {
  23460. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23461. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  23462. } // If element has custom eventData of components
  23463. else if (el && el.eventData) {
  23464. params = extend({}, el.eventData);
  23465. } // Contract: if params prepared in mouse event,
  23466. // these properties must be specified:
  23467. // {
  23468. // componentType: string (component main type)
  23469. // componentIndex: number
  23470. // }
  23471. // Otherwise event query can not work.
  23472. if (params) {
  23473. var componentType = params.componentType;
  23474. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  23475. // markLine/markPoint/markArea, the componentType is
  23476. // 'markLine'/'markPoint'/'markArea', but we should better
  23477. // enable them to be queried by seriesIndex, since their
  23478. // option is set in each series.
  23479. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  23480. componentType = 'series';
  23481. componentIndex = params.seriesIndex;
  23482. }
  23483. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  23484. var view = model && this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  23485. params.event = e;
  23486. params.type = eveName;
  23487. this._ecEventProcessor.eventInfo = {
  23488. targetEl: el,
  23489. packedEvent: params,
  23490. model: model,
  23491. view: view
  23492. };
  23493. this.trigger(eveName, params);
  23494. }
  23495. }; // Consider that some component (like tooltip, brush, ...)
  23496. // register zr event handler, but user event handler might
  23497. // do anything, such as call `setOption` or `dispatchAction`,
  23498. // which probably update any of the content and probably
  23499. // cause problem if it is called previous other inner handlers.
  23500. handler.zrEventfulCallAtLast = true;
  23501. this._zr.on(eveName, handler, this);
  23502. }, this);
  23503. each(eventActionMap, function (actionType, eventType) {
  23504. this._messageCenter.on(eventType, function (event) {
  23505. this.trigger(eventType, event);
  23506. }, this);
  23507. }, this);
  23508. };
  23509. /**
  23510. * @return {boolean}
  23511. */
  23512. echartsProto.isDisposed = function () {
  23513. return this._disposed;
  23514. };
  23515. /**
  23516. * Clear
  23517. */
  23518. echartsProto.clear = function () {
  23519. if (this._disposed) {
  23520. return;
  23521. }
  23522. this.setOption({
  23523. series: []
  23524. }, true);
  23525. };
  23526. /**
  23527. * Dispose instance
  23528. */
  23529. echartsProto.dispose = function () {
  23530. if (this._disposed) {
  23531. return;
  23532. }
  23533. this._disposed = true;
  23534. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  23535. var api = this._api;
  23536. var ecModel = this._model;
  23537. each(this._componentsViews, function (component) {
  23538. component.dispose(ecModel, api);
  23539. });
  23540. each(this._chartsViews, function (chart) {
  23541. chart.dispose(ecModel, api);
  23542. }); // Dispose after all views disposed
  23543. this._zr.dispose();
  23544. delete instances[this.id];
  23545. };
  23546. mixin(ECharts, Eventful);
  23547. function updateHoverLayerStatus(ecIns, ecModel) {
  23548. var zr = ecIns._zr;
  23549. var storage = zr.storage;
  23550. var elCount = 0;
  23551. storage.traverse(function (el) {
  23552. elCount++;
  23553. });
  23554. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  23555. ecModel.eachSeries(function (seriesModel) {
  23556. if (seriesModel.preventUsingHoverLayer) {
  23557. return;
  23558. }
  23559. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23560. if (chartView.__alive) {
  23561. chartView.group.traverse(function (el) {
  23562. // Don't switch back.
  23563. el.useHoverLayer = true;
  23564. });
  23565. }
  23566. });
  23567. }
  23568. }
  23569. /**
  23570. * Update chart progressive and blend.
  23571. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23572. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23573. */
  23574. function updateBlend(seriesModel, chartView) {
  23575. var blendMode = seriesModel.get('blendMode') || null;
  23576. chartView.group.traverse(function (el) {
  23577. // FIXME marker and other components
  23578. if (!el.isGroup) {
  23579. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  23580. if (el.style.blend !== blendMode) {
  23581. el.setStyle('blend', blendMode);
  23582. }
  23583. }
  23584. if (el.eachPendingDisplayable) {
  23585. el.eachPendingDisplayable(function (displayable) {
  23586. displayable.setStyle('blend', blendMode);
  23587. });
  23588. }
  23589. });
  23590. }
  23591. /**
  23592. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23593. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23594. */
  23595. function updateZ(model, view) {
  23596. var z = model.get('z');
  23597. var zlevel = model.get('zlevel'); // Set z and zlevel
  23598. view.group.traverse(function (el) {
  23599. if (el.type !== 'group') {
  23600. z != null && (el.z = z);
  23601. zlevel != null && (el.zlevel = zlevel);
  23602. }
  23603. });
  23604. }
  23605. function createExtensionAPI(ecInstance) {
  23606. var coordSysMgr = ecInstance._coordSysMgr;
  23607. return extend(new ExtensionAPI(ecInstance), {
  23608. // Inject methods
  23609. getCoordinateSystems: bind(coordSysMgr.getCoordinateSystems, coordSysMgr),
  23610. getComponentByElement: function (el) {
  23611. while (el) {
  23612. var modelInfo = el.__ecComponentInfo;
  23613. if (modelInfo != null) {
  23614. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  23615. }
  23616. el = el.parent;
  23617. }
  23618. }
  23619. });
  23620. }
  23621. /**
  23622. * @class
  23623. * Usage of query:
  23624. * `chart.on('click', query, handler);`
  23625. * The `query` can be:
  23626. * + The component type query string, only `mainType` or `mainType.subType`,
  23627. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23628. * + The component query object, like:
  23629. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23630. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23631. * + The data query object, like:
  23632. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23633. * + The other query object (cmponent customized query), like:
  23634. * `{element: 'some'}` (only available in custom series).
  23635. *
  23636. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23637. * same as there is no such prop in the `query` object.
  23638. */
  23639. function EventProcessor() {
  23640. // These info required: targetEl, packedEvent, model, view
  23641. this.eventInfo;
  23642. }
  23643. EventProcessor.prototype = {
  23644. constructor: EventProcessor,
  23645. normalizeQuery: function (query) {
  23646. var cptQuery = {};
  23647. var dataQuery = {};
  23648. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23649. if (isString(query)) {
  23650. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23651. cptQuery.mainType = condCptType.main || null;
  23652. cptQuery.subType = condCptType.sub || null;
  23653. } // `query` is an object, convert to {mainType, index, name, id}.
  23654. else {
  23655. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23656. // can not be used in `compomentModel.filterForExposedEvent`.
  23657. var suffixes = ['Index', 'Name', 'Id'];
  23658. var dataKeys = {
  23659. name: 1,
  23660. dataIndex: 1,
  23661. dataType: 1
  23662. };
  23663. each$1(query, function (val, key) {
  23664. var reserved = false;
  23665. for (var i = 0; i < suffixes.length; i++) {
  23666. var propSuffix = suffixes[i];
  23667. var suffixPos = key.lastIndexOf(propSuffix);
  23668. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23669. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23670. if (mainType !== 'data') {
  23671. cptQuery.mainType = mainType;
  23672. cptQuery[propSuffix.toLowerCase()] = val;
  23673. reserved = true;
  23674. }
  23675. }
  23676. }
  23677. if (dataKeys.hasOwnProperty(key)) {
  23678. dataQuery[key] = val;
  23679. reserved = true;
  23680. }
  23681. if (!reserved) {
  23682. otherQuery[key] = val;
  23683. }
  23684. });
  23685. }
  23686. return {
  23687. cptQuery: cptQuery,
  23688. dataQuery: dataQuery,
  23689. otherQuery: otherQuery
  23690. };
  23691. },
  23692. filter: function (eventType, query, args) {
  23693. // They should be assigned before each trigger call.
  23694. var eventInfo = this.eventInfo;
  23695. if (!eventInfo) {
  23696. return true;
  23697. }
  23698. var targetEl = eventInfo.targetEl;
  23699. var packedEvent = eventInfo.packedEvent;
  23700. var model = eventInfo.model;
  23701. var view = eventInfo.view; // For event like 'globalout'.
  23702. if (!model || !view) {
  23703. return true;
  23704. }
  23705. var cptQuery = query.cptQuery;
  23706. var dataQuery = query.dataQuery;
  23707. 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));
  23708. function check(query, host, prop, propOnHost) {
  23709. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23710. }
  23711. },
  23712. afterTrigger: function () {
  23713. // Make sure the eventInfo wont be used in next trigger.
  23714. this.eventInfo = null;
  23715. }
  23716. };
  23717. /**
  23718. * @type {Object} key: actionType.
  23719. * @inner
  23720. */
  23721. var actions = {};
  23722. /**
  23723. * Map eventType to actionType
  23724. * @type {Object}
  23725. */
  23726. var eventActionMap = {};
  23727. /**
  23728. * Data processor functions of each stage
  23729. * @type {Array.<Object.<string, Function>>}
  23730. * @inner
  23731. */
  23732. var dataProcessorFuncs = [];
  23733. /**
  23734. * @type {Array.<Function>}
  23735. * @inner
  23736. */
  23737. var optionPreprocessorFuncs = [];
  23738. /**
  23739. * @type {Array.<Function>}
  23740. * @inner
  23741. */
  23742. var postUpdateFuncs = [];
  23743. /**
  23744. * Visual encoding functions of each stage
  23745. * @type {Array.<Object.<string, Function>>}
  23746. */
  23747. var visualFuncs = [];
  23748. /**
  23749. * Theme storage
  23750. * @type {Object.<key, Object>}
  23751. */
  23752. var themeStorage = {};
  23753. /**
  23754. * Loading effects
  23755. */
  23756. var loadingEffects = {};
  23757. var instances = {};
  23758. var connectedGroups = {};
  23759. var idBase = new Date() - 0;
  23760. var groupIdBase = new Date() - 0;
  23761. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  23762. function enableConnect(chart) {
  23763. var STATUS_PENDING = 0;
  23764. var STATUS_UPDATING = 1;
  23765. var STATUS_UPDATED = 2;
  23766. var STATUS_KEY = '__connectUpdateStatus';
  23767. function updateConnectedChartsStatus(charts, status) {
  23768. for (var i = 0; i < charts.length; i++) {
  23769. var otherChart = charts[i];
  23770. otherChart[STATUS_KEY] = status;
  23771. }
  23772. }
  23773. each(eventActionMap, function (actionType, eventType) {
  23774. chart._messageCenter.on(eventType, function (event) {
  23775. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  23776. if (event && event.escapeConnect) {
  23777. return;
  23778. }
  23779. var action = chart.makeActionFromEvent(event);
  23780. var otherCharts = [];
  23781. each(instances, function (otherChart) {
  23782. if (otherChart !== chart && otherChart.group === chart.group) {
  23783. otherCharts.push(otherChart);
  23784. }
  23785. });
  23786. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  23787. each(otherCharts, function (otherChart) {
  23788. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  23789. otherChart.dispatchAction(action);
  23790. }
  23791. });
  23792. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  23793. }
  23794. });
  23795. });
  23796. }
  23797. /**
  23798. * @param {HTMLElement} dom
  23799. * @param {Object} [theme]
  23800. * @param {Object} opts
  23801. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  23802. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  23803. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  23804. * Can be 'auto' (the same as null/undefined)
  23805. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  23806. * Can be 'auto' (the same as null/undefined)
  23807. */
  23808. function init(dom, theme$$1, opts) {
  23809. var existInstance = getInstanceByDom(dom);
  23810. if (existInstance) {
  23811. return existInstance;
  23812. }
  23813. var chart = new ECharts(dom, theme$$1, opts);
  23814. chart.id = 'ec_' + idBase++;
  23815. instances[chart.id] = chart;
  23816. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  23817. enableConnect(chart);
  23818. return chart;
  23819. }
  23820. /**
  23821. * @return {string|Array.<module:echarts~ECharts>} groupId
  23822. */
  23823. function connect(groupId) {
  23824. // Is array of charts
  23825. if (isArray(groupId)) {
  23826. var charts = groupId;
  23827. groupId = null; // If any chart has group
  23828. each(charts, function (chart) {
  23829. if (chart.group != null) {
  23830. groupId = chart.group;
  23831. }
  23832. });
  23833. groupId = groupId || 'g_' + groupIdBase++;
  23834. each(charts, function (chart) {
  23835. chart.group = groupId;
  23836. });
  23837. }
  23838. connectedGroups[groupId] = true;
  23839. return groupId;
  23840. }
  23841. /**
  23842. * @DEPRECATED
  23843. * @return {string} groupId
  23844. */
  23845. function disConnect(groupId) {
  23846. connectedGroups[groupId] = false;
  23847. }
  23848. /**
  23849. * @return {string} groupId
  23850. */
  23851. var disconnect = disConnect;
  23852. /**
  23853. * Dispose a chart instance
  23854. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  23855. */
  23856. function dispose(chart) {
  23857. if (typeof chart === 'string') {
  23858. chart = instances[chart];
  23859. } else if (!(chart instanceof ECharts)) {
  23860. // Try to treat as dom
  23861. chart = getInstanceByDom(chart);
  23862. }
  23863. if (chart instanceof ECharts && !chart.isDisposed()) {
  23864. chart.dispose();
  23865. }
  23866. }
  23867. /**
  23868. * @param {HTMLElement} dom
  23869. * @return {echarts~ECharts}
  23870. */
  23871. function getInstanceByDom(dom) {
  23872. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  23873. }
  23874. /**
  23875. * @param {string} key
  23876. * @return {echarts~ECharts}
  23877. */
  23878. function getInstanceById(key) {
  23879. return instances[key];
  23880. }
  23881. /**
  23882. * Register theme
  23883. */
  23884. function registerTheme(name, theme$$1) {
  23885. themeStorage[name] = theme$$1;
  23886. }
  23887. /**
  23888. * Register option preprocessor
  23889. * @param {Function} preprocessorFunc
  23890. */
  23891. function registerPreprocessor(preprocessorFunc) {
  23892. optionPreprocessorFuncs.push(preprocessorFunc);
  23893. }
  23894. /**
  23895. * @param {number} [priority=1000]
  23896. * @param {Object|Function} processor
  23897. */
  23898. function registerProcessor(priority, processor) {
  23899. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  23900. }
  23901. /**
  23902. * Register postUpdater
  23903. * @param {Function} postUpdateFunc
  23904. */
  23905. function registerPostUpdate(postUpdateFunc) {
  23906. postUpdateFuncs.push(postUpdateFunc);
  23907. }
  23908. /**
  23909. * Usage:
  23910. * registerAction('someAction', 'someEvent', function () { ... });
  23911. * registerAction('someAction', function () { ... });
  23912. * registerAction(
  23913. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  23914. * function () { ... }
  23915. * );
  23916. *
  23917. * @param {(string|Object)} actionInfo
  23918. * @param {string} actionInfo.type
  23919. * @param {string} [actionInfo.event]
  23920. * @param {string} [actionInfo.update]
  23921. * @param {string} [eventName]
  23922. * @param {Function} action
  23923. */
  23924. function registerAction(actionInfo, eventName, action) {
  23925. if (typeof eventName === 'function') {
  23926. action = eventName;
  23927. eventName = '';
  23928. }
  23929. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  23930. event: eventName
  23931. }][0]; // Event name is all lowercase
  23932. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  23933. eventName = actionInfo.event; // Validate action type and event name.
  23934. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  23935. if (!actions[actionType]) {
  23936. actions[actionType] = {
  23937. action: action,
  23938. actionInfo: actionInfo
  23939. };
  23940. }
  23941. eventActionMap[eventName] = actionType;
  23942. }
  23943. /**
  23944. * @param {string} type
  23945. * @param {*} CoordinateSystem
  23946. */
  23947. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  23948. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  23949. }
  23950. /**
  23951. * Get dimensions of specified coordinate system.
  23952. * @param {string} type
  23953. * @return {Array.<string|Object>}
  23954. */
  23955. function getCoordinateSystemDimensions(type) {
  23956. var coordSysCreator = CoordinateSystemManager.get(type);
  23957. if (coordSysCreator) {
  23958. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  23959. }
  23960. }
  23961. /**
  23962. * Layout is a special stage of visual encoding
  23963. * Most visual encoding like color are common for different chart
  23964. * But each chart has it's own layout algorithm
  23965. *
  23966. * @param {number} [priority=1000]
  23967. * @param {Function} layoutTask
  23968. */
  23969. function registerLayout(priority, layoutTask) {
  23970. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  23971. }
  23972. /**
  23973. * @param {number} [priority=3000]
  23974. * @param {module:echarts/stream/Task} visualTask
  23975. */
  23976. function registerVisual(priority, visualTask) {
  23977. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  23978. }
  23979. /**
  23980. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  23981. */
  23982. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  23983. if (isFunction(priority) || isObject(priority)) {
  23984. fn = priority;
  23985. priority = defaultPriority;
  23986. }
  23987. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  23988. stageHandler.__prio = priority;
  23989. stageHandler.__raw = fn;
  23990. targetList.push(stageHandler);
  23991. return stageHandler;
  23992. }
  23993. /**
  23994. * @param {string} name
  23995. */
  23996. function registerLoading(name, loadingFx) {
  23997. loadingEffects[name] = loadingFx;
  23998. }
  23999. /**
  24000. * @param {Object} opts
  24001. * @param {string} [superClass]
  24002. */
  24003. function extendComponentModel(opts
  24004. /*, superClass*/
  24005. ) {
  24006. // var Clazz = ComponentModel;
  24007. // if (superClass) {
  24008. // var classType = parseClassType(superClass);
  24009. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24010. // }
  24011. return ComponentModel.extend(opts);
  24012. }
  24013. /**
  24014. * @param {Object} opts
  24015. * @param {string} [superClass]
  24016. */
  24017. function extendComponentView(opts
  24018. /*, superClass*/
  24019. ) {
  24020. // var Clazz = ComponentView;
  24021. // if (superClass) {
  24022. // var classType = parseClassType(superClass);
  24023. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  24024. // }
  24025. return Component$1.extend(opts);
  24026. }
  24027. /**
  24028. * @param {Object} opts
  24029. * @param {string} [superClass]
  24030. */
  24031. function extendSeriesModel(opts
  24032. /*, superClass*/
  24033. ) {
  24034. // var Clazz = SeriesModel;
  24035. // if (superClass) {
  24036. // superClass = 'series.' + superClass.replace('series.', '');
  24037. // var classType = parseClassType(superClass);
  24038. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24039. // }
  24040. return SeriesModel.extend(opts);
  24041. }
  24042. /**
  24043. * @param {Object} opts
  24044. * @param {string} [superClass]
  24045. */
  24046. function extendChartView(opts
  24047. /*, superClass*/
  24048. ) {
  24049. // var Clazz = ChartView;
  24050. // if (superClass) {
  24051. // superClass = superClass.replace('series.', '');
  24052. // var classType = parseClassType(superClass);
  24053. // Clazz = ChartView.getClass(classType.main, true);
  24054. // }
  24055. return Chart.extend(opts);
  24056. }
  24057. /**
  24058. * ZRender need a canvas context to do measureText.
  24059. * But in node environment canvas may be created by node-canvas.
  24060. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  24061. *
  24062. * Be careful of using it in the browser.
  24063. *
  24064. * @param {Function} creator
  24065. * @example
  24066. * var Canvas = require('canvas');
  24067. * var echarts = require('echarts');
  24068. * echarts.setCanvasCreator(function () {
  24069. * // Small size is enough.
  24070. * return new Canvas(32, 32);
  24071. * });
  24072. */
  24073. function setCanvasCreator(creator) {
  24074. $override('createCanvas', creator);
  24075. }
  24076. /**
  24077. * @param {string} mapName
  24078. * @param {Array.<Object>|Object|string} geoJson
  24079. * @param {Object} [specialAreas]
  24080. *
  24081. * @example GeoJSON
  24082. * $.get('USA.json', function (geoJson) {
  24083. * echarts.registerMap('USA', geoJson);
  24084. * // Or
  24085. * echarts.registerMap('USA', {
  24086. * geoJson: geoJson,
  24087. * specialAreas: {}
  24088. * })
  24089. * });
  24090. *
  24091. * $.get('airport.svg', function (svg) {
  24092. * echarts.registerMap('airport', {
  24093. * svg: svg
  24094. * }
  24095. * });
  24096. *
  24097. * echarts.registerMap('eu', [
  24098. * {svg: eu-topographic.svg},
  24099. * {geoJSON: eu.json}
  24100. * ])
  24101. */
  24102. function registerMap(mapName, geoJson, specialAreas) {
  24103. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  24104. }
  24105. /**
  24106. * @param {string} mapName
  24107. * @return {Object}
  24108. */
  24109. function getMap(mapName) {
  24110. // For backward compatibility, only return the first one.
  24111. var records = mapDataStorage.retrieveMap(mapName);
  24112. return records && records[0] && {
  24113. geoJson: records[0].geoJSON,
  24114. specialAreas: records[0].specialAreas
  24115. };
  24116. }
  24117. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  24118. registerPreprocessor(backwardCompat);
  24119. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  24120. registerLoading('default', loadingDefault); // Default actions
  24121. registerAction({
  24122. type: 'highlight',
  24123. event: 'highlight',
  24124. update: 'highlight'
  24125. }, noop);
  24126. registerAction({
  24127. type: 'downplay',
  24128. event: 'downplay',
  24129. update: 'downplay'
  24130. }, noop); // Default theme
  24131. registerTheme('light', lightTheme);
  24132. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  24133. // be mounted on `echarts` is the extension `dataTool` is imported.
  24134. var dataTool = {};
  24135. /*
  24136. * Licensed to the Apache Software Foundation (ASF) under one
  24137. * or more contributor license agreements. See the NOTICE file
  24138. * distributed with this work for additional information
  24139. * regarding copyright ownership. The ASF licenses this file
  24140. * to you under the Apache License, Version 2.0 (the
  24141. * "License"); you may not use this file except in compliance
  24142. * with the License. You may obtain a copy of the License at
  24143. *
  24144. * http://www.apache.org/licenses/LICENSE-2.0
  24145. *
  24146. * Unless required by applicable law or agreed to in writing,
  24147. * software distributed under the License is distributed on an
  24148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24149. * KIND, either express or implied. See the License for the
  24150. * specific language governing permissions and limitations
  24151. * under the License.
  24152. */
  24153. function defaultKeyGetter(item) {
  24154. return item;
  24155. }
  24156. /**
  24157. * @param {Array} oldArr
  24158. * @param {Array} newArr
  24159. * @param {Function} oldKeyGetter
  24160. * @param {Function} newKeyGetter
  24161. * @param {Object} [context] Can be visited by this.context in callback.
  24162. */
  24163. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  24164. this._old = oldArr;
  24165. this._new = newArr;
  24166. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  24167. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  24168. this.context = context;
  24169. }
  24170. DataDiffer.prototype = {
  24171. constructor: DataDiffer,
  24172. /**
  24173. * Callback function when add a data
  24174. */
  24175. add: function (func) {
  24176. this._add = func;
  24177. return this;
  24178. },
  24179. /**
  24180. * Callback function when update a data
  24181. */
  24182. update: function (func) {
  24183. this._update = func;
  24184. return this;
  24185. },
  24186. /**
  24187. * Callback function when remove a data
  24188. */
  24189. remove: function (func) {
  24190. this._remove = func;
  24191. return this;
  24192. },
  24193. execute: function () {
  24194. var oldArr = this._old;
  24195. var newArr = this._new;
  24196. var oldDataIndexMap = {};
  24197. var newDataIndexMap = {};
  24198. var oldDataKeyArr = [];
  24199. var newDataKeyArr = [];
  24200. var i;
  24201. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  24202. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  24203. for (i = 0; i < oldArr.length; i++) {
  24204. var key = oldDataKeyArr[i];
  24205. var idx = newDataIndexMap[key]; // idx can never be empty array here. see 'set null' logic below.
  24206. if (idx != null) {
  24207. // Consider there is duplicate key (for example, use dataItem.name as key).
  24208. // We should make sure every item in newArr and oldArr can be visited.
  24209. var len = idx.length;
  24210. if (len) {
  24211. len === 1 && (newDataIndexMap[key] = null);
  24212. idx = idx.shift();
  24213. } else {
  24214. newDataIndexMap[key] = null;
  24215. }
  24216. this._update && this._update(idx, i);
  24217. } else {
  24218. this._remove && this._remove(i);
  24219. }
  24220. }
  24221. for (var i = 0; i < newDataKeyArr.length; i++) {
  24222. var key = newDataKeyArr[i];
  24223. if (newDataIndexMap.hasOwnProperty(key)) {
  24224. var idx = newDataIndexMap[key];
  24225. if (idx == null) {
  24226. continue;
  24227. } // idx can never be empty array here. see 'set null' logic above.
  24228. if (!idx.length) {
  24229. this._add && this._add(idx);
  24230. } else {
  24231. for (var j = 0, len = idx.length; j < len; j++) {
  24232. this._add && this._add(idx[j]);
  24233. }
  24234. }
  24235. }
  24236. }
  24237. }
  24238. };
  24239. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  24240. for (var i = 0; i < arr.length; i++) {
  24241. // Add prefix to avoid conflict with Object.prototype.
  24242. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  24243. var existence = map[key];
  24244. if (existence == null) {
  24245. keyArr.push(key);
  24246. map[key] = i;
  24247. } else {
  24248. if (!existence.length) {
  24249. map[key] = existence = [existence];
  24250. }
  24251. existence.push(i);
  24252. }
  24253. }
  24254. }
  24255. /*
  24256. * Licensed to the Apache Software Foundation (ASF) under one
  24257. * or more contributor license agreements. See the NOTICE file
  24258. * distributed with this work for additional information
  24259. * regarding copyright ownership. The ASF licenses this file
  24260. * to you under the Apache License, Version 2.0 (the
  24261. * "License"); you may not use this file except in compliance
  24262. * with the License. You may obtain a copy of the License at
  24263. *
  24264. * http://www.apache.org/licenses/LICENSE-2.0
  24265. *
  24266. * Unless required by applicable law or agreed to in writing,
  24267. * software distributed under the License is distributed on an
  24268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24269. * KIND, either express or implied. See the License for the
  24270. * specific language governing permissions and limitations
  24271. * under the License.
  24272. */
  24273. var OTHER_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']);
  24274. function summarizeDimensions(data) {
  24275. var summary = {};
  24276. var encode = summary.encode = {};
  24277. var notExtraCoordDimMap = createHashMap();
  24278. var defaultedLabel = [];
  24279. var defaultedTooltip = []; // See the comment of `List.js#userOutput`.
  24280. var userOutput = summary.userOutput = {
  24281. dimensionNames: data.dimensions.slice(),
  24282. encode: {}
  24283. };
  24284. each$1(data.dimensions, function (dimName) {
  24285. var dimItem = data.getDimensionInfo(dimName);
  24286. var coordDim = dimItem.coordDim;
  24287. if (coordDim) {
  24288. var coordDimIndex = dimItem.coordDimIndex;
  24289. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  24290. if (!dimItem.isExtraCoord) {
  24291. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  24292. // because when dataset is used, it is hard to guess which dimension
  24293. // can be value dimension. If both show x, y on label is not look good,
  24294. // and conventionally y axis is focused more.
  24295. if (mayLabelDimType(dimItem.type)) {
  24296. defaultedLabel[0] = dimName;
  24297. } // User output encode do not contain generated coords.
  24298. // And it only has index. User can use index to retrieve value from the raw item array.
  24299. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  24300. }
  24301. if (dimItem.defaultTooltip) {
  24302. defaultedTooltip.push(dimName);
  24303. }
  24304. }
  24305. OTHER_DIMENSIONS.each(function (v, otherDim) {
  24306. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  24307. var dimIndex = dimItem.otherDims[otherDim];
  24308. if (dimIndex != null && dimIndex !== false) {
  24309. encodeArr[dimIndex] = dimItem.name;
  24310. }
  24311. });
  24312. });
  24313. var dataDimsOnCoord = [];
  24314. var encodeFirstDimNotExtra = {};
  24315. notExtraCoordDimMap.each(function (v, coordDim) {
  24316. var dimArr = encode[coordDim]; // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  24317. // But should fix the case that radar axes: simplify the logic
  24318. // of `completeDimension`, remove `extraPrefix`.
  24319. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  24320. // dim canot on more than one coordDim.
  24321. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  24322. });
  24323. summary.dataDimsOnCoord = dataDimsOnCoord;
  24324. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  24325. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  24326. // in this way. Use label.formatter instead. May be remove this approach someday.
  24327. if (encodeLabel && encodeLabel.length) {
  24328. defaultedLabel = encodeLabel.slice();
  24329. }
  24330. var encodeTooltip = encode.tooltip;
  24331. if (encodeTooltip && encodeTooltip.length) {
  24332. defaultedTooltip = encodeTooltip.slice();
  24333. } else if (!defaultedTooltip.length) {
  24334. defaultedTooltip = defaultedLabel.slice();
  24335. }
  24336. encode.defaultedLabel = defaultedLabel;
  24337. encode.defaultedTooltip = defaultedTooltip;
  24338. return summary;
  24339. }
  24340. function getOrCreateEncodeArr(encode, dim) {
  24341. if (!encode.hasOwnProperty(dim)) {
  24342. encode[dim] = [];
  24343. }
  24344. return encode[dim];
  24345. }
  24346. function getDimensionTypeByAxis(axisType) {
  24347. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  24348. }
  24349. function mayLabelDimType(dimType) {
  24350. // In most cases, ordinal and time do not suitable for label.
  24351. // Ordinal info can be displayed on axis. Time is too long.
  24352. return !(dimType === 'ordinal' || dimType === 'time');
  24353. } // function findTheLastDimMayLabel(data) {
  24354. // // Get last value dim
  24355. // var dimensions = data.dimensions.slice();
  24356. // var valueType;
  24357. // var valueDim;
  24358. // while (dimensions.length && (
  24359. // valueDim = dimensions.pop(),
  24360. // valueType = data.getDimensionInfo(valueDim).type,
  24361. // valueType === 'ordinal' || valueType === 'time'
  24362. // )) {} // jshint ignore:line
  24363. // return valueDim;
  24364. // }
  24365. /*
  24366. * Licensed to the Apache Software Foundation (ASF) under one
  24367. * or more contributor license agreements. See the NOTICE file
  24368. * distributed with this work for additional information
  24369. * regarding copyright ownership. The ASF licenses this file
  24370. * to you under the Apache License, Version 2.0 (the
  24371. * "License"); you may not use this file except in compliance
  24372. * with the License. You may obtain a copy of the License at
  24373. *
  24374. * http://www.apache.org/licenses/LICENSE-2.0
  24375. *
  24376. * Unless required by applicable law or agreed to in writing,
  24377. * software distributed under the License is distributed on an
  24378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24379. * KIND, either express or implied. See the License for the
  24380. * specific language governing permissions and limitations
  24381. * under the License.
  24382. */
  24383. /**
  24384. * @class
  24385. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  24386. */
  24387. function DataDimensionInfo(opt) {
  24388. if (opt != null) {
  24389. extend(this, opt);
  24390. }
  24391. /**
  24392. * Dimension name.
  24393. * Mandatory.
  24394. * @type {string}
  24395. */
  24396. // this.name;
  24397. /**
  24398. * The origin name in dimsDef, see source helper.
  24399. * If displayName given, the tooltip will displayed vertically.
  24400. * Optional.
  24401. * @type {string}
  24402. */
  24403. // this.displayName;
  24404. /**
  24405. * Which coordSys dimension this dimension mapped to.
  24406. * A `coordDim` can be a "coordSysDim" that the coordSys required
  24407. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  24408. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  24409. * (That is determined by whether `isExtraCoord` is `true`).
  24410. * Mandatory.
  24411. * @type {string}
  24412. */
  24413. // this.coordDim;
  24414. /**
  24415. * The index of this dimension in `series.encode[coordDim]`.
  24416. * Mandatory.
  24417. * @type {number}
  24418. */
  24419. // this.coordDimIndex;
  24420. /**
  24421. * Dimension type. The enumerable values are the key of
  24422. * `dataCtors` of `data/List`.
  24423. * Optional.
  24424. * @type {string}
  24425. */
  24426. // this.type;
  24427. /**
  24428. * This index of this dimension info in `data/List#_dimensionInfos`.
  24429. * Mandatory after added to `data/List`.
  24430. * @type {number}
  24431. */
  24432. // this.index;
  24433. /**
  24434. * The format of `otherDims` is:
  24435. * ```js
  24436. * {
  24437. * tooltip: number optional,
  24438. * label: number optional,
  24439. * itemName: number optional,
  24440. * seriesName: number optional,
  24441. * }
  24442. * ```
  24443. *
  24444. * A `series.encode` can specified these fields:
  24445. * ```js
  24446. * encode: {
  24447. * // "3, 1, 5" is the index of data dimension.
  24448. * tooltip: [3, 1, 5],
  24449. * label: [0, 3],
  24450. * ...
  24451. * }
  24452. * ```
  24453. * `otherDims` is the parse result of the `series.encode` above, like:
  24454. * ```js
  24455. * // Suppose the index of this data dimension is `3`.
  24456. * this.otherDims = {
  24457. * // `3` is at the index `0` of the `encode.tooltip`
  24458. * tooltip: 0,
  24459. * // `3` is at the index `1` of the `encode.tooltip`
  24460. * label: 1
  24461. * };
  24462. * ```
  24463. *
  24464. * This prop should never be `null`/`undefined` after initialized.
  24465. * @type {Object}
  24466. */
  24467. this.otherDims = {};
  24468. /**
  24469. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  24470. * "coordSys" required.
  24471. * Mandatory.
  24472. * @type {boolean}
  24473. */
  24474. // this.isExtraCoord;
  24475. /**
  24476. * @type {module:data/OrdinalMeta}
  24477. */
  24478. // this.ordinalMeta;
  24479. /**
  24480. * Whether to create inverted indices.
  24481. * @type {boolean}
  24482. */
  24483. // this.createInvertedIndices;
  24484. }
  24485. /*
  24486. * Licensed to the Apache Software Foundation (ASF) under one
  24487. * or more contributor license agreements. See the NOTICE file
  24488. * distributed with this work for additional information
  24489. * regarding copyright ownership. The ASF licenses this file
  24490. * to you under the Apache License, Version 2.0 (the
  24491. * "License"); you may not use this file except in compliance
  24492. * with the License. You may obtain a copy of the License at
  24493. *
  24494. * http://www.apache.org/licenses/LICENSE-2.0
  24495. *
  24496. * Unless required by applicable law or agreed to in writing,
  24497. * software distributed under the License is distributed on an
  24498. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24499. * KIND, either express or implied. See the License for the
  24500. * specific language governing permissions and limitations
  24501. * under the License.
  24502. */
  24503. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  24504. /**
  24505. * List for data storage
  24506. * @module echarts/data/List
  24507. */
  24508. var isObject$4 = isObject$1;
  24509. var UNDEFINED = 'undefined';
  24510. var INDEX_NOT_FOUND = -1; // Use prefix to avoid index to be the same as otherIdList[idx],
  24511. // which will cause weird udpate animation.
  24512. var ID_PREFIX = 'e\0\0';
  24513. var dataCtors = {
  24514. 'float': typeof Float64Array === UNDEFINED ? Array : Float64Array,
  24515. 'int': typeof Int32Array === UNDEFINED ? Array : Int32Array,
  24516. // Ordinal data type can be string or int
  24517. 'ordinal': Array,
  24518. 'number': Array,
  24519. 'time': Array
  24520. }; // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  24521. // different from the Ctor of typed array.
  24522. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  24523. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  24524. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  24525. function getIndicesCtor(list) {
  24526. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  24527. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  24528. }
  24529. function cloneChunk(originalChunk) {
  24530. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  24531. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  24532. }
  24533. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'];
  24534. var CLONE_PROPERTIES = ['_extent', '_approximateExtent', '_rawExtent'];
  24535. function transferProperties(target, source) {
  24536. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24537. if (source.hasOwnProperty(propName)) {
  24538. target[propName] = source[propName];
  24539. }
  24540. });
  24541. target.__wrappedMethods = source.__wrappedMethods;
  24542. each$1(CLONE_PROPERTIES, function (propName) {
  24543. target[propName] = clone(source[propName]);
  24544. });
  24545. target._calculationInfo = extend(source._calculationInfo);
  24546. }
  24547. /**
  24548. * @constructor
  24549. * @alias module:echarts/data/List
  24550. *
  24551. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  24552. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  24553. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  24554. * @param {module:echarts/model/Model} hostModel
  24555. */
  24556. var List = function (dimensions, hostModel) {
  24557. dimensions = dimensions || ['x', 'y'];
  24558. var dimensionInfos = {};
  24559. var dimensionNames = [];
  24560. var invertedIndicesMap = {};
  24561. for (var i = 0; i < dimensions.length; i++) {
  24562. // Use the original dimensions[i], where other flag props may exists.
  24563. var dimensionInfo = dimensions[i];
  24564. if (isString(dimensionInfo)) {
  24565. dimensionInfo = new DataDimensionInfo({
  24566. name: dimensionInfo
  24567. });
  24568. } else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  24569. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  24570. }
  24571. var dimensionName = dimensionInfo.name;
  24572. dimensionInfo.type = dimensionInfo.type || 'float';
  24573. if (!dimensionInfo.coordDim) {
  24574. dimensionInfo.coordDim = dimensionName;
  24575. dimensionInfo.coordDimIndex = 0;
  24576. }
  24577. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  24578. dimensionNames.push(dimensionName);
  24579. dimensionInfos[dimensionName] = dimensionInfo;
  24580. dimensionInfo.index = i;
  24581. if (dimensionInfo.createInvertedIndices) {
  24582. invertedIndicesMap[dimensionName] = [];
  24583. }
  24584. }
  24585. /**
  24586. * @readOnly
  24587. * @type {Array.<string>}
  24588. */
  24589. this.dimensions = dimensionNames;
  24590. /**
  24591. * Infomation of each data dimension, like data type.
  24592. * @type {Object}
  24593. */
  24594. this._dimensionInfos = dimensionInfos;
  24595. /**
  24596. * @type {module:echarts/model/Model}
  24597. */
  24598. this.hostModel = hostModel;
  24599. /**
  24600. * @type {module:echarts/model/Model}
  24601. */
  24602. this.dataType;
  24603. /**
  24604. * Indices stores the indices of data subset after filtered.
  24605. * This data subset will be used in chart.
  24606. * @type {Array.<number>}
  24607. * @readOnly
  24608. */
  24609. this._indices = null;
  24610. this._count = 0;
  24611. this._rawCount = 0;
  24612. /**
  24613. * Data storage
  24614. * @type {Object.<key, Array.<TypedArray|Array>>}
  24615. * @private
  24616. */
  24617. this._storage = {};
  24618. /**
  24619. * @type {Array.<string>}
  24620. */
  24621. this._nameList = [];
  24622. /**
  24623. * @type {Array.<string>}
  24624. */
  24625. this._idList = [];
  24626. /**
  24627. * Models of data option is stored sparse for optimizing memory cost
  24628. * @type {Array.<module:echarts/model/Model>}
  24629. * @private
  24630. */
  24631. this._optionModels = [];
  24632. /**
  24633. * Global visual properties after visual coding
  24634. * @type {Object}
  24635. * @private
  24636. */
  24637. this._visual = {};
  24638. /**
  24639. * Globel layout properties.
  24640. * @type {Object}
  24641. * @private
  24642. */
  24643. this._layout = {};
  24644. /**
  24645. * Item visual properties after visual coding
  24646. * @type {Array.<Object>}
  24647. * @private
  24648. */
  24649. this._itemVisuals = [];
  24650. /**
  24651. * Key: visual type, Value: boolean
  24652. * @type {Object}
  24653. * @readOnly
  24654. */
  24655. this.hasItemVisual = {};
  24656. /**
  24657. * Item layout properties after layout
  24658. * @type {Array.<Object>}
  24659. * @private
  24660. */
  24661. this._itemLayouts = [];
  24662. /**
  24663. * Graphic elemnents
  24664. * @type {Array.<module:zrender/Element>}
  24665. * @private
  24666. */
  24667. this._graphicEls = [];
  24668. /**
  24669. * Max size of each chunk.
  24670. * @type {number}
  24671. * @private
  24672. */
  24673. this._chunkSize = 1e5;
  24674. /**
  24675. * @type {number}
  24676. * @private
  24677. */
  24678. this._chunkCount = 0;
  24679. /**
  24680. * @type {Array.<Array|Object>}
  24681. * @private
  24682. */
  24683. this._rawData;
  24684. /**
  24685. * Raw extent will not be cloned, but only transfered.
  24686. * It will not be calculated util needed.
  24687. * key: dim,
  24688. * value: {end: number, extent: Array.<number>}
  24689. * @type {Object}
  24690. * @private
  24691. */
  24692. this._rawExtent = {};
  24693. /**
  24694. * @type {Object}
  24695. * @private
  24696. */
  24697. this._extent = {};
  24698. /**
  24699. * key: dim
  24700. * value: extent
  24701. * @type {Object}
  24702. * @private
  24703. */
  24704. this._approximateExtent = {};
  24705. /**
  24706. * Cache summary info for fast visit. See "dimensionHelper".
  24707. * @type {Object}
  24708. * @private
  24709. */
  24710. this._dimensionsSummary = summarizeDimensions(this);
  24711. /**
  24712. * @type {Object.<Array|TypedArray>}
  24713. * @private
  24714. */
  24715. this._invertedIndicesMap = invertedIndicesMap;
  24716. /**
  24717. * @type {Object}
  24718. * @private
  24719. */
  24720. this._calculationInfo = {};
  24721. /**
  24722. * User output info of this data.
  24723. * DO NOT use it in other places!
  24724. *
  24725. * When preparing user params for user callbacks, we have
  24726. * to clone these inner data structures to prevent users
  24727. * from modifying them to effect built-in logic. And for
  24728. * performance consideration we make this `userOutput` to
  24729. * avoid clone them too many times.
  24730. *
  24731. * @type {Object}
  24732. * @readOnly
  24733. */
  24734. this.userOutput = this._dimensionsSummary.userOutput;
  24735. };
  24736. var listProto = List.prototype;
  24737. listProto.type = 'list';
  24738. /**
  24739. * If each data item has it's own option
  24740. * @type {boolean}
  24741. */
  24742. listProto.hasItemOption = true;
  24743. /**
  24744. * The meanings of the input parameter `dim`:
  24745. *
  24746. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  24747. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  24748. * + If dim is a number-like string (e.g., `"1"`):
  24749. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  24750. * + If not, it will be converted to a number, which means the index of the dimension.
  24751. * (why? because of the backward compatbility. We have been tolerating number-like string in
  24752. * dimension setting, although now it seems that it is not a good idea.)
  24753. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  24754. * if no dimension name is defined as `"1"`.
  24755. * + If dim is a not-number-like string, it means the concrete dim name.
  24756. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  24757. * or customized in `dimensions` property of option like `"age"`.
  24758. *
  24759. * Get dimension name
  24760. * @param {string|number} dim See above.
  24761. * @return {string} Concrete dim name.
  24762. */
  24763. listProto.getDimension = function (dim) {
  24764. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  24765. || !isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim)) {
  24766. dim = this.dimensions[dim];
  24767. }
  24768. return dim;
  24769. };
  24770. /**
  24771. * Get type and calculation info of particular dimension
  24772. * @param {string|number} dim
  24773. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24774. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24775. */
  24776. listProto.getDimensionInfo = function (dim) {
  24777. // Do not clone, because there may be categories in dimInfo.
  24778. return this._dimensionInfos[this.getDimension(dim)];
  24779. };
  24780. /**
  24781. * @return {Array.<string>} concrete dimension name list on coord.
  24782. */
  24783. listProto.getDimensionsOnCoord = function () {
  24784. return this._dimensionsSummary.dataDimsOnCoord.slice();
  24785. };
  24786. /**
  24787. * @param {string} coordDim
  24788. * @param {number} [idx] A coordDim may map to more than one data dim.
  24789. * If idx is `true`, return a array of all mapped dims.
  24790. * If idx is not specified, return the first dim not extra.
  24791. * @return {string|Array.<string>} concrete data dim.
  24792. * If idx is number, and not found, return null/undefined.
  24793. * If idx is `true`, and not found, return empty array (always return array).
  24794. */
  24795. listProto.mapDimension = function (coordDim, idx) {
  24796. var dimensionsSummary = this._dimensionsSummary;
  24797. if (idx == null) {
  24798. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  24799. }
  24800. var dims = dimensionsSummary.encode[coordDim];
  24801. return idx === true // always return array if idx is `true`
  24802. ? (dims || []).slice() : dims && dims[idx];
  24803. };
  24804. /**
  24805. * Initialize from data
  24806. * @param {Array.<Object|number|Array>} data source or data or data provider.
  24807. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  24808. * defualt label/tooltip.
  24809. * A name can be specified in encode.itemName,
  24810. * or dataItem.name (only for series option data),
  24811. * or provided in nameList from outside.
  24812. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  24813. */
  24814. listProto.initData = function (data, nameList, dimValueGetter) {
  24815. var notProvider = Source.isInstance(data) || isArrayLike(data);
  24816. if (notProvider) {
  24817. data = new DefaultDataProvider(data, this.dimensions.length);
  24818. }
  24819. this._rawData = data; // Clear
  24820. this._storage = {};
  24821. this._indices = null;
  24822. this._nameList = nameList || [];
  24823. this._idList = [];
  24824. this._nameRepeatCount = {};
  24825. if (!dimValueGetter) {
  24826. this.hasItemOption = false;
  24827. }
  24828. /**
  24829. * @readOnly
  24830. */
  24831. this.defaultDimValueGetter = defaultDimValueGetters[this._rawData.getSource().sourceFormat]; // Default dim value getter
  24832. this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter;
  24833. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows; // Reset raw extent.
  24834. this._rawExtent = {};
  24835. this._initDataFromProvider(0, data.count()); // If data has no item option.
  24836. if (data.pure) {
  24837. this.hasItemOption = false;
  24838. }
  24839. };
  24840. listProto.getProvider = function () {
  24841. return this._rawData;
  24842. };
  24843. /**
  24844. * Caution: Can be only called on raw data (before `this._indices` created).
  24845. */
  24846. listProto.appendData = function (data) {
  24847. var rawData = this._rawData;
  24848. var start = this.count();
  24849. rawData.appendData(data);
  24850. var end = rawData.count();
  24851. if (!rawData.persistent) {
  24852. end += start;
  24853. }
  24854. this._initDataFromProvider(start, end);
  24855. };
  24856. /**
  24857. * Caution: Can be only called on raw data (before `this._indices` created).
  24858. * This method does not modify `rawData` (`dataProvider`), but only
  24859. * add values to storage.
  24860. *
  24861. * The final count will be increased by `Math.max(values.length, names.length)`.
  24862. *
  24863. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  24864. * [
  24865. * [12, 33, 44],
  24866. * [NaN, 43, 1],
  24867. * ['-', 'asdf', 0]
  24868. * ]
  24869. * Each item is exaclty cooresponding to a dimension.
  24870. * @param {Array.<string>} [names]
  24871. */
  24872. listProto.appendValues = function (values, names) {
  24873. var chunkSize = this._chunkSize;
  24874. var storage = this._storage;
  24875. var dimensions = this.dimensions;
  24876. var dimLen = dimensions.length;
  24877. var rawExtent = this._rawExtent;
  24878. var start = this.count();
  24879. var end = start + Math.max(values.length, names ? names.length : 0);
  24880. var originalChunkCount = this._chunkCount;
  24881. for (var i = 0; i < dimLen; i++) {
  24882. var dim = dimensions[i];
  24883. if (!rawExtent[dim]) {
  24884. rawExtent[dim] = getInitialExtent();
  24885. }
  24886. if (!storage[dim]) {
  24887. storage[dim] = [];
  24888. }
  24889. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  24890. this._chunkCount = storage[dim].length;
  24891. }
  24892. var emptyDataItem = new Array(dimLen);
  24893. for (var idx = start; idx < end; idx++) {
  24894. var sourceIdx = idx - start;
  24895. var chunkIndex = Math.floor(idx / chunkSize);
  24896. var chunkOffset = idx % chunkSize; // Store the data by dimensions
  24897. for (var k = 0; k < dimLen; k++) {
  24898. var dim = dimensions[k];
  24899. var val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, k);
  24900. storage[dim][chunkIndex][chunkOffset] = val;
  24901. var dimRawExtent = rawExtent[dim];
  24902. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  24903. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  24904. }
  24905. if (names) {
  24906. this._nameList[idx] = names[sourceIdx];
  24907. }
  24908. }
  24909. this._rawCount = this._count = end; // Reset data extent
  24910. this._extent = {};
  24911. prepareInvertedIndex(this);
  24912. };
  24913. listProto._initDataFromProvider = function (start, end) {
  24914. // Optimize.
  24915. if (start >= end) {
  24916. return;
  24917. }
  24918. var chunkSize = this._chunkSize;
  24919. var rawData = this._rawData;
  24920. var storage = this._storage;
  24921. var dimensions = this.dimensions;
  24922. var dimLen = dimensions.length;
  24923. var dimensionInfoMap = this._dimensionInfos;
  24924. var nameList = this._nameList;
  24925. var idList = this._idList;
  24926. var rawExtent = this._rawExtent;
  24927. var nameRepeatCount = this._nameRepeatCount = {};
  24928. var nameDimIdx;
  24929. var originalChunkCount = this._chunkCount;
  24930. for (var i = 0; i < dimLen; i++) {
  24931. var dim = dimensions[i];
  24932. if (!rawExtent[dim]) {
  24933. rawExtent[dim] = getInitialExtent();
  24934. }
  24935. var dimInfo = dimensionInfoMap[dim];
  24936. if (dimInfo.otherDims.itemName === 0) {
  24937. nameDimIdx = this._nameDimIdx = i;
  24938. }
  24939. if (dimInfo.otherDims.itemId === 0) {
  24940. this._idDimIdx = i;
  24941. }
  24942. if (!storage[dim]) {
  24943. storage[dim] = [];
  24944. }
  24945. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  24946. this._chunkCount = storage[dim].length;
  24947. }
  24948. var dataItem = new Array(dimLen);
  24949. for (var idx = start; idx < end; idx++) {
  24950. // NOTICE: Try not to write things into dataItem
  24951. dataItem = rawData.getItem(idx, dataItem); // Each data item is value
  24952. // [1, 2]
  24953. // 2
  24954. // Bar chart, line chart which uses category axis
  24955. // only gives the 'y' value. 'x' value is the indices of category
  24956. // Use a tempValue to normalize the value to be a (x, y) value
  24957. var chunkIndex = Math.floor(idx / chunkSize);
  24958. var chunkOffset = idx % chunkSize; // Store the data by dimensions
  24959. for (var k = 0; k < dimLen; k++) {
  24960. var dim = dimensions[k];
  24961. var dimStorage = storage[dim][chunkIndex]; // PENDING NULL is empty or zero
  24962. var val = this._dimValueGetter(dataItem, dim, idx, k);
  24963. dimStorage[chunkOffset] = val;
  24964. var dimRawExtent = rawExtent[dim];
  24965. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  24966. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  24967. } // ??? FIXME not check by pure but sourceFormat?
  24968. // TODO refactor these logic.
  24969. if (!rawData.pure) {
  24970. var name = nameList[idx];
  24971. if (dataItem && name == null) {
  24972. // If dataItem is {name: ...}, it has highest priority.
  24973. // That is appropriate for many common cases.
  24974. if (dataItem.name != null) {
  24975. // There is no other place to persistent dataItem.name,
  24976. // so save it to nameList.
  24977. nameList[idx] = name = dataItem.name;
  24978. } else if (nameDimIdx != null) {
  24979. var nameDim = dimensions[nameDimIdx];
  24980. var nameDimChunk = storage[nameDim][chunkIndex];
  24981. if (nameDimChunk) {
  24982. name = nameDimChunk[chunkOffset];
  24983. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  24984. if (ordinalMeta && ordinalMeta.categories.length) {
  24985. name = ordinalMeta.categories[name];
  24986. }
  24987. }
  24988. }
  24989. } // Try using the id in option
  24990. // id or name is used on dynamical data, mapping old and new items.
  24991. var id = dataItem == null ? null : dataItem.id;
  24992. if (id == null && name != null) {
  24993. // Use name as id and add counter to avoid same name
  24994. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  24995. id = name;
  24996. if (nameRepeatCount[name] > 0) {
  24997. id += '__ec__' + nameRepeatCount[name];
  24998. }
  24999. nameRepeatCount[name]++;
  25000. }
  25001. id != null && (idList[idx] = id);
  25002. }
  25003. }
  25004. if (!rawData.persistent && rawData.clean) {
  25005. // Clean unused data if data source is typed array.
  25006. rawData.clean();
  25007. }
  25008. this._rawCount = this._count = end; // Reset data extent
  25009. this._extent = {};
  25010. prepareInvertedIndex(this);
  25011. };
  25012. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  25013. var DataCtor = dataCtors[dimInfo.type];
  25014. var lastChunkIndex = chunkCount - 1;
  25015. var dim = dimInfo.name;
  25016. var resizeChunkArray = storage[dim][lastChunkIndex];
  25017. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  25018. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize)); // The cost of the copy is probably inconsiderable
  25019. // within the initial chunkSize.
  25020. for (var j = 0; j < resizeChunkArray.length; j++) {
  25021. newStore[j] = resizeChunkArray[j];
  25022. }
  25023. storage[dim][lastChunkIndex] = newStore;
  25024. } // Create new chunks.
  25025. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  25026. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  25027. }
  25028. }
  25029. function prepareInvertedIndex(list) {
  25030. var invertedIndicesMap = list._invertedIndicesMap;
  25031. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  25032. var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  25033. var ordinalMeta = dimInfo.ordinalMeta;
  25034. if (ordinalMeta) {
  25035. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  25036. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  25037. for (var i = 0; i < invertedIndices.length; i++) {
  25038. invertedIndices[i] = INDEX_NOT_FOUND;
  25039. }
  25040. for (var i = 0; i < list._count; i++) {
  25041. // Only support the case that all values are distinct.
  25042. invertedIndices[list.get(dim, i)] = i;
  25043. }
  25044. }
  25045. });
  25046. }
  25047. function getRawValueFromStore(list, dimIndex, rawIndex) {
  25048. var val;
  25049. if (dimIndex != null) {
  25050. var chunkSize = list._chunkSize;
  25051. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25052. var chunkOffset = rawIndex % chunkSize;
  25053. var dim = list.dimensions[dimIndex];
  25054. var chunk = list._storage[dim][chunkIndex];
  25055. if (chunk) {
  25056. val = chunk[chunkOffset];
  25057. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  25058. if (ordinalMeta && ordinalMeta.categories.length) {
  25059. val = ordinalMeta.categories[val];
  25060. }
  25061. }
  25062. }
  25063. return val;
  25064. }
  25065. /**
  25066. * @return {number}
  25067. */
  25068. listProto.count = function () {
  25069. return this._count;
  25070. };
  25071. listProto.getIndices = function () {
  25072. var newIndices;
  25073. var indices = this._indices;
  25074. if (indices) {
  25075. var Ctor = indices.constructor;
  25076. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  25077. if (Ctor === Array) {
  25078. newIndices = new Ctor(thisCount);
  25079. for (var i = 0; i < thisCount; i++) {
  25080. newIndices[i] = indices[i];
  25081. }
  25082. } else {
  25083. newIndices = new Ctor(indices.buffer, 0, thisCount);
  25084. }
  25085. } else {
  25086. var Ctor = getIndicesCtor(this);
  25087. var newIndices = new Ctor(this.count());
  25088. for (var i = 0; i < newIndices.length; i++) {
  25089. newIndices[i] = i;
  25090. }
  25091. }
  25092. return newIndices;
  25093. };
  25094. /**
  25095. * Get value. Return NaN if idx is out of range.
  25096. * @param {string} dim Dim must be concrete name.
  25097. * @param {number} idx
  25098. * @param {boolean} stack
  25099. * @return {number}
  25100. */
  25101. listProto.get = function (dim, idx
  25102. /*, stack */
  25103. ) {
  25104. if (!(idx >= 0 && idx < this._count)) {
  25105. return NaN;
  25106. }
  25107. var storage = this._storage;
  25108. if (!storage[dim]) {
  25109. // TODO Warn ?
  25110. return NaN;
  25111. }
  25112. idx = this.getRawIndex(idx);
  25113. var chunkIndex = Math.floor(idx / this._chunkSize);
  25114. var chunkOffset = idx % this._chunkSize;
  25115. var chunkStore = storage[dim][chunkIndex];
  25116. var value = chunkStore[chunkOffset]; // FIXME ordinal data type is not stackable
  25117. // if (stack) {
  25118. // var dimensionInfo = this._dimensionInfos[dim];
  25119. // if (dimensionInfo && dimensionInfo.stackable) {
  25120. // var stackedOn = this.stackedOn;
  25121. // while (stackedOn) {
  25122. // // Get no stacked data of stacked on
  25123. // var stackedValue = stackedOn.get(dim, idx);
  25124. // // Considering positive stack, negative stack and empty data
  25125. // if ((value >= 0 && stackedValue > 0) // Positive stack
  25126. // || (value <= 0 && stackedValue < 0) // Negative stack
  25127. // ) {
  25128. // value += stackedValue;
  25129. // }
  25130. // stackedOn = stackedOn.stackedOn;
  25131. // }
  25132. // }
  25133. // }
  25134. return value;
  25135. };
  25136. /**
  25137. * @param {string} dim concrete dim
  25138. * @param {number} rawIndex
  25139. * @return {number|string}
  25140. */
  25141. listProto.getByRawIndex = function (dim, rawIdx) {
  25142. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  25143. return NaN;
  25144. }
  25145. var dimStore = this._storage[dim];
  25146. if (!dimStore) {
  25147. // TODO Warn ?
  25148. return NaN;
  25149. }
  25150. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25151. var chunkOffset = rawIdx % this._chunkSize;
  25152. var chunkStore = dimStore[chunkIndex];
  25153. return chunkStore[chunkOffset];
  25154. };
  25155. /**
  25156. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  25157. * Hack a much simpler _getFast
  25158. * @private
  25159. */
  25160. listProto._getFast = function (dim, rawIdx) {
  25161. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25162. var chunkOffset = rawIdx % this._chunkSize;
  25163. var chunkStore = this._storage[dim][chunkIndex];
  25164. return chunkStore[chunkOffset];
  25165. };
  25166. /**
  25167. * Get value for multi dimensions.
  25168. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  25169. * @param {number} idx
  25170. * @return {number}
  25171. */
  25172. listProto.getValues = function (dimensions, idx
  25173. /*, stack */
  25174. ) {
  25175. var values = [];
  25176. if (!isArray(dimensions)) {
  25177. // stack = idx;
  25178. idx = dimensions;
  25179. dimensions = this.dimensions;
  25180. }
  25181. for (var i = 0, len = dimensions.length; i < len; i++) {
  25182. values.push(this.get(dimensions[i], idx
  25183. /*, stack */
  25184. ));
  25185. }
  25186. return values;
  25187. };
  25188. /**
  25189. * If value is NaN. Inlcuding '-'
  25190. * Only check the coord dimensions.
  25191. * @param {string} dim
  25192. * @param {number} idx
  25193. * @return {number}
  25194. */
  25195. listProto.hasValue = function (idx) {
  25196. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  25197. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  25198. // Ordinal type originally can be string or number.
  25199. // But when an ordinal type is used on coord, it can
  25200. // not be string but only number. So we can also use isNaN.
  25201. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  25202. return false;
  25203. }
  25204. }
  25205. return true;
  25206. };
  25207. /**
  25208. * Get extent of data in one dimension
  25209. * @param {string} dim
  25210. * @param {boolean} stack
  25211. */
  25212. listProto.getDataExtent = function (dim
  25213. /*, stack */
  25214. ) {
  25215. // Make sure use concrete dim as cache name.
  25216. dim = this.getDimension(dim);
  25217. var dimData = this._storage[dim];
  25218. var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim));
  25219. if (!dimData) {
  25220. return initialExtent;
  25221. } // Make more strict checkings to ensure hitting cache.
  25222. var currEnd = this.count(); // var cacheName = [dim, !!stack].join('_');
  25223. // var cacheName = dim;
  25224. // Consider the most cases when using data zoom, `getDataExtent`
  25225. // happened before filtering. We cache raw extent, which is not
  25226. // necessary to be cleared and recalculated when restore data.
  25227. var useRaw = !this._indices; // && !stack;
  25228. var dimExtent;
  25229. if (useRaw) {
  25230. return this._rawExtent[dim].slice();
  25231. }
  25232. dimExtent = this._extent[dim];
  25233. if (dimExtent) {
  25234. return dimExtent.slice();
  25235. }
  25236. dimExtent = initialExtent;
  25237. var min = dimExtent[0];
  25238. var max = dimExtent[1];
  25239. for (var i = 0; i < currEnd; i++) {
  25240. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  25241. var value = this._getFast(dim, this.getRawIndex(i));
  25242. value < min && (min = value);
  25243. value > max && (max = value);
  25244. }
  25245. dimExtent = [min, max];
  25246. this._extent[dim] = dimExtent;
  25247. return dimExtent;
  25248. };
  25249. /**
  25250. * Optimize for the scenario that data is filtered by a given extent.
  25251. * Consider that if data amount is more than hundreds of thousand,
  25252. * extent calculation will cost more than 10ms and the cache will
  25253. * be erased because of the filtering.
  25254. */
  25255. listProto.getApproximateExtent = function (dim
  25256. /*, stack */
  25257. ) {
  25258. dim = this.getDimension(dim);
  25259. return this._approximateExtent[dim] || this.getDataExtent(dim
  25260. /*, stack */
  25261. );
  25262. };
  25263. listProto.setApproximateExtent = function (extent, dim
  25264. /*, stack */
  25265. ) {
  25266. dim = this.getDimension(dim);
  25267. this._approximateExtent[dim] = extent.slice();
  25268. };
  25269. /**
  25270. * @param {string} key
  25271. * @return {*}
  25272. */
  25273. listProto.getCalculationInfo = function (key) {
  25274. return this._calculationInfo[key];
  25275. };
  25276. /**
  25277. * @param {string|Object} key or k-v object
  25278. * @param {*} [value]
  25279. */
  25280. listProto.setCalculationInfo = function (key, value) {
  25281. isObject$4(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  25282. };
  25283. /**
  25284. * Get sum of data in one dimension
  25285. * @param {string} dim
  25286. */
  25287. listProto.getSum = function (dim
  25288. /*, stack */
  25289. ) {
  25290. var dimData = this._storage[dim];
  25291. var sum = 0;
  25292. if (dimData) {
  25293. for (var i = 0, len = this.count(); i < len; i++) {
  25294. var value = this.get(dim, i
  25295. /*, stack */
  25296. );
  25297. if (!isNaN(value)) {
  25298. sum += value;
  25299. }
  25300. }
  25301. }
  25302. return sum;
  25303. };
  25304. /**
  25305. * Get median of data in one dimension
  25306. * @param {string} dim
  25307. */
  25308. listProto.getMedian = function (dim
  25309. /*, stack */
  25310. ) {
  25311. var dimDataArray = []; // map all data of one dimension
  25312. this.each(dim, function (val, idx) {
  25313. if (!isNaN(val)) {
  25314. dimDataArray.push(val);
  25315. }
  25316. }); // TODO
  25317. // Use quick select?
  25318. // immutability & sort
  25319. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  25320. return a - b;
  25321. });
  25322. var len = this.count(); // calculate median
  25323. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  25324. }; // /**
  25325. // * Retreive the index with given value
  25326. // * @param {string} dim Concrete dimension.
  25327. // * @param {number} value
  25328. // * @return {number}
  25329. // */
  25330. // Currently incorrect: should return dataIndex but not rawIndex.
  25331. // Do not fix it until this method is to be used somewhere.
  25332. // FIXME Precision of float value
  25333. // listProto.indexOf = function (dim, value) {
  25334. // var storage = this._storage;
  25335. // var dimData = storage[dim];
  25336. // var chunkSize = this._chunkSize;
  25337. // if (dimData) {
  25338. // for (var i = 0, len = this.count(); i < len; i++) {
  25339. // var chunkIndex = Math.floor(i / chunkSize);
  25340. // var chunkOffset = i % chunkSize;
  25341. // if (dimData[chunkIndex][chunkOffset] === value) {
  25342. // return i;
  25343. // }
  25344. // }
  25345. // }
  25346. // return -1;
  25347. // };
  25348. /**
  25349. * Only support the dimension which inverted index created.
  25350. * Do not support other cases until required.
  25351. * @param {string} concrete dim
  25352. * @param {number|string} value
  25353. * @return {number} rawIndex
  25354. */
  25355. listProto.rawIndexOf = function (dim, value) {
  25356. var invertedIndices = dim && this._invertedIndicesMap[dim];
  25357. var rawIndex = invertedIndices[value];
  25358. if (rawIndex == null || isNaN(rawIndex)) {
  25359. return INDEX_NOT_FOUND;
  25360. }
  25361. return rawIndex;
  25362. };
  25363. /**
  25364. * Retreive the index with given name
  25365. * @param {number} idx
  25366. * @param {number} name
  25367. * @return {number}
  25368. */
  25369. listProto.indexOfName = function (name) {
  25370. for (var i = 0, len = this.count(); i < len; i++) {
  25371. if (this.getName(i) === name) {
  25372. return i;
  25373. }
  25374. }
  25375. return -1;
  25376. };
  25377. /**
  25378. * Retreive the index with given raw data index
  25379. * @param {number} idx
  25380. * @param {number} name
  25381. * @return {number}
  25382. */
  25383. listProto.indexOfRawIndex = function (rawIndex) {
  25384. if (rawIndex >= this._rawCount || rawIndex < 0) {
  25385. return -1;
  25386. }
  25387. if (!this._indices) {
  25388. return rawIndex;
  25389. } // Indices are ascending
  25390. var indices = this._indices; // If rawIndex === dataIndex
  25391. var rawDataIndex = indices[rawIndex];
  25392. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  25393. return rawIndex;
  25394. }
  25395. var left = 0;
  25396. var right = this._count - 1;
  25397. while (left <= right) {
  25398. var mid = (left + right) / 2 | 0;
  25399. if (indices[mid] < rawIndex) {
  25400. left = mid + 1;
  25401. } else if (indices[mid] > rawIndex) {
  25402. right = mid - 1;
  25403. } else {
  25404. return mid;
  25405. }
  25406. }
  25407. return -1;
  25408. };
  25409. /**
  25410. * Retreive the index of nearest value
  25411. * @param {string} dim
  25412. * @param {number} value
  25413. * @param {number} [maxDistance=Infinity]
  25414. * @return {Array.<number>} If and only if multiple indices has
  25415. * the same value, they are put to the result.
  25416. */
  25417. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  25418. var storage = this._storage;
  25419. var dimData = storage[dim];
  25420. var nearestIndices = [];
  25421. if (!dimData) {
  25422. return nearestIndices;
  25423. }
  25424. if (maxDistance == null) {
  25425. maxDistance = Infinity;
  25426. }
  25427. var minDist = Infinity;
  25428. var minDiff = -1;
  25429. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/List.js`.
  25430. for (var i = 0, len = this.count(); i < len; i++) {
  25431. var diff = value - this.get(dim, i);
  25432. var dist = Math.abs(diff);
  25433. if (dist <= maxDistance) {
  25434. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  25435. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  25436. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  25437. // So we chose the one that `diff >= 0` in this csae.
  25438. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  25439. // should be push to `nearestIndices`.
  25440. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  25441. minDist = dist;
  25442. minDiff = diff;
  25443. nearestIndicesLen = 0;
  25444. }
  25445. if (diff === minDiff) {
  25446. nearestIndices[nearestIndicesLen++] = i;
  25447. }
  25448. }
  25449. }
  25450. nearestIndices.length = nearestIndicesLen;
  25451. return nearestIndices;
  25452. };
  25453. /**
  25454. * Get raw data index
  25455. * @param {number} idx
  25456. * @return {number}
  25457. */
  25458. listProto.getRawIndex = getRawIndexWithoutIndices;
  25459. function getRawIndexWithoutIndices(idx) {
  25460. return idx;
  25461. }
  25462. function getRawIndexWithIndices(idx) {
  25463. if (idx < this._count && idx >= 0) {
  25464. return this._indices[idx];
  25465. }
  25466. return -1;
  25467. }
  25468. /**
  25469. * Get raw data item
  25470. * @param {number} idx
  25471. * @return {number}
  25472. */
  25473. listProto.getRawDataItem = function (idx) {
  25474. if (!this._rawData.persistent) {
  25475. var val = [];
  25476. for (var i = 0; i < this.dimensions.length; i++) {
  25477. var dim = this.dimensions[i];
  25478. val.push(this.get(dim, idx));
  25479. }
  25480. return val;
  25481. } else {
  25482. return this._rawData.getItem(this.getRawIndex(idx));
  25483. }
  25484. };
  25485. /**
  25486. * @param {number} idx
  25487. * @param {boolean} [notDefaultIdx=false]
  25488. * @return {string}
  25489. */
  25490. listProto.getName = function (idx) {
  25491. var rawIndex = this.getRawIndex(idx);
  25492. return this._nameList[rawIndex] || getRawValueFromStore(this, this._nameDimIdx, rawIndex) || '';
  25493. };
  25494. /**
  25495. * @param {number} idx
  25496. * @param {boolean} [notDefaultIdx=false]
  25497. * @return {string}
  25498. */
  25499. listProto.getId = function (idx) {
  25500. return getId(this, this.getRawIndex(idx));
  25501. };
  25502. function getId(list, rawIndex) {
  25503. var id = list._idList[rawIndex];
  25504. if (id == null) {
  25505. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  25506. }
  25507. if (id == null) {
  25508. // FIXME Check the usage in graph, should not use prefix.
  25509. id = ID_PREFIX + rawIndex;
  25510. }
  25511. return id;
  25512. }
  25513. function normalizeDimensions(dimensions) {
  25514. if (!isArray(dimensions)) {
  25515. dimensions = [dimensions];
  25516. }
  25517. return dimensions;
  25518. }
  25519. /**
  25520. * Data iteration
  25521. * @param {string|Array.<string>}
  25522. * @param {Function} cb
  25523. * @param {*} [context=this]
  25524. *
  25525. * @example
  25526. * list.each('x', function (x, idx) {});
  25527. * list.each(['x', 'y'], function (x, y, idx) {});
  25528. * list.each(function (idx) {})
  25529. */
  25530. listProto.each = function (dims, cb, context, contextCompat) {
  25531. 'use strict';
  25532. if (!this._count) {
  25533. return;
  25534. }
  25535. if (typeof dims === 'function') {
  25536. contextCompat = context;
  25537. context = cb;
  25538. cb = dims;
  25539. dims = [];
  25540. } // contextCompat just for compat echarts3
  25541. context = context || contextCompat || this;
  25542. dims = map(normalizeDimensions(dims), this.getDimension, this);
  25543. var dimSize = dims.length;
  25544. for (var i = 0; i < this.count(); i++) {
  25545. // Simple optimization
  25546. switch (dimSize) {
  25547. case 0:
  25548. cb.call(context, i);
  25549. break;
  25550. case 1:
  25551. cb.call(context, this.get(dims[0], i), i);
  25552. break;
  25553. case 2:
  25554. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  25555. break;
  25556. default:
  25557. var k = 0;
  25558. var value = [];
  25559. for (; k < dimSize; k++) {
  25560. value[k] = this.get(dims[k], i);
  25561. } // Index
  25562. value[k] = i;
  25563. cb.apply(context, value);
  25564. }
  25565. }
  25566. };
  25567. /**
  25568. * Data filter
  25569. * @param {string|Array.<string>}
  25570. * @param {Function} cb
  25571. * @param {*} [context=this]
  25572. */
  25573. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  25574. 'use strict';
  25575. if (!this._count) {
  25576. return;
  25577. }
  25578. if (typeof dimensions === 'function') {
  25579. contextCompat = context;
  25580. context = cb;
  25581. cb = dimensions;
  25582. dimensions = [];
  25583. } // contextCompat just for compat echarts3
  25584. context = context || contextCompat || this;
  25585. dimensions = map(normalizeDimensions(dimensions), this.getDimension, this);
  25586. var count = this.count();
  25587. var Ctor = getIndicesCtor(this);
  25588. var newIndices = new Ctor(count);
  25589. var value = [];
  25590. var dimSize = dimensions.length;
  25591. var offset = 0;
  25592. var dim0 = dimensions[0];
  25593. for (var i = 0; i < count; i++) {
  25594. var keep;
  25595. var rawIdx = this.getRawIndex(i); // Simple optimization
  25596. if (dimSize === 0) {
  25597. keep = cb.call(context, i);
  25598. } else if (dimSize === 1) {
  25599. var val = this._getFast(dim0, rawIdx);
  25600. keep = cb.call(context, val, i);
  25601. } else {
  25602. for (var k = 0; k < dimSize; k++) {
  25603. value[k] = this._getFast(dim0, rawIdx);
  25604. }
  25605. value[k] = i;
  25606. keep = cb.apply(context, value);
  25607. }
  25608. if (keep) {
  25609. newIndices[offset++] = rawIdx;
  25610. }
  25611. } // Set indices after filtered.
  25612. if (offset < count) {
  25613. this._indices = newIndices;
  25614. }
  25615. this._count = offset; // Reset data extent
  25616. this._extent = {};
  25617. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25618. return this;
  25619. };
  25620. /**
  25621. * Select data in range. (For optimization of filter)
  25622. * (Manually inline code, support 5 million data filtering in data zoom.)
  25623. */
  25624. listProto.selectRange = function (range) {
  25625. 'use strict';
  25626. if (!this._count) {
  25627. return;
  25628. }
  25629. var dimensions = [];
  25630. for (var dim in range) {
  25631. if (range.hasOwnProperty(dim)) {
  25632. dimensions.push(dim);
  25633. }
  25634. }
  25635. var dimSize = dimensions.length;
  25636. if (!dimSize) {
  25637. return;
  25638. }
  25639. var originalCount = this.count();
  25640. var Ctor = getIndicesCtor(this);
  25641. var newIndices = new Ctor(originalCount);
  25642. var offset = 0;
  25643. var dim0 = dimensions[0];
  25644. var min = range[dim0][0];
  25645. var max = range[dim0][1];
  25646. var quickFinished = false;
  25647. if (!this._indices) {
  25648. // Extreme optimization for common case. About 2x faster in chrome.
  25649. var idx = 0;
  25650. if (dimSize === 1) {
  25651. var dimStorage = this._storage[dimensions[0]];
  25652. for (var k = 0; k < this._chunkCount; k++) {
  25653. var chunkStorage = dimStorage[k];
  25654. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25655. for (var i = 0; i < len; i++) {
  25656. var val = chunkStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  25657. // value indicates the line should be broken. But for the case like
  25658. // scatter plot, a data item with empty value will not be rendered,
  25659. // but the axis extent may be effected if some other dim of the data
  25660. // item has value. Fortunately it is not a significant negative effect.
  25661. if (val >= min && val <= max || isNaN(val)) {
  25662. newIndices[offset++] = idx;
  25663. }
  25664. idx++;
  25665. }
  25666. }
  25667. quickFinished = true;
  25668. } else if (dimSize === 2) {
  25669. var dimStorage = this._storage[dim0];
  25670. var dimStorage2 = this._storage[dimensions[1]];
  25671. var min2 = range[dimensions[1]][0];
  25672. var max2 = range[dimensions[1]][1];
  25673. for (var k = 0; k < this._chunkCount; k++) {
  25674. var chunkStorage = dimStorage[k];
  25675. var chunkStorage2 = dimStorage2[k];
  25676. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25677. for (var i = 0; i < len; i++) {
  25678. var val = chunkStorage[i];
  25679. var val2 = chunkStorage2[i]; // Do not filter NaN, see comment above.
  25680. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  25681. newIndices[offset++] = idx;
  25682. }
  25683. idx++;
  25684. }
  25685. }
  25686. quickFinished = true;
  25687. }
  25688. }
  25689. if (!quickFinished) {
  25690. if (dimSize === 1) {
  25691. for (var i = 0; i < originalCount; i++) {
  25692. var rawIndex = this.getRawIndex(i);
  25693. var val = this._getFast(dim0, rawIndex); // Do not filter NaN, see comment above.
  25694. if (val >= min && val <= max || isNaN(val)) {
  25695. newIndices[offset++] = rawIndex;
  25696. }
  25697. }
  25698. } else {
  25699. for (var i = 0; i < originalCount; i++) {
  25700. var keep = true;
  25701. var rawIndex = this.getRawIndex(i);
  25702. for (var k = 0; k < dimSize; k++) {
  25703. var dimk = dimensions[k];
  25704. var val = this._getFast(dim, rawIndex); // Do not filter NaN, see comment above.
  25705. if (val < range[dimk][0] || val > range[dimk][1]) {
  25706. keep = false;
  25707. }
  25708. }
  25709. if (keep) {
  25710. newIndices[offset++] = this.getRawIndex(i);
  25711. }
  25712. }
  25713. }
  25714. } // Set indices after filtered.
  25715. if (offset < originalCount) {
  25716. this._indices = newIndices;
  25717. }
  25718. this._count = offset; // Reset data extent
  25719. this._extent = {};
  25720. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25721. return this;
  25722. };
  25723. /**
  25724. * Data mapping to a plain array
  25725. * @param {string|Array.<string>} [dimensions]
  25726. * @param {Function} cb
  25727. * @param {*} [context=this]
  25728. * @return {Array}
  25729. */
  25730. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  25731. 'use strict';
  25732. if (typeof dimensions === 'function') {
  25733. contextCompat = context;
  25734. context = cb;
  25735. cb = dimensions;
  25736. dimensions = [];
  25737. } // contextCompat just for compat echarts3
  25738. context = context || contextCompat || this;
  25739. var result = [];
  25740. this.each(dimensions, function () {
  25741. result.push(cb && cb.apply(this, arguments));
  25742. }, context);
  25743. return result;
  25744. }; // Data in excludeDimensions is copied, otherwise transfered.
  25745. function cloneListForMapAndSample(original, excludeDimensions) {
  25746. var allDimensions = original.dimensions;
  25747. var list = new List(map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  25748. transferProperties(list, original);
  25749. var storage = list._storage = {};
  25750. var originalStorage = original._storage; // Init storage
  25751. for (var i = 0; i < allDimensions.length; i++) {
  25752. var dim = allDimensions[i];
  25753. if (originalStorage[dim]) {
  25754. // Notice that we do not reset invertedIndicesMap here, becuase
  25755. // there is no scenario of mapping or sampling ordinal dimension.
  25756. if (indexOf(excludeDimensions, dim) >= 0) {
  25757. storage[dim] = cloneDimStore(originalStorage[dim]);
  25758. list._rawExtent[dim] = getInitialExtent();
  25759. list._extent[dim] = null;
  25760. } else {
  25761. // Direct reference for other dimensions
  25762. storage[dim] = originalStorage[dim];
  25763. }
  25764. }
  25765. }
  25766. return list;
  25767. }
  25768. function cloneDimStore(originalDimStore) {
  25769. var newDimStore = new Array(originalDimStore.length);
  25770. for (var j = 0; j < originalDimStore.length; j++) {
  25771. newDimStore[j] = cloneChunk(originalDimStore[j]);
  25772. }
  25773. return newDimStore;
  25774. }
  25775. function getInitialExtent() {
  25776. return [Infinity, -Infinity];
  25777. }
  25778. /**
  25779. * Data mapping to a new List with given dimensions
  25780. * @param {string|Array.<string>} dimensions
  25781. * @param {Function} cb
  25782. * @param {*} [context=this]
  25783. * @return {Array}
  25784. */
  25785. listProto.map = function (dimensions, cb, context, contextCompat) {
  25786. 'use strict'; // contextCompat just for compat echarts3
  25787. context = context || contextCompat || this;
  25788. dimensions = map(normalizeDimensions(dimensions), this.getDimension, this);
  25789. var list = cloneListForMapAndSample(this, dimensions); // Following properties are all immutable.
  25790. // So we can reference to the same value
  25791. list._indices = this._indices;
  25792. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25793. var storage = list._storage;
  25794. var tmpRetValue = [];
  25795. var chunkSize = this._chunkSize;
  25796. var dimSize = dimensions.length;
  25797. var dataCount = this.count();
  25798. var values = [];
  25799. var rawExtent = list._rawExtent;
  25800. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  25801. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  25802. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex
  25803. /*, stack */
  25804. );
  25805. }
  25806. values[dimSize] = dataIndex;
  25807. var retValue = cb && cb.apply(context, values);
  25808. if (retValue != null) {
  25809. // a number or string (in oridinal dimension)?
  25810. if (typeof retValue !== 'object') {
  25811. tmpRetValue[0] = retValue;
  25812. retValue = tmpRetValue;
  25813. }
  25814. var rawIndex = this.getRawIndex(dataIndex);
  25815. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25816. var chunkOffset = rawIndex % chunkSize;
  25817. for (var i = 0; i < retValue.length; i++) {
  25818. var dim = dimensions[i];
  25819. var val = retValue[i];
  25820. var rawExtentOnDim = rawExtent[dim];
  25821. var dimStore = storage[dim];
  25822. if (dimStore) {
  25823. dimStore[chunkIndex][chunkOffset] = val;
  25824. }
  25825. if (val < rawExtentOnDim[0]) {
  25826. rawExtentOnDim[0] = val;
  25827. }
  25828. if (val > rawExtentOnDim[1]) {
  25829. rawExtentOnDim[1] = val;
  25830. }
  25831. }
  25832. }
  25833. }
  25834. return list;
  25835. };
  25836. /**
  25837. * Large data down sampling on given dimension
  25838. * @param {string} dimension
  25839. * @param {number} rate
  25840. * @param {Function} sampleValue
  25841. * @param {Function} sampleIndex Sample index for name and id
  25842. */
  25843. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  25844. var list = cloneListForMapAndSample(this, [dimension]);
  25845. var targetStorage = list._storage;
  25846. var frameValues = [];
  25847. var frameSize = Math.floor(1 / rate);
  25848. var dimStore = targetStorage[dimension];
  25849. var len = this.count();
  25850. var chunkSize = this._chunkSize;
  25851. var rawExtentOnDim = list._rawExtent[dimension];
  25852. var newIndices = new (getIndicesCtor(this))(len);
  25853. var offset = 0;
  25854. for (var i = 0; i < len; i += frameSize) {
  25855. // Last frame
  25856. if (frameSize > len - i) {
  25857. frameSize = len - i;
  25858. frameValues.length = frameSize;
  25859. }
  25860. for (var k = 0; k < frameSize; k++) {
  25861. var dataIdx = this.getRawIndex(i + k);
  25862. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  25863. var originalChunkOffset = dataIdx % chunkSize;
  25864. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  25865. }
  25866. var value = sampleValue(frameValues);
  25867. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  25868. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  25869. var sampleChunkOffset = sampleFrameIdx % chunkSize; // Only write value on the filtered data
  25870. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  25871. if (value < rawExtentOnDim[0]) {
  25872. rawExtentOnDim[0] = value;
  25873. }
  25874. if (value > rawExtentOnDim[1]) {
  25875. rawExtentOnDim[1] = value;
  25876. }
  25877. newIndices[offset++] = sampleFrameIdx;
  25878. }
  25879. list._count = offset;
  25880. list._indices = newIndices;
  25881. list.getRawIndex = getRawIndexWithIndices;
  25882. return list;
  25883. };
  25884. /**
  25885. * Get model of one data item.
  25886. *
  25887. * @param {number} idx
  25888. */
  25889. // FIXME Model proxy ?
  25890. listProto.getItemModel = function (idx) {
  25891. var hostModel = this.hostModel;
  25892. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  25893. };
  25894. /**
  25895. * Create a data differ
  25896. * @param {module:echarts/data/List} otherList
  25897. * @return {module:echarts/data/DataDiffer}
  25898. */
  25899. listProto.diff = function (otherList) {
  25900. var thisList = this;
  25901. return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) {
  25902. return getId(otherList, idx);
  25903. }, function (idx) {
  25904. return getId(thisList, idx);
  25905. });
  25906. };
  25907. /**
  25908. * Get visual property.
  25909. * @param {string} key
  25910. */
  25911. listProto.getVisual = function (key) {
  25912. var visual = this._visual;
  25913. return visual && visual[key];
  25914. };
  25915. /**
  25916. * Set visual property
  25917. * @param {string|Object} key
  25918. * @param {*} [value]
  25919. *
  25920. * @example
  25921. * setVisual('color', color);
  25922. * setVisual({
  25923. * 'color': color
  25924. * });
  25925. */
  25926. listProto.setVisual = function (key, val) {
  25927. if (isObject$4(key)) {
  25928. for (var name in key) {
  25929. if (key.hasOwnProperty(name)) {
  25930. this.setVisual(name, key[name]);
  25931. }
  25932. }
  25933. return;
  25934. }
  25935. this._visual = this._visual || {};
  25936. this._visual[key] = val;
  25937. };
  25938. /**
  25939. * Set layout property.
  25940. * @param {string|Object} key
  25941. * @param {*} [val]
  25942. */
  25943. listProto.setLayout = function (key, val) {
  25944. if (isObject$4(key)) {
  25945. for (var name in key) {
  25946. if (key.hasOwnProperty(name)) {
  25947. this.setLayout(name, key[name]);
  25948. }
  25949. }
  25950. return;
  25951. }
  25952. this._layout[key] = val;
  25953. };
  25954. /**
  25955. * Get layout property.
  25956. * @param {string} key.
  25957. * @return {*}
  25958. */
  25959. listProto.getLayout = function (key) {
  25960. return this._layout[key];
  25961. };
  25962. /**
  25963. * Get layout of single data item
  25964. * @param {number} idx
  25965. */
  25966. listProto.getItemLayout = function (idx) {
  25967. return this._itemLayouts[idx];
  25968. };
  25969. /**
  25970. * Set layout of single data item
  25971. * @param {number} idx
  25972. * @param {Object} layout
  25973. * @param {boolean=} [merge=false]
  25974. */
  25975. listProto.setItemLayout = function (idx, layout, merge$$1) {
  25976. this._itemLayouts[idx] = merge$$1 ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  25977. };
  25978. /**
  25979. * Clear all layout of single data item
  25980. */
  25981. listProto.clearItemLayouts = function () {
  25982. this._itemLayouts.length = 0;
  25983. };
  25984. /**
  25985. * Get visual property of single data item
  25986. * @param {number} idx
  25987. * @param {string} key
  25988. * @param {boolean} [ignoreParent=false]
  25989. */
  25990. listProto.getItemVisual = function (idx, key, ignoreParent) {
  25991. var itemVisual = this._itemVisuals[idx];
  25992. var val = itemVisual && itemVisual[key];
  25993. if (val == null && !ignoreParent) {
  25994. // Use global visual property
  25995. return this.getVisual(key);
  25996. }
  25997. return val;
  25998. };
  25999. /**
  26000. * Set visual property of single data item
  26001. *
  26002. * @param {number} idx
  26003. * @param {string|Object} key
  26004. * @param {*} [value]
  26005. *
  26006. * @example
  26007. * setItemVisual(0, 'color', color);
  26008. * setItemVisual(0, {
  26009. * 'color': color
  26010. * });
  26011. */
  26012. listProto.setItemVisual = function (idx, key, value) {
  26013. var itemVisual = this._itemVisuals[idx] || {};
  26014. var hasItemVisual = this.hasItemVisual;
  26015. this._itemVisuals[idx] = itemVisual;
  26016. if (isObject$4(key)) {
  26017. for (var name in key) {
  26018. if (key.hasOwnProperty(name)) {
  26019. itemVisual[name] = key[name];
  26020. hasItemVisual[name] = true;
  26021. }
  26022. }
  26023. return;
  26024. }
  26025. itemVisual[key] = value;
  26026. hasItemVisual[key] = true;
  26027. };
  26028. /**
  26029. * Clear itemVisuals and list visual.
  26030. */
  26031. listProto.clearAllVisual = function () {
  26032. this._visual = {};
  26033. this._itemVisuals = [];
  26034. this.hasItemVisual = {};
  26035. };
  26036. var setItemDataAndSeriesIndex = function (child) {
  26037. child.seriesIndex = this.seriesIndex;
  26038. child.dataIndex = this.dataIndex;
  26039. child.dataType = this.dataType;
  26040. };
  26041. /**
  26042. * Set graphic element relative to data. It can be set as null
  26043. * @param {number} idx
  26044. * @param {module:zrender/Element} [el]
  26045. */
  26046. listProto.setItemGraphicEl = function (idx, el) {
  26047. var hostModel = this.hostModel;
  26048. if (el) {
  26049. // Add data index and series index for indexing the data by element
  26050. // Useful in tooltip
  26051. el.dataIndex = idx;
  26052. el.dataType = this.dataType;
  26053. el.seriesIndex = hostModel && hostModel.seriesIndex;
  26054. if (el.type === 'group') {
  26055. el.traverse(setItemDataAndSeriesIndex, el);
  26056. }
  26057. }
  26058. this._graphicEls[idx] = el;
  26059. };
  26060. /**
  26061. * @param {number} idx
  26062. * @return {module:zrender/Element}
  26063. */
  26064. listProto.getItemGraphicEl = function (idx) {
  26065. return this._graphicEls[idx];
  26066. };
  26067. /**
  26068. * @param {Function} cb
  26069. * @param {*} context
  26070. */
  26071. listProto.eachItemGraphicEl = function (cb, context) {
  26072. each$1(this._graphicEls, function (el, idx) {
  26073. if (el) {
  26074. cb && cb.call(context, el, idx);
  26075. }
  26076. });
  26077. };
  26078. /**
  26079. * Shallow clone a new list except visual and layout properties, and graph elements.
  26080. * New list only change the indices.
  26081. */
  26082. listProto.cloneShallow = function (list) {
  26083. if (!list) {
  26084. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  26085. list = new List(dimensionInfoList, this.hostModel);
  26086. } // FIXME
  26087. list._storage = this._storage;
  26088. transferProperties(list, this); // Clone will not change the data extent and indices
  26089. if (this._indices) {
  26090. var Ctor = this._indices.constructor;
  26091. list._indices = new Ctor(this._indices);
  26092. } else {
  26093. list._indices = null;
  26094. }
  26095. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26096. return list;
  26097. };
  26098. /**
  26099. * Wrap some method to add more feature
  26100. * @param {string} methodName
  26101. * @param {Function} injectFunction
  26102. */
  26103. listProto.wrapMethod = function (methodName, injectFunction) {
  26104. var originalMethod = this[methodName];
  26105. if (typeof originalMethod !== 'function') {
  26106. return;
  26107. }
  26108. this.__wrappedMethods = this.__wrappedMethods || [];
  26109. this.__wrappedMethods.push(methodName);
  26110. this[methodName] = function () {
  26111. var res = originalMethod.apply(this, arguments);
  26112. return injectFunction.apply(this, [res].concat(slice(arguments)));
  26113. };
  26114. }; // Methods that create a new list based on this list should be listed here.
  26115. // Notice that those method should `RETURN` the new list.
  26116. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map']; // Methods that change indices of this list should be listed here.
  26117. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26118. /*
  26119. * Licensed to the Apache Software Foundation (ASF) under one
  26120. * or more contributor license agreements. See the NOTICE file
  26121. * distributed with this work for additional information
  26122. * regarding copyright ownership. The ASF licenses this file
  26123. * to you under the Apache License, Version 2.0 (the
  26124. * "License"); you may not use this file except in compliance
  26125. * with the License. You may obtain a copy of the License at
  26126. *
  26127. * http://www.apache.org/licenses/LICENSE-2.0
  26128. *
  26129. * Unless required by applicable law or agreed to in writing,
  26130. * software distributed under the License is distributed on an
  26131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26132. * KIND, either express or implied. See the License for the
  26133. * specific language governing permissions and limitations
  26134. * under the License.
  26135. */
  26136. /**
  26137. * @deprecated
  26138. * Use `echarts/data/helper/createDimensions` instead.
  26139. */
  26140. /**
  26141. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  26142. *
  26143. * This method builds the relationship between:
  26144. * + "what the coord sys or series requires (see `sysDims`)",
  26145. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  26146. * + "what the data source provids (see `source`)".
  26147. *
  26148. * Some guess strategy will be adapted if user does not define something.
  26149. * If no 'value' dimension specified, the first no-named dimension will be
  26150. * named as 'value'.
  26151. *
  26152. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  26153. * provides not only dim template, but also default order.
  26154. * properties: 'name', 'type', 'displayName'.
  26155. * `name` of each item provides default coord name.
  26156. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  26157. * provide dims count that the sysDim required.
  26158. * [{ordinalMeta}] can be specified.
  26159. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  26160. * @param {Object} [opt]
  26161. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  26162. * For example: ['asdf', {name, type}, ...].
  26163. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  26164. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  26165. * If not specified, auto find the next available data dim.
  26166. * param source {module:data/Source}
  26167. * param dimCount {number}
  26168. * return {Object} encode Never be `null/undefined`.
  26169. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  26170. * If not specified, extra dim names will be:
  26171. * 'value', 'value0', 'value1', ...
  26172. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  26173. * If `generateCoordCount` specified, the generated dim names will be:
  26174. * `generateCoord` + 0, `generateCoord` + 1, ...
  26175. * can be Infinity, indicate that use all of the remain columns.
  26176. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  26177. * @return {Array.<module:data/DataDimensionInfo>}
  26178. */
  26179. function completeDimensions(sysDims, source, opt) {
  26180. if (!Source.isInstance(source)) {
  26181. source = Source.seriesDataToSource(source);
  26182. }
  26183. opt = opt || {};
  26184. sysDims = (sysDims || []).slice();
  26185. var dimsDef = (opt.dimsDef || []).slice();
  26186. var dataDimNameMap = createHashMap();
  26187. var coordDimNameMap = createHashMap(); // var valueCandidate;
  26188. var result = [];
  26189. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result.
  26190. for (var i = 0; i < dimCount; i++) {
  26191. var dimDefItem = dimsDef[i] = extend({}, isObject$1(dimsDef[i]) ? dimsDef[i] : {
  26192. name: dimsDef[i]
  26193. });
  26194. var userDimName = dimDefItem.name;
  26195. var resultItem = result[i] = new DataDimensionInfo(); // Name will be applied later for avoiding duplication.
  26196. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  26197. // Only if `series.dimensions` is defined in option
  26198. // displayName, will be set, and dimension will be diplayed vertically in
  26199. // tooltip by default.
  26200. resultItem.name = resultItem.displayName = userDimName;
  26201. dataDimNameMap.set(userDimName, i);
  26202. }
  26203. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  26204. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  26205. }
  26206. var encodeDef = opt.encodeDef;
  26207. if (!encodeDef && opt.encodeDefaulter) {
  26208. encodeDef = opt.encodeDefaulter(source, dimCount);
  26209. }
  26210. encodeDef = createHashMap(encodeDef); // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  26211. encodeDef.each(function (dataDims, coordDim) {
  26212. dataDims = normalizeToArray(dataDims).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  26213. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  26214. // this case.
  26215. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  26216. encodeDef.set(coordDim, false);
  26217. return;
  26218. }
  26219. var validDataDims = encodeDef.set(coordDim, []);
  26220. each$1(dataDims, function (resultDimIdx, idx) {
  26221. // The input resultDimIdx can be dim name or index.
  26222. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  26223. if (resultDimIdx != null && resultDimIdx < dimCount) {
  26224. validDataDims[idx] = resultDimIdx;
  26225. applyDim(result[resultDimIdx], coordDim, idx);
  26226. }
  26227. });
  26228. }); // Apply templetes and default order from `sysDims`.
  26229. var availDimIdx = 0;
  26230. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  26231. var coordDim;
  26232. var sysDimItem;
  26233. var sysDimItemDimsDef;
  26234. var sysDimItemOtherDims;
  26235. if (isString(sysDimItem)) {
  26236. coordDim = sysDimItem;
  26237. sysDimItem = {};
  26238. } else {
  26239. coordDim = sysDimItem.name;
  26240. var ordinalMeta = sysDimItem.ordinalMeta;
  26241. sysDimItem.ordinalMeta = null;
  26242. sysDimItem = clone(sysDimItem);
  26243. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  26244. sysDimItemDimsDef = sysDimItem.dimsDef;
  26245. sysDimItemOtherDims = sysDimItem.otherDims;
  26246. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  26247. }
  26248. var dataDims = encodeDef.get(coordDim); // negative resultDimIdx means no need to mapping.
  26249. if (dataDims === false) {
  26250. return;
  26251. }
  26252. var dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  26253. if (!dataDims.length) {
  26254. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  26255. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  26256. availDimIdx++;
  26257. }
  26258. availDimIdx < result.length && dataDims.push(availDimIdx++);
  26259. }
  26260. } // Apply templates.
  26261. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  26262. var resultItem = result[resultDimIdx];
  26263. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  26264. if (resultItem.name == null && sysDimItemDimsDef) {
  26265. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  26266. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  26267. name: sysDimItemDimsDefItem
  26268. });
  26269. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  26270. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  26271. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  26272. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  26273. });
  26274. });
  26275. function applyDim(resultItem, coordDim, coordDimIndex) {
  26276. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  26277. resultItem.otherDims[coordDim] = coordDimIndex;
  26278. } else {
  26279. resultItem.coordDim = coordDim;
  26280. resultItem.coordDimIndex = coordDimIndex;
  26281. coordDimNameMap.set(coordDim, true);
  26282. }
  26283. } // Make sure the first extra dim is 'value'.
  26284. var generateCoord = opt.generateCoord;
  26285. var generateCoordCount = opt.generateCoordCount;
  26286. var fromZero = generateCoordCount != null;
  26287. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  26288. var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props.
  26289. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  26290. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  26291. var coordDim = resultItem.coordDim;
  26292. if (coordDim == null) {
  26293. resultItem.coordDim = genName(extra, coordDimNameMap, fromZero);
  26294. resultItem.coordDimIndex = 0;
  26295. if (!generateCoord || generateCoordCount <= 0) {
  26296. resultItem.isExtraCoord = true;
  26297. }
  26298. generateCoordCount--;
  26299. }
  26300. resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap));
  26301. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must // Consider the case:
  26302. // {
  26303. // dataset: {source: [
  26304. // ['2001', 123],
  26305. // ['2002', 456],
  26306. // ...
  26307. // ['The others', 987],
  26308. // ]},
  26309. // series: {type: 'pie'}
  26310. // }
  26311. // The first colum should better be treated as a "ordinal" although it
  26312. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  26313. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  26314. resultItem.type = 'ordinal';
  26315. }
  26316. }
  26317. return result;
  26318. } // ??? TODO
  26319. // Originally detect dimCount by data[0]. Should we
  26320. // optimize it to only by sysDims and dimensions and encode.
  26321. // So only necessary dims will be initialized.
  26322. // But
  26323. // (1) custom series should be considered. where other dims
  26324. // may be visited.
  26325. // (2) sometimes user need to calcualte bubble size or use visualMap
  26326. // on other dimensions besides coordSys needed.
  26327. // So, dims that is not used by system, should be shared in storage?
  26328. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  26329. // Note that the result dimCount should not small than columns count
  26330. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  26331. var dimCount = Math.max(source.dimensionsDetectCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  26332. each$1(sysDims, function (sysDimItem) {
  26333. var sysDimItemDimsDef = sysDimItem.dimsDef;
  26334. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  26335. });
  26336. return dimCount;
  26337. }
  26338. function genName(name, map$$1, fromZero) {
  26339. if (fromZero || map$$1.get(name) != null) {
  26340. var i = 0;
  26341. while (map$$1.get(name + i) != null) {
  26342. i++;
  26343. }
  26344. name += i;
  26345. }
  26346. map$$1.set(name, true);
  26347. return name;
  26348. }
  26349. /*
  26350. * Licensed to the Apache Software Foundation (ASF) under one
  26351. * or more contributor license agreements. See the NOTICE file
  26352. * distributed with this work for additional information
  26353. * regarding copyright ownership. The ASF licenses this file
  26354. * to you under the Apache License, Version 2.0 (the
  26355. * "License"); you may not use this file except in compliance
  26356. * with the License. You may obtain a copy of the License at
  26357. *
  26358. * http://www.apache.org/licenses/LICENSE-2.0
  26359. *
  26360. * Unless required by applicable law or agreed to in writing,
  26361. * software distributed under the License is distributed on an
  26362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26363. * KIND, either express or implied. See the License for the
  26364. * specific language governing permissions and limitations
  26365. * under the License.
  26366. */
  26367. /**
  26368. * Substitute `completeDimensions`.
  26369. * `completeDimensions` is to be deprecated.
  26370. */
  26371. /**
  26372. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  26373. * @param {Object|Array} [opt]
  26374. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  26375. * @param {number} [opt.dimensionsCount]
  26376. * @param {string} [opt.generateCoord]
  26377. * @param {string} [opt.generateCoordCount]
  26378. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  26379. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  26380. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  26381. * @return {Array.<Object>} dimensionsInfo
  26382. */
  26383. var createDimensions = function (source, opt) {
  26384. opt = opt || {};
  26385. return completeDimensions(opt.coordDimensions || [], source, {
  26386. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  26387. encodeDef: opt.encodeDefine || source.encodeDefine,
  26388. dimCount: opt.dimensionsCount,
  26389. encodeDefaulter: opt.encodeDefaulter,
  26390. generateCoord: opt.generateCoord,
  26391. generateCoordCount: opt.generateCoordCount
  26392. });
  26393. };
  26394. /*
  26395. * Licensed to the Apache Software Foundation (ASF) under one
  26396. * or more contributor license agreements. See the NOTICE file
  26397. * distributed with this work for additional information
  26398. * regarding copyright ownership. The ASF licenses this file
  26399. * to you under the Apache License, Version 2.0 (the
  26400. * "License"); you may not use this file except in compliance
  26401. * with the License. You may obtain a copy of the License at
  26402. *
  26403. * http://www.apache.org/licenses/LICENSE-2.0
  26404. *
  26405. * Unless required by applicable law or agreed to in writing,
  26406. * software distributed under the License is distributed on an
  26407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26408. * KIND, either express or implied. See the License for the
  26409. * specific language governing permissions and limitations
  26410. * under the License.
  26411. */
  26412. /**
  26413. * Helper for model references.
  26414. * There are many manners to refer axis/coordSys.
  26415. */
  26416. // TODO
  26417. // merge relevant logic to this file?
  26418. // check: "modelHelper" of tooltip and "BrushTargetManager".
  26419. /**
  26420. * @class
  26421. * For example:
  26422. * {
  26423. * coordSysName: 'cartesian2d',
  26424. * coordSysDims: ['x', 'y', ...],
  26425. * axisMap: HashMap({
  26426. * x: xAxisModel,
  26427. * y: yAxisModel
  26428. * }),
  26429. * categoryAxisMap: HashMap({
  26430. * x: xAxisModel,
  26431. * y: undefined
  26432. * }),
  26433. * // The index of the first category axis in `coordSysDims`.
  26434. * // `null/undefined` means no category axis exists.
  26435. * firstCategoryDimIndex: 1,
  26436. * // To replace user specified encode.
  26437. * }
  26438. */
  26439. function CoordSysInfo(coordSysName) {
  26440. /**
  26441. * @type {string}
  26442. */
  26443. this.coordSysName = coordSysName;
  26444. /**
  26445. * @type {Array.<string>}
  26446. */
  26447. this.coordSysDims = [];
  26448. /**
  26449. * @type {module:zrender/core/util#HashMap}
  26450. */
  26451. this.axisMap = createHashMap();
  26452. /**
  26453. * @type {module:zrender/core/util#HashMap}
  26454. */
  26455. this.categoryAxisMap = createHashMap();
  26456. /**
  26457. * @type {number}
  26458. */
  26459. this.firstCategoryDimIndex = null;
  26460. }
  26461. /**
  26462. * @return {module:model/referHelper#CoordSysInfo}
  26463. */
  26464. function getCoordSysInfoBySeries(seriesModel) {
  26465. var coordSysName = seriesModel.get('coordinateSystem');
  26466. var result = new CoordSysInfo(coordSysName);
  26467. var fetch = fetchers[coordSysName];
  26468. if (fetch) {
  26469. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  26470. return result;
  26471. }
  26472. }
  26473. var fetchers = {
  26474. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  26475. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  26476. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  26477. result.coordSysDims = ['x', 'y'];
  26478. axisMap.set('x', xAxisModel);
  26479. axisMap.set('y', yAxisModel);
  26480. if (isCategory(xAxisModel)) {
  26481. categoryAxisMap.set('x', xAxisModel);
  26482. result.firstCategoryDimIndex = 0;
  26483. }
  26484. if (isCategory(yAxisModel)) {
  26485. categoryAxisMap.set('y', yAxisModel);
  26486. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  26487. }
  26488. },
  26489. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  26490. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  26491. result.coordSysDims = ['single'];
  26492. axisMap.set('single', singleAxisModel);
  26493. if (isCategory(singleAxisModel)) {
  26494. categoryAxisMap.set('single', singleAxisModel);
  26495. result.firstCategoryDimIndex = 0;
  26496. }
  26497. },
  26498. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  26499. var polarModel = seriesModel.getReferringComponents('polar')[0];
  26500. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  26501. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  26502. result.coordSysDims = ['radius', 'angle'];
  26503. axisMap.set('radius', radiusAxisModel);
  26504. axisMap.set('angle', angleAxisModel);
  26505. if (isCategory(radiusAxisModel)) {
  26506. categoryAxisMap.set('radius', radiusAxisModel);
  26507. result.firstCategoryDimIndex = 0;
  26508. }
  26509. if (isCategory(angleAxisModel)) {
  26510. categoryAxisMap.set('angle', angleAxisModel);
  26511. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  26512. }
  26513. },
  26514. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  26515. result.coordSysDims = ['lng', 'lat'];
  26516. },
  26517. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  26518. var ecModel = seriesModel.ecModel;
  26519. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  26520. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  26521. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  26522. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  26523. var axisDim = coordSysDims[index];
  26524. axisMap.set(axisDim, axisModel);
  26525. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  26526. categoryAxisMap.set(axisDim, axisModel);
  26527. result.firstCategoryDimIndex = index;
  26528. }
  26529. });
  26530. }
  26531. };
  26532. function isCategory(axisModel) {
  26533. return axisModel.get('type') === 'category';
  26534. }
  26535. /*
  26536. * Licensed to the Apache Software Foundation (ASF) under one
  26537. * or more contributor license agreements. See the NOTICE file
  26538. * distributed with this work for additional information
  26539. * regarding copyright ownership. The ASF licenses this file
  26540. * to you under the Apache License, Version 2.0 (the
  26541. * "License"); you may not use this file except in compliance
  26542. * with the License. You may obtain a copy of the License at
  26543. *
  26544. * http://www.apache.org/licenses/LICENSE-2.0
  26545. *
  26546. * Unless required by applicable law or agreed to in writing,
  26547. * software distributed under the License is distributed on an
  26548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26549. * KIND, either express or implied. See the License for the
  26550. * specific language governing permissions and limitations
  26551. * under the License.
  26552. */
  26553. /**
  26554. * Note that it is too complicated to support 3d stack by value
  26555. * (have to create two-dimension inverted index), so in 3d case
  26556. * we just support that stacked by index.
  26557. *
  26558. * @param {module:echarts/model/Series} seriesModel
  26559. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  26560. * The input dimensionInfoList will be modified.
  26561. * @param {Object} [opt]
  26562. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  26563. * @param {boolean} [opt.byIndex=false]
  26564. * @return {Object} calculationInfo
  26565. * {
  26566. * stackedDimension: string
  26567. * stackedByDimension: string
  26568. * isStackedByIndex: boolean
  26569. * stackedOverDimension: string
  26570. * stackResultDimension: string
  26571. * }
  26572. */
  26573. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  26574. opt = opt || {};
  26575. var byIndex = opt.byIndex;
  26576. var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack.
  26577. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  26578. var stackedByDimInfo;
  26579. var stackedDimInfo;
  26580. var stackResultDimension;
  26581. var stackedOverDimension;
  26582. each$1(dimensionInfoList, function (dimensionInfo, index) {
  26583. if (isString(dimensionInfo)) {
  26584. dimensionInfoList[index] = dimensionInfo = {
  26585. name: dimensionInfo
  26586. };
  26587. }
  26588. if (mayStack && !dimensionInfo.isExtraCoord) {
  26589. // Find the first ordinal dimension as the stackedByDimInfo.
  26590. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  26591. stackedByDimInfo = dimensionInfo;
  26592. } // Find the first stackable dimension as the stackedDimInfo.
  26593. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  26594. stackedDimInfo = dimensionInfo;
  26595. }
  26596. }
  26597. });
  26598. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  26599. // Compatible with previous design, value axis (time axis) only stack by index.
  26600. // It may make sense if the user provides elaborately constructed data.
  26601. byIndex = true;
  26602. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  26603. // That put stack logic in List is for using conveniently in echarts extensions, but it
  26604. // might not be a good way.
  26605. if (stackedDimInfo) {
  26606. // Use a weird name that not duplicated with other names.
  26607. stackResultDimension = '__\0ecstackresult';
  26608. stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value.
  26609. if (stackedByDimInfo) {
  26610. stackedByDimInfo.createInvertedIndices = true;
  26611. }
  26612. var stackedDimCoordDim = stackedDimInfo.coordDim;
  26613. var stackedDimType = stackedDimInfo.type;
  26614. var stackedDimCoordIndex = 0;
  26615. each$1(dimensionInfoList, function (dimensionInfo) {
  26616. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  26617. stackedDimCoordIndex++;
  26618. }
  26619. });
  26620. dimensionInfoList.push({
  26621. name: stackResultDimension,
  26622. coordDim: stackedDimCoordDim,
  26623. coordDimIndex: stackedDimCoordIndex,
  26624. type: stackedDimType,
  26625. isExtraCoord: true,
  26626. isCalculationCoord: true
  26627. });
  26628. stackedDimCoordIndex++;
  26629. dimensionInfoList.push({
  26630. name: stackedOverDimension,
  26631. // This dimension contains stack base (generally, 0), so do not set it as
  26632. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  26633. coordDim: stackedOverDimension,
  26634. coordDimIndex: stackedDimCoordIndex,
  26635. type: stackedDimType,
  26636. isExtraCoord: true,
  26637. isCalculationCoord: true
  26638. });
  26639. }
  26640. return {
  26641. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  26642. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  26643. isStackedByIndex: byIndex,
  26644. stackedOverDimension: stackedOverDimension,
  26645. stackResultDimension: stackResultDimension
  26646. };
  26647. }
  26648. /**
  26649. * @param {module:echarts/data/List} data
  26650. * @param {string} stackedDim
  26651. */
  26652. function isDimensionStacked(data, stackedDim
  26653. /*, stackedByDim*/
  26654. ) {
  26655. // Each single series only maps to one pair of axis. So we do not need to
  26656. // check stackByDim, whatever stacked by a dimension or stacked by index.
  26657. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); // && (
  26658. // stackedByDim != null
  26659. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  26660. // : data.getCalculationInfo('isStackedByIndex')
  26661. // );
  26662. }
  26663. /**
  26664. * @param {module:echarts/data/List} data
  26665. * @param {string} targetDim
  26666. * @param {string} [stackedByDim] If not input this parameter, check whether
  26667. * stacked by index.
  26668. * @return {string} dimension
  26669. */
  26670. function getStackedDimension(data, targetDim) {
  26671. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  26672. }
  26673. /*
  26674. * Licensed to the Apache Software Foundation (ASF) under one
  26675. * or more contributor license agreements. See the NOTICE file
  26676. * distributed with this work for additional information
  26677. * regarding copyright ownership. The ASF licenses this file
  26678. * to you under the Apache License, Version 2.0 (the
  26679. * "License"); you may not use this file except in compliance
  26680. * with the License. You may obtain a copy of the License at
  26681. *
  26682. * http://www.apache.org/licenses/LICENSE-2.0
  26683. *
  26684. * Unless required by applicable law or agreed to in writing,
  26685. * software distributed under the License is distributed on an
  26686. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26687. * KIND, either express or implied. See the License for the
  26688. * specific language governing permissions and limitations
  26689. * under the License.
  26690. */
  26691. /**
  26692. * @param {module:echarts/data/Source|Array} source Or raw data.
  26693. * @param {module:echarts/model/Series} seriesModel
  26694. * @param {Object} [opt]
  26695. * @param {string} [opt.generateCoord]
  26696. * @param {boolean} [opt.useEncodeDefaulter]
  26697. */
  26698. function createListFromArray(source, seriesModel, opt) {
  26699. opt = opt || {};
  26700. if (!Source.isInstance(source)) {
  26701. source = Source.seriesDataToSource(source);
  26702. }
  26703. var coordSysName = seriesModel.get('coordinateSystem');
  26704. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  26705. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  26706. var coordSysDimDefs;
  26707. if (coordSysInfo) {
  26708. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  26709. var dimInfo = {
  26710. name: dim
  26711. };
  26712. var axisModel = coordSysInfo.axisMap.get(dim);
  26713. if (axisModel) {
  26714. var axisType = axisModel.get('type');
  26715. dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType);
  26716. }
  26717. return dimInfo;
  26718. });
  26719. }
  26720. if (!coordSysDimDefs) {
  26721. // Get dimensions from registered coordinate system
  26722. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  26723. }
  26724. var dimInfoList = createDimensions(source, {
  26725. coordDimensions: coordSysDimDefs,
  26726. generateCoord: opt.generateCoord,
  26727. encodeDefaulter: opt.useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null
  26728. });
  26729. var firstCategoryDimIndex;
  26730. var hasNameEncode;
  26731. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  26732. var coordDim = dimInfo.coordDim;
  26733. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  26734. if (categoryAxisModel) {
  26735. if (firstCategoryDimIndex == null) {
  26736. firstCategoryDimIndex = dimIndex;
  26737. }
  26738. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  26739. }
  26740. if (dimInfo.otherDims.itemName != null) {
  26741. hasNameEncode = true;
  26742. }
  26743. });
  26744. if (!hasNameEncode && firstCategoryDimIndex != null) {
  26745. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  26746. }
  26747. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  26748. var list = new List(dimInfoList, seriesModel);
  26749. list.setCalculationInfo(stackCalculationInfo);
  26750. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  26751. // Use dataIndex as ordinal value in categoryAxis
  26752. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  26753. } : null;
  26754. list.hasItemOption = false;
  26755. list.initData(source, null, dimValueGetter);
  26756. return list;
  26757. }
  26758. function isNeedCompleteOrdinalData(source) {
  26759. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  26760. var sampleItem = firstDataNotNull(source.data || []);
  26761. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  26762. }
  26763. }
  26764. function firstDataNotNull(data) {
  26765. var i = 0;
  26766. while (i < data.length && data[i] == null) {
  26767. i++;
  26768. }
  26769. return data[i];
  26770. }
  26771. /*
  26772. * Licensed to the Apache Software Foundation (ASF) under one
  26773. * or more contributor license agreements. See the NOTICE file
  26774. * distributed with this work for additional information
  26775. * regarding copyright ownership. The ASF licenses this file
  26776. * to you under the Apache License, Version 2.0 (the
  26777. * "License"); you may not use this file except in compliance
  26778. * with the License. You may obtain a copy of the License at
  26779. *
  26780. * http://www.apache.org/licenses/LICENSE-2.0
  26781. *
  26782. * Unless required by applicable law or agreed to in writing,
  26783. * software distributed under the License is distributed on an
  26784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26785. * KIND, either express or implied. See the License for the
  26786. * specific language governing permissions and limitations
  26787. * under the License.
  26788. */
  26789. /**
  26790. * // Scale class management
  26791. * @module echarts/scale/Scale
  26792. */
  26793. /**
  26794. * @param {Object} [setting]
  26795. */
  26796. function Scale(setting) {
  26797. this._setting = setting || {};
  26798. /**
  26799. * Extent
  26800. * @type {Array.<number>}
  26801. * @protected
  26802. */
  26803. this._extent = [Infinity, -Infinity];
  26804. /**
  26805. * Step is calculated in adjustExtent
  26806. * @type {Array.<number>}
  26807. * @protected
  26808. */
  26809. this._interval = 0;
  26810. this.init && this.init.apply(this, arguments);
  26811. }
  26812. /**
  26813. * Parse input val to valid inner number.
  26814. * @param {*} val
  26815. * @return {number}
  26816. */
  26817. Scale.prototype.parse = function (val) {
  26818. // Notice: This would be a trap here, If the implementation
  26819. // of this method depends on extent, and this method is used
  26820. // before extent set (like in dataZoom), it would be wrong.
  26821. // Nevertheless, parse does not depend on extent generally.
  26822. return val;
  26823. };
  26824. Scale.prototype.getSetting = function (name) {
  26825. return this._setting[name];
  26826. };
  26827. Scale.prototype.contain = function (val) {
  26828. var extent = this._extent;
  26829. return val >= extent[0] && val <= extent[1];
  26830. };
  26831. /**
  26832. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  26833. * @param {number} val
  26834. * @return {number}
  26835. */
  26836. Scale.prototype.normalize = function (val) {
  26837. var extent = this._extent;
  26838. if (extent[1] === extent[0]) {
  26839. return 0.5;
  26840. }
  26841. return (val - extent[0]) / (extent[1] - extent[0]);
  26842. };
  26843. /**
  26844. * Scale normalized value
  26845. * @param {number} val
  26846. * @return {number}
  26847. */
  26848. Scale.prototype.scale = function (val) {
  26849. var extent = this._extent;
  26850. return val * (extent[1] - extent[0]) + extent[0];
  26851. };
  26852. /**
  26853. * Set extent from data
  26854. * @param {Array.<number>} other
  26855. */
  26856. Scale.prototype.unionExtent = function (other) {
  26857. var extent = this._extent;
  26858. other[0] < extent[0] && (extent[0] = other[0]);
  26859. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  26860. // this.setExtent(extent[0], extent[1]);
  26861. };
  26862. /**
  26863. * Set extent from data
  26864. * @param {module:echarts/data/List} data
  26865. * @param {string} dim
  26866. */
  26867. Scale.prototype.unionExtentFromData = function (data, dim) {
  26868. this.unionExtent(data.getApproximateExtent(dim));
  26869. };
  26870. /**
  26871. * Get extent
  26872. * @return {Array.<number>}
  26873. */
  26874. Scale.prototype.getExtent = function () {
  26875. return this._extent.slice();
  26876. };
  26877. /**
  26878. * Set extent
  26879. * @param {number} start
  26880. * @param {number} end
  26881. */
  26882. Scale.prototype.setExtent = function (start, end) {
  26883. var thisExtent = this._extent;
  26884. if (!isNaN(start)) {
  26885. thisExtent[0] = start;
  26886. }
  26887. if (!isNaN(end)) {
  26888. thisExtent[1] = end;
  26889. }
  26890. };
  26891. /**
  26892. * When axis extent depends on data and no data exists,
  26893. * axis ticks should not be drawn, which is named 'blank'.
  26894. */
  26895. Scale.prototype.isBlank = function () {
  26896. return this._isBlank;
  26897. },
  26898. /**
  26899. * When axis extent depends on data and no data exists,
  26900. * axis ticks should not be drawn, which is named 'blank'.
  26901. */
  26902. Scale.prototype.setBlank = function (isBlank) {
  26903. this._isBlank = isBlank;
  26904. };
  26905. /**
  26906. * @abstract
  26907. * @param {*} tick
  26908. * @return {string} label of the tick.
  26909. */
  26910. Scale.prototype.getLabel = null;
  26911. enableClassExtend(Scale);
  26912. enableClassManagement(Scale, {
  26913. registerWhenExtend: true
  26914. });
  26915. /*
  26916. * Licensed to the Apache Software Foundation (ASF) under one
  26917. * or more contributor license agreements. See the NOTICE file
  26918. * distributed with this work for additional information
  26919. * regarding copyright ownership. The ASF licenses this file
  26920. * to you under the Apache License, Version 2.0 (the
  26921. * "License"); you may not use this file except in compliance
  26922. * with the License. You may obtain a copy of the License at
  26923. *
  26924. * http://www.apache.org/licenses/LICENSE-2.0
  26925. *
  26926. * Unless required by applicable law or agreed to in writing,
  26927. * software distributed under the License is distributed on an
  26928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26929. * KIND, either express or implied. See the License for the
  26930. * specific language governing permissions and limitations
  26931. * under the License.
  26932. */
  26933. /**
  26934. * @constructor
  26935. * @param {Object} [opt]
  26936. * @param {Object} [opt.categories=[]]
  26937. * @param {Object} [opt.needCollect=false]
  26938. * @param {Object} [opt.deduplication=false]
  26939. */
  26940. function OrdinalMeta(opt) {
  26941. /**
  26942. * @readOnly
  26943. * @type {Array.<string>}
  26944. */
  26945. this.categories = opt.categories || [];
  26946. /**
  26947. * @private
  26948. * @type {boolean}
  26949. */
  26950. this._needCollect = opt.needCollect;
  26951. /**
  26952. * @private
  26953. * @type {boolean}
  26954. */
  26955. this._deduplication = opt.deduplication;
  26956. /**
  26957. * @private
  26958. * @type {boolean}
  26959. */
  26960. this._map;
  26961. }
  26962. /**
  26963. * @param {module:echarts/model/Model} axisModel
  26964. * @return {module:echarts/data/OrdinalMeta}
  26965. */
  26966. OrdinalMeta.createByAxisModel = function (axisModel) {
  26967. var option = axisModel.option;
  26968. var data = option.data;
  26969. var categories = data && map(data, getName);
  26970. return new OrdinalMeta({
  26971. categories: categories,
  26972. needCollect: !categories,
  26973. // deduplication is default in axis.
  26974. deduplication: option.dedplication !== false
  26975. });
  26976. };
  26977. var proto$1 = OrdinalMeta.prototype;
  26978. /**
  26979. * @param {string} category
  26980. * @return {number} ordinal
  26981. */
  26982. proto$1.getOrdinal = function (category) {
  26983. return getOrCreateMap(this).get(category);
  26984. };
  26985. /**
  26986. * @param {*} category
  26987. * @return {number} The ordinal. If not found, return NaN.
  26988. */
  26989. proto$1.parseAndCollect = function (category) {
  26990. var index;
  26991. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  26992. // This feature is only supported when !needCollect, because we should
  26993. // consider a common case: a value is 2017, which is a number but is
  26994. // expected to be tread as a category. This case usually happen in dataset,
  26995. // where it happent to be no need of the index feature.
  26996. if (typeof category !== 'string' && !needCollect) {
  26997. return category;
  26998. } // Optimize for the scenario:
  26999. // category is ['2012-01-01', '2012-01-02', ...], where the input
  27000. // data has been ensured not duplicate and is large data.
  27001. // Notice, if a dataset dimension provide categroies, usually echarts
  27002. // should remove duplication except user tell echarts dont do that
  27003. // (set axis.deduplication = false), because echarts do not know whether
  27004. // the values in the category dimension has duplication (consider the
  27005. // parallel-aqi example)
  27006. if (needCollect && !this._deduplication) {
  27007. index = this.categories.length;
  27008. this.categories[index] = category;
  27009. return index;
  27010. }
  27011. var map$$1 = getOrCreateMap(this);
  27012. index = map$$1.get(category);
  27013. if (index == null) {
  27014. if (needCollect) {
  27015. index = this.categories.length;
  27016. this.categories[index] = category;
  27017. map$$1.set(category, index);
  27018. } else {
  27019. index = NaN;
  27020. }
  27021. }
  27022. return index;
  27023. }; // Consider big data, do not create map until needed.
  27024. function getOrCreateMap(ordinalMeta) {
  27025. return ordinalMeta._map || (ordinalMeta._map = createHashMap(ordinalMeta.categories));
  27026. }
  27027. function getName(obj) {
  27028. if (isObject$1(obj) && obj.value != null) {
  27029. return obj.value;
  27030. } else {
  27031. return obj + '';
  27032. }
  27033. }
  27034. /*
  27035. * Licensed to the Apache Software Foundation (ASF) under one
  27036. * or more contributor license agreements. See the NOTICE file
  27037. * distributed with this work for additional information
  27038. * regarding copyright ownership. The ASF licenses this file
  27039. * to you under the Apache License, Version 2.0 (the
  27040. * "License"); you may not use this file except in compliance
  27041. * with the License. You may obtain a copy of the License at
  27042. *
  27043. * http://www.apache.org/licenses/LICENSE-2.0
  27044. *
  27045. * Unless required by applicable law or agreed to in writing,
  27046. * software distributed under the License is distributed on an
  27047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27048. * KIND, either express or implied. See the License for the
  27049. * specific language governing permissions and limitations
  27050. * under the License.
  27051. */
  27052. /**
  27053. * Linear continuous scale
  27054. * @module echarts/coord/scale/Ordinal
  27055. *
  27056. * http://en.wikipedia.org/wiki/Level_of_measurement
  27057. */
  27058. // FIXME only one data
  27059. var scaleProto = Scale.prototype;
  27060. var OrdinalScale = Scale.extend({
  27061. type: 'ordinal',
  27062. /**
  27063. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  27064. */
  27065. init: function (ordinalMeta, extent) {
  27066. // Caution: Should not use instanceof, consider ec-extensions using
  27067. // import approach to get OrdinalMeta class.
  27068. if (!ordinalMeta || isArray(ordinalMeta)) {
  27069. ordinalMeta = new OrdinalMeta({
  27070. categories: ordinalMeta
  27071. });
  27072. }
  27073. this._ordinalMeta = ordinalMeta;
  27074. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  27075. },
  27076. parse: function (val) {
  27077. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  27078. : Math.round(val);
  27079. },
  27080. contain: function (rank) {
  27081. rank = this.parse(rank);
  27082. return scaleProto.contain.call(this, rank) && this._ordinalMeta.categories[rank] != null;
  27083. },
  27084. /**
  27085. * Normalize given rank or name to linear [0, 1]
  27086. * @param {number|string} [val]
  27087. * @return {number}
  27088. */
  27089. normalize: function (val) {
  27090. return scaleProto.normalize.call(this, this.parse(val));
  27091. },
  27092. scale: function (val) {
  27093. return Math.round(scaleProto.scale.call(this, val));
  27094. },
  27095. /**
  27096. * @return {Array}
  27097. */
  27098. getTicks: function () {
  27099. var ticks = [];
  27100. var extent = this._extent;
  27101. var rank = extent[0];
  27102. while (rank <= extent[1]) {
  27103. ticks.push(rank);
  27104. rank++;
  27105. }
  27106. return ticks;
  27107. },
  27108. /**
  27109. * Get item on rank n
  27110. * @param {number} n
  27111. * @return {string}
  27112. */
  27113. getLabel: function (n) {
  27114. if (!this.isBlank()) {
  27115. // Note that if no data, ordinalMeta.categories is an empty array.
  27116. return this._ordinalMeta.categories[n];
  27117. }
  27118. },
  27119. /**
  27120. * @return {number}
  27121. */
  27122. count: function () {
  27123. return this._extent[1] - this._extent[0] + 1;
  27124. },
  27125. /**
  27126. * @override
  27127. */
  27128. unionExtentFromData: function (data, dim) {
  27129. this.unionExtent(data.getApproximateExtent(dim));
  27130. },
  27131. getOrdinalMeta: function () {
  27132. return this._ordinalMeta;
  27133. },
  27134. niceTicks: noop,
  27135. niceExtent: noop
  27136. });
  27137. /**
  27138. * @return {module:echarts/scale/Time}
  27139. */
  27140. OrdinalScale.create = function () {
  27141. return new OrdinalScale();
  27142. };
  27143. /*
  27144. * Licensed to the Apache Software Foundation (ASF) under one
  27145. * or more contributor license agreements. See the NOTICE file
  27146. * distributed with this work for additional information
  27147. * regarding copyright ownership. The ASF licenses this file
  27148. * to you under the Apache License, Version 2.0 (the
  27149. * "License"); you may not use this file except in compliance
  27150. * with the License. You may obtain a copy of the License at
  27151. *
  27152. * http://www.apache.org/licenses/LICENSE-2.0
  27153. *
  27154. * Unless required by applicable law or agreed to in writing,
  27155. * software distributed under the License is distributed on an
  27156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27157. * KIND, either express or implied. See the License for the
  27158. * specific language governing permissions and limitations
  27159. * under the License.
  27160. */
  27161. /**
  27162. * For testable.
  27163. */
  27164. var roundNumber$1 = round$1;
  27165. /**
  27166. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  27167. * Should be extent[0] < extent[1].
  27168. * @param {number} splitNumber splitNumber should be >= 1.
  27169. * @param {number} [minInterval]
  27170. * @param {number} [maxInterval]
  27171. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  27172. */
  27173. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  27174. var result = {};
  27175. var span = extent[1] - extent[0];
  27176. var interval = result.interval = nice(span / splitNumber, true);
  27177. if (minInterval != null && interval < minInterval) {
  27178. interval = result.interval = minInterval;
  27179. }
  27180. if (maxInterval != null && interval > maxInterval) {
  27181. interval = result.interval = maxInterval;
  27182. } // Tow more digital for tick.
  27183. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  27184. var niceTickExtent = result.niceTickExtent = [roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision), roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)];
  27185. fixExtent(niceTickExtent, extent);
  27186. return result;
  27187. }
  27188. /**
  27189. * @param {number} interval
  27190. * @return {number} interval precision
  27191. */
  27192. function getIntervalPrecision(interval) {
  27193. // Tow more digital for tick.
  27194. return getPrecisionSafe(interval) + 2;
  27195. }
  27196. function clamp(niceTickExtent, idx, extent) {
  27197. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  27198. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  27199. function fixExtent(niceTickExtent, extent) {
  27200. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  27201. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  27202. clamp(niceTickExtent, 0, extent);
  27203. clamp(niceTickExtent, 1, extent);
  27204. if (niceTickExtent[0] > niceTickExtent[1]) {
  27205. niceTickExtent[0] = niceTickExtent[1];
  27206. }
  27207. }
  27208. /*
  27209. * Licensed to the Apache Software Foundation (ASF) under one
  27210. * or more contributor license agreements. See the NOTICE file
  27211. * distributed with this work for additional information
  27212. * regarding copyright ownership. The ASF licenses this file
  27213. * to you under the Apache License, Version 2.0 (the
  27214. * "License"); you may not use this file except in compliance
  27215. * with the License. You may obtain a copy of the License at
  27216. *
  27217. * http://www.apache.org/licenses/LICENSE-2.0
  27218. *
  27219. * Unless required by applicable law or agreed to in writing,
  27220. * software distributed under the License is distributed on an
  27221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27222. * KIND, either express or implied. See the License for the
  27223. * specific language governing permissions and limitations
  27224. * under the License.
  27225. */
  27226. /**
  27227. * Interval scale
  27228. * @module echarts/scale/Interval
  27229. */
  27230. var roundNumber = round$1;
  27231. /**
  27232. * @alias module:echarts/coord/scale/Interval
  27233. * @constructor
  27234. */
  27235. var IntervalScale = Scale.extend({
  27236. type: 'interval',
  27237. _interval: 0,
  27238. _intervalPrecision: 2,
  27239. setExtent: function (start, end) {
  27240. var thisExtent = this._extent; //start,end may be a Number like '25',so...
  27241. if (!isNaN(start)) {
  27242. thisExtent[0] = parseFloat(start);
  27243. }
  27244. if (!isNaN(end)) {
  27245. thisExtent[1] = parseFloat(end);
  27246. }
  27247. },
  27248. unionExtent: function (other) {
  27249. var extent = this._extent;
  27250. other[0] < extent[0] && (extent[0] = other[0]);
  27251. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  27252. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  27253. },
  27254. /**
  27255. * Get interval
  27256. */
  27257. getInterval: function () {
  27258. return this._interval;
  27259. },
  27260. /**
  27261. * Set interval
  27262. */
  27263. setInterval: function (interval) {
  27264. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  27265. // We assume user wan't to set both interval, min, max to get a better result
  27266. this._niceExtent = this._extent.slice();
  27267. this._intervalPrecision = getIntervalPrecision(interval);
  27268. },
  27269. /**
  27270. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  27271. * @return {Array.<number>}
  27272. */
  27273. getTicks: function (expandToNicedExtent) {
  27274. var interval = this._interval;
  27275. var extent = this._extent;
  27276. var niceTickExtent = this._niceExtent;
  27277. var intervalPrecision = this._intervalPrecision;
  27278. var ticks = []; // If interval is 0, return [];
  27279. if (!interval) {
  27280. return ticks;
  27281. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  27282. var safeLimit = 10000;
  27283. if (extent[0] < niceTickExtent[0]) {
  27284. if (expandToNicedExtent) {
  27285. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  27286. } else {
  27287. ticks.push(extent[0]);
  27288. }
  27289. }
  27290. var tick = niceTickExtent[0];
  27291. while (tick <= niceTickExtent[1]) {
  27292. ticks.push(tick); // Avoid rounding error
  27293. tick = roundNumber(tick + interval, intervalPrecision);
  27294. if (tick === ticks[ticks.length - 1]) {
  27295. // Consider out of safe float point, e.g.,
  27296. // -3711126.9907707 + 2e-10 === -3711126.9907707
  27297. break;
  27298. }
  27299. if (ticks.length > safeLimit) {
  27300. return [];
  27301. }
  27302. } // Consider this case: the last item of ticks is smaller
  27303. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  27304. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  27305. if (extent[1] > lastNiceTick) {
  27306. if (expandToNicedExtent) {
  27307. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  27308. } else {
  27309. ticks.push(extent[1]);
  27310. }
  27311. }
  27312. return ticks;
  27313. },
  27314. /**
  27315. * @param {number} [splitNumber=5]
  27316. * @return {Array.<Array.<number>>}
  27317. */
  27318. getMinorTicks: function (splitNumber) {
  27319. var ticks = this.getTicks(true);
  27320. var minorTicks = [];
  27321. var extent = this.getExtent();
  27322. for (var i = 1; i < ticks.length; i++) {
  27323. var nextTick = ticks[i];
  27324. var prevTick = ticks[i - 1];
  27325. var count = 0;
  27326. var minorTicksGroup = [];
  27327. var interval = nextTick - prevTick;
  27328. var minorInterval = interval / splitNumber;
  27329. while (count < splitNumber - 1) {
  27330. var minorTick = round$1(prevTick + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  27331. if (minorTick > extent[0] && minorTick < extent[1]) {
  27332. minorTicksGroup.push(minorTick);
  27333. }
  27334. count++;
  27335. }
  27336. minorTicks.push(minorTicksGroup);
  27337. }
  27338. return minorTicks;
  27339. },
  27340. /**
  27341. * @param {number} data
  27342. * @param {Object} [opt]
  27343. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  27344. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  27345. * @return {string}
  27346. */
  27347. getLabel: function (data, opt) {
  27348. if (data == null) {
  27349. return '';
  27350. }
  27351. var precision = opt && opt.precision;
  27352. if (precision == null) {
  27353. precision = getPrecisionSafe(data) || 0;
  27354. } else if (precision === 'auto') {
  27355. // Should be more precise then tick.
  27356. precision = this._intervalPrecision;
  27357. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  27358. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  27359. data = roundNumber(data, precision, true);
  27360. return addCommas(data);
  27361. },
  27362. /**
  27363. * Update interval and extent of intervals for nice ticks
  27364. *
  27365. * @param {number} [splitNumber = 5] Desired number of ticks
  27366. * @param {number} [minInterval]
  27367. * @param {number} [maxInterval]
  27368. */
  27369. niceTicks: function (splitNumber, minInterval, maxInterval) {
  27370. splitNumber = splitNumber || 5;
  27371. var extent = this._extent;
  27372. var span = extent[1] - extent[0];
  27373. if (!isFinite(span)) {
  27374. return;
  27375. } // User may set axis min 0 and data are all negative
  27376. // FIXME If it needs to reverse ?
  27377. if (span < 0) {
  27378. span = -span;
  27379. extent.reverse();
  27380. }
  27381. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  27382. this._intervalPrecision = result.intervalPrecision;
  27383. this._interval = result.interval;
  27384. this._niceExtent = result.niceTickExtent;
  27385. },
  27386. /**
  27387. * Nice extent.
  27388. * @param {Object} opt
  27389. * @param {number} [opt.splitNumber = 5] Given approx tick number
  27390. * @param {boolean} [opt.fixMin=false]
  27391. * @param {boolean} [opt.fixMax=false]
  27392. * @param {boolean} [opt.minInterval]
  27393. * @param {boolean} [opt.maxInterval]
  27394. */
  27395. niceExtent: function (opt) {
  27396. var extent = this._extent; // If extent start and end are same, expand them
  27397. if (extent[0] === extent[1]) {
  27398. if (extent[0] !== 0) {
  27399. // Expand extent
  27400. var expandSize = extent[0]; // In the fowllowing case
  27401. // Axis has been fixed max 100
  27402. // Plus data are all 100 and axis extent are [100, 100].
  27403. // Extend to the both side will cause expanded max is larger than fixed max.
  27404. // So only expand to the smaller side.
  27405. if (!opt.fixMax) {
  27406. extent[1] += expandSize / 2;
  27407. extent[0] -= expandSize / 2;
  27408. } else {
  27409. extent[0] -= expandSize / 2;
  27410. }
  27411. } else {
  27412. extent[1] = 1;
  27413. }
  27414. }
  27415. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  27416. if (!isFinite(span)) {
  27417. extent[0] = 0;
  27418. extent[1] = 1;
  27419. }
  27420. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent;
  27421. var interval = this._interval;
  27422. if (!opt.fixMin) {
  27423. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  27424. }
  27425. if (!opt.fixMax) {
  27426. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  27427. }
  27428. }
  27429. });
  27430. /**
  27431. * @return {module:echarts/scale/Time}
  27432. */
  27433. IntervalScale.create = function () {
  27434. return new IntervalScale();
  27435. };
  27436. /*
  27437. * Licensed to the Apache Software Foundation (ASF) under one
  27438. * or more contributor license agreements. See the NOTICE file
  27439. * distributed with this work for additional information
  27440. * regarding copyright ownership. The ASF licenses this file
  27441. * to you under the Apache License, Version 2.0 (the
  27442. * "License"); you may not use this file except in compliance
  27443. * with the License. You may obtain a copy of the License at
  27444. *
  27445. * http://www.apache.org/licenses/LICENSE-2.0
  27446. *
  27447. * Unless required by applicable law or agreed to in writing,
  27448. * software distributed under the License is distributed on an
  27449. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27450. * KIND, either express or implied. See the License for the
  27451. * specific language governing permissions and limitations
  27452. * under the License.
  27453. */
  27454. /* global Float32Array */
  27455. var STACK_PREFIX = '__ec_stack_';
  27456. var LARGE_BAR_MIN_WIDTH = 0.5;
  27457. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  27458. function getSeriesStackId(seriesModel) {
  27459. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  27460. }
  27461. function getAxisKey(axis) {
  27462. return axis.dim + axis.index;
  27463. }
  27464. /**
  27465. * @param {Object} opt
  27466. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  27467. * @param {number} opt.count Positive interger.
  27468. * @param {number} [opt.barWidth]
  27469. * @param {number} [opt.barMaxWidth]
  27470. * @param {number} [opt.barMinWidth]
  27471. * @param {number} [opt.barGap]
  27472. * @param {number} [opt.barCategoryGap]
  27473. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  27474. */
  27475. function prepareLayoutBarSeries(seriesType, ecModel) {
  27476. var seriesModels = [];
  27477. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  27478. // Check series coordinate, do layout for cartesian2d only
  27479. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  27480. seriesModels.push(seriesModel);
  27481. }
  27482. });
  27483. return seriesModels;
  27484. }
  27485. /**
  27486. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  27487. * values.
  27488. * This works for time axes, value axes, and log axes.
  27489. * For a single time axis, return value is in the form like
  27490. * {'x_0': [1000000]}.
  27491. * The value of 1000000 is in milliseconds.
  27492. */
  27493. function getValueAxesMinGaps(barSeries) {
  27494. /**
  27495. * Map from axis.index to values.
  27496. * For a single time axis, axisValues is in the form like
  27497. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  27498. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  27499. * series.
  27500. */
  27501. var axisValues = {};
  27502. each$1(barSeries, function (seriesModel) {
  27503. var cartesian = seriesModel.coordinateSystem;
  27504. var baseAxis = cartesian.getBaseAxis();
  27505. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  27506. return;
  27507. }
  27508. var data = seriesModel.getData();
  27509. var key = baseAxis.dim + '_' + baseAxis.index;
  27510. var dim = data.mapDimension(baseAxis.dim);
  27511. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  27512. var value = data.get(dim, i);
  27513. if (!axisValues[key]) {
  27514. // No previous data for the axis
  27515. axisValues[key] = [value];
  27516. } else {
  27517. // No value in previous series
  27518. axisValues[key].push(value);
  27519. } // Ignore duplicated time values in the same axis
  27520. }
  27521. });
  27522. var axisMinGaps = [];
  27523. for (var key in axisValues) {
  27524. if (axisValues.hasOwnProperty(key)) {
  27525. var valuesInAxis = axisValues[key];
  27526. if (valuesInAxis) {
  27527. // Sort axis values into ascending order to calculate gaps
  27528. valuesInAxis.sort(function (a, b) {
  27529. return a - b;
  27530. });
  27531. var min = null;
  27532. for (var j = 1; j < valuesInAxis.length; ++j) {
  27533. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  27534. if (delta > 0) {
  27535. // Ignore 0 delta because they are of the same axis value
  27536. min = min === null ? delta : Math.min(min, delta);
  27537. }
  27538. } // Set to null if only have one data
  27539. axisMinGaps[key] = min;
  27540. }
  27541. }
  27542. }
  27543. return axisMinGaps;
  27544. }
  27545. function makeColumnLayout(barSeries) {
  27546. var axisMinGaps = getValueAxesMinGaps(barSeries);
  27547. var seriesInfoList = [];
  27548. each$1(barSeries, function (seriesModel) {
  27549. var cartesian = seriesModel.coordinateSystem;
  27550. var baseAxis = cartesian.getBaseAxis();
  27551. var axisExtent = baseAxis.getExtent();
  27552. var bandWidth;
  27553. if (baseAxis.type === 'category') {
  27554. bandWidth = baseAxis.getBandWidth();
  27555. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  27556. var key = baseAxis.dim + '_' + baseAxis.index;
  27557. var minGap = axisMinGaps[key];
  27558. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  27559. var scale = baseAxis.scale.getExtent();
  27560. var scaleSpan = Math.abs(scale[1] - scale[0]);
  27561. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  27562. } else {
  27563. var data = seriesModel.getData();
  27564. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  27565. }
  27566. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  27567. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  27568. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  27569. // the auto-calculated bar width might be less than 1.
  27570. seriesModel.get('barMinWidth') || 1, bandWidth);
  27571. var barGap = seriesModel.get('barGap');
  27572. var barCategoryGap = seriesModel.get('barCategoryGap');
  27573. seriesInfoList.push({
  27574. bandWidth: bandWidth,
  27575. barWidth: barWidth,
  27576. barMaxWidth: barMaxWidth,
  27577. barMinWidth: barMinWidth,
  27578. barGap: barGap,
  27579. barCategoryGap: barCategoryGap,
  27580. axisKey: getAxisKey(baseAxis),
  27581. stackId: getSeriesStackId(seriesModel)
  27582. });
  27583. });
  27584. return doCalBarWidthAndOffset(seriesInfoList);
  27585. }
  27586. function doCalBarWidthAndOffset(seriesInfoList) {
  27587. // Columns info on each category axis. Key is cartesian name
  27588. var columnsMap = {};
  27589. each$1(seriesInfoList, function (seriesInfo, idx) {
  27590. var axisKey = seriesInfo.axisKey;
  27591. var bandWidth = seriesInfo.bandWidth;
  27592. var columnsOnAxis = columnsMap[axisKey] || {
  27593. bandWidth: bandWidth,
  27594. remainedWidth: bandWidth,
  27595. autoWidthCount: 0,
  27596. categoryGap: '20%',
  27597. gap: '30%',
  27598. stacks: {}
  27599. };
  27600. var stacks = columnsOnAxis.stacks;
  27601. columnsMap[axisKey] = columnsOnAxis;
  27602. var stackId = seriesInfo.stackId;
  27603. if (!stacks[stackId]) {
  27604. columnsOnAxis.autoWidthCount++;
  27605. }
  27606. stacks[stackId] = stacks[stackId] || {
  27607. width: 0,
  27608. maxWidth: 0
  27609. }; // Caution: In a single coordinate system, these barGrid attributes
  27610. // will be shared by series. Consider that they have default values,
  27611. // only the attributes set on the last series will work.
  27612. // Do not change this fact unless there will be a break change.
  27613. var barWidth = seriesInfo.barWidth;
  27614. if (barWidth && !stacks[stackId].width) {
  27615. // See #6312, do not restrict width.
  27616. stacks[stackId].width = barWidth;
  27617. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  27618. columnsOnAxis.remainedWidth -= barWidth;
  27619. }
  27620. var barMaxWidth = seriesInfo.barMaxWidth;
  27621. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  27622. var barMinWidth = seriesInfo.barMinWidth;
  27623. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  27624. var barGap = seriesInfo.barGap;
  27625. barGap != null && (columnsOnAxis.gap = barGap);
  27626. var barCategoryGap = seriesInfo.barCategoryGap;
  27627. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  27628. });
  27629. var result = {};
  27630. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  27631. result[coordSysName] = {};
  27632. var stacks = columnsOnAxis.stacks;
  27633. var bandWidth = columnsOnAxis.bandWidth;
  27634. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  27635. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  27636. var remainedWidth = columnsOnAxis.remainedWidth;
  27637. var autoWidthCount = columnsOnAxis.autoWidthCount;
  27638. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27639. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  27640. each$1(stacks, function (column) {
  27641. var maxWidth = column.maxWidth;
  27642. var minWidth = column.minWidth;
  27643. if (!column.width) {
  27644. var finalWidth = autoWidth;
  27645. if (maxWidth && maxWidth < finalWidth) {
  27646. finalWidth = Math.min(maxWidth, remainedWidth);
  27647. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  27648. // bar is able to be visible. So `minWidth` should not be restricted
  27649. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  27650. // the extreme cases for `value` axis, bars are allowed to overlap
  27651. // with each other if `minWidth` specified.
  27652. if (minWidth && minWidth > finalWidth) {
  27653. finalWidth = minWidth;
  27654. }
  27655. if (finalWidth !== autoWidth) {
  27656. column.width = finalWidth;
  27657. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  27658. autoWidthCount--;
  27659. }
  27660. } else {
  27661. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  27662. // CSS does. Becuase barWidth can be a percent value, where
  27663. // `barMaxWidth` can be used to restrict the final width.
  27664. var finalWidth = column.width;
  27665. if (maxWidth) {
  27666. finalWidth = Math.min(finalWidth, maxWidth);
  27667. } // `minWidth` has higher priority, as described above
  27668. if (minWidth) {
  27669. finalWidth = Math.max(finalWidth, minWidth);
  27670. }
  27671. column.width = finalWidth;
  27672. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  27673. autoWidthCount--;
  27674. }
  27675. }); // Recalculate width again
  27676. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27677. autoWidth = Math.max(autoWidth, 0);
  27678. var widthSum = 0;
  27679. var lastColumn;
  27680. each$1(stacks, function (column, idx) {
  27681. if (!column.width) {
  27682. column.width = autoWidth;
  27683. }
  27684. lastColumn = column;
  27685. widthSum += column.width * (1 + barGapPercent);
  27686. });
  27687. if (lastColumn) {
  27688. widthSum -= lastColumn.width * barGapPercent;
  27689. }
  27690. var offset = -widthSum / 2;
  27691. each$1(stacks, function (column, stackId) {
  27692. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  27693. bandWidth: bandWidth,
  27694. offset: offset,
  27695. width: column.width
  27696. };
  27697. offset += column.width * (1 + barGapPercent);
  27698. });
  27699. });
  27700. return result;
  27701. }
  27702. /**
  27703. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  27704. * @param {module:echarts/coord/Axis} axis
  27705. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  27706. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  27707. */
  27708. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  27709. if (barWidthAndOffset && axis) {
  27710. var result = barWidthAndOffset[getAxisKey(axis)];
  27711. if (result != null && seriesModel != null) {
  27712. result = result[getSeriesStackId(seriesModel)];
  27713. }
  27714. return result;
  27715. }
  27716. }
  27717. /**
  27718. * @param {string} seriesType
  27719. * @param {module:echarts/model/Global} ecModel
  27720. */
  27721. function layout(seriesType, ecModel) {
  27722. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  27723. var barWidthAndOffset = makeColumnLayout(seriesModels);
  27724. var lastStackCoords = {};
  27725. each$1(seriesModels, function (seriesModel) {
  27726. var data = seriesModel.getData();
  27727. var cartesian = seriesModel.coordinateSystem;
  27728. var baseAxis = cartesian.getBaseAxis();
  27729. var stackId = getSeriesStackId(seriesModel);
  27730. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27731. var columnOffset = columnLayoutInfo.offset;
  27732. var columnWidth = columnLayoutInfo.width;
  27733. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27734. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27735. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27736. data.setLayout({
  27737. bandWidth: columnLayoutInfo.bandWidth,
  27738. offset: columnOffset,
  27739. size: columnWidth
  27740. });
  27741. var valueDim = data.mapDimension(valueAxis.dim);
  27742. var baseDim = data.mapDimension(baseAxis.dim);
  27743. var stacked = isDimensionStacked(data, valueDim
  27744. /*, baseDim*/
  27745. );
  27746. var isValueAxisH = valueAxis.isHorizontal();
  27747. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  27748. for (var idx = 0, len = data.count(); idx < len; idx++) {
  27749. var value = data.get(valueDim, idx);
  27750. var baseValue = data.get(baseDim, idx);
  27751. var sign = value >= 0 ? 'p' : 'n';
  27752. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  27753. // stackResultDimension directly.
  27754. if (stacked) {
  27755. // Only ordinal axis can be stacked.
  27756. if (!lastStackCoords[stackId][baseValue]) {
  27757. lastStackCoords[stackId][baseValue] = {
  27758. p: valueAxisStart,
  27759. // Positive stack
  27760. n: valueAxisStart // Negative stack
  27761. };
  27762. } // Should also consider #4243
  27763. baseCoord = lastStackCoords[stackId][baseValue][sign];
  27764. }
  27765. var x;
  27766. var y;
  27767. var width;
  27768. var height;
  27769. if (isValueAxisH) {
  27770. var coord = cartesian.dataToPoint([value, baseValue]);
  27771. x = baseCoord;
  27772. y = coord[1] + columnOffset;
  27773. width = coord[0] - valueAxisStart;
  27774. height = columnWidth;
  27775. if (Math.abs(width) < barMinHeight) {
  27776. width = (width < 0 ? -1 : 1) * barMinHeight;
  27777. } // Ignore stack from NaN value
  27778. if (!isNaN(width)) {
  27779. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  27780. }
  27781. } else {
  27782. var coord = cartesian.dataToPoint([baseValue, value]);
  27783. x = coord[0] + columnOffset;
  27784. y = baseCoord;
  27785. width = columnWidth;
  27786. height = coord[1] - valueAxisStart;
  27787. if (Math.abs(height) < barMinHeight) {
  27788. // Include zero to has a positive bar
  27789. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27790. } // Ignore stack from NaN value
  27791. if (!isNaN(height)) {
  27792. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  27793. }
  27794. }
  27795. data.setItemLayout(idx, {
  27796. x: x,
  27797. y: y,
  27798. width: width,
  27799. height: height
  27800. });
  27801. }
  27802. }, this);
  27803. } // TODO: Do not support stack in large mode yet.
  27804. var largeLayout = {
  27805. seriesType: 'bar',
  27806. plan: createRenderPlanner(),
  27807. reset: function (seriesModel) {
  27808. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  27809. return;
  27810. }
  27811. var data = seriesModel.getData();
  27812. var cartesian = seriesModel.coordinateSystem;
  27813. var coordLayout = cartesian.grid.getRect();
  27814. var baseAxis = cartesian.getBaseAxis();
  27815. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27816. var valueDim = data.mapDimension(valueAxis.dim);
  27817. var baseDim = data.mapDimension(baseAxis.dim);
  27818. var valueAxisHorizontal = valueAxis.isHorizontal();
  27819. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  27820. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  27821. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  27822. // jshint ignore:line
  27823. barWidth = LARGE_BAR_MIN_WIDTH;
  27824. }
  27825. return {
  27826. progress: progress
  27827. };
  27828. function progress(params, data) {
  27829. var count = params.count;
  27830. var largePoints = new LargeArr(count * 2);
  27831. var largeBackgroundPoints = new LargeArr(count * 2);
  27832. var largeDataIndices = new LargeArr(count);
  27833. var dataIndex;
  27834. var coord = [];
  27835. var valuePair = [];
  27836. var pointsOffset = 0;
  27837. var idxOffset = 0;
  27838. while ((dataIndex = params.next()) != null) {
  27839. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  27840. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  27841. coord = cartesian.dataToPoint(valuePair, null, coord); // Data index might not be in order, depends on `progressiveChunkMode`.
  27842. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  27843. largePoints[pointsOffset++] = coord[0];
  27844. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  27845. largePoints[pointsOffset++] = coord[1];
  27846. largeDataIndices[idxOffset++] = dataIndex;
  27847. }
  27848. data.setLayout({
  27849. largePoints: largePoints,
  27850. largeDataIndices: largeDataIndices,
  27851. largeBackgroundPoints: largeBackgroundPoints,
  27852. barWidth: barWidth,
  27853. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  27854. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  27855. valueAxisHorizontal: valueAxisHorizontal
  27856. });
  27857. }
  27858. }
  27859. };
  27860. function isOnCartesian(seriesModel) {
  27861. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  27862. }
  27863. function isInLargeMode(seriesModel) {
  27864. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  27865. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  27866. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  27867. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  27868. }
  27869. /*
  27870. * Licensed to the Apache Software Foundation (ASF) under one
  27871. * or more contributor license agreements. See the NOTICE file
  27872. * distributed with this work for additional information
  27873. * regarding copyright ownership. The ASF licenses this file
  27874. * to you under the Apache License, Version 2.0 (the
  27875. * "License"); you may not use this file except in compliance
  27876. * with the License. You may obtain a copy of the License at
  27877. *
  27878. * http://www.apache.org/licenses/LICENSE-2.0
  27879. *
  27880. * Unless required by applicable law or agreed to in writing,
  27881. * software distributed under the License is distributed on an
  27882. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27883. * KIND, either express or implied. See the License for the
  27884. * specific language governing permissions and limitations
  27885. * under the License.
  27886. */
  27887. /*
  27888. * A third-party license is embeded for some of the code in this file:
  27889. * The "scaleLevels" was originally copied from "d3.js" with some
  27890. * modifications made for this project.
  27891. * (See more details in the comment on the definition of "scaleLevels" below.)
  27892. * The use of the source code of this file is also subject to the terms
  27893. * and consitions of the license of "d3.js" (BSD-3Clause, see
  27894. * </licenses/LICENSE-d3>).
  27895. */
  27896. // [About UTC and local time zone]:
  27897. // In most cases, `number.parseDate` will treat input data string as local time
  27898. // (except time zone is specified in time string). And `format.formateTime` returns
  27899. // local time by default. option.useUTC is false by default. This design have
  27900. // concidered these common case:
  27901. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  27902. // in local time by default.
  27903. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  27904. // as its original time, without any time difference.
  27905. var intervalScaleProto = IntervalScale.prototype;
  27906. var mathCeil = Math.ceil;
  27907. var mathFloor = Math.floor;
  27908. var ONE_SECOND = 1000;
  27909. var ONE_MINUTE = ONE_SECOND * 60;
  27910. var ONE_HOUR = ONE_MINUTE * 60;
  27911. var ONE_DAY = ONE_HOUR * 24; // FIXME 公用?
  27912. var bisect = function (a, x, lo, hi) {
  27913. while (lo < hi) {
  27914. var mid = lo + hi >>> 1;
  27915. if (a[mid][1] < x) {
  27916. lo = mid + 1;
  27917. } else {
  27918. hi = mid;
  27919. }
  27920. }
  27921. return lo;
  27922. };
  27923. /**
  27924. * @alias module:echarts/coord/scale/Time
  27925. * @constructor
  27926. */
  27927. var TimeScale = IntervalScale.extend({
  27928. type: 'time',
  27929. /**
  27930. * @override
  27931. */
  27932. getLabel: function (val) {
  27933. var stepLvl = this._stepLvl;
  27934. var date = new Date(val);
  27935. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  27936. },
  27937. /**
  27938. * @override
  27939. */
  27940. niceExtent: function (opt) {
  27941. var extent = this._extent; // If extent start and end are same, expand them
  27942. if (extent[0] === extent[1]) {
  27943. // Expand extent
  27944. extent[0] -= ONE_DAY;
  27945. extent[1] += ONE_DAY;
  27946. } // If there are no data and extent are [Infinity, -Infinity]
  27947. if (extent[1] === -Infinity && extent[0] === Infinity) {
  27948. var d = new Date();
  27949. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  27950. extent[0] = extent[1] - ONE_DAY;
  27951. }
  27952. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent;
  27953. var interval = this._interval;
  27954. if (!opt.fixMin) {
  27955. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  27956. }
  27957. if (!opt.fixMax) {
  27958. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  27959. }
  27960. },
  27961. /**
  27962. * @override
  27963. */
  27964. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  27965. approxTickNum = approxTickNum || 10;
  27966. var extent = this._extent;
  27967. var span = extent[1] - extent[0];
  27968. var approxInterval = span / approxTickNum;
  27969. if (minInterval != null && approxInterval < minInterval) {
  27970. approxInterval = minInterval;
  27971. }
  27972. if (maxInterval != null && approxInterval > maxInterval) {
  27973. approxInterval = maxInterval;
  27974. }
  27975. var scaleLevelsLen = scaleLevels.length;
  27976. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  27977. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  27978. var interval = level[1]; // Same with interval scale if span is much larger than 1 year
  27979. if (level[0] === 'year') {
  27980. var yearSpan = span / interval; // From "Nice Numbers for Graph Labels" of Graphic Gems
  27981. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  27982. var yearStep = nice(yearSpan / approxTickNum, true);
  27983. interval *= yearStep;
  27984. }
  27985. var timezoneOffset = this.getSetting('useUTC') ? 0 : new Date(+extent[0] || +extent[1]).getTimezoneOffset() * 60 * 1000;
  27986. var niceExtent = [Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset), Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)];
  27987. fixExtent(niceExtent, extent);
  27988. this._stepLvl = level; // Interval will be used in getTicks
  27989. this._interval = interval;
  27990. this._niceExtent = niceExtent;
  27991. },
  27992. parse: function (val) {
  27993. // val might be float.
  27994. return +parseDate(val);
  27995. }
  27996. });
  27997. each$1(['contain', 'normalize'], function (methodName) {
  27998. TimeScale.prototype[methodName] = function (val) {
  27999. return intervalScaleProto[methodName].call(this, this.parse(val));
  28000. };
  28001. });
  28002. /**
  28003. * This implementation was originally copied from "d3.js"
  28004. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  28005. * with some modifications made for this program.
  28006. * See the license statement at the head of this file.
  28007. */
  28008. var scaleLevels = [// Format interval
  28009. ['hh:mm:ss', ONE_SECOND], // 1s
  28010. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  28011. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  28012. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  28013. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  28014. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  28015. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  28016. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  28017. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  28018. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  28019. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  28020. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  28021. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  28022. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  28023. ['MM-dd\nyyyy', ONE_DAY], // 1d
  28024. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  28025. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  28026. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  28027. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  28028. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  28029. ['week', ONE_DAY * 7], // 7d
  28030. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  28031. ['week', ONE_DAY * 14], // 2w
  28032. ['week', ONE_DAY * 21], // 3w
  28033. ['month', ONE_DAY * 31], // 1M
  28034. ['week', ONE_DAY * 42], // 6w
  28035. ['month', ONE_DAY * 62], // 2M
  28036. ['week', ONE_DAY * 70], // 10w
  28037. ['quarter', ONE_DAY * 95], // 3M
  28038. ['month', ONE_DAY * 31 * 4], // 4M
  28039. ['month', ONE_DAY * 31 * 5], // 5M
  28040. ['half-year', ONE_DAY * 380 / 2], // 6M
  28041. ['month', ONE_DAY * 31 * 8], // 8M
  28042. ['month', ONE_DAY * 31 * 10], // 10M
  28043. ['year', ONE_DAY * 380] // 1Y
  28044. ];
  28045. /**
  28046. * @param {module:echarts/model/Model}
  28047. * @return {module:echarts/scale/Time}
  28048. */
  28049. TimeScale.create = function (model) {
  28050. return new TimeScale({
  28051. useUTC: model.ecModel.get('useUTC')
  28052. });
  28053. };
  28054. /*
  28055. * Licensed to the Apache Software Foundation (ASF) under one
  28056. * or more contributor license agreements. See the NOTICE file
  28057. * distributed with this work for additional information
  28058. * regarding copyright ownership. The ASF licenses this file
  28059. * to you under the Apache License, Version 2.0 (the
  28060. * "License"); you may not use this file except in compliance
  28061. * with the License. You may obtain a copy of the License at
  28062. *
  28063. * http://www.apache.org/licenses/LICENSE-2.0
  28064. *
  28065. * Unless required by applicable law or agreed to in writing,
  28066. * software distributed under the License is distributed on an
  28067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28068. * KIND, either express or implied. See the License for the
  28069. * specific language governing permissions and limitations
  28070. * under the License.
  28071. */
  28072. /**
  28073. * Log scale
  28074. * @module echarts/scale/Log
  28075. */
  28076. var scaleProto$1 = Scale.prototype;
  28077. var intervalScaleProto$1 = IntervalScale.prototype;
  28078. var getPrecisionSafe$1 = getPrecisionSafe;
  28079. var roundingErrorFix = round$1;
  28080. var mathFloor$1 = Math.floor;
  28081. var mathCeil$1 = Math.ceil;
  28082. var mathPow$1 = Math.pow;
  28083. var mathLog = Math.log;
  28084. var LogScale = Scale.extend({
  28085. type: 'log',
  28086. base: 10,
  28087. $constructor: function () {
  28088. Scale.apply(this, arguments);
  28089. this._originalScale = new IntervalScale();
  28090. },
  28091. /**
  28092. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  28093. * @return {Array.<number>}
  28094. */
  28095. getTicks: function (expandToNicedExtent) {
  28096. var originalScale = this._originalScale;
  28097. var extent = this._extent;
  28098. var originalExtent = originalScale.getExtent();
  28099. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  28100. var powVal = round$1(mathPow$1(this.base, val)); // Fix #4158
  28101. powVal = val === extent[0] && originalScale.__fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  28102. powVal = val === extent[1] && originalScale.__fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  28103. return powVal;
  28104. }, this);
  28105. },
  28106. /**
  28107. * @param {number} splitNumber
  28108. * @return {Array.<Array.<number>>}
  28109. */
  28110. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  28111. /**
  28112. * @param {number} val
  28113. * @return {string}
  28114. */
  28115. getLabel: intervalScaleProto$1.getLabel,
  28116. /**
  28117. * @param {number} val
  28118. * @return {number}
  28119. */
  28120. scale: function (val) {
  28121. val = scaleProto$1.scale.call(this, val);
  28122. return mathPow$1(this.base, val);
  28123. },
  28124. /**
  28125. * @param {number} start
  28126. * @param {number} end
  28127. */
  28128. setExtent: function (start, end) {
  28129. var base = this.base;
  28130. start = mathLog(start) / mathLog(base);
  28131. end = mathLog(end) / mathLog(base);
  28132. intervalScaleProto$1.setExtent.call(this, start, end);
  28133. },
  28134. /**
  28135. * @return {number} end
  28136. */
  28137. getExtent: function () {
  28138. var base = this.base;
  28139. var extent = scaleProto$1.getExtent.call(this);
  28140. extent[0] = mathPow$1(base, extent[0]);
  28141. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  28142. var originalScale = this._originalScale;
  28143. var originalExtent = originalScale.getExtent();
  28144. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  28145. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  28146. return extent;
  28147. },
  28148. /**
  28149. * @param {Array.<number>} extent
  28150. */
  28151. unionExtent: function (extent) {
  28152. this._originalScale.unionExtent(extent);
  28153. var base = this.base;
  28154. extent[0] = mathLog(extent[0]) / mathLog(base);
  28155. extent[1] = mathLog(extent[1]) / mathLog(base);
  28156. scaleProto$1.unionExtent.call(this, extent);
  28157. },
  28158. /**
  28159. * @override
  28160. */
  28161. unionExtentFromData: function (data, dim) {
  28162. // TODO
  28163. // filter value that <= 0
  28164. this.unionExtent(data.getApproximateExtent(dim));
  28165. },
  28166. /**
  28167. * Update interval and extent of intervals for nice ticks
  28168. * @param {number} [approxTickNum = 10] Given approx tick number
  28169. */
  28170. niceTicks: function (approxTickNum) {
  28171. approxTickNum = approxTickNum || 10;
  28172. var extent = this._extent;
  28173. var span = extent[1] - extent[0];
  28174. if (span === Infinity || span <= 0) {
  28175. return;
  28176. }
  28177. var interval = quantity(span);
  28178. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  28179. if (err <= 0.5) {
  28180. interval *= 10;
  28181. } // Interval should be integer
  28182. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  28183. interval *= 10;
  28184. }
  28185. var niceExtent = [round$1(mathCeil$1(extent[0] / interval) * interval), round$1(mathFloor$1(extent[1] / interval) * interval)];
  28186. this._interval = interval;
  28187. this._niceExtent = niceExtent;
  28188. },
  28189. /**
  28190. * Nice extent.
  28191. * @override
  28192. */
  28193. niceExtent: function (opt) {
  28194. intervalScaleProto$1.niceExtent.call(this, opt);
  28195. var originalScale = this._originalScale;
  28196. originalScale.__fixMin = opt.fixMin;
  28197. originalScale.__fixMax = opt.fixMax;
  28198. }
  28199. });
  28200. each$1(['contain', 'normalize'], function (methodName) {
  28201. LogScale.prototype[methodName] = function (val) {
  28202. val = mathLog(val) / mathLog(this.base);
  28203. return scaleProto$1[methodName].call(this, val);
  28204. };
  28205. });
  28206. LogScale.create = function () {
  28207. return new LogScale();
  28208. };
  28209. function fixRoundingError(val, originalVal) {
  28210. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  28211. }
  28212. /*
  28213. * Licensed to the Apache Software Foundation (ASF) under one
  28214. * or more contributor license agreements. See the NOTICE file
  28215. * distributed with this work for additional information
  28216. * regarding copyright ownership. The ASF licenses this file
  28217. * to you under the Apache License, Version 2.0 (the
  28218. * "License"); you may not use this file except in compliance
  28219. * with the License. You may obtain a copy of the License at
  28220. *
  28221. * http://www.apache.org/licenses/LICENSE-2.0
  28222. *
  28223. * Unless required by applicable law or agreed to in writing,
  28224. * software distributed under the License is distributed on an
  28225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28226. * KIND, either express or implied. See the License for the
  28227. * specific language governing permissions and limitations
  28228. * under the License.
  28229. */
  28230. /**
  28231. * Get axis scale extent before niced.
  28232. * Item of returned array can only be number (including Infinity and NaN).
  28233. */
  28234. function getScaleExtent(scale, model) {
  28235. var scaleType = scale.type;
  28236. var min = model.getMin();
  28237. var max = model.getMax();
  28238. var originalExtent = scale.getExtent();
  28239. var axisDataLen;
  28240. var boundaryGap;
  28241. var span;
  28242. if (scaleType === 'ordinal') {
  28243. axisDataLen = model.getCategories().length;
  28244. } else {
  28245. boundaryGap = model.get('boundaryGap');
  28246. if (!isArray(boundaryGap)) {
  28247. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  28248. }
  28249. if (typeof boundaryGap[0] === 'boolean') {
  28250. boundaryGap = [0, 0];
  28251. }
  28252. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  28253. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  28254. span = originalExtent[1] - originalExtent[0] || Math.abs(originalExtent[0]);
  28255. } // Notice: When min/max is not set (that is, when there are null/undefined,
  28256. // which is the most common case), these cases should be ensured:
  28257. // (1) For 'ordinal', show all axis.data.
  28258. // (2) For others:
  28259. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  28260. // disabled).
  28261. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  28262. // be the result that originalExtent enlarged by boundaryGap.
  28263. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  28264. // FIXME
  28265. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  28266. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  28267. // that the results processed by boundaryGap are positive/negative?
  28268. if (min === 'dataMin') {
  28269. min = originalExtent[0];
  28270. } else if (typeof min === 'function') {
  28271. min = min({
  28272. min: originalExtent[0],
  28273. max: originalExtent[1]
  28274. });
  28275. }
  28276. if (max === 'dataMax') {
  28277. max = originalExtent[1];
  28278. } else if (typeof max === 'function') {
  28279. max = max({
  28280. min: originalExtent[0],
  28281. max: originalExtent[1]
  28282. });
  28283. }
  28284. var fixMin = min != null;
  28285. var fixMax = max != null;
  28286. if (min == null) {
  28287. min = scaleType === 'ordinal' ? axisDataLen ? 0 : NaN : originalExtent[0] - boundaryGap[0] * span;
  28288. }
  28289. if (max == null) {
  28290. max = scaleType === 'ordinal' ? axisDataLen ? axisDataLen - 1 : NaN : originalExtent[1] + boundaryGap[1] * span;
  28291. }
  28292. (min == null || !isFinite(min)) && (min = NaN);
  28293. (max == null || !isFinite(max)) && (max = NaN);
  28294. scale.setBlank(eqNaN(min) || eqNaN(max) || scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length); // Evaluate if axis needs cross zero
  28295. if (model.getNeedCrossZero()) {
  28296. // Axis is over zero and min is not set
  28297. if (min > 0 && max > 0 && !fixMin) {
  28298. min = 0;
  28299. } // Axis is under zero and max is not set
  28300. if (min < 0 && max < 0 && !fixMax) {
  28301. max = 0;
  28302. }
  28303. } // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  28304. // is base axis
  28305. // FIXME
  28306. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  28307. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  28308. // Should not depend on series type `bar`?
  28309. // (3) Fix that might overlap when using dataZoom.
  28310. // (4) Consider other chart types using `barGrid`?
  28311. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  28312. var ecModel = model.ecModel;
  28313. if (ecModel && scaleType === 'time'
  28314. /*|| scaleType === 'interval' */
  28315. ) {
  28316. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  28317. var isBaseAxisAndHasBarSeries;
  28318. each$1(barSeriesModels, function (seriesModel) {
  28319. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  28320. });
  28321. if (isBaseAxisAndHasBarSeries) {
  28322. // Calculate placement of bars on axis
  28323. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  28324. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  28325. min = adjustedScale.min;
  28326. max = adjustedScale.max;
  28327. }
  28328. }
  28329. return {
  28330. extent: [min, max],
  28331. // "fix" means "fixed", the value should not be
  28332. // changed in the subsequent steps.
  28333. fixMin: fixMin,
  28334. fixMax: fixMax
  28335. };
  28336. }
  28337. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  28338. // Get Axis Length
  28339. var axisExtent = model.axis.getExtent();
  28340. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  28341. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  28342. if (barsOnCurrentAxis === undefined) {
  28343. return {
  28344. min: min,
  28345. max: max
  28346. };
  28347. }
  28348. var minOverflow = Infinity;
  28349. each$1(barsOnCurrentAxis, function (item) {
  28350. minOverflow = Math.min(item.offset, minOverflow);
  28351. });
  28352. var maxOverflow = -Infinity;
  28353. each$1(barsOnCurrentAxis, function (item) {
  28354. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  28355. });
  28356. minOverflow = Math.abs(minOverflow);
  28357. maxOverflow = Math.abs(maxOverflow);
  28358. var totalOverFlow = minOverflow + maxOverflow; // Calulate required buffer based on old range and overflow
  28359. var oldRange = max - min;
  28360. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  28361. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  28362. max += overflowBuffer * (maxOverflow / totalOverFlow);
  28363. min -= overflowBuffer * (minOverflow / totalOverFlow);
  28364. return {
  28365. min: min,
  28366. max: max
  28367. };
  28368. }
  28369. function niceScaleExtent(scale, model) {
  28370. var extentInfo = getScaleExtent(scale, model);
  28371. var extent = extentInfo.extent;
  28372. var splitNumber = model.get('splitNumber');
  28373. if (scale.type === 'log') {
  28374. scale.base = model.get('logBase');
  28375. }
  28376. var scaleType = scale.type;
  28377. scale.setExtent(extent[0], extent[1]);
  28378. scale.niceExtent({
  28379. splitNumber: splitNumber,
  28380. fixMin: extentInfo.fixMin,
  28381. fixMax: extentInfo.fixMax,
  28382. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  28383. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  28384. }); // If some one specified the min, max. And the default calculated interval
  28385. // is not good enough. He can specify the interval. It is often appeared
  28386. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  28387. // to be 60.
  28388. // FIXME
  28389. var interval = model.get('interval');
  28390. if (interval != null) {
  28391. scale.setInterval && scale.setInterval(interval);
  28392. }
  28393. }
  28394. /**
  28395. * @param {module:echarts/model/Model} model
  28396. * @param {string} [axisType] Default retrieve from model.type
  28397. * @return {module:echarts/scale/*}
  28398. */
  28399. function createScaleByModel(model, axisType) {
  28400. axisType = axisType || model.get('type');
  28401. if (axisType) {
  28402. switch (axisType) {
  28403. // Buildin scale
  28404. case 'category':
  28405. return new OrdinalScale(model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(), [Infinity, -Infinity]);
  28406. case 'value':
  28407. return new IntervalScale();
  28408. // Extended scale, like time and log
  28409. default:
  28410. return (Scale.getClass(axisType) || IntervalScale).create(model);
  28411. }
  28412. }
  28413. }
  28414. /**
  28415. * Check if the axis corss 0
  28416. */
  28417. function ifAxisCrossZero(axis) {
  28418. var dataExtent = axis.scale.getExtent();
  28419. var min = dataExtent[0];
  28420. var max = dataExtent[1];
  28421. return !(min > 0 && max > 0 || min < 0 && max < 0);
  28422. }
  28423. /**
  28424. * @param {module:echarts/coord/Axis} axis
  28425. * @return {Function} Label formatter function.
  28426. * param: {number} tickValue,
  28427. * param: {number} idx, the index in all ticks.
  28428. * If category axis, this param is not requied.
  28429. * return: {string} label string.
  28430. */
  28431. function makeLabelFormatter(axis) {
  28432. var labelFormatter = axis.getLabelModel().get('formatter');
  28433. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  28434. if (typeof labelFormatter === 'string') {
  28435. labelFormatter = function (tpl) {
  28436. return function (val) {
  28437. // For category axis, get raw value; for numeric axis,
  28438. // get foramtted label like '1,333,444'.
  28439. val = axis.scale.getLabel(val);
  28440. return tpl.replace('{value}', val != null ? val : '');
  28441. };
  28442. }(labelFormatter); // Consider empty array
  28443. return labelFormatter;
  28444. } else if (typeof labelFormatter === 'function') {
  28445. return function (tickValue, idx) {
  28446. // The original intention of `idx` is "the index of the tick in all ticks".
  28447. // But the previous implementation of category axis do not consider the
  28448. // `axisLabel.interval`, which cause that, for example, the `interval` is
  28449. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  28450. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  28451. // the definition here for back compatibility.
  28452. if (categoryTickStart != null) {
  28453. idx = tickValue - categoryTickStart;
  28454. }
  28455. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  28456. };
  28457. } else {
  28458. return function (tick) {
  28459. return axis.scale.getLabel(tick);
  28460. };
  28461. }
  28462. }
  28463. function getAxisRawValue(axis, value) {
  28464. // In category axis with data zoom, tick is not the original
  28465. // index of axis.data. So tick should not be exposed to user
  28466. // in category axis.
  28467. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  28468. }
  28469. /**
  28470. * @param {module:echarts/coord/Axis} axis
  28471. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  28472. */
  28473. function estimateLabelUnionRect(axis) {
  28474. var axisModel = axis.model;
  28475. var scale = axis.scale;
  28476. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  28477. return;
  28478. }
  28479. var isCategory = axis.type === 'category';
  28480. var realNumberScaleTicks;
  28481. var tickCount;
  28482. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  28483. if (isCategory) {
  28484. tickCount = scale.count();
  28485. } else {
  28486. realNumberScaleTicks = scale.getTicks();
  28487. tickCount = realNumberScaleTicks.length;
  28488. }
  28489. var axisLabelModel = axis.getLabelModel();
  28490. var labelFormatter = makeLabelFormatter(axis);
  28491. var rect;
  28492. var step = 1; // Simple optimization for large amount of labels
  28493. if (tickCount > 40) {
  28494. step = Math.ceil(tickCount / 40);
  28495. }
  28496. for (var i = 0; i < tickCount; i += step) {
  28497. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  28498. var label = labelFormatter(tickValue);
  28499. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  28500. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  28501. rect ? rect.union(singleRect) : rect = singleRect;
  28502. }
  28503. return rect;
  28504. }
  28505. function rotateTextRect(textRect, rotate) {
  28506. var rotateRadians = rotate * Math.PI / 180;
  28507. var boundingBox = textRect.plain();
  28508. var beforeWidth = boundingBox.width;
  28509. var beforeHeight = boundingBox.height;
  28510. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  28511. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  28512. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  28513. return rotatedRect;
  28514. }
  28515. /**
  28516. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  28517. * @return {number|String} Can be null|'auto'|number|function
  28518. */
  28519. function getOptionCategoryInterval(model) {
  28520. var interval = model.get('interval');
  28521. return interval == null ? 'auto' : interval;
  28522. }
  28523. /**
  28524. * Set `categoryInterval` as 0 implicitly indicates that
  28525. * show all labels reguardless of overlap.
  28526. * @param {Object} axis axisModel.axis
  28527. * @return {boolean}
  28528. */
  28529. function shouldShowAllLabels(axis) {
  28530. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  28531. }
  28532. /*
  28533. * Licensed to the Apache Software Foundation (ASF) under one
  28534. * or more contributor license agreements. See the NOTICE file
  28535. * distributed with this work for additional information
  28536. * regarding copyright ownership. The ASF licenses this file
  28537. * to you under the Apache License, Version 2.0 (the
  28538. * "License"); you may not use this file except in compliance
  28539. * with the License. You may obtain a copy of the License at
  28540. *
  28541. * http://www.apache.org/licenses/LICENSE-2.0
  28542. *
  28543. * Unless required by applicable law or agreed to in writing,
  28544. * software distributed under the License is distributed on an
  28545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28546. * KIND, either express or implied. See the License for the
  28547. * specific language governing permissions and limitations
  28548. * under the License.
  28549. */
  28550. var axisModelCommonMixin = {
  28551. /**
  28552. * @param {boolean} origin
  28553. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  28554. */
  28555. getMin: function (origin) {
  28556. var option = this.option;
  28557. var min = !origin && option.rangeStart != null ? option.rangeStart : option.min;
  28558. if (this.axis && min != null && min !== 'dataMin' && typeof min !== 'function' && !eqNaN(min)) {
  28559. min = this.axis.scale.parse(min);
  28560. }
  28561. return min;
  28562. },
  28563. /**
  28564. * @param {boolean} origin
  28565. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  28566. */
  28567. getMax: function (origin) {
  28568. var option = this.option;
  28569. var max = !origin && option.rangeEnd != null ? option.rangeEnd : option.max;
  28570. if (this.axis && max != null && max !== 'dataMax' && typeof max !== 'function' && !eqNaN(max)) {
  28571. max = this.axis.scale.parse(max);
  28572. }
  28573. return max;
  28574. },
  28575. /**
  28576. * @return {boolean}
  28577. */
  28578. getNeedCrossZero: function () {
  28579. var option = this.option;
  28580. return option.rangeStart != null || option.rangeEnd != null ? false : !option.scale;
  28581. },
  28582. /**
  28583. * Should be implemented by each axis model if necessary.
  28584. * @return {module:echarts/model/Component} coordinate system model
  28585. */
  28586. getCoordSysModel: noop,
  28587. /**
  28588. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  28589. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  28590. */
  28591. setRange: function (rangeStart, rangeEnd) {
  28592. this.option.rangeStart = rangeStart;
  28593. this.option.rangeEnd = rangeEnd;
  28594. },
  28595. /**
  28596. * Reset range
  28597. */
  28598. resetRange: function () {
  28599. // rangeStart and rangeEnd is readonly.
  28600. this.option.rangeStart = this.option.rangeEnd = null;
  28601. }
  28602. };
  28603. /*
  28604. * Licensed to the Apache Software Foundation (ASF) under one
  28605. * or more contributor license agreements. See the NOTICE file
  28606. * distributed with this work for additional information
  28607. * regarding copyright ownership. The ASF licenses this file
  28608. * to you under the Apache License, Version 2.0 (the
  28609. * "License"); you may not use this file except in compliance
  28610. * with the License. You may obtain a copy of the License at
  28611. *
  28612. * http://www.apache.org/licenses/LICENSE-2.0
  28613. *
  28614. * Unless required by applicable law or agreed to in writing,
  28615. * software distributed under the License is distributed on an
  28616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28617. * KIND, either express or implied. See the License for the
  28618. * specific language governing permissions and limitations
  28619. * under the License.
  28620. */
  28621. // Symbol factory
  28622. /**
  28623. * Triangle shape
  28624. * @inner
  28625. */
  28626. var Triangle = extendShape({
  28627. type: 'triangle',
  28628. shape: {
  28629. cx: 0,
  28630. cy: 0,
  28631. width: 0,
  28632. height: 0
  28633. },
  28634. buildPath: function (path, shape) {
  28635. var cx = shape.cx;
  28636. var cy = shape.cy;
  28637. var width = shape.width / 2;
  28638. var height = shape.height / 2;
  28639. path.moveTo(cx, cy - height);
  28640. path.lineTo(cx + width, cy + height);
  28641. path.lineTo(cx - width, cy + height);
  28642. path.closePath();
  28643. }
  28644. });
  28645. /**
  28646. * Diamond shape
  28647. * @inner
  28648. */
  28649. var Diamond = extendShape({
  28650. type: 'diamond',
  28651. shape: {
  28652. cx: 0,
  28653. cy: 0,
  28654. width: 0,
  28655. height: 0
  28656. },
  28657. buildPath: function (path, shape) {
  28658. var cx = shape.cx;
  28659. var cy = shape.cy;
  28660. var width = shape.width / 2;
  28661. var height = shape.height / 2;
  28662. path.moveTo(cx, cy - height);
  28663. path.lineTo(cx + width, cy);
  28664. path.lineTo(cx, cy + height);
  28665. path.lineTo(cx - width, cy);
  28666. path.closePath();
  28667. }
  28668. });
  28669. /**
  28670. * Pin shape
  28671. * @inner
  28672. */
  28673. var Pin = extendShape({
  28674. type: 'pin',
  28675. shape: {
  28676. // x, y on the cusp
  28677. x: 0,
  28678. y: 0,
  28679. width: 0,
  28680. height: 0
  28681. },
  28682. buildPath: function (path, shape) {
  28683. var x = shape.x;
  28684. var y = shape.y;
  28685. var w = shape.width / 5 * 3; // Height must be larger than width
  28686. var h = Math.max(w, shape.height);
  28687. var r = w / 2; // Dist on y with tangent point and circle center
  28688. var dy = r * r / (h - r);
  28689. var cy = y - h + r + dy;
  28690. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  28691. var dx = Math.cos(angle) * r;
  28692. var tanX = Math.sin(angle);
  28693. var tanY = Math.cos(angle);
  28694. var cpLen = r * 0.6;
  28695. var cpLen2 = r * 0.7;
  28696. path.moveTo(x - dx, cy + dy);
  28697. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  28698. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  28699. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  28700. path.closePath();
  28701. }
  28702. });
  28703. /**
  28704. * Arrow shape
  28705. * @inner
  28706. */
  28707. var Arrow = extendShape({
  28708. type: 'arrow',
  28709. shape: {
  28710. x: 0,
  28711. y: 0,
  28712. width: 0,
  28713. height: 0
  28714. },
  28715. buildPath: function (ctx, shape) {
  28716. var height = shape.height;
  28717. var width = shape.width;
  28718. var x = shape.x;
  28719. var y = shape.y;
  28720. var dx = width / 3 * 2;
  28721. ctx.moveTo(x, y);
  28722. ctx.lineTo(x + dx, y + height);
  28723. ctx.lineTo(x, y + height / 4 * 3);
  28724. ctx.lineTo(x - dx, y + height);
  28725. ctx.lineTo(x, y);
  28726. ctx.closePath();
  28727. }
  28728. });
  28729. /**
  28730. * Map of path contructors
  28731. * @type {Object.<string, module:zrender/graphic/Path>}
  28732. */
  28733. var symbolCtors = {
  28734. line: Line,
  28735. rect: Rect,
  28736. roundRect: Rect,
  28737. square: Rect,
  28738. circle: Circle,
  28739. diamond: Diamond,
  28740. pin: Pin,
  28741. arrow: Arrow,
  28742. triangle: Triangle
  28743. };
  28744. var symbolShapeMakers = {
  28745. line: function (x, y, w, h, shape) {
  28746. // FIXME
  28747. shape.x1 = x;
  28748. shape.y1 = y + h / 2;
  28749. shape.x2 = x + w;
  28750. shape.y2 = y + h / 2;
  28751. },
  28752. rect: function (x, y, w, h, shape) {
  28753. shape.x = x;
  28754. shape.y = y;
  28755. shape.width = w;
  28756. shape.height = h;
  28757. },
  28758. roundRect: function (x, y, w, h, shape) {
  28759. shape.x = x;
  28760. shape.y = y;
  28761. shape.width = w;
  28762. shape.height = h;
  28763. shape.r = Math.min(w, h) / 4;
  28764. },
  28765. square: function (x, y, w, h, shape) {
  28766. var size = Math.min(w, h);
  28767. shape.x = x;
  28768. shape.y = y;
  28769. shape.width = size;
  28770. shape.height = size;
  28771. },
  28772. circle: function (x, y, w, h, shape) {
  28773. // Put circle in the center of square
  28774. shape.cx = x + w / 2;
  28775. shape.cy = y + h / 2;
  28776. shape.r = Math.min(w, h) / 2;
  28777. },
  28778. diamond: function (x, y, w, h, shape) {
  28779. shape.cx = x + w / 2;
  28780. shape.cy = y + h / 2;
  28781. shape.width = w;
  28782. shape.height = h;
  28783. },
  28784. pin: function (x, y, w, h, shape) {
  28785. shape.x = x + w / 2;
  28786. shape.y = y + h / 2;
  28787. shape.width = w;
  28788. shape.height = h;
  28789. },
  28790. arrow: function (x, y, w, h, shape) {
  28791. shape.x = x + w / 2;
  28792. shape.y = y + h / 2;
  28793. shape.width = w;
  28794. shape.height = h;
  28795. },
  28796. triangle: function (x, y, w, h, shape) {
  28797. shape.cx = x + w / 2;
  28798. shape.cy = y + h / 2;
  28799. shape.width = w;
  28800. shape.height = h;
  28801. }
  28802. };
  28803. var symbolBuildProxies = {};
  28804. each$1(symbolCtors, function (Ctor, name) {
  28805. symbolBuildProxies[name] = new Ctor();
  28806. });
  28807. var SymbolClz = extendShape({
  28808. type: 'symbol',
  28809. shape: {
  28810. symbolType: '',
  28811. x: 0,
  28812. y: 0,
  28813. width: 0,
  28814. height: 0
  28815. },
  28816. calculateTextPosition: function (out, style, rect) {
  28817. var res = calculateTextPosition(out, style, rect);
  28818. var shape = this.shape;
  28819. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28820. res.y = rect.y + rect.height * 0.4;
  28821. }
  28822. return res;
  28823. },
  28824. buildPath: function (ctx, shape, inBundle) {
  28825. var symbolType = shape.symbolType;
  28826. if (symbolType !== 'none') {
  28827. var proxySymbol = symbolBuildProxies[symbolType];
  28828. if (!proxySymbol) {
  28829. // Default rect
  28830. symbolType = 'rect';
  28831. proxySymbol = symbolBuildProxies[symbolType];
  28832. }
  28833. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  28834. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28835. }
  28836. }
  28837. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28838. function symbolPathSetColor(color, innerColor) {
  28839. if (this.type !== 'image') {
  28840. var symbolStyle = this.style;
  28841. var symbolShape = this.shape;
  28842. if (symbolShape && symbolShape.symbolType === 'line') {
  28843. symbolStyle.stroke = color;
  28844. } else if (this.__isEmptyBrush) {
  28845. symbolStyle.stroke = color;
  28846. symbolStyle.fill = innerColor || '#fff';
  28847. } else {
  28848. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28849. symbolStyle.fill && (symbolStyle.fill = color);
  28850. symbolStyle.stroke && (symbolStyle.stroke = color);
  28851. }
  28852. this.dirty(false);
  28853. }
  28854. }
  28855. /**
  28856. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28857. * @param {string} symbolType
  28858. * @param {number} x
  28859. * @param {number} y
  28860. * @param {number} w
  28861. * @param {number} h
  28862. * @param {string} color
  28863. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28864. * for path and image only.
  28865. */
  28866. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28867. // TODO Support image object, DynamicImage.
  28868. var isEmpty = symbolType.indexOf('empty') === 0;
  28869. if (isEmpty) {
  28870. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28871. }
  28872. var symbolPath;
  28873. if (symbolType.indexOf('image://') === 0) {
  28874. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  28875. } else if (symbolType.indexOf('path://') === 0) {
  28876. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  28877. } else {
  28878. symbolPath = new SymbolClz({
  28879. shape: {
  28880. symbolType: symbolType,
  28881. x: x,
  28882. y: y,
  28883. width: w,
  28884. height: h
  28885. }
  28886. });
  28887. }
  28888. symbolPath.__isEmptyBrush = isEmpty;
  28889. symbolPath.setColor = symbolPathSetColor;
  28890. symbolPath.setColor(color);
  28891. return symbolPath;
  28892. }
  28893. /*
  28894. * Licensed to the Apache Software Foundation (ASF) under one
  28895. * or more contributor license agreements. See the NOTICE file
  28896. * distributed with this work for additional information
  28897. * regarding copyright ownership. The ASF licenses this file
  28898. * to you under the Apache License, Version 2.0 (the
  28899. * "License"); you may not use this file except in compliance
  28900. * with the License. You may obtain a copy of the License at
  28901. *
  28902. * http://www.apache.org/licenses/LICENSE-2.0
  28903. *
  28904. * Unless required by applicable law or agreed to in writing,
  28905. * software distributed under the License is distributed on an
  28906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28907. * KIND, either express or implied. See the License for the
  28908. * specific language governing permissions and limitations
  28909. * under the License.
  28910. */
  28911. /**
  28912. * Create a muti dimension List structure from seriesModel.
  28913. * @param {module:echarts/model/Model} seriesModel
  28914. * @return {module:echarts/data/List} list
  28915. */
  28916. function createList(seriesModel) {
  28917. return createListFromArray(seriesModel.getSource(), seriesModel);
  28918. } // export function createGraph(seriesModel) {
  28919. var dataStack$1 = {
  28920. isDimensionStacked: isDimensionStacked,
  28921. enableDataStack: enableDataStack,
  28922. getStackedDimension: getStackedDimension
  28923. };
  28924. /**
  28925. * Create scale
  28926. * @param {Array.<number>} dataExtent
  28927. * @param {Object|module:echarts/Model} option
  28928. */
  28929. function createScale(dataExtent, option) {
  28930. var axisModel = option;
  28931. if (!Model.isInstance(option)) {
  28932. axisModel = new Model(option);
  28933. mixin(axisModel, axisModelCommonMixin);
  28934. }
  28935. var scale = createScaleByModel(axisModel);
  28936. scale.setExtent(dataExtent[0], dataExtent[1]);
  28937. niceScaleExtent(scale, axisModel);
  28938. return scale;
  28939. }
  28940. /**
  28941. * Mixin common methods to axis model,
  28942. *
  28943. * Inlcude methods
  28944. * `getFormattedLabels() => Array.<string>`
  28945. * `getCategories() => Array.<string>`
  28946. * `getMin(origin: boolean) => number`
  28947. * `getMax(origin: boolean) => number`
  28948. * `getNeedCrossZero() => boolean`
  28949. * `setRange(start: number, end: number)`
  28950. * `resetRange()`
  28951. */
  28952. function mixinAxisModelCommonMethods(Model$$1) {
  28953. mixin(Model$$1, axisModelCommonMixin);
  28954. }
  28955. var helper = (Object.freeze || Object)({
  28956. createList: createList,
  28957. getLayoutRect: getLayoutRect,
  28958. dataStack: dataStack$1,
  28959. createScale: createScale,
  28960. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  28961. completeDimensions: completeDimensions,
  28962. createDimensions: createDimensions,
  28963. createSymbol: createSymbol
  28964. });
  28965. var EPSILON$3 = 1e-8;
  28966. function isAroundEqual$1(a, b) {
  28967. return Math.abs(a - b) < EPSILON$3;
  28968. }
  28969. function contain$1(points, x, y) {
  28970. var w = 0;
  28971. var p = points[0];
  28972. if (!p) {
  28973. return false;
  28974. }
  28975. for (var i = 1; i < points.length; i++) {
  28976. var p2 = points[i];
  28977. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  28978. p = p2;
  28979. } // Close polygon
  28980. var p0 = points[0];
  28981. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  28982. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  28983. }
  28984. return w !== 0;
  28985. }
  28986. /*
  28987. * Licensed to the Apache Software Foundation (ASF) under one
  28988. * or more contributor license agreements. See the NOTICE file
  28989. * distributed with this work for additional information
  28990. * regarding copyright ownership. The ASF licenses this file
  28991. * to you under the Apache License, Version 2.0 (the
  28992. * "License"); you may not use this file except in compliance
  28993. * with the License. You may obtain a copy of the License at
  28994. *
  28995. * http://www.apache.org/licenses/LICENSE-2.0
  28996. *
  28997. * Unless required by applicable law or agreed to in writing,
  28998. * software distributed under the License is distributed on an
  28999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29000. * KIND, either express or implied. See the License for the
  29001. * specific language governing permissions and limitations
  29002. * under the License.
  29003. */
  29004. /**
  29005. * @module echarts/coord/geo/Region
  29006. */
  29007. /**
  29008. * @param {string|Region} name
  29009. * @param {Array} geometries
  29010. * @param {Array.<number>} cp
  29011. */
  29012. function Region(name, geometries, cp) {
  29013. /**
  29014. * @type {string}
  29015. * @readOnly
  29016. */
  29017. this.name = name;
  29018. /**
  29019. * @type {Array.<Array>}
  29020. * @readOnly
  29021. */
  29022. this.geometries = geometries;
  29023. if (!cp) {
  29024. var rect = this.getBoundingRect();
  29025. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  29026. } else {
  29027. cp = [cp[0], cp[1]];
  29028. }
  29029. /**
  29030. * @type {Array.<number>}
  29031. */
  29032. this.center = cp;
  29033. }
  29034. Region.prototype = {
  29035. constructor: Region,
  29036. properties: null,
  29037. /**
  29038. * @return {module:zrender/core/BoundingRect}
  29039. */
  29040. getBoundingRect: function () {
  29041. var rect = this._rect;
  29042. if (rect) {
  29043. return rect;
  29044. }
  29045. var MAX_NUMBER = Number.MAX_VALUE;
  29046. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  29047. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  29048. var min2 = [];
  29049. var max2 = [];
  29050. var geometries = this.geometries;
  29051. for (var i = 0; i < geometries.length; i++) {
  29052. // Only support polygon
  29053. if (geometries[i].type !== 'polygon') {
  29054. continue;
  29055. } // Doesn't consider hole
  29056. var exterior = geometries[i].exterior;
  29057. fromPoints(exterior, min2, max2);
  29058. min(min$$1, min$$1, min2);
  29059. max(max$$1, max$$1, max2);
  29060. } // No data
  29061. if (i === 0) {
  29062. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  29063. }
  29064. return this._rect = new BoundingRect(min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]);
  29065. },
  29066. /**
  29067. * @param {<Array.<number>} coord
  29068. * @return {boolean}
  29069. */
  29070. contain: function (coord) {
  29071. var rect = this.getBoundingRect();
  29072. var geometries = this.geometries;
  29073. if (!rect.contain(coord[0], coord[1])) {
  29074. return false;
  29075. }
  29076. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  29077. // Only support polygon.
  29078. if (geometries[i].type !== 'polygon') {
  29079. continue;
  29080. }
  29081. var exterior = geometries[i].exterior;
  29082. var interiors = geometries[i].interiors;
  29083. if (contain$1(exterior, coord[0], coord[1])) {
  29084. // Not in the region if point is in the hole.
  29085. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  29086. if (contain$1(interiors[k])) {
  29087. continue loopGeo;
  29088. }
  29089. }
  29090. return true;
  29091. }
  29092. }
  29093. return false;
  29094. },
  29095. transformTo: function (x, y, width, height) {
  29096. var rect = this.getBoundingRect();
  29097. var aspect = rect.width / rect.height;
  29098. if (!width) {
  29099. width = aspect * height;
  29100. } else if (!height) {
  29101. height = width / aspect;
  29102. }
  29103. var target = new BoundingRect(x, y, width, height);
  29104. var transform = rect.calculateTransform(target);
  29105. var geometries = this.geometries;
  29106. for (var i = 0; i < geometries.length; i++) {
  29107. // Only support polygon.
  29108. if (geometries[i].type !== 'polygon') {
  29109. continue;
  29110. }
  29111. var exterior = geometries[i].exterior;
  29112. var interiors = geometries[i].interiors;
  29113. for (var p = 0; p < exterior.length; p++) {
  29114. applyTransform(exterior[p], exterior[p], transform);
  29115. }
  29116. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  29117. for (var p = 0; p < interiors[h].length; p++) {
  29118. applyTransform(interiors[h][p], interiors[h][p], transform);
  29119. }
  29120. }
  29121. }
  29122. rect = this._rect;
  29123. rect.copy(target); // Update center
  29124. this.center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  29125. },
  29126. cloneShallow: function (name) {
  29127. name == null && (name = this.name);
  29128. var newRegion = new Region(name, this.geometries, this.center);
  29129. newRegion._rect = this._rect;
  29130. newRegion.transformTo = null; // Simply avoid to be called.
  29131. return newRegion;
  29132. }
  29133. };
  29134. /*
  29135. * Licensed to the Apache Software Foundation (ASF) under one
  29136. * or more contributor license agreements. See the NOTICE file
  29137. * distributed with this work for additional information
  29138. * regarding copyright ownership. The ASF licenses this file
  29139. * to you under the Apache License, Version 2.0 (the
  29140. * "License"); you may not use this file except in compliance
  29141. * with the License. You may obtain a copy of the License at
  29142. *
  29143. * http://www.apache.org/licenses/LICENSE-2.0
  29144. *
  29145. * Unless required by applicable law or agreed to in writing,
  29146. * software distributed under the License is distributed on an
  29147. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29148. * KIND, either express or implied. See the License for the
  29149. * specific language governing permissions and limitations
  29150. * under the License.
  29151. */
  29152. /**
  29153. * Parse and decode geo json
  29154. * @module echarts/coord/geo/parseGeoJson
  29155. */
  29156. function decode(json) {
  29157. if (!json.UTF8Encoding) {
  29158. return json;
  29159. }
  29160. var encodeScale = json.UTF8Scale;
  29161. if (encodeScale == null) {
  29162. encodeScale = 1024;
  29163. }
  29164. var features = json.features;
  29165. for (var f = 0; f < features.length; f++) {
  29166. var feature = features[f];
  29167. var geometry = feature.geometry;
  29168. var coordinates = geometry.coordinates;
  29169. var encodeOffsets = geometry.encodeOffsets;
  29170. for (var c = 0; c < coordinates.length; c++) {
  29171. var coordinate = coordinates[c];
  29172. if (geometry.type === 'Polygon') {
  29173. coordinates[c] = decodePolygon(coordinate, encodeOffsets[c], encodeScale);
  29174. } else if (geometry.type === 'MultiPolygon') {
  29175. for (var c2 = 0; c2 < coordinate.length; c2++) {
  29176. var polygon = coordinate[c2];
  29177. coordinate[c2] = decodePolygon(polygon, encodeOffsets[c][c2], encodeScale);
  29178. }
  29179. }
  29180. }
  29181. } // Has been decoded
  29182. json.UTF8Encoding = false;
  29183. return json;
  29184. }
  29185. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  29186. var result = [];
  29187. var prevX = encodeOffsets[0];
  29188. var prevY = encodeOffsets[1];
  29189. for (var i = 0; i < coordinate.length; i += 2) {
  29190. var x = coordinate.charCodeAt(i) - 64;
  29191. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  29192. x = x >> 1 ^ -(x & 1);
  29193. y = y >> 1 ^ -(y & 1); // Delta deocding
  29194. x += prevX;
  29195. y += prevY;
  29196. prevX = x;
  29197. prevY = y; // Dequantize
  29198. result.push([x / encodeScale, y / encodeScale]);
  29199. }
  29200. return result;
  29201. }
  29202. /**
  29203. * @alias module:echarts/coord/geo/parseGeoJson
  29204. * @param {Object} geoJson
  29205. * @param {string} nameProperty
  29206. * @return {module:zrender/container/Group}
  29207. */
  29208. var parseGeoJSON = function (geoJson, nameProperty) {
  29209. decode(geoJson);
  29210. return map(filter(geoJson.features, function (featureObj) {
  29211. // Output of mapshaper may have geometry null
  29212. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  29213. }), function (featureObj) {
  29214. var properties = featureObj.properties;
  29215. var geo = featureObj.geometry;
  29216. var coordinates = geo.coordinates;
  29217. var geometries = [];
  29218. if (geo.type === 'Polygon') {
  29219. geometries.push({
  29220. type: 'polygon',
  29221. // According to the GeoJSON specification.
  29222. // First must be exterior, and the rest are all interior(holes).
  29223. exterior: coordinates[0],
  29224. interiors: coordinates.slice(1)
  29225. });
  29226. }
  29227. if (geo.type === 'MultiPolygon') {
  29228. each$1(coordinates, function (item) {
  29229. if (item[0]) {
  29230. geometries.push({
  29231. type: 'polygon',
  29232. exterior: item[0],
  29233. interiors: item.slice(1)
  29234. });
  29235. }
  29236. });
  29237. }
  29238. var region = new Region(properties[nameProperty || 'name'], geometries, properties.cp);
  29239. region.properties = properties;
  29240. return region;
  29241. });
  29242. };
  29243. /*
  29244. * Licensed to the Apache Software Foundation (ASF) under one
  29245. * or more contributor license agreements. See the NOTICE file
  29246. * distributed with this work for additional information
  29247. * regarding copyright ownership. The ASF licenses this file
  29248. * to you under the Apache License, Version 2.0 (the
  29249. * "License"); you may not use this file except in compliance
  29250. * with the License. You may obtain a copy of the License at
  29251. *
  29252. * http://www.apache.org/licenses/LICENSE-2.0
  29253. *
  29254. * Unless required by applicable law or agreed to in writing,
  29255. * software distributed under the License is distributed on an
  29256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29257. * KIND, either express or implied. See the License for the
  29258. * specific language governing permissions and limitations
  29259. * under the License.
  29260. */
  29261. var inner$6 = makeInner();
  29262. /**
  29263. * @param {module:echats/coord/Axis} axis
  29264. * @return {Object} {
  29265. * labels: [{
  29266. * formattedLabel: string,
  29267. * rawLabel: string,
  29268. * tickValue: number
  29269. * }, ...],
  29270. * labelCategoryInterval: number
  29271. * }
  29272. */
  29273. function createAxisLabels(axis) {
  29274. // Only ordinal scale support tick interval
  29275. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  29276. }
  29277. /**
  29278. * @param {module:echats/coord/Axis} axis
  29279. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  29280. * @return {Object} {
  29281. * ticks: Array.<number>
  29282. * tickCategoryInterval: number
  29283. * }
  29284. */
  29285. function createAxisTicks(axis, tickModel) {
  29286. // Only ordinal scale support tick interval
  29287. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  29288. ticks: axis.scale.getTicks()
  29289. };
  29290. }
  29291. function makeCategoryLabels(axis) {
  29292. var labelModel = axis.getLabelModel();
  29293. var result = makeCategoryLabelsActually(axis, labelModel);
  29294. return !labelModel.get('show') || axis.scale.isBlank() ? {
  29295. labels: [],
  29296. labelCategoryInterval: result.labelCategoryInterval
  29297. } : result;
  29298. }
  29299. function makeCategoryLabelsActually(axis, labelModel) {
  29300. var labelsCache = getListCache(axis, 'labels');
  29301. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  29302. var result = listCacheGet(labelsCache, optionLabelInterval);
  29303. if (result) {
  29304. return result;
  29305. }
  29306. var labels;
  29307. var numericLabelInterval;
  29308. if (isFunction$1(optionLabelInterval)) {
  29309. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  29310. } else {
  29311. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  29312. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  29313. } // Cache to avoid calling interval function repeatly.
  29314. return listCacheSet(labelsCache, optionLabelInterval, {
  29315. labels: labels,
  29316. labelCategoryInterval: numericLabelInterval
  29317. });
  29318. }
  29319. function makeCategoryTicks(axis, tickModel) {
  29320. var ticksCache = getListCache(axis, 'ticks');
  29321. var optionTickInterval = getOptionCategoryInterval(tickModel);
  29322. var result = listCacheGet(ticksCache, optionTickInterval);
  29323. if (result) {
  29324. return result;
  29325. }
  29326. var ticks;
  29327. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  29328. // we should not return all ticks.
  29329. if (!tickModel.get('show') || axis.scale.isBlank()) {
  29330. ticks = [];
  29331. }
  29332. if (isFunction$1(optionTickInterval)) {
  29333. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  29334. } // Always use label interval by default despite label show. Consider this
  29335. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  29336. // labels. `splitLine` and `axisTick` should be consistent in this case.
  29337. else if (optionTickInterval === 'auto') {
  29338. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  29339. tickCategoryInterval = labelsResult.labelCategoryInterval;
  29340. ticks = map(labelsResult.labels, function (labelItem) {
  29341. return labelItem.tickValue;
  29342. });
  29343. } else {
  29344. tickCategoryInterval = optionTickInterval;
  29345. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  29346. } // Cache to avoid calling interval function repeatly.
  29347. return listCacheSet(ticksCache, optionTickInterval, {
  29348. ticks: ticks,
  29349. tickCategoryInterval: tickCategoryInterval
  29350. });
  29351. }
  29352. function makeRealNumberLabels(axis) {
  29353. var ticks = axis.scale.getTicks();
  29354. var labelFormatter = makeLabelFormatter(axis);
  29355. return {
  29356. labels: map(ticks, function (tickValue, idx) {
  29357. return {
  29358. formattedLabel: labelFormatter(tickValue, idx),
  29359. rawLabel: axis.scale.getLabel(tickValue),
  29360. tickValue: tickValue
  29361. };
  29362. })
  29363. };
  29364. } // Large category data calculation is performence sensitive, and ticks and label
  29365. // probably be fetched by multiple times. So we cache the result.
  29366. // axis is created each time during a ec process, so we do not need to clear cache.
  29367. function getListCache(axis, prop) {
  29368. // Because key can be funciton, and cache size always be small, we use array cache.
  29369. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  29370. }
  29371. function listCacheGet(cache, key) {
  29372. for (var i = 0; i < cache.length; i++) {
  29373. if (cache[i].key === key) {
  29374. return cache[i].value;
  29375. }
  29376. }
  29377. }
  29378. function listCacheSet(cache, key, value) {
  29379. cache.push({
  29380. key: key,
  29381. value: value
  29382. });
  29383. return value;
  29384. }
  29385. function makeAutoCategoryInterval(axis) {
  29386. var result = inner$6(axis).autoInterval;
  29387. return result != null ? result : inner$6(axis).autoInterval = axis.calculateCategoryInterval();
  29388. }
  29389. /**
  29390. * Calculate interval for category axis ticks and labels.
  29391. * To get precise result, at least one of `getRotate` and `isHorizontal`
  29392. * should be implemented in axis.
  29393. */
  29394. function calculateCategoryInterval(axis) {
  29395. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  29396. var labelFormatter = makeLabelFormatter(axis);
  29397. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  29398. var ordinalScale = axis.scale;
  29399. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  29400. // avoid generating a long array by `getTicks`
  29401. // in large category data case.
  29402. var tickCount = ordinalScale.count();
  29403. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  29404. return 0;
  29405. }
  29406. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  29407. if (tickCount > 40) {
  29408. step = Math.max(1, Math.floor(tickCount / 40));
  29409. }
  29410. var tickValue = ordinalExtent[0];
  29411. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  29412. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  29413. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  29414. var maxW = 0;
  29415. var maxH = 0; // Caution: Performance sensitive for large category data.
  29416. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  29417. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  29418. var width = 0;
  29419. var height = 0; // Not precise, do not consider align and vertical align
  29420. // and each distance from axis line yet.
  29421. var rect = getBoundingRect(labelFormatter(tickValue), params.font, 'center', 'top'); // Magic number
  29422. width = rect.width * 1.3;
  29423. height = rect.height * 1.3; // Min size, void long loop.
  29424. maxW = Math.max(maxW, width, 7);
  29425. maxH = Math.max(maxH, height, 7);
  29426. }
  29427. var dw = maxW / unitW;
  29428. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  29429. isNaN(dw) && (dw = Infinity);
  29430. isNaN(dh) && (dh = Infinity);
  29431. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  29432. var cache = inner$6(axis.model);
  29433. var axisExtent = axis.getExtent();
  29434. var lastAutoInterval = cache.lastAutoInterval;
  29435. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  29436. // otherwise the calculated interval might jitter when the zoom
  29437. // window size is close to the interval-changing size.
  29438. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  29439. // The jitter will cause that sometimes the displayed labels are
  29440. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  29441. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  29442. // point is not the same when zooming in or zooming out.
  29443. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  29444. // be used. Otherwise some hiden labels might not be shown again.
  29445. && cache.axisExtend0 === axisExtent[0] && cache.axisExtend1 === axisExtent[1]) {
  29446. interval = lastAutoInterval;
  29447. } // Only update cache if cache not used, otherwise the
  29448. // changing of interval is too insensitive.
  29449. else {
  29450. cache.lastTickCount = tickCount;
  29451. cache.lastAutoInterval = interval;
  29452. cache.axisExtend0 = axisExtent[0];
  29453. cache.axisExtend1 = axisExtent[1];
  29454. }
  29455. return interval;
  29456. }
  29457. function fetchAutoCategoryIntervalCalculationParams(axis) {
  29458. var labelModel = axis.getLabelModel();
  29459. return {
  29460. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  29461. labelRotate: labelModel.get('rotate') || 0,
  29462. font: labelModel.getFont()
  29463. };
  29464. }
  29465. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  29466. var labelFormatter = makeLabelFormatter(axis);
  29467. var ordinalScale = axis.scale;
  29468. var ordinalExtent = ordinalScale.getExtent();
  29469. var labelModel = axis.getLabelModel();
  29470. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  29471. var step = Math.max((categoryInterval || 0) + 1, 1);
  29472. var startTick = ordinalExtent[0];
  29473. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  29474. // while zooming and moving while interval > 0. Otherwise the selection
  29475. // of displayable ticks and symbols probably keep changing.
  29476. // 3 is empirical value.
  29477. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  29478. startTick = Math.round(Math.ceil(startTick / step) * step);
  29479. } // (1) Only add min max label here but leave overlap checking
  29480. // to render stage, which also ensure the returned list
  29481. // suitable for splitLine and splitArea rendering.
  29482. // (2) Scales except category always contain min max label so
  29483. // do not need to perform this process.
  29484. var showAllLabel = shouldShowAllLabels(axis);
  29485. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  29486. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  29487. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  29488. addItem(ordinalExtent[0]);
  29489. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  29490. var tickValue = startTick;
  29491. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  29492. addItem(tickValue);
  29493. }
  29494. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  29495. addItem(ordinalExtent[1]);
  29496. }
  29497. function addItem(tVal) {
  29498. result.push(onlyTick ? tVal : {
  29499. formattedLabel: labelFormatter(tVal),
  29500. rawLabel: ordinalScale.getLabel(tVal),
  29501. tickValue: tVal
  29502. });
  29503. }
  29504. return result;
  29505. } // When interval is function, the result `false` means ignore the tick.
  29506. // It is time consuming for large category data.
  29507. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  29508. var ordinalScale = axis.scale;
  29509. var labelFormatter = makeLabelFormatter(axis);
  29510. var result = [];
  29511. each$1(ordinalScale.getTicks(), function (tickValue) {
  29512. var rawLabel = ordinalScale.getLabel(tickValue);
  29513. if (categoryInterval(tickValue, rawLabel)) {
  29514. result.push(onlyTick ? tickValue : {
  29515. formattedLabel: labelFormatter(tickValue),
  29516. rawLabel: rawLabel,
  29517. tickValue: tickValue
  29518. });
  29519. }
  29520. });
  29521. return result;
  29522. }
  29523. /*
  29524. * Licensed to the Apache Software Foundation (ASF) under one
  29525. * or more contributor license agreements. See the NOTICE file
  29526. * distributed with this work for additional information
  29527. * regarding copyright ownership. The ASF licenses this file
  29528. * to you under the Apache License, Version 2.0 (the
  29529. * "License"); you may not use this file except in compliance
  29530. * with the License. You may obtain a copy of the License at
  29531. *
  29532. * http://www.apache.org/licenses/LICENSE-2.0
  29533. *
  29534. * Unless required by applicable law or agreed to in writing,
  29535. * software distributed under the License is distributed on an
  29536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29537. * KIND, either express or implied. See the License for the
  29538. * specific language governing permissions and limitations
  29539. * under the License.
  29540. */
  29541. var NORMALIZED_EXTENT = [0, 1];
  29542. /**
  29543. * Base class of Axis.
  29544. * @constructor
  29545. */
  29546. var Axis = function (dim, scale, extent) {
  29547. /**
  29548. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  29549. * @type {string}
  29550. */
  29551. this.dim = dim;
  29552. /**
  29553. * Axis scale
  29554. * @type {module:echarts/coord/scale/*}
  29555. */
  29556. this.scale = scale;
  29557. /**
  29558. * @type {Array.<number>}
  29559. * @private
  29560. */
  29561. this._extent = extent || [0, 0];
  29562. /**
  29563. * @type {boolean}
  29564. */
  29565. this.inverse = false;
  29566. /**
  29567. * Usually true when axis has a ordinal scale
  29568. * @type {boolean}
  29569. */
  29570. this.onBand = false;
  29571. };
  29572. Axis.prototype = {
  29573. constructor: Axis,
  29574. /**
  29575. * If axis extent contain given coord
  29576. * @param {number} coord
  29577. * @return {boolean}
  29578. */
  29579. contain: function (coord) {
  29580. var extent = this._extent;
  29581. var min = Math.min(extent[0], extent[1]);
  29582. var max = Math.max(extent[0], extent[1]);
  29583. return coord >= min && coord <= max;
  29584. },
  29585. /**
  29586. * If axis extent contain given data
  29587. * @param {number} data
  29588. * @return {boolean}
  29589. */
  29590. containData: function (data) {
  29591. return this.scale.contain(data);
  29592. },
  29593. /**
  29594. * Get coord extent.
  29595. * @return {Array.<number>}
  29596. */
  29597. getExtent: function () {
  29598. return this._extent.slice();
  29599. },
  29600. /**
  29601. * Get precision used for formatting
  29602. * @param {Array.<number>} [dataExtent]
  29603. * @return {number}
  29604. */
  29605. getPixelPrecision: function (dataExtent) {
  29606. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  29607. },
  29608. /**
  29609. * Set coord extent
  29610. * @param {number} start
  29611. * @param {number} end
  29612. */
  29613. setExtent: function (start, end) {
  29614. var extent = this._extent;
  29615. extent[0] = start;
  29616. extent[1] = end;
  29617. },
  29618. /**
  29619. * Convert data to coord. Data is the rank if it has an ordinal scale
  29620. * @param {number} data
  29621. * @param {boolean} clamp
  29622. * @return {number}
  29623. */
  29624. dataToCoord: function (data, clamp) {
  29625. var extent = this._extent;
  29626. var scale = this.scale;
  29627. data = scale.normalize(data);
  29628. if (this.onBand && scale.type === 'ordinal') {
  29629. extent = extent.slice();
  29630. fixExtentWithBands(extent, scale.count());
  29631. }
  29632. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  29633. },
  29634. /**
  29635. * Convert coord to data. Data is the rank if it has an ordinal scale
  29636. * @param {number} coord
  29637. * @param {boolean} clamp
  29638. * @return {number}
  29639. */
  29640. coordToData: function (coord, clamp) {
  29641. var extent = this._extent;
  29642. var scale = this.scale;
  29643. if (this.onBand && scale.type === 'ordinal') {
  29644. extent = extent.slice();
  29645. fixExtentWithBands(extent, scale.count());
  29646. }
  29647. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  29648. return this.scale.scale(t);
  29649. },
  29650. /**
  29651. * Convert pixel point to data in axis
  29652. * @param {Array.<number>} point
  29653. * @param {boolean} clamp
  29654. * @return {number} data
  29655. */
  29656. pointToData: function (point, clamp) {// Should be implemented in derived class if necessary.
  29657. },
  29658. /**
  29659. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  29660. * `axis.getTicksCoords` considers `onBand`, which is used by
  29661. * `boundaryGap:true` of category axis and splitLine and splitArea.
  29662. * @param {Object} [opt]
  29663. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  29664. * @param {boolean} [opt.clamp] If `true`, the first and the last
  29665. * tick must be at the axis end points. Otherwise, clip ticks
  29666. * that outside the axis extent.
  29667. * @return {Array.<Object>} [{
  29668. * coord: ...,
  29669. * tickValue: ...
  29670. * }, ...]
  29671. */
  29672. getTicksCoords: function (opt) {
  29673. opt = opt || {};
  29674. var tickModel = opt.tickModel || this.getTickModel();
  29675. var result = createAxisTicks(this, tickModel);
  29676. var ticks = result.ticks;
  29677. var ticksCoords = map(ticks, function (tickValue) {
  29678. return {
  29679. coord: this.dataToCoord(tickValue),
  29680. tickValue: tickValue
  29681. };
  29682. }, this);
  29683. var alignWithLabel = tickModel.get('alignWithLabel');
  29684. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  29685. return ticksCoords;
  29686. },
  29687. /**
  29688. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  29689. */
  29690. getMinorTicksCoords: function () {
  29691. if (this.scale.type === 'ordinal') {
  29692. // Category axis doesn't support minor ticks
  29693. return [];
  29694. }
  29695. var minorTickModel = this.model.getModel('minorTick');
  29696. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  29697. if (!(splitNumber > 0 && splitNumber < 100)) {
  29698. splitNumber = 5;
  29699. }
  29700. var minorTicks = this.scale.getMinorTicks(splitNumber);
  29701. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  29702. return map(minorTicksGroup, function (minorTick) {
  29703. return {
  29704. coord: this.dataToCoord(minorTick),
  29705. tickValue: minorTick
  29706. };
  29707. }, this);
  29708. }, this);
  29709. return minorTicksCoords;
  29710. },
  29711. /**
  29712. * @return {Array.<Object>} [{
  29713. * formattedLabel: string,
  29714. * rawLabel: axis.scale.getLabel(tickValue)
  29715. * tickValue: number
  29716. * }, ...]
  29717. */
  29718. getViewLabels: function () {
  29719. return createAxisLabels(this).labels;
  29720. },
  29721. /**
  29722. * @return {module:echarts/coord/model/Model}
  29723. */
  29724. getLabelModel: function () {
  29725. return this.model.getModel('axisLabel');
  29726. },
  29727. /**
  29728. * Notice here we only get the default tick model. For splitLine
  29729. * or splitArea, we should pass the splitLineModel or splitAreaModel
  29730. * manually when calling `getTicksCoords`.
  29731. * In GL, this method may be overrided to:
  29732. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  29733. * @return {module:echarts/coord/model/Model}
  29734. */
  29735. getTickModel: function () {
  29736. return this.model.getModel('axisTick');
  29737. },
  29738. /**
  29739. * Get width of band
  29740. * @return {number}
  29741. */
  29742. getBandWidth: function () {
  29743. var axisExtent = this._extent;
  29744. var dataExtent = this.scale.getExtent();
  29745. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  29746. len === 0 && (len = 1);
  29747. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  29748. return Math.abs(size) / len;
  29749. },
  29750. /**
  29751. * @abstract
  29752. * @return {boolean} Is horizontal
  29753. */
  29754. isHorizontal: null,
  29755. /**
  29756. * @abstract
  29757. * @return {number} Get axis rotate, by degree.
  29758. */
  29759. getRotate: null,
  29760. /**
  29761. * Only be called in category axis.
  29762. * Can be overrided, consider other axes like in 3D.
  29763. * @return {number} Auto interval for cateogry axis tick and label
  29764. */
  29765. calculateCategoryInterval: function () {
  29766. return calculateCategoryInterval(this);
  29767. }
  29768. };
  29769. function fixExtentWithBands(extent, nTick) {
  29770. var size = extent[1] - extent[0];
  29771. var len = nTick;
  29772. var margin = size / len / 2;
  29773. extent[0] += margin;
  29774. extent[1] -= margin;
  29775. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  29776. // |---1---|---2---|---3---|---4---|.
  29777. // So the displayed ticks and splitLine/splitArea should between
  29778. // each data item, otherwise cause misleading (e.g., split tow bars
  29779. // of a single data item when there are two bar series).
  29780. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  29781. // splitLine/spliteArea should layout appropriately corresponding
  29782. // to displayed labels. (So we should not use `getBandWidth` in this
  29783. // case).
  29784. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  29785. var ticksLen = ticksCoords.length;
  29786. if (!axis.onBand || alignWithLabel || !ticksLen) {
  29787. return;
  29788. }
  29789. var axisExtent = axis.getExtent();
  29790. var last;
  29791. var diffSize;
  29792. if (ticksLen === 1) {
  29793. ticksCoords[0].coord = axisExtent[0];
  29794. last = ticksCoords[1] = {
  29795. coord: axisExtent[0]
  29796. };
  29797. } else {
  29798. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  29799. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  29800. each$1(ticksCoords, function (ticksItem) {
  29801. ticksItem.coord -= shift / 2;
  29802. });
  29803. var dataExtent = axis.scale.getExtent();
  29804. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  29805. last = {
  29806. coord: ticksCoords[ticksLen - 1].coord + shift * diffSize
  29807. };
  29808. ticksCoords.push(last);
  29809. }
  29810. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  29811. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  29812. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  29813. }
  29814. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  29815. ticksCoords.unshift({
  29816. coord: axisExtent[0]
  29817. });
  29818. }
  29819. if (littleThan(axisExtent[1], last.coord)) {
  29820. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  29821. }
  29822. if (clamp && littleThan(last.coord, axisExtent[1])) {
  29823. ticksCoords.push({
  29824. coord: axisExtent[1]
  29825. });
  29826. }
  29827. function littleThan(a, b) {
  29828. // Avoid rounding error cause calculated tick coord different with extent.
  29829. // It may cause an extra unecessary tick added.
  29830. a = round$1(a);
  29831. b = round$1(b);
  29832. return inverse ? a > b : a < b;
  29833. }
  29834. }
  29835. /*
  29836. * Licensed to the Apache Software Foundation (ASF) under one
  29837. * or more contributor license agreements. See the NOTICE file
  29838. * distributed with this work for additional information
  29839. * regarding copyright ownership. The ASF licenses this file
  29840. * to you under the Apache License, Version 2.0 (the
  29841. * "License"); you may not use this file except in compliance
  29842. * with the License. You may obtain a copy of the License at
  29843. *
  29844. * http://www.apache.org/licenses/LICENSE-2.0
  29845. *
  29846. * Unless required by applicable law or agreed to in writing,
  29847. * software distributed under the License is distributed on an
  29848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29849. * KIND, either express or implied. See the License for the
  29850. * specific language governing permissions and limitations
  29851. * under the License.
  29852. */
  29853. /**
  29854. * Do not mount those modules on 'src/echarts' for better tree shaking.
  29855. */
  29856. var parseGeoJson = parseGeoJSON;
  29857. var ecUtil = {};
  29858. each$1(['map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter', 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction', 'extend', 'defaults', 'clone', 'merge'], function (name) {
  29859. ecUtil[name] = zrUtil[name];
  29860. });
  29861. var graphic$1 = {};
  29862. each$1(['extendShape', 'extendPath', 'makePath', 'makeImage', 'mergePath', 'resizePath', 'createIcon', 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText', 'getFont', 'updateProps', 'initProps', 'getTransform', 'clipPointsByRect', 'clipRectByRect', 'registerShape', 'getShapeClass', 'Group', 'Image', 'Text', 'Circle', 'Sector', 'Ring', 'Polygon', 'Polyline', 'Rect', 'Line', 'BezierCurve', 'Arc', 'IncrementalDisplayable', 'CompoundPath', 'LinearGradient', 'RadialGradient', 'BoundingRect'], function (name) {
  29863. graphic$1[name] = graphic[name];
  29864. });
  29865. /*
  29866. * Licensed to the Apache Software Foundation (ASF) under one
  29867. * or more contributor license agreements. See the NOTICE file
  29868. * distributed with this work for additional information
  29869. * regarding copyright ownership. The ASF licenses this file
  29870. * to you under the Apache License, Version 2.0 (the
  29871. * "License"); you may not use this file except in compliance
  29872. * with the License. You may obtain a copy of the License at
  29873. *
  29874. * http://www.apache.org/licenses/LICENSE-2.0
  29875. *
  29876. * Unless required by applicable law or agreed to in writing,
  29877. * software distributed under the License is distributed on an
  29878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29879. * KIND, either express or implied. See the License for the
  29880. * specific language governing permissions and limitations
  29881. * under the License.
  29882. */
  29883. /**
  29884. * Cartesian coordinate system
  29885. * @module echarts/coord/Cartesian
  29886. *
  29887. */
  29888. function dimAxisMapper(dim) {
  29889. return this._axes[dim];
  29890. }
  29891. /**
  29892. * @alias module:echarts/coord/Cartesian
  29893. * @constructor
  29894. */
  29895. var Cartesian = function (name) {
  29896. this._axes = {};
  29897. this._dimList = [];
  29898. /**
  29899. * @type {string}
  29900. */
  29901. this.name = name || '';
  29902. };
  29903. Cartesian.prototype = {
  29904. constructor: Cartesian,
  29905. type: 'cartesian',
  29906. /**
  29907. * Get axis
  29908. * @param {number|string} dim
  29909. * @return {module:echarts/coord/Cartesian~Axis}
  29910. */
  29911. getAxis: function (dim) {
  29912. return this._axes[dim];
  29913. },
  29914. /**
  29915. * Get axes list
  29916. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  29917. */
  29918. getAxes: function () {
  29919. return map(this._dimList, dimAxisMapper, this);
  29920. },
  29921. /**
  29922. * Get axes list by given scale type
  29923. */
  29924. getAxesByScale: function (scaleType) {
  29925. scaleType = scaleType.toLowerCase();
  29926. return filter(this.getAxes(), function (axis) {
  29927. return axis.scale.type === scaleType;
  29928. });
  29929. },
  29930. /**
  29931. * Add axis
  29932. * @param {module:echarts/coord/Cartesian.Axis}
  29933. */
  29934. addAxis: function (axis) {
  29935. var dim = axis.dim;
  29936. this._axes[dim] = axis;
  29937. this._dimList.push(dim);
  29938. },
  29939. /**
  29940. * Convert data to coord in nd space
  29941. * @param {Array.<number>|Object.<string, number>} val
  29942. * @return {Array.<number>|Object.<string, number>}
  29943. */
  29944. dataToCoord: function (val) {
  29945. return this._dataCoordConvert(val, 'dataToCoord');
  29946. },
  29947. /**
  29948. * Convert coord in nd space to data
  29949. * @param {Array.<number>|Object.<string, number>} val
  29950. * @return {Array.<number>|Object.<string, number>}
  29951. */
  29952. coordToData: function (val) {
  29953. return this._dataCoordConvert(val, 'coordToData');
  29954. },
  29955. _dataCoordConvert: function (input, method) {
  29956. var dimList = this._dimList;
  29957. var output = input instanceof Array ? [] : {};
  29958. for (var i = 0; i < dimList.length; i++) {
  29959. var dim = dimList[i];
  29960. var axis = this._axes[dim];
  29961. output[dim] = axis[method](input[dim]);
  29962. }
  29963. return output;
  29964. }
  29965. };
  29966. /*
  29967. * Licensed to the Apache Software Foundation (ASF) under one
  29968. * or more contributor license agreements. See the NOTICE file
  29969. * distributed with this work for additional information
  29970. * regarding copyright ownership. The ASF licenses this file
  29971. * to you under the Apache License, Version 2.0 (the
  29972. * "License"); you may not use this file except in compliance
  29973. * with the License. You may obtain a copy of the License at
  29974. *
  29975. * http://www.apache.org/licenses/LICENSE-2.0
  29976. *
  29977. * Unless required by applicable law or agreed to in writing,
  29978. * software distributed under the License is distributed on an
  29979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29980. * KIND, either express or implied. See the License for the
  29981. * specific language governing permissions and limitations
  29982. * under the License.
  29983. */
  29984. function Cartesian2D(name) {
  29985. Cartesian.call(this, name);
  29986. }
  29987. Cartesian2D.prototype = {
  29988. constructor: Cartesian2D,
  29989. type: 'cartesian2d',
  29990. /**
  29991. * @type {Array.<string>}
  29992. * @readOnly
  29993. */
  29994. dimensions: ['x', 'y'],
  29995. /**
  29996. * Base axis will be used on stacking.
  29997. *
  29998. * @return {module:echarts/coord/cartesian/Axis2D}
  29999. */
  30000. getBaseAxis: function () {
  30001. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  30002. },
  30003. /**
  30004. * If contain point
  30005. * @param {Array.<number>} point
  30006. * @return {boolean}
  30007. */
  30008. containPoint: function (point) {
  30009. var axisX = this.getAxis('x');
  30010. var axisY = this.getAxis('y');
  30011. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  30012. },
  30013. /**
  30014. * If contain data
  30015. * @param {Array.<number>} data
  30016. * @return {boolean}
  30017. */
  30018. containData: function (data) {
  30019. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  30020. },
  30021. /**
  30022. * @param {Array.<number>} data
  30023. * @param {Array.<number>} out
  30024. * @return {Array.<number>}
  30025. */
  30026. dataToPoint: function (data, reserved, out) {
  30027. var xAxis = this.getAxis('x');
  30028. var yAxis = this.getAxis('y');
  30029. out = out || [];
  30030. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  30031. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  30032. return out;
  30033. },
  30034. /**
  30035. * @param {Array.<number>} data
  30036. * @param {Array.<number>} out
  30037. * @return {Array.<number>}
  30038. */
  30039. clampData: function (data, out) {
  30040. var xScale = this.getAxis('x').scale;
  30041. var yScale = this.getAxis('y').scale;
  30042. var xAxisExtent = xScale.getExtent();
  30043. var yAxisExtent = yScale.getExtent();
  30044. var x = xScale.parse(data[0]);
  30045. var y = yScale.parse(data[1]);
  30046. out = out || [];
  30047. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  30048. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  30049. return out;
  30050. },
  30051. /**
  30052. * @param {Array.<number>} point
  30053. * @param {Array.<number>} out
  30054. * @return {Array.<number>}
  30055. */
  30056. pointToData: function (point, out) {
  30057. var xAxis = this.getAxis('x');
  30058. var yAxis = this.getAxis('y');
  30059. out = out || [];
  30060. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  30061. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  30062. return out;
  30063. },
  30064. /**
  30065. * Get other axis
  30066. * @param {module:echarts/coord/cartesian/Axis2D} axis
  30067. */
  30068. getOtherAxis: function (axis) {
  30069. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  30070. },
  30071. /**
  30072. * Get rect area of cartesian.
  30073. * Area will have a contain function to determine if a point is in the coordinate system.
  30074. * @return {BoundingRect}
  30075. */
  30076. getArea: function () {
  30077. var xExtent = this.getAxis('x').getGlobalExtent();
  30078. var yExtent = this.getAxis('y').getGlobalExtent();
  30079. var x = Math.min(xExtent[0], xExtent[1]);
  30080. var y = Math.min(yExtent[0], yExtent[1]);
  30081. var width = Math.max(xExtent[0], xExtent[1]) - x;
  30082. var height = Math.max(yExtent[0], yExtent[1]) - y;
  30083. var rect = new BoundingRect(x, y, width, height);
  30084. return rect;
  30085. }
  30086. };
  30087. inherits(Cartesian2D, Cartesian);
  30088. /*
  30089. * Licensed to the Apache Software Foundation (ASF) under one
  30090. * or more contributor license agreements. See the NOTICE file
  30091. * distributed with this work for additional information
  30092. * regarding copyright ownership. The ASF licenses this file
  30093. * to you under the Apache License, Version 2.0 (the
  30094. * "License"); you may not use this file except in compliance
  30095. * with the License. You may obtain a copy of the License at
  30096. *
  30097. * http://www.apache.org/licenses/LICENSE-2.0
  30098. *
  30099. * Unless required by applicable law or agreed to in writing,
  30100. * software distributed under the License is distributed on an
  30101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30102. * KIND, either express or implied. See the License for the
  30103. * specific language governing permissions and limitations
  30104. * under the License.
  30105. */
  30106. /**
  30107. * Extend axis 2d
  30108. * @constructor module:echarts/coord/cartesian/Axis2D
  30109. * @extends {module:echarts/coord/cartesian/Axis}
  30110. * @param {string} dim
  30111. * @param {*} scale
  30112. * @param {Array.<number>} coordExtent
  30113. * @param {string} axisType
  30114. * @param {string} position
  30115. */
  30116. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  30117. Axis.call(this, dim, scale, coordExtent);
  30118. /**
  30119. * Axis type
  30120. * - 'category'
  30121. * - 'value'
  30122. * - 'time'
  30123. * - 'log'
  30124. * @type {string}
  30125. */
  30126. this.type = axisType || 'value';
  30127. /**
  30128. * Axis position
  30129. * - 'top'
  30130. * - 'bottom'
  30131. * - 'left'
  30132. * - 'right'
  30133. */
  30134. this.position = position || 'bottom';
  30135. };
  30136. Axis2D.prototype = {
  30137. constructor: Axis2D,
  30138. /**
  30139. * Index of axis, can be used as key
  30140. */
  30141. index: 0,
  30142. /**
  30143. * Implemented in <module:echarts/coord/cartesian/Grid>.
  30144. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  30145. * If not on zero of other axis, return null/undefined.
  30146. * If no axes, return an empty array.
  30147. */
  30148. getAxesOnZeroOf: null,
  30149. /**
  30150. * Axis model
  30151. * @param {module:echarts/coord/cartesian/AxisModel}
  30152. */
  30153. model: null,
  30154. isHorizontal: function () {
  30155. var position = this.position;
  30156. return position === 'top' || position === 'bottom';
  30157. },
  30158. /**
  30159. * Each item cooresponds to this.getExtent(), which
  30160. * means globalExtent[0] may greater than globalExtent[1],
  30161. * unless `asc` is input.
  30162. *
  30163. * @param {boolean} [asc]
  30164. * @return {Array.<number>}
  30165. */
  30166. getGlobalExtent: function (asc) {
  30167. var ret = this.getExtent();
  30168. ret[0] = this.toGlobalCoord(ret[0]);
  30169. ret[1] = this.toGlobalCoord(ret[1]);
  30170. asc && ret[0] > ret[1] && ret.reverse();
  30171. return ret;
  30172. },
  30173. getOtherAxis: function () {
  30174. this.grid.getOtherAxis();
  30175. },
  30176. /**
  30177. * @override
  30178. */
  30179. pointToData: function (point, clamp) {
  30180. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  30181. },
  30182. /**
  30183. * Transform global coord to local coord,
  30184. * i.e. var localCoord = axis.toLocalCoord(80);
  30185. * designate by module:echarts/coord/cartesian/Grid.
  30186. * @type {Function}
  30187. */
  30188. toLocalCoord: null,
  30189. /**
  30190. * Transform global coord to local coord,
  30191. * i.e. var globalCoord = axis.toLocalCoord(40);
  30192. * designate by module:echarts/coord/cartesian/Grid.
  30193. * @type {Function}
  30194. */
  30195. toGlobalCoord: null
  30196. };
  30197. inherits(Axis2D, Axis);
  30198. /*
  30199. * Licensed to the Apache Software Foundation (ASF) under one
  30200. * or more contributor license agreements. See the NOTICE file
  30201. * distributed with this work for additional information
  30202. * regarding copyright ownership. The ASF licenses this file
  30203. * to you under the Apache License, Version 2.0 (the
  30204. * "License"); you may not use this file except in compliance
  30205. * with the License. You may obtain a copy of the License at
  30206. *
  30207. * http://www.apache.org/licenses/LICENSE-2.0
  30208. *
  30209. * Unless required by applicable law or agreed to in writing,
  30210. * software distributed under the License is distributed on an
  30211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30212. * KIND, either express or implied. See the License for the
  30213. * specific language governing permissions and limitations
  30214. * under the License.
  30215. */
  30216. var defaultOption = {
  30217. show: true,
  30218. zlevel: 0,
  30219. z: 0,
  30220. // Inverse the axis.
  30221. inverse: false,
  30222. // Axis name displayed.
  30223. name: '',
  30224. // 'start' | 'middle' | 'end'
  30225. nameLocation: 'end',
  30226. // By degree. By defualt auto rotate by nameLocation.
  30227. nameRotate: null,
  30228. nameTruncate: {
  30229. maxWidth: null,
  30230. ellipsis: '...',
  30231. placeholder: '.'
  30232. },
  30233. // Use global text style by default.
  30234. nameTextStyle: {},
  30235. // The gap between axisName and axisLine.
  30236. nameGap: 15,
  30237. // Default `false` to support tooltip.
  30238. silent: false,
  30239. // Default `false` to avoid legacy user event listener fail.
  30240. triggerEvent: false,
  30241. tooltip: {
  30242. show: false
  30243. },
  30244. axisPointer: {},
  30245. axisLine: {
  30246. show: true,
  30247. onZero: true,
  30248. onZeroAxisIndex: null,
  30249. lineStyle: {
  30250. color: '#333',
  30251. width: 1,
  30252. type: 'solid'
  30253. },
  30254. // The arrow at both ends the the axis.
  30255. symbol: ['none', 'none'],
  30256. symbolSize: [10, 15]
  30257. },
  30258. axisTick: {
  30259. show: true,
  30260. // Whether axisTick is inside the grid or outside the grid.
  30261. inside: false,
  30262. // The length of axisTick.
  30263. length: 5,
  30264. lineStyle: {
  30265. width: 1
  30266. }
  30267. },
  30268. axisLabel: {
  30269. show: true,
  30270. // Whether axisLabel is inside the grid or outside the grid.
  30271. inside: false,
  30272. rotate: 0,
  30273. // true | false | null/undefined (auto)
  30274. showMinLabel: null,
  30275. // true | false | null/undefined (auto)
  30276. showMaxLabel: null,
  30277. margin: 8,
  30278. // formatter: null,
  30279. fontSize: 12
  30280. },
  30281. splitLine: {
  30282. show: true,
  30283. lineStyle: {
  30284. color: ['#ccc'],
  30285. width: 1,
  30286. type: 'solid'
  30287. }
  30288. },
  30289. splitArea: {
  30290. show: false,
  30291. areaStyle: {
  30292. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  30293. }
  30294. }
  30295. };
  30296. var axisDefault = {};
  30297. axisDefault.categoryAxis = merge({
  30298. // The gap at both ends of the axis. For categoryAxis, boolean.
  30299. boundaryGap: true,
  30300. // Set false to faster category collection.
  30301. // Only usefull in the case like: category is
  30302. // ['2012-01-01', '2012-01-02', ...], where the input
  30303. // data has been ensured not duplicate and is large data.
  30304. // null means "auto":
  30305. // if axis.data provided, do not deduplication,
  30306. // else do deduplication.
  30307. deduplication: null,
  30308. // splitArea: {
  30309. // show: false
  30310. // },
  30311. splitLine: {
  30312. show: false
  30313. },
  30314. axisTick: {
  30315. // If tick is align with label when boundaryGap is true
  30316. alignWithLabel: false,
  30317. interval: 'auto'
  30318. },
  30319. axisLabel: {
  30320. interval: 'auto'
  30321. }
  30322. }, defaultOption);
  30323. axisDefault.valueAxis = merge({
  30324. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  30325. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  30326. boundaryGap: [0, 0],
  30327. // TODO
  30328. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  30329. // Min value of the axis. can be:
  30330. // + a number
  30331. // + 'dataMin': use the min value in data.
  30332. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  30333. // min: null,
  30334. // Max value of the axis. can be:
  30335. // + a number
  30336. // + 'dataMax': use the max value in data.
  30337. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  30338. // max: null,
  30339. // Readonly prop, specifies start value of the range when using data zoom.
  30340. // rangeStart: null
  30341. // Readonly prop, specifies end value of the range when using data zoom.
  30342. // rangeEnd: null
  30343. // Optional value can be:
  30344. // + `false`: always include value 0.
  30345. // + `true`: the extent do not consider value 0.
  30346. // scale: false,
  30347. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  30348. splitNumber: 5,
  30349. // Interval specifies the span of the ticks is mandatorily.
  30350. // interval: null
  30351. // Specify min interval when auto calculate tick interval.
  30352. // minInterval: null
  30353. // Specify max interval when auto calculate tick interval.
  30354. // maxInterval: null
  30355. minorTick: {
  30356. // Minor tick, not available for cateogry axis.
  30357. show: false,
  30358. // Split number of minor ticks. The value should be in range of (0, 100)
  30359. splitNumber: 5,
  30360. // Lenght of minor tick
  30361. length: 3,
  30362. // Same inside with axisTick
  30363. // Line style
  30364. lineStyle: {// Default to be same with axisTick
  30365. }
  30366. },
  30367. minorSplitLine: {
  30368. show: false,
  30369. lineStyle: {
  30370. color: '#eee',
  30371. width: 1
  30372. }
  30373. }
  30374. }, defaultOption);
  30375. axisDefault.timeAxis = defaults({
  30376. scale: true,
  30377. min: 'dataMin',
  30378. max: 'dataMax'
  30379. }, axisDefault.valueAxis);
  30380. axisDefault.logAxis = defaults({
  30381. scale: true,
  30382. logBase: 10
  30383. }, axisDefault.valueAxis);
  30384. /*
  30385. * Licensed to the Apache Software Foundation (ASF) under one
  30386. * or more contributor license agreements. See the NOTICE file
  30387. * distributed with this work for additional information
  30388. * regarding copyright ownership. The ASF licenses this file
  30389. * to you under the Apache License, Version 2.0 (the
  30390. * "License"); you may not use this file except in compliance
  30391. * with the License. You may obtain a copy of the License at
  30392. *
  30393. * http://www.apache.org/licenses/LICENSE-2.0
  30394. *
  30395. * Unless required by applicable law or agreed to in writing,
  30396. * software distributed under the License is distributed on an
  30397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30398. * KIND, either express or implied. See the License for the
  30399. * specific language governing permissions and limitations
  30400. * under the License.
  30401. */
  30402. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  30403. /**
  30404. * Generate sub axis model class
  30405. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  30406. * @param {module:echarts/model/Component} BaseAxisModelClass
  30407. * @param {Function} axisTypeDefaulter
  30408. * @param {Object} [extraDefaultOption]
  30409. */
  30410. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  30411. each$1(AXIS_TYPES, function (axisType) {
  30412. BaseAxisModelClass.extend({
  30413. /**
  30414. * @readOnly
  30415. */
  30416. type: axisName + 'Axis.' + axisType,
  30417. mergeDefaultAndTheme: function (option, ecModel) {
  30418. var layoutMode = this.layoutMode;
  30419. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  30420. var themeModel = ecModel.getTheme();
  30421. merge(option, themeModel.get(axisType + 'Axis'));
  30422. merge(option, this.getDefaultOption());
  30423. option.type = axisTypeDefaulter(axisName, option);
  30424. if (layoutMode) {
  30425. mergeLayoutParam(option, inputPositionParams, layoutMode);
  30426. }
  30427. },
  30428. /**
  30429. * @override
  30430. */
  30431. optionUpdated: function () {
  30432. var thisOption = this.option;
  30433. if (thisOption.type === 'category') {
  30434. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  30435. }
  30436. },
  30437. /**
  30438. * Should not be called before all of 'getInitailData' finished.
  30439. * Because categories are collected during initializing data.
  30440. */
  30441. getCategories: function (rawData) {
  30442. var option = this.option; // FIXME
  30443. // warning if called before all of 'getInitailData' finished.
  30444. if (option.type === 'category') {
  30445. if (rawData) {
  30446. return option.data;
  30447. }
  30448. return this.__ordinalMeta.categories;
  30449. }
  30450. },
  30451. getOrdinalMeta: function () {
  30452. return this.__ordinalMeta;
  30453. },
  30454. defaultOption: mergeAll([{}, axisDefault[axisType + 'Axis'], extraDefaultOption], true)
  30455. });
  30456. });
  30457. ComponentModel.registerSubTypeDefaulter(axisName + 'Axis', curry(axisTypeDefaulter, axisName));
  30458. };
  30459. /*
  30460. * Licensed to the Apache Software Foundation (ASF) under one
  30461. * or more contributor license agreements. See the NOTICE file
  30462. * distributed with this work for additional information
  30463. * regarding copyright ownership. The ASF licenses this file
  30464. * to you under the Apache License, Version 2.0 (the
  30465. * "License"); you may not use this file except in compliance
  30466. * with the License. You may obtain a copy of the License at
  30467. *
  30468. * http://www.apache.org/licenses/LICENSE-2.0
  30469. *
  30470. * Unless required by applicable law or agreed to in writing,
  30471. * software distributed under the License is distributed on an
  30472. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30473. * KIND, either express or implied. See the License for the
  30474. * specific language governing permissions and limitations
  30475. * under the License.
  30476. */
  30477. var AxisModel = ComponentModel.extend({
  30478. type: 'cartesian2dAxis',
  30479. /**
  30480. * @type {module:echarts/coord/cartesian/Axis2D}
  30481. */
  30482. axis: null,
  30483. /**
  30484. * @override
  30485. */
  30486. init: function () {
  30487. AxisModel.superApply(this, 'init', arguments);
  30488. this.resetRange();
  30489. },
  30490. /**
  30491. * @override
  30492. */
  30493. mergeOption: function () {
  30494. AxisModel.superApply(this, 'mergeOption', arguments);
  30495. this.resetRange();
  30496. },
  30497. /**
  30498. * @override
  30499. */
  30500. restoreData: function () {
  30501. AxisModel.superApply(this, 'restoreData', arguments);
  30502. this.resetRange();
  30503. },
  30504. /**
  30505. * @override
  30506. * @return {module:echarts/model/Component}
  30507. */
  30508. getCoordSysModel: function () {
  30509. return this.ecModel.queryComponents({
  30510. mainType: 'grid',
  30511. index: this.option.gridIndex,
  30512. id: this.option.gridId
  30513. })[0];
  30514. }
  30515. });
  30516. function getAxisType(axisDim, option) {
  30517. // Default axis with data is category axis
  30518. return option.type || (option.data ? 'category' : 'value');
  30519. }
  30520. merge(AxisModel.prototype, axisModelCommonMixin);
  30521. var extraOption = {
  30522. // gridIndex: 0,
  30523. // gridId: '',
  30524. // Offset is for multiple axis on the same position
  30525. offset: 0
  30526. };
  30527. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  30528. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  30529. /*
  30530. * Licensed to the Apache Software Foundation (ASF) under one
  30531. * or more contributor license agreements. See the NOTICE file
  30532. * distributed with this work for additional information
  30533. * regarding copyright ownership. The ASF licenses this file
  30534. * to you under the Apache License, Version 2.0 (the
  30535. * "License"); you may not use this file except in compliance
  30536. * with the License. You may obtain a copy of the License at
  30537. *
  30538. * http://www.apache.org/licenses/LICENSE-2.0
  30539. *
  30540. * Unless required by applicable law or agreed to in writing,
  30541. * software distributed under the License is distributed on an
  30542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30543. * KIND, either express or implied. See the License for the
  30544. * specific language governing permissions and limitations
  30545. * under the License.
  30546. */
  30547. // Grid 是在有直角坐标系的时候必须要存在的
  30548. // 所以这里也要被 Cartesian2D 依赖
  30549. ComponentModel.extend({
  30550. type: 'grid',
  30551. dependencies: ['xAxis', 'yAxis'],
  30552. layoutMode: 'box',
  30553. /**
  30554. * @type {module:echarts/coord/cartesian/Grid}
  30555. */
  30556. coordinateSystem: null,
  30557. defaultOption: {
  30558. show: false,
  30559. zlevel: 0,
  30560. z: 0,
  30561. left: '10%',
  30562. top: 60,
  30563. right: '10%',
  30564. bottom: 60,
  30565. // If grid size contain label
  30566. containLabel: false,
  30567. // width: {totalWidth} - left - right,
  30568. // height: {totalHeight} - top - bottom,
  30569. backgroundColor: 'rgba(0,0,0,0)',
  30570. borderWidth: 1,
  30571. borderColor: '#ccc'
  30572. }
  30573. });
  30574. /*
  30575. * Licensed to the Apache Software Foundation (ASF) under one
  30576. * or more contributor license agreements. See the NOTICE file
  30577. * distributed with this work for additional information
  30578. * regarding copyright ownership. The ASF licenses this file
  30579. * to you under the Apache License, Version 2.0 (the
  30580. * "License"); you may not use this file except in compliance
  30581. * with the License. You may obtain a copy of the License at
  30582. *
  30583. * http://www.apache.org/licenses/LICENSE-2.0
  30584. *
  30585. * Unless required by applicable law or agreed to in writing,
  30586. * software distributed under the License is distributed on an
  30587. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30588. * KIND, either express or implied. See the License for the
  30589. * specific language governing permissions and limitations
  30590. * under the License.
  30591. */
  30592. /**
  30593. * Grid is a region which contains at most 4 cartesian systems
  30594. *
  30595. * TODO Default cartesian
  30596. */
  30597. /**
  30598. * Check if the axis is used in the specified grid
  30599. * @inner
  30600. */
  30601. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  30602. return axisModel.getCoordSysModel() === gridModel;
  30603. }
  30604. function Grid(gridModel, ecModel, api) {
  30605. /**
  30606. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  30607. * @private
  30608. */
  30609. this._coordsMap = {};
  30610. /**
  30611. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  30612. * @private
  30613. */
  30614. this._coordsList = [];
  30615. /**
  30616. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  30617. * @private
  30618. */
  30619. this._axesMap = {};
  30620. /**
  30621. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  30622. * @private
  30623. */
  30624. this._axesList = [];
  30625. this._initCartesian(gridModel, ecModel, api);
  30626. this.model = gridModel;
  30627. }
  30628. var gridProto = Grid.prototype;
  30629. gridProto.type = 'grid';
  30630. gridProto.axisPointerEnabled = true;
  30631. gridProto.getRect = function () {
  30632. return this._rect;
  30633. };
  30634. gridProto.update = function (ecModel, api) {
  30635. var axesMap = this._axesMap;
  30636. this._updateScale(ecModel, this.model);
  30637. each$1(axesMap.x, function (xAxis) {
  30638. niceScaleExtent(xAxis.scale, xAxis.model);
  30639. });
  30640. each$1(axesMap.y, function (yAxis) {
  30641. niceScaleExtent(yAxis.scale, yAxis.model);
  30642. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  30643. var onZeroRecords = {};
  30644. each$1(axesMap.x, function (xAxis) {
  30645. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  30646. });
  30647. each$1(axesMap.y, function (yAxis) {
  30648. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  30649. }); // Resize again if containLabel is enabled
  30650. // FIXME It may cause getting wrong grid size in data processing stage
  30651. this.resize(this.model, api);
  30652. };
  30653. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  30654. axis.getAxesOnZeroOf = function () {
  30655. // TODO: onZero of multiple axes.
  30656. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  30657. }; // onZero can not be enabled in these two situations:
  30658. // 1. When any other axis is a category axis.
  30659. // 2. When no axis is cross 0 point.
  30660. var otherAxes = axesMap[otherAxisDim];
  30661. var otherAxisOnZeroOf;
  30662. var axisModel = axis.model;
  30663. var onZero = axisModel.get('axisLine.onZero');
  30664. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30665. if (!onZero) {
  30666. return;
  30667. } // If target axis is specified.
  30668. if (onZeroAxisIndex != null) {
  30669. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  30670. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  30671. }
  30672. } else {
  30673. // Find the first available other axis.
  30674. for (var idx in otherAxes) {
  30675. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  30676. // if both onZero, the two Y axes overlap.
  30677. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  30678. otherAxisOnZeroOf = otherAxes[idx];
  30679. break;
  30680. }
  30681. }
  30682. }
  30683. if (otherAxisOnZeroOf) {
  30684. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  30685. }
  30686. function getOnZeroRecordKey(axis) {
  30687. return axis.dim + '_' + axis.index;
  30688. }
  30689. }
  30690. function canOnZeroToAxis(axis) {
  30691. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  30692. }
  30693. /**
  30694. * Resize the grid
  30695. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30696. * @param {module:echarts/ExtensionAPI} api
  30697. */
  30698. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  30699. var gridRect = getLayoutRect(gridModel.getBoxLayoutParams(), {
  30700. width: api.getWidth(),
  30701. height: api.getHeight()
  30702. });
  30703. this._rect = gridRect;
  30704. var axesList = this._axesList;
  30705. adjustAxes(); // Minus label size
  30706. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  30707. each$1(axesList, function (axis) {
  30708. if (!axis.model.get('axisLabel.inside')) {
  30709. var labelUnionRect = estimateLabelUnionRect(axis);
  30710. if (labelUnionRect) {
  30711. var dim = axis.isHorizontal() ? 'height' : 'width';
  30712. var margin = axis.model.get('axisLabel.margin');
  30713. gridRect[dim] -= labelUnionRect[dim] + margin;
  30714. if (axis.position === 'top') {
  30715. gridRect.y += labelUnionRect.height + margin;
  30716. } else if (axis.position === 'left') {
  30717. gridRect.x += labelUnionRect.width + margin;
  30718. }
  30719. }
  30720. }
  30721. });
  30722. adjustAxes();
  30723. }
  30724. function adjustAxes() {
  30725. each$1(axesList, function (axis) {
  30726. var isHorizontal = axis.isHorizontal();
  30727. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  30728. var idx = axis.inverse ? 1 : 0;
  30729. axis.setExtent(extent[idx], extent[1 - idx]);
  30730. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  30731. });
  30732. }
  30733. };
  30734. /**
  30735. * @param {string} axisType
  30736. * @param {number} [axisIndex]
  30737. */
  30738. gridProto.getAxis = function (axisType, axisIndex) {
  30739. var axesMapOnDim = this._axesMap[axisType];
  30740. if (axesMapOnDim != null) {
  30741. if (axisIndex == null) {
  30742. // Find first axis
  30743. for (var name in axesMapOnDim) {
  30744. if (axesMapOnDim.hasOwnProperty(name)) {
  30745. return axesMapOnDim[name];
  30746. }
  30747. }
  30748. }
  30749. return axesMapOnDim[axisIndex];
  30750. }
  30751. };
  30752. /**
  30753. * @return {Array.<module:echarts/coord/Axis>}
  30754. */
  30755. gridProto.getAxes = function () {
  30756. return this._axesList.slice();
  30757. };
  30758. /**
  30759. * Usage:
  30760. * grid.getCartesian(xAxisIndex, yAxisIndex);
  30761. * grid.getCartesian(xAxisIndex);
  30762. * grid.getCartesian(null, yAxisIndex);
  30763. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  30764. *
  30765. * @param {number|Object} [xAxisIndex]
  30766. * @param {number} [yAxisIndex]
  30767. */
  30768. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  30769. if (xAxisIndex != null && yAxisIndex != null) {
  30770. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30771. return this._coordsMap[key];
  30772. }
  30773. if (isObject$1(xAxisIndex)) {
  30774. yAxisIndex = xAxisIndex.yAxisIndex;
  30775. xAxisIndex = xAxisIndex.xAxisIndex;
  30776. } // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  30777. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  30778. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  30779. return coordList[i];
  30780. }
  30781. }
  30782. };
  30783. gridProto.getCartesians = function () {
  30784. return this._coordsList.slice();
  30785. };
  30786. /**
  30787. * @implements
  30788. * see {module:echarts/CoodinateSystem}
  30789. */
  30790. gridProto.convertToPixel = function (ecModel, finder, value) {
  30791. var target = this._findConvertTarget(ecModel, finder);
  30792. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  30793. };
  30794. /**
  30795. * @implements
  30796. * see {module:echarts/CoodinateSystem}
  30797. */
  30798. gridProto.convertFromPixel = function (ecModel, finder, value) {
  30799. var target = this._findConvertTarget(ecModel, finder);
  30800. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  30801. };
  30802. /**
  30803. * @inner
  30804. */
  30805. gridProto._findConvertTarget = function (ecModel, finder) {
  30806. var seriesModel = finder.seriesModel;
  30807. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis')[0];
  30808. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis')[0];
  30809. var gridModel = finder.gridModel;
  30810. var coordsList = this._coordsList;
  30811. var cartesian;
  30812. var axis;
  30813. if (seriesModel) {
  30814. cartesian = seriesModel.coordinateSystem;
  30815. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  30816. } else if (xAxisModel && yAxisModel) {
  30817. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  30818. } else if (xAxisModel) {
  30819. axis = this.getAxis('x', xAxisModel.componentIndex);
  30820. } else if (yAxisModel) {
  30821. axis = this.getAxis('y', yAxisModel.componentIndex);
  30822. } // Lowest priority.
  30823. else if (gridModel) {
  30824. var grid = gridModel.coordinateSystem;
  30825. if (grid === this) {
  30826. cartesian = this._coordsList[0];
  30827. }
  30828. }
  30829. return {
  30830. cartesian: cartesian,
  30831. axis: axis
  30832. };
  30833. };
  30834. /**
  30835. * @implements
  30836. * see {module:echarts/CoodinateSystem}
  30837. */
  30838. gridProto.containPoint = function (point) {
  30839. var coord = this._coordsList[0];
  30840. if (coord) {
  30841. return coord.containPoint(point);
  30842. }
  30843. };
  30844. /**
  30845. * Initialize cartesian coordinate systems
  30846. * @private
  30847. */
  30848. gridProto._initCartesian = function (gridModel, ecModel, api) {
  30849. var axisPositionUsed = {
  30850. left: false,
  30851. right: false,
  30852. top: false,
  30853. bottom: false
  30854. };
  30855. var axesMap = {
  30856. x: {},
  30857. y: {}
  30858. };
  30859. var axesCount = {
  30860. x: 0,
  30861. y: 0
  30862. }; /// Create axis
  30863. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  30864. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  30865. if (!axesCount.x || !axesCount.y) {
  30866. // Roll back when there no either x or y axis
  30867. this._axesMap = {};
  30868. this._axesList = [];
  30869. return;
  30870. }
  30871. this._axesMap = axesMap; /// Create cartesian2d
  30872. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  30873. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  30874. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30875. var cartesian = new Cartesian2D(key);
  30876. cartesian.grid = this;
  30877. cartesian.model = gridModel;
  30878. this._coordsMap[key] = cartesian;
  30879. this._coordsList.push(cartesian);
  30880. cartesian.addAxis(xAxis);
  30881. cartesian.addAxis(yAxis);
  30882. }, this);
  30883. }, this);
  30884. function createAxisCreator(axisType) {
  30885. return function (axisModel, idx) {
  30886. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  30887. return;
  30888. }
  30889. var axisPosition = axisModel.get('position');
  30890. if (axisType === 'x') {
  30891. // Fix position
  30892. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  30893. // Default bottom of X
  30894. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  30895. }
  30896. } else {
  30897. // Fix position
  30898. if (axisPosition !== 'left' && axisPosition !== 'right') {
  30899. // Default left of Y
  30900. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  30901. }
  30902. }
  30903. axisPositionUsed[axisPosition] = true;
  30904. var axis = new Axis2D(axisType, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  30905. var isCategory = axis.type === 'category';
  30906. axis.onBand = isCategory && axisModel.get('boundaryGap');
  30907. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  30908. axisModel.axis = axis; // Inject axisModel into axis
  30909. axis.model = axisModel; // Inject grid info axis
  30910. axis.grid = this; // Index of axis, can be used as key
  30911. axis.index = idx;
  30912. this._axesList.push(axis);
  30913. axesMap[axisType][idx] = axis;
  30914. axesCount[axisType]++;
  30915. };
  30916. }
  30917. };
  30918. /**
  30919. * Update cartesian properties from series
  30920. * @param {module:echarts/model/Option} option
  30921. * @private
  30922. */
  30923. gridProto._updateScale = function (ecModel, gridModel) {
  30924. // Reset scale
  30925. each$1(this._axesList, function (axis) {
  30926. axis.scale.setExtent(Infinity, -Infinity);
  30927. });
  30928. ecModel.eachSeries(function (seriesModel) {
  30929. if (isCartesian2D(seriesModel)) {
  30930. var axesModels = findAxesModels(seriesModel, ecModel);
  30931. var xAxisModel = axesModels[0];
  30932. var yAxisModel = axesModels[1];
  30933. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)) {
  30934. return;
  30935. }
  30936. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  30937. var data = seriesModel.getData();
  30938. var xAxis = cartesian.getAxis('x');
  30939. var yAxis = cartesian.getAxis('y');
  30940. if (data.type === 'list') {
  30941. unionExtent(data, xAxis, seriesModel);
  30942. unionExtent(data, yAxis, seriesModel);
  30943. }
  30944. }
  30945. }, this);
  30946. function unionExtent(data, axis, seriesModel) {
  30947. each$1(data.mapDimension(axis.dim, true), function (dim) {
  30948. axis.scale.unionExtentFromData( // For example, the extent of the orginal dimension
  30949. // is [0.1, 0.5], the extent of the `stackResultDimension`
  30950. // is [7, 9], the final extent should not include [0.1, 0.5].
  30951. data, getStackedDimension(data, dim));
  30952. });
  30953. }
  30954. };
  30955. /**
  30956. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  30957. * @return {Object} {baseAxes: [], otherAxes: []}
  30958. */
  30959. gridProto.getTooltipAxes = function (dim) {
  30960. var baseAxes = [];
  30961. var otherAxes = [];
  30962. each$1(this.getCartesians(), function (cartesian) {
  30963. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  30964. var otherAxis = cartesian.getOtherAxis(baseAxis);
  30965. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  30966. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  30967. });
  30968. return {
  30969. baseAxes: baseAxes,
  30970. otherAxes: otherAxes
  30971. };
  30972. };
  30973. /**
  30974. * @inner
  30975. */
  30976. function updateAxisTransform(axis, coordBase) {
  30977. var axisExtent = axis.getExtent();
  30978. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  30979. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  30980. return coord + coordBase;
  30981. } : function (coord) {
  30982. return axisExtentSum - coord + coordBase;
  30983. };
  30984. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  30985. return coord - coordBase;
  30986. } : function (coord) {
  30987. return axisExtentSum - coord + coordBase;
  30988. };
  30989. }
  30990. var axesTypes = ['xAxis', 'yAxis'];
  30991. /**
  30992. * @inner
  30993. */
  30994. function findAxesModels(seriesModel, ecModel) {
  30995. return map(axesTypes, function (axisType) {
  30996. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  30997. return axisModel;
  30998. });
  30999. }
  31000. /**
  31001. * @inner
  31002. */
  31003. function isCartesian2D(seriesModel) {
  31004. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  31005. }
  31006. Grid.create = function (ecModel, api) {
  31007. var grids = [];
  31008. ecModel.eachComponent('grid', function (gridModel, idx) {
  31009. var grid = new Grid(gridModel, ecModel, api);
  31010. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  31011. // should be performed in create stage.
  31012. grid.resize(gridModel, api, true);
  31013. gridModel.coordinateSystem = grid;
  31014. grids.push(grid);
  31015. }); // Inject the coordinateSystems into seriesModel
  31016. ecModel.eachSeries(function (seriesModel) {
  31017. if (!isCartesian2D(seriesModel)) {
  31018. return;
  31019. }
  31020. var axesModels = findAxesModels(seriesModel, ecModel);
  31021. var xAxisModel = axesModels[0];
  31022. var yAxisModel = axesModels[1];
  31023. var gridModel = xAxisModel.getCoordSysModel();
  31024. var grid = gridModel.coordinateSystem;
  31025. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  31026. });
  31027. return grids;
  31028. }; // For deciding which dimensions to use when creating list data
  31029. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  31030. CoordinateSystemManager.register('cartesian2d', Grid);
  31031. /*
  31032. * Licensed to the Apache Software Foundation (ASF) under one
  31033. * or more contributor license agreements. See the NOTICE file
  31034. * distributed with this work for additional information
  31035. * regarding copyright ownership. The ASF licenses this file
  31036. * to you under the Apache License, Version 2.0 (the
  31037. * "License"); you may not use this file except in compliance
  31038. * with the License. You may obtain a copy of the License at
  31039. *
  31040. * http://www.apache.org/licenses/LICENSE-2.0
  31041. *
  31042. * Unless required by applicable law or agreed to in writing,
  31043. * software distributed under the License is distributed on an
  31044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31045. * KIND, either express or implied. See the License for the
  31046. * specific language governing permissions and limitations
  31047. * under the License.
  31048. */
  31049. var BaseBarSeries = SeriesModel.extend({
  31050. type: 'series.__base_bar__',
  31051. getInitialData: function (option, ecModel) {
  31052. return createListFromArray(this.getSource(), this, {
  31053. useEncodeDefaulter: true
  31054. });
  31055. },
  31056. getMarkerPosition: function (value) {
  31057. var coordSys = this.coordinateSystem;
  31058. if (coordSys) {
  31059. // PENDING if clamp ?
  31060. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31061. var data = this.getData();
  31062. var offset = data.getLayout('offset');
  31063. var size = data.getLayout('size');
  31064. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31065. pt[offsetIndex] += offset + size / 2;
  31066. return pt;
  31067. }
  31068. return [NaN, NaN];
  31069. },
  31070. defaultOption: {
  31071. zlevel: 0,
  31072. // 一级层叠
  31073. z: 2,
  31074. // 二级层叠
  31075. coordinateSystem: 'cartesian2d',
  31076. legendHoverLink: true,
  31077. // stack: null
  31078. // Cartesian coordinate system
  31079. // xAxisIndex: 0,
  31080. // yAxisIndex: 0,
  31081. // 最小高度改为0
  31082. barMinHeight: 0,
  31083. // 最小角度为0,仅对极坐标系下的柱状图有效
  31084. barMinAngle: 0,
  31085. // cursor: null,
  31086. large: false,
  31087. largeThreshold: 400,
  31088. progressive: 3e3,
  31089. progressiveChunkMode: 'mod',
  31090. // barMaxWidth: null,
  31091. // In cartesian, the default value is 1. Otherwise null.
  31092. // barMinWidth: null,
  31093. // 默认自适应
  31094. // barWidth: null,
  31095. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31096. // barGap: '30%',
  31097. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31098. // barCategoryGap: '20%',
  31099. // label: {
  31100. // show: false
  31101. // },
  31102. itemStyle: {},
  31103. emphasis: {}
  31104. }
  31105. });
  31106. /*
  31107. * Licensed to the Apache Software Foundation (ASF) under one
  31108. * or more contributor license agreements. See the NOTICE file
  31109. * distributed with this work for additional information
  31110. * regarding copyright ownership. The ASF licenses this file
  31111. * to you under the Apache License, Version 2.0 (the
  31112. * "License"); you may not use this file except in compliance
  31113. * with the License. You may obtain a copy of the License at
  31114. *
  31115. * http://www.apache.org/licenses/LICENSE-2.0
  31116. *
  31117. * Unless required by applicable law or agreed to in writing,
  31118. * software distributed under the License is distributed on an
  31119. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31120. * KIND, either express or implied. See the License for the
  31121. * specific language governing permissions and limitations
  31122. * under the License.
  31123. */
  31124. BaseBarSeries.extend({
  31125. type: 'series.bar',
  31126. dependencies: ['grid', 'polar'],
  31127. brushSelector: 'rect',
  31128. /**
  31129. * @override
  31130. */
  31131. getProgressive: function () {
  31132. // Do not support progressive in normal mode.
  31133. return this.get('large') ? this.get('progressive') : false;
  31134. },
  31135. /**
  31136. * @override
  31137. */
  31138. getProgressiveThreshold: function () {
  31139. // Do not support progressive in normal mode.
  31140. var progressiveThreshold = this.get('progressiveThreshold');
  31141. var largeThreshold = this.get('largeThreshold');
  31142. if (largeThreshold > progressiveThreshold) {
  31143. progressiveThreshold = largeThreshold;
  31144. }
  31145. return progressiveThreshold;
  31146. },
  31147. defaultOption: {
  31148. // If clipped
  31149. // Only available on cartesian2d
  31150. clip: true,
  31151. // If use caps on two sides of bars
  31152. // Only available on tangential polar bar
  31153. roundCap: false,
  31154. showBackground: false,
  31155. backgroundStyle: {
  31156. color: 'rgba(180, 180, 180, 0.2)',
  31157. borderColor: null,
  31158. borderWidth: 0,
  31159. borderType: 'solid',
  31160. borderRadius: 0,
  31161. shadowBlur: 0,
  31162. shadowColor: null,
  31163. shadowOffsetX: 0,
  31164. shadowOffsetY: 0,
  31165. opacity: 1
  31166. }
  31167. }
  31168. });
  31169. /*
  31170. * Licensed to the Apache Software Foundation (ASF) under one
  31171. * or more contributor license agreements. See the NOTICE file
  31172. * distributed with this work for additional information
  31173. * regarding copyright ownership. The ASF licenses this file
  31174. * to you under the Apache License, Version 2.0 (the
  31175. * "License"); you may not use this file except in compliance
  31176. * with the License. You may obtain a copy of the License at
  31177. *
  31178. * http://www.apache.org/licenses/LICENSE-2.0
  31179. *
  31180. * Unless required by applicable law or agreed to in writing,
  31181. * software distributed under the License is distributed on an
  31182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31183. * KIND, either express or implied. See the License for the
  31184. * specific language governing permissions and limitations
  31185. * under the License.
  31186. */
  31187. /**
  31188. * @param {module:echarts/data/List} data
  31189. * @param {number} dataIndex
  31190. * @return {string} label string. Not null/undefined
  31191. */
  31192. function getDefaultLabel(data, dataIndex) {
  31193. var labelDims = data.mapDimension('defaultedLabel', true);
  31194. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  31195. if (len === 1) {
  31196. return retrieveRawValue(data, dataIndex, labelDims[0]);
  31197. } else if (len) {
  31198. var vals = [];
  31199. for (var i = 0; i < labelDims.length; i++) {
  31200. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  31201. vals.push(val);
  31202. }
  31203. return vals.join(' ');
  31204. }
  31205. }
  31206. /*
  31207. * Licensed to the Apache Software Foundation (ASF) under one
  31208. * or more contributor license agreements. See the NOTICE file
  31209. * distributed with this work for additional information
  31210. * regarding copyright ownership. The ASF licenses this file
  31211. * to you under the Apache License, Version 2.0 (the
  31212. * "License"); you may not use this file except in compliance
  31213. * with the License. You may obtain a copy of the License at
  31214. *
  31215. * http://www.apache.org/licenses/LICENSE-2.0
  31216. *
  31217. * Unless required by applicable law or agreed to in writing,
  31218. * software distributed under the License is distributed on an
  31219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31220. * KIND, either express or implied. See the License for the
  31221. * specific language governing permissions and limitations
  31222. * under the License.
  31223. */
  31224. function setLabel(normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside) {
  31225. var labelModel = itemModel.getModel('label');
  31226. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31227. setLabelStyle(normalStyle, hoverStyle, labelModel, hoverLabelModel, {
  31228. labelFetcher: seriesModel,
  31229. labelDataIndex: dataIndex,
  31230. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31231. isRectText: true,
  31232. autoColor: color
  31233. });
  31234. fixPosition(normalStyle);
  31235. fixPosition(hoverStyle);
  31236. }
  31237. function fixPosition(style, labelPositionOutside) {
  31238. if (style.textPosition === 'outside') {
  31239. style.textPosition = labelPositionOutside;
  31240. }
  31241. }
  31242. /*
  31243. * Licensed to the Apache Software Foundation (ASF) under one
  31244. * or more contributor license agreements. See the NOTICE file
  31245. * distributed with this work for additional information
  31246. * regarding copyright ownership. The ASF licenses this file
  31247. * to you under the Apache License, Version 2.0 (the
  31248. * "License"); you may not use this file except in compliance
  31249. * with the License. You may obtain a copy of the License at
  31250. *
  31251. * http://www.apache.org/licenses/LICENSE-2.0
  31252. *
  31253. * Unless required by applicable law or agreed to in writing,
  31254. * software distributed under the License is distributed on an
  31255. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31256. * KIND, either express or implied. See the License for the
  31257. * specific language governing permissions and limitations
  31258. * under the License.
  31259. */
  31260. var getBarItemStyle = makeStyleMapper([['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], // Compatitable with 2
  31261. ['stroke', 'barBorderColor'], ['lineWidth', 'barBorderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor']]);
  31262. var barItemStyle = {
  31263. getBarItemStyle: function (excludes) {
  31264. var style = getBarItemStyle(this, excludes);
  31265. if (this.getBorderLineDash) {
  31266. var lineDash = this.getBorderLineDash();
  31267. lineDash && (style.lineDash = lineDash);
  31268. }
  31269. return style;
  31270. }
  31271. };
  31272. /*
  31273. * Licensed to the Apache Software Foundation (ASF) under one
  31274. * or more contributor license agreements. See the NOTICE file
  31275. * distributed with this work for additional information
  31276. * regarding copyright ownership. The ASF licenses this file
  31277. * to you under the Apache License, Version 2.0 (the
  31278. * "License"); you may not use this file except in compliance
  31279. * with the License. You may obtain a copy of the License at
  31280. *
  31281. * http://www.apache.org/licenses/LICENSE-2.0
  31282. *
  31283. * Unless required by applicable law or agreed to in writing,
  31284. * software distributed under the License is distributed on an
  31285. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31286. * KIND, either express or implied. See the License for the
  31287. * specific language governing permissions and limitations
  31288. * under the License.
  31289. */
  31290. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  31291. var rect = cartesian.getArea();
  31292. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  31293. var x = rect.x;
  31294. var y = rect.y;
  31295. var width = rect.width;
  31296. var height = rect.height;
  31297. var lineWidth = seriesModel.get('lineStyle.width') || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  31298. x -= lineWidth / 2;
  31299. y -= lineWidth / 2;
  31300. width += lineWidth;
  31301. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  31302. x = Math.floor(x);
  31303. width = Math.round(width);
  31304. var clipPath = new Rect({
  31305. shape: {
  31306. x: x,
  31307. y: y,
  31308. width: width,
  31309. height: height
  31310. }
  31311. });
  31312. if (hasAnimation) {
  31313. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  31314. initProps(clipPath, {
  31315. shape: {
  31316. width: width,
  31317. height: height
  31318. }
  31319. }, seriesModel);
  31320. }
  31321. return clipPath;
  31322. }
  31323. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  31324. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  31325. var clipPath = new Sector({
  31326. shape: {
  31327. cx: round$1(polar.cx, 1),
  31328. cy: round$1(polar.cy, 1),
  31329. r0: round$1(sectorArea.r0, 1),
  31330. r: round$1(sectorArea.r, 1),
  31331. startAngle: sectorArea.startAngle,
  31332. endAngle: sectorArea.endAngle,
  31333. clockwise: sectorArea.clockwise
  31334. }
  31335. });
  31336. if (hasAnimation) {
  31337. clipPath.shape.endAngle = sectorArea.startAngle;
  31338. initProps(clipPath, {
  31339. shape: {
  31340. endAngle: sectorArea.endAngle
  31341. }
  31342. }, seriesModel);
  31343. }
  31344. return clipPath;
  31345. }
  31346. function createClipPath(coordSys, hasAnimation, seriesModel) {
  31347. if (!coordSys) {
  31348. return null;
  31349. } else if (coordSys.type === 'polar') {
  31350. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  31351. } else if (coordSys.type === 'cartesian2d') {
  31352. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  31353. }
  31354. return null;
  31355. }
  31356. /*
  31357. * Licensed to the Apache Software Foundation (ASF) under one
  31358. * or more contributor license agreements. See the NOTICE file
  31359. * distributed with this work for additional information
  31360. * regarding copyright ownership. The ASF licenses this file
  31361. * to you under the Apache License, Version 2.0 (the
  31362. * "License"); you may not use this file except in compliance
  31363. * with the License. You may obtain a copy of the License at
  31364. *
  31365. * http://www.apache.org/licenses/LICENSE-2.0
  31366. *
  31367. * Unless required by applicable law or agreed to in writing,
  31368. * software distributed under the License is distributed on an
  31369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31370. * KIND, either express or implied. See the License for the
  31371. * specific language governing permissions and limitations
  31372. * under the License.
  31373. */
  31374. /**
  31375. * Sausage: similar to sector, but have half circle on both sides
  31376. * @public
  31377. */
  31378. var Sausage = extendShape({
  31379. type: 'sausage',
  31380. shape: {
  31381. cx: 0,
  31382. cy: 0,
  31383. r0: 0,
  31384. r: 0,
  31385. startAngle: 0,
  31386. endAngle: Math.PI * 2,
  31387. clockwise: true
  31388. },
  31389. buildPath: function (ctx, shape) {
  31390. var x = shape.cx;
  31391. var y = shape.cy;
  31392. var r0 = Math.max(shape.r0 || 0, 0);
  31393. var r = Math.max(shape.r, 0);
  31394. var dr = (r - r0) * 0.5;
  31395. var rCenter = r0 + dr;
  31396. var startAngle = shape.startAngle;
  31397. var endAngle = shape.endAngle;
  31398. var clockwise = shape.clockwise;
  31399. var unitStartX = Math.cos(startAngle);
  31400. var unitStartY = Math.sin(startAngle);
  31401. var unitEndX = Math.cos(endAngle);
  31402. var unitEndY = Math.sin(endAngle);
  31403. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  31404. if (lessThanCircle) {
  31405. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  31406. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  31407. }
  31408. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  31409. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  31410. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  31411. if (r0 !== 0) {
  31412. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  31413. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  31414. }
  31415. ctx.closePath();
  31416. }
  31417. });
  31418. /*
  31419. * Licensed to the Apache Software Foundation (ASF) under one
  31420. * or more contributor license agreements. See the NOTICE file
  31421. * distributed with this work for additional information
  31422. * regarding copyright ownership. The ASF licenses this file
  31423. * to you under the Apache License, Version 2.0 (the
  31424. * "License"); you may not use this file except in compliance
  31425. * with the License. You may obtain a copy of the License at
  31426. *
  31427. * http://www.apache.org/licenses/LICENSE-2.0
  31428. *
  31429. * Unless required by applicable law or agreed to in writing,
  31430. * software distributed under the License is distributed on an
  31431. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31432. * KIND, either express or implied. See the License for the
  31433. * specific language governing permissions and limitations
  31434. * under the License.
  31435. */
  31436. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31437. var _eventPos = [0, 0]; // FIXME
  31438. // Just for compatible with ec2.
  31439. extend(Model.prototype, barItemStyle);
  31440. function getClipArea(coord, data) {
  31441. var coordSysClipArea = coord.getArea && coord.getArea();
  31442. if (coord.type === 'cartesian2d') {
  31443. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  31444. // We should not clip this part.
  31445. // See test/bar2.html
  31446. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  31447. var expandWidth = data.getLayout('bandWidth');
  31448. if (baseAxis.isHorizontal()) {
  31449. coordSysClipArea.x -= expandWidth;
  31450. coordSysClipArea.width += expandWidth * 2;
  31451. } else {
  31452. coordSysClipArea.y -= expandWidth;
  31453. coordSysClipArea.height += expandWidth * 2;
  31454. }
  31455. }
  31456. }
  31457. return coordSysClipArea;
  31458. }
  31459. extendChartView({
  31460. type: 'bar',
  31461. render: function (seriesModel, ecModel, api) {
  31462. this._updateDrawMode(seriesModel);
  31463. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31464. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  31465. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api);
  31466. } else {}
  31467. return this.group;
  31468. },
  31469. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  31470. this._clear();
  31471. this._updateDrawMode(seriesModel);
  31472. },
  31473. incrementalRender: function (params, seriesModel, ecModel, api) {
  31474. // Do not support progressive in normal mode.
  31475. this._incrementalRenderLarge(params, seriesModel);
  31476. },
  31477. _updateDrawMode: function (seriesModel) {
  31478. var isLargeDraw = seriesModel.pipelineContext.large;
  31479. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  31480. this._isLargeDraw = isLargeDraw;
  31481. this._clear();
  31482. }
  31483. },
  31484. _renderNormal: function (seriesModel, ecModel, api) {
  31485. var group = this.group;
  31486. var data = seriesModel.getData();
  31487. var oldData = this._data;
  31488. var coord = seriesModel.coordinateSystem;
  31489. var baseAxis = coord.getBaseAxis();
  31490. var isHorizontalOrRadial;
  31491. if (coord.type === 'cartesian2d') {
  31492. isHorizontalOrRadial = baseAxis.isHorizontal();
  31493. } else if (coord.type === 'polar') {
  31494. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31495. }
  31496. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31497. var needsClip = seriesModel.get('clip', true);
  31498. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  31499. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  31500. // And don't want the label are clipped.
  31501. var roundCap = seriesModel.get('roundCap', true);
  31502. var drawBackground = seriesModel.get('showBackground', true);
  31503. var backgroundModel = seriesModel.getModel('backgroundStyle');
  31504. var barBorderRadius = backgroundModel.get('barBorderRadius') || 0;
  31505. var bgEls = [];
  31506. var oldBgEls = this._backgroundEls || [];
  31507. data.diff(oldData).add(function (dataIndex) {
  31508. var itemModel = data.getItemModel(dataIndex);
  31509. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31510. if (drawBackground) {
  31511. var bgLayout = getLayout[coord.type](data, dataIndex);
  31512. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  31513. bgEl.useStyle(backgroundModel.getBarItemStyle()); // Only cartesian2d support borderRadius.
  31514. if (coord.type === 'cartesian2d') {
  31515. bgEl.setShape('r', barBorderRadius);
  31516. }
  31517. bgEls[dataIndex] = bgEl;
  31518. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  31519. if (!data.hasValue(dataIndex)) {
  31520. return;
  31521. }
  31522. if (needsClip) {
  31523. // Clip will modify the layout params.
  31524. // And return a boolean to determine if the shape are fully clipped.
  31525. var isClipped = clip[coord.type](coordSysClipArea, layout);
  31526. if (isClipped) {
  31527. group.remove(el);
  31528. return;
  31529. }
  31530. }
  31531. var el = elementCreator[coord.type](dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap);
  31532. data.setItemGraphicEl(dataIndex, el);
  31533. group.add(el);
  31534. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  31535. }).update(function (newIndex, oldIndex) {
  31536. var itemModel = data.getItemModel(newIndex);
  31537. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31538. if (drawBackground) {
  31539. var bgEl = oldBgEls[oldIndex];
  31540. bgEl.useStyle(backgroundModel.getBarItemStyle()); // Only cartesian2d support borderRadius.
  31541. if (coord.type === 'cartesian2d') {
  31542. bgEl.setShape('r', barBorderRadius);
  31543. }
  31544. bgEls[newIndex] = bgEl;
  31545. var bgLayout = getLayout[coord.type](data, newIndex);
  31546. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  31547. updateProps(bgEl, {
  31548. shape: shape
  31549. }, animationModel, newIndex);
  31550. }
  31551. var el = oldData.getItemGraphicEl(oldIndex);
  31552. if (!data.hasValue(newIndex)) {
  31553. group.remove(el);
  31554. return;
  31555. }
  31556. if (needsClip) {
  31557. var isClipped = clip[coord.type](coordSysClipArea, layout);
  31558. if (isClipped) {
  31559. group.remove(el);
  31560. return;
  31561. }
  31562. }
  31563. if (el) {
  31564. updateProps(el, {
  31565. shape: layout
  31566. }, animationModel, newIndex);
  31567. } else {
  31568. el = elementCreator[coord.type](newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap);
  31569. }
  31570. data.setItemGraphicEl(newIndex, el); // Add back
  31571. group.add(el);
  31572. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  31573. }).remove(function (dataIndex) {
  31574. var el = oldData.getItemGraphicEl(dataIndex);
  31575. if (coord.type === 'cartesian2d') {
  31576. el && removeRect(dataIndex, animationModel, el);
  31577. } else {
  31578. el && removeSector(dataIndex, animationModel, el);
  31579. }
  31580. }).execute();
  31581. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  31582. bgGroup.removeAll();
  31583. for (var i = 0; i < bgEls.length; ++i) {
  31584. bgGroup.add(bgEls[i]);
  31585. }
  31586. group.add(bgGroup);
  31587. this._backgroundEls = bgEls;
  31588. this._data = data;
  31589. },
  31590. _renderLarge: function (seriesModel, ecModel, api) {
  31591. this._clear();
  31592. createLarge(seriesModel, this.group); // Use clipPath in large mode.
  31593. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  31594. if (clipPath) {
  31595. this.group.setClipPath(clipPath);
  31596. } else {
  31597. this.group.removeClipPath();
  31598. }
  31599. },
  31600. _incrementalRenderLarge: function (params, seriesModel) {
  31601. this._removeBackground();
  31602. createLarge(seriesModel, this.group, true);
  31603. },
  31604. dispose: noop,
  31605. remove: function (ecModel) {
  31606. this._clear(ecModel);
  31607. },
  31608. _clear: function (ecModel) {
  31609. var group = this.group;
  31610. var data = this._data;
  31611. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  31612. this._removeBackground();
  31613. this._backgroundEls = [];
  31614. data.eachItemGraphicEl(function (el) {
  31615. if (el.type === 'sector') {
  31616. removeSector(el.dataIndex, ecModel, el);
  31617. } else {
  31618. removeRect(el.dataIndex, ecModel, el);
  31619. }
  31620. });
  31621. } else {
  31622. group.removeAll();
  31623. }
  31624. this._data = null;
  31625. },
  31626. _removeBackground: function () {
  31627. this.group.remove(this._backgroundGroup);
  31628. this._backgroundGroup = null;
  31629. }
  31630. });
  31631. var mathMax$4 = Math.max;
  31632. var mathMin$4 = Math.min;
  31633. var clip = {
  31634. cartesian2d: function (coordSysBoundingRect, layout) {
  31635. var signWidth = layout.width < 0 ? -1 : 1;
  31636. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  31637. if (signWidth < 0) {
  31638. layout.x += layout.width;
  31639. layout.width = -layout.width;
  31640. }
  31641. if (signHeight < 0) {
  31642. layout.y += layout.height;
  31643. layout.height = -layout.height;
  31644. }
  31645. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  31646. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  31647. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  31648. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  31649. layout.x = x;
  31650. layout.y = y;
  31651. layout.width = x2 - x;
  31652. layout.height = y2 - y;
  31653. var clipped = layout.width < 0 || layout.height < 0; // Reverse back
  31654. if (signWidth < 0) {
  31655. layout.x += layout.width;
  31656. layout.width = -layout.width;
  31657. }
  31658. if (signHeight < 0) {
  31659. layout.y += layout.height;
  31660. layout.height = -layout.height;
  31661. }
  31662. return clipped;
  31663. },
  31664. polar: function (coordSysClipArea) {
  31665. return false;
  31666. }
  31667. };
  31668. var elementCreator = {
  31669. cartesian2d: function (dataIndex, layout, isHorizontal, animationModel, isUpdate) {
  31670. var rect = new Rect({
  31671. shape: extend({}, layout),
  31672. z2: 1
  31673. });
  31674. rect.name = 'item'; // Animation
  31675. if (animationModel) {
  31676. var rectShape = rect.shape;
  31677. var animateProperty = isHorizontal ? 'height' : 'width';
  31678. var animateTarget = {};
  31679. rectShape[animateProperty] = 0;
  31680. animateTarget[animateProperty] = layout[animateProperty];
  31681. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31682. shape: animateTarget
  31683. }, animationModel, dataIndex);
  31684. }
  31685. return rect;
  31686. },
  31687. polar: function (dataIndex, layout, isRadial, animationModel, isUpdate, roundCap) {
  31688. // Keep the same logic with bar in catesion: use end value to control
  31689. // direction. Notice that if clockwise is true (by default), the sector
  31690. // will always draw clockwisely, no matter whether endAngle is greater
  31691. // or less than startAngle.
  31692. var clockwise = layout.startAngle < layout.endAngle;
  31693. var ShapeClass = !isRadial && roundCap ? Sausage : Sector;
  31694. var sector = new ShapeClass({
  31695. shape: defaults({
  31696. clockwise: clockwise
  31697. }, layout),
  31698. z2: 1
  31699. });
  31700. sector.name = 'item'; // Animation
  31701. if (animationModel) {
  31702. var sectorShape = sector.shape;
  31703. var animateProperty = isRadial ? 'r' : 'endAngle';
  31704. var animateTarget = {};
  31705. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31706. animateTarget[animateProperty] = layout[animateProperty];
  31707. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31708. shape: animateTarget
  31709. }, animationModel, dataIndex);
  31710. }
  31711. return sector;
  31712. }
  31713. };
  31714. function removeRect(dataIndex, animationModel, el) {
  31715. // Not show text when animating
  31716. el.style.text = null;
  31717. updateProps(el, {
  31718. shape: {
  31719. width: 0
  31720. }
  31721. }, animationModel, dataIndex, function () {
  31722. el.parent && el.parent.remove(el);
  31723. });
  31724. }
  31725. function removeSector(dataIndex, animationModel, el) {
  31726. // Not show text when animating
  31727. el.style.text = null;
  31728. updateProps(el, {
  31729. shape: {
  31730. r: el.shape.r0
  31731. }
  31732. }, animationModel, dataIndex, function () {
  31733. el.parent && el.parent.remove(el);
  31734. });
  31735. }
  31736. var getLayout = {
  31737. // itemModel is only used to get borderWidth, which is not needed
  31738. // when calculating bar background layout.
  31739. cartesian2d: function (data, dataIndex, itemModel) {
  31740. var layout = data.getItemLayout(dataIndex);
  31741. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  31742. var signX = layout.width > 0 ? 1 : -1;
  31743. var signY = layout.height > 0 ? 1 : -1;
  31744. return {
  31745. x: layout.x + signX * fixedLineWidth / 2,
  31746. y: layout.y + signY * fixedLineWidth / 2,
  31747. width: layout.width - signX * fixedLineWidth,
  31748. height: layout.height - signY * fixedLineWidth
  31749. };
  31750. },
  31751. polar: function (data, dataIndex, itemModel) {
  31752. var layout = data.getItemLayout(dataIndex);
  31753. return {
  31754. cx: layout.cx,
  31755. cy: layout.cy,
  31756. r0: layout.r0,
  31757. r: layout.r,
  31758. startAngle: layout.startAngle,
  31759. endAngle: layout.endAngle
  31760. };
  31761. }
  31762. };
  31763. function isZeroOnPolar(layout) {
  31764. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  31765. }
  31766. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) {
  31767. var color = data.getItemVisual(dataIndex, 'color');
  31768. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31769. var stroke = data.getVisual('borderColor');
  31770. var itemStyleModel = itemModel.getModel('itemStyle');
  31771. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31772. if (!isPolar) {
  31773. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31774. }
  31775. el.useStyle(defaults({
  31776. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  31777. fill: isZeroOnPolar(layout) ? 'none' : color,
  31778. opacity: opacity
  31779. }, itemStyleModel.getBarItemStyle()));
  31780. var cursorStyle = itemModel.getShallow('cursor');
  31781. cursorStyle && el.attr('cursor', cursorStyle);
  31782. var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right';
  31783. if (!isPolar) {
  31784. setLabel(el.style, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside);
  31785. }
  31786. if (isZeroOnPolar(layout)) {
  31787. hoverStyle.fill = hoverStyle.stroke = 'none';
  31788. }
  31789. setHoverStyle(el, hoverStyle);
  31790. } // In case width or height are too small.
  31791. function getLineWidth(itemModel, rawLayout) {
  31792. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; // width or height may be NaN for empty data
  31793. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  31794. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  31795. return Math.min(lineWidth, width, height);
  31796. }
  31797. var LargePath = Path.extend({
  31798. type: 'largeBar',
  31799. shape: {
  31800. points: []
  31801. },
  31802. buildPath: function (ctx, shape) {
  31803. // Drawing lines is more efficient than drawing
  31804. // a whole line or drawing rects.
  31805. var points = shape.points;
  31806. var startPoint = this.__startPoint;
  31807. var baseDimIdx = this.__baseDimIdx;
  31808. for (var i = 0; i < points.length; i += 2) {
  31809. startPoint[baseDimIdx] = points[i + baseDimIdx];
  31810. ctx.moveTo(startPoint[0], startPoint[1]);
  31811. ctx.lineTo(points[i], points[i + 1]);
  31812. }
  31813. }
  31814. });
  31815. function createLarge(seriesModel, group, incremental) {
  31816. // TODO support polar
  31817. var data = seriesModel.getData();
  31818. var startPoint = [];
  31819. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  31820. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  31821. var largeDataIndices = data.getLayout('largeDataIndices');
  31822. var barWidth = data.getLayout('barWidth');
  31823. var backgroundModel = seriesModel.getModel('backgroundStyle');
  31824. var drawBackground = seriesModel.get('showBackground', true);
  31825. if (drawBackground) {
  31826. var points = data.getLayout('largeBackgroundPoints');
  31827. var backgroundStartPoint = [];
  31828. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  31829. var bgEl = new LargePath({
  31830. shape: {
  31831. points: points
  31832. },
  31833. incremental: !!incremental,
  31834. __startPoint: backgroundStartPoint,
  31835. __baseDimIdx: baseDimIdx,
  31836. __largeDataIndices: largeDataIndices,
  31837. __barWidth: barWidth,
  31838. silent: true,
  31839. z2: 0
  31840. });
  31841. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  31842. group.add(bgEl);
  31843. }
  31844. var el = new LargePath({
  31845. shape: {
  31846. points: data.getLayout('largePoints')
  31847. },
  31848. incremental: !!incremental,
  31849. __startPoint: startPoint,
  31850. __baseDimIdx: baseDimIdx,
  31851. __largeDataIndices: largeDataIndices,
  31852. __barWidth: barWidth
  31853. });
  31854. group.add(el);
  31855. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  31856. el.seriesIndex = seriesModel.seriesIndex;
  31857. if (!seriesModel.get('silent')) {
  31858. el.on('mousedown', largePathUpdateDataIndex);
  31859. el.on('mousemove', largePathUpdateDataIndex);
  31860. }
  31861. } // Use throttle to avoid frequently traverse to find dataIndex.
  31862. var largePathUpdateDataIndex = throttle(function (event) {
  31863. var largePath = this;
  31864. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  31865. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  31866. }, 30, false);
  31867. function largePathFindDataIndex(largePath, x, y) {
  31868. var baseDimIdx = largePath.__baseDimIdx;
  31869. var valueDimIdx = 1 - baseDimIdx;
  31870. var points = largePath.shape.points;
  31871. var largeDataIndices = largePath.__largeDataIndices;
  31872. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  31873. var startValueVal = largePath.__startPoint[valueDimIdx];
  31874. _eventPos[0] = x;
  31875. _eventPos[1] = y;
  31876. var pointerBaseVal = _eventPos[baseDimIdx];
  31877. var pointerValueVal = _eventPos[1 - baseDimIdx];
  31878. var baseLowerBound = pointerBaseVal - barWidthHalf;
  31879. var baseUpperBound = pointerBaseVal + barWidthHalf;
  31880. for (var i = 0, len = points.length / 2; i < len; i++) {
  31881. var ii = i * 2;
  31882. var barBaseVal = points[ii + baseDimIdx];
  31883. var barValueVal = points[ii + valueDimIdx];
  31884. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  31885. return largeDataIndices[i];
  31886. }
  31887. }
  31888. return -1;
  31889. }
  31890. function setLargeStyle(el, seriesModel, data) {
  31891. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  31892. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  31893. el.useStyle(itemStyle);
  31894. el.style.fill = null;
  31895. el.style.stroke = borderColor;
  31896. el.style.lineWidth = data.getLayout('barWidth');
  31897. }
  31898. function setLargeBackgroundStyle(el, backgroundModel, data) {
  31899. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  31900. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  31901. el.useStyle(itemStyle);
  31902. el.style.fill = null;
  31903. el.style.stroke = borderColor;
  31904. el.style.lineWidth = data.getLayout('barWidth');
  31905. }
  31906. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  31907. var coordLayout;
  31908. var isPolar = coord.type === 'polar';
  31909. if (isPolar) {
  31910. coordLayout = coord.getArea();
  31911. } else {
  31912. coordLayout = coord.grid.getRect();
  31913. }
  31914. if (isPolar) {
  31915. return {
  31916. cx: coordLayout.cx,
  31917. cy: coordLayout.cy,
  31918. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  31919. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  31920. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  31921. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  31922. };
  31923. } else {
  31924. return {
  31925. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  31926. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  31927. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  31928. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  31929. };
  31930. }
  31931. }
  31932. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  31933. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  31934. return new ElementClz({
  31935. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  31936. silent: true,
  31937. z2: 0
  31938. });
  31939. }
  31940. /*
  31941. * Licensed to the Apache Software Foundation (ASF) under one
  31942. * or more contributor license agreements. See the NOTICE file
  31943. * distributed with this work for additional information
  31944. * regarding copyright ownership. The ASF licenses this file
  31945. * to you under the Apache License, Version 2.0 (the
  31946. * "License"); you may not use this file except in compliance
  31947. * with the License. You may obtain a copy of the License at
  31948. *
  31949. * http://www.apache.org/licenses/LICENSE-2.0
  31950. *
  31951. * Unless required by applicable law or agreed to in writing,
  31952. * software distributed under the License is distributed on an
  31953. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31954. * KIND, either express or implied. See the License for the
  31955. * specific language governing permissions and limitations
  31956. * under the License.
  31957. */
  31958. var PI$2 = Math.PI;
  31959. /**
  31960. * A final axis is translated and rotated from a "standard axis".
  31961. * So opt.position and opt.rotation is required.
  31962. *
  31963. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  31964. * for example: (0, 0) ------------> (0, 50)
  31965. *
  31966. * nameDirection or tickDirection or labelDirection is 1 means tick
  31967. * or label is below the standard axis, whereas is -1 means above
  31968. * the standard axis. labelOffset means offset between label and axis,
  31969. * which is useful when 'onZero', where axisLabel is in the grid and
  31970. * label in outside grid.
  31971. *
  31972. * Tips: like always,
  31973. * positive rotation represents anticlockwise, and negative rotation
  31974. * represents clockwise.
  31975. * The direction of position coordinate is the same as the direction
  31976. * of screen coordinate.
  31977. *
  31978. * Do not need to consider axis 'inverse', which is auto processed by
  31979. * axis extent.
  31980. *
  31981. * @param {module:zrender/container/Group} group
  31982. * @param {Object} axisModel
  31983. * @param {Object} opt Standard axis parameters.
  31984. * @param {Array.<number>} opt.position [x, y]
  31985. * @param {number} opt.rotation by radian
  31986. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  31987. * @param {number} [opt.tickDirection=1] 1 or -1
  31988. * @param {number} [opt.labelDirection=1] 1 or -1
  31989. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  31990. * @param {string} [opt.axisLabelShow] default get from axisModel.
  31991. * @param {string} [opt.axisName] default get from axisModel.
  31992. * @param {number} [opt.axisNameAvailableWidth]
  31993. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  31994. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  31995. * @param {number} [opt.nameTruncateMaxWidth]
  31996. */
  31997. var AxisBuilder = function (axisModel, opt) {
  31998. /**
  31999. * @readOnly
  32000. */
  32001. this.opt = opt;
  32002. /**
  32003. * @readOnly
  32004. */
  32005. this.axisModel = axisModel; // Default value
  32006. defaults(opt, {
  32007. labelOffset: 0,
  32008. nameDirection: 1,
  32009. tickDirection: 1,
  32010. labelDirection: 1,
  32011. silent: true
  32012. });
  32013. /**
  32014. * @readOnly
  32015. */
  32016. this.group = new Group(); // FIXME Not use a seperate text group?
  32017. var dumbGroup = new Group({
  32018. position: opt.position.slice(),
  32019. rotation: opt.rotation
  32020. }); // this.group.add(dumbGroup);
  32021. // this._dumbGroup = dumbGroup;
  32022. dumbGroup.updateTransform();
  32023. this._transform = dumbGroup.transform;
  32024. this._dumbGroup = dumbGroup;
  32025. };
  32026. AxisBuilder.prototype = {
  32027. constructor: AxisBuilder,
  32028. hasBuilder: function (name) {
  32029. return !!builders[name];
  32030. },
  32031. add: function (name) {
  32032. builders[name].call(this);
  32033. },
  32034. getGroup: function () {
  32035. return this.group;
  32036. }
  32037. };
  32038. var builders = {
  32039. /**
  32040. * @private
  32041. */
  32042. axisLine: function () {
  32043. var opt = this.opt;
  32044. var axisModel = this.axisModel;
  32045. if (!axisModel.get('axisLine.show')) {
  32046. return;
  32047. }
  32048. var extent = this.axisModel.axis.getExtent();
  32049. var matrix = this._transform;
  32050. var pt1 = [extent[0], 0];
  32051. var pt2 = [extent[1], 0];
  32052. if (matrix) {
  32053. applyTransform(pt1, pt1, matrix);
  32054. applyTransform(pt2, pt2, matrix);
  32055. }
  32056. var lineStyle = extend({
  32057. lineCap: 'round'
  32058. }, axisModel.getModel('axisLine.lineStyle').getLineStyle());
  32059. this.group.add(new Line({
  32060. // Id for animation
  32061. anid: 'line',
  32062. subPixelOptimize: true,
  32063. shape: {
  32064. x1: pt1[0],
  32065. y1: pt1[1],
  32066. x2: pt2[0],
  32067. y2: pt2[1]
  32068. },
  32069. style: lineStyle,
  32070. strokeContainThreshold: opt.strokeContainThreshold || 5,
  32071. silent: true,
  32072. z2: 1
  32073. }));
  32074. var arrows = axisModel.get('axisLine.symbol');
  32075. var arrowSize = axisModel.get('axisLine.symbolSize');
  32076. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  32077. if (typeof arrowOffset === 'number') {
  32078. arrowOffset = [arrowOffset, arrowOffset];
  32079. }
  32080. if (arrows != null) {
  32081. if (typeof arrows === 'string') {
  32082. // Use the same arrow for start and end point
  32083. arrows = [arrows, arrows];
  32084. }
  32085. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  32086. // Use the same size for width and height
  32087. arrowSize = [arrowSize, arrowSize];
  32088. }
  32089. var symbolWidth = arrowSize[0];
  32090. var symbolHeight = arrowSize[1];
  32091. each$1([{
  32092. rotate: opt.rotation + Math.PI / 2,
  32093. offset: arrowOffset[0],
  32094. r: 0
  32095. }, {
  32096. rotate: opt.rotation - Math.PI / 2,
  32097. offset: arrowOffset[1],
  32098. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  32099. }], function (point, index) {
  32100. if (arrows[index] !== 'none' && arrows[index] != null) {
  32101. var symbol = createSymbol(arrows[index], -symbolWidth / 2, -symbolHeight / 2, symbolWidth, symbolHeight, lineStyle.stroke, true); // Calculate arrow position with offset
  32102. var r = point.r + point.offset;
  32103. var pos = [pt1[0] + r * Math.cos(opt.rotation), pt1[1] - r * Math.sin(opt.rotation)];
  32104. symbol.attr({
  32105. rotation: point.rotate,
  32106. position: pos,
  32107. silent: true,
  32108. z2: 11
  32109. });
  32110. this.group.add(symbol);
  32111. }
  32112. }, this);
  32113. }
  32114. },
  32115. /**
  32116. * @private
  32117. */
  32118. axisTickLabel: function () {
  32119. var axisModel = this.axisModel;
  32120. var opt = this.opt;
  32121. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  32122. var labelEls = buildAxisLabel(this, axisModel, opt);
  32123. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  32124. buildAxisMinorTicks(this, axisModel, opt);
  32125. },
  32126. /**
  32127. * @private
  32128. */
  32129. axisName: function () {
  32130. var opt = this.opt;
  32131. var axisModel = this.axisModel;
  32132. var name = retrieve(opt.axisName, axisModel.get('name'));
  32133. if (!name) {
  32134. return;
  32135. }
  32136. var nameLocation = axisModel.get('nameLocation');
  32137. var nameDirection = opt.nameDirection;
  32138. var textStyleModel = axisModel.getModel('nameTextStyle');
  32139. var gap = axisModel.get('nameGap') || 0;
  32140. var extent = this.axisModel.axis.getExtent();
  32141. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  32142. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // 'middle'
  32143. // Reuse labelOffset.
  32144. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  32145. var labelLayout;
  32146. var nameRotation = axisModel.get('nameRotate');
  32147. if (nameRotation != null) {
  32148. nameRotation = nameRotation * PI$2 / 180; // To radian.
  32149. }
  32150. var axisNameAvailableWidth;
  32151. if (isNameLocationCenter(nameLocation)) {
  32152. labelLayout = innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  32153. nameDirection);
  32154. } else {
  32155. labelLayout = endTextLayout(opt, nameLocation, nameRotation || 0, extent);
  32156. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  32157. if (axisNameAvailableWidth != null) {
  32158. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  32159. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  32160. }
  32161. }
  32162. var textFont = textStyleModel.getFont();
  32163. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  32164. var ellipsis = truncateOpt.ellipsis;
  32165. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth); // FIXME
  32166. // truncate rich text? (consider performance)
  32167. var truncatedText = ellipsis != null && maxWidth != null ? truncateText$1(name, maxWidth, textFont, ellipsis, {
  32168. minChar: 2,
  32169. placeholder: truncateOpt.placeholder
  32170. }) : name;
  32171. var tooltipOpt = axisModel.get('tooltip', true);
  32172. var mainType = axisModel.mainType;
  32173. var formatterParams = {
  32174. componentType: mainType,
  32175. name: name,
  32176. $vars: ['name']
  32177. };
  32178. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  32179. var textEl = new Text({
  32180. // Id for animation
  32181. anid: 'name',
  32182. __fullText: name,
  32183. __truncatedText: truncatedText,
  32184. position: pos,
  32185. rotation: labelLayout.rotation,
  32186. silent: isLabelSilent(axisModel),
  32187. z2: 1,
  32188. tooltip: tooltipOpt && tooltipOpt.show ? extend({
  32189. content: name,
  32190. formatter: function () {
  32191. return name;
  32192. },
  32193. formatterParams: formatterParams
  32194. }, tooltipOpt) : null
  32195. });
  32196. setTextStyle(textEl.style, textStyleModel, {
  32197. text: truncatedText,
  32198. textFont: textFont,
  32199. textFill: textStyleModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'),
  32200. textAlign: textStyleModel.get('align') || labelLayout.textAlign,
  32201. textVerticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  32202. });
  32203. if (axisModel.get('triggerEvent')) {
  32204. textEl.eventData = makeAxisEventDataBase(axisModel);
  32205. textEl.eventData.targetType = 'axisName';
  32206. textEl.eventData.name = name;
  32207. } // FIXME
  32208. this._dumbGroup.add(textEl);
  32209. textEl.updateTransform();
  32210. this.group.add(textEl);
  32211. textEl.decomposeTransform();
  32212. }
  32213. };
  32214. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  32215. var eventData = {
  32216. componentType: axisModel.mainType,
  32217. componentIndex: axisModel.componentIndex
  32218. };
  32219. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  32220. return eventData;
  32221. };
  32222. /**
  32223. * @public
  32224. * @static
  32225. * @param {Object} opt
  32226. * @param {number} axisRotation in radian
  32227. * @param {number} textRotation in radian
  32228. * @param {number} direction
  32229. * @return {Object} {
  32230. * rotation, // according to axis
  32231. * textAlign,
  32232. * textVerticalAlign
  32233. * }
  32234. */
  32235. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  32236. var rotationDiff = remRadian(textRotation - axisRotation);
  32237. var textAlign;
  32238. var textVerticalAlign;
  32239. if (isRadianAroundZero(rotationDiff)) {
  32240. // Label is parallel with axis line.
  32241. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  32242. textAlign = 'center';
  32243. } else if (isRadianAroundZero(rotationDiff - PI$2)) {
  32244. // Label is inverse parallel with axis line.
  32245. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  32246. textAlign = 'center';
  32247. } else {
  32248. textVerticalAlign = 'middle';
  32249. if (rotationDiff > 0 && rotationDiff < PI$2) {
  32250. textAlign = direction > 0 ? 'right' : 'left';
  32251. } else {
  32252. textAlign = direction > 0 ? 'left' : 'right';
  32253. }
  32254. }
  32255. return {
  32256. rotation: rotationDiff,
  32257. textAlign: textAlign,
  32258. textVerticalAlign: textVerticalAlign
  32259. };
  32260. };
  32261. function endTextLayout(opt, textPosition, textRotate, extent) {
  32262. var rotationDiff = remRadian(textRotate - opt.rotation);
  32263. var textAlign;
  32264. var textVerticalAlign;
  32265. var inverse = extent[0] > extent[1];
  32266. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  32267. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  32268. textVerticalAlign = onLeft ? 'bottom' : 'top';
  32269. textAlign = 'center';
  32270. } else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  32271. textVerticalAlign = onLeft ? 'top' : 'bottom';
  32272. textAlign = 'center';
  32273. } else {
  32274. textVerticalAlign = 'middle';
  32275. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  32276. textAlign = onLeft ? 'left' : 'right';
  32277. } else {
  32278. textAlign = onLeft ? 'right' : 'left';
  32279. }
  32280. }
  32281. return {
  32282. rotation: rotationDiff,
  32283. textAlign: textAlign,
  32284. textVerticalAlign: textVerticalAlign
  32285. };
  32286. }
  32287. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  32288. var tooltipOpt = axisModel.get('tooltip');
  32289. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  32290. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  32291. };
  32292. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  32293. if (shouldShowAllLabels(axisModel.axis)) {
  32294. return;
  32295. } // If min or max are user set, we need to check
  32296. // If the tick on min(max) are overlap on their neighbour tick
  32297. // If they are overlapped, we need to hide the min(max) tick label
  32298. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  32299. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); // FIXME
  32300. // Have not consider onBand yet, where tick els is more than label els.
  32301. labelEls = labelEls || [];
  32302. tickEls = tickEls || [];
  32303. var firstLabel = labelEls[0];
  32304. var nextLabel = labelEls[1];
  32305. var lastLabel = labelEls[labelEls.length - 1];
  32306. var prevLabel = labelEls[labelEls.length - 2];
  32307. var firstTick = tickEls[0];
  32308. var nextTick = tickEls[1];
  32309. var lastTick = tickEls[tickEls.length - 1];
  32310. var prevTick = tickEls[tickEls.length - 2];
  32311. if (showMinLabel === false) {
  32312. ignoreEl(firstLabel);
  32313. ignoreEl(firstTick);
  32314. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  32315. if (showMinLabel) {
  32316. ignoreEl(nextLabel);
  32317. ignoreEl(nextTick);
  32318. } else {
  32319. ignoreEl(firstLabel);
  32320. ignoreEl(firstTick);
  32321. }
  32322. }
  32323. if (showMaxLabel === false) {
  32324. ignoreEl(lastLabel);
  32325. ignoreEl(lastTick);
  32326. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  32327. if (showMaxLabel) {
  32328. ignoreEl(prevLabel);
  32329. ignoreEl(prevTick);
  32330. } else {
  32331. ignoreEl(lastLabel);
  32332. ignoreEl(lastTick);
  32333. }
  32334. }
  32335. }
  32336. function ignoreEl(el) {
  32337. el && (el.ignore = true);
  32338. }
  32339. function isTwoLabelOverlapped(current, next, labelLayout) {
  32340. // current and next has the same rotation.
  32341. var firstRect = current && current.getBoundingRect().clone();
  32342. var nextRect = next && next.getBoundingRect().clone();
  32343. if (!firstRect || !nextRect) {
  32344. return;
  32345. } // When checking intersect of two rotated labels, we use mRotationBack
  32346. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  32347. var mRotationBack = identity([]);
  32348. rotate(mRotationBack, mRotationBack, -current.rotation);
  32349. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  32350. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  32351. return firstRect.intersect(nextRect);
  32352. }
  32353. function isNameLocationCenter(nameLocation) {
  32354. return nameLocation === 'middle' || nameLocation === 'center';
  32355. }
  32356. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  32357. var tickEls = [];
  32358. var pt1 = [];
  32359. var pt2 = [];
  32360. for (var i = 0; i < ticksCoords.length; i++) {
  32361. var tickCoord = ticksCoords[i].coord;
  32362. pt1[0] = tickCoord;
  32363. pt1[1] = 0;
  32364. pt2[0] = tickCoord;
  32365. pt2[1] = tickEndCoord;
  32366. if (tickTransform) {
  32367. applyTransform(pt1, pt1, tickTransform);
  32368. applyTransform(pt2, pt2, tickTransform);
  32369. } // Tick line, Not use group transform to have better line draw
  32370. var tickEl = new Line({
  32371. // Id for animation
  32372. anid: aniid + '_' + ticksCoords[i].tickValue,
  32373. subPixelOptimize: true,
  32374. shape: {
  32375. x1: pt1[0],
  32376. y1: pt1[1],
  32377. x2: pt2[0],
  32378. y2: pt2[1]
  32379. },
  32380. style: tickLineStyle,
  32381. z2: 2,
  32382. silent: true
  32383. });
  32384. tickEls.push(tickEl);
  32385. }
  32386. return tickEls;
  32387. }
  32388. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  32389. var axis = axisModel.axis;
  32390. var tickModel = axisModel.getModel('axisTick');
  32391. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32392. return;
  32393. }
  32394. var lineStyleModel = tickModel.getModel('lineStyle');
  32395. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  32396. var ticksCoords = axis.getTicksCoords();
  32397. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  32398. stroke: axisModel.get('axisLine.lineStyle.color')
  32399. }), 'ticks');
  32400. for (var i = 0; i < ticksEls.length; i++) {
  32401. axisBuilder.group.add(ticksEls[i]);
  32402. }
  32403. return ticksEls;
  32404. }
  32405. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  32406. var axis = axisModel.axis;
  32407. var minorTickModel = axisModel.getModel('minorTick');
  32408. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  32409. return;
  32410. }
  32411. var minorTicksCoords = axis.getMinorTicksCoords();
  32412. if (!minorTicksCoords.length) {
  32413. return;
  32414. }
  32415. var lineStyleModel = minorTickModel.getModel('lineStyle');
  32416. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  32417. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  32418. stroke: axisModel.get('axisLine.lineStyle.color')
  32419. }));
  32420. for (var i = 0; i < minorTicksCoords.length; i++) {
  32421. var minorTicksEls = createTicks(minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  32422. for (var k = 0; k < minorTicksEls.length; k++) {
  32423. axisBuilder.group.add(minorTicksEls[k]);
  32424. }
  32425. }
  32426. }
  32427. function buildAxisLabel(axisBuilder, axisModel, opt) {
  32428. var axis = axisModel.axis;
  32429. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  32430. if (!show || axis.scale.isBlank()) {
  32431. return;
  32432. }
  32433. var labelModel = axisModel.getModel('axisLabel');
  32434. var labelMargin = labelModel.get('margin');
  32435. var labels = axis.getViewLabels(); // Special label rotate.
  32436. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$2 / 180;
  32437. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  32438. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  32439. var labelEls = [];
  32440. var silent = isLabelSilent(axisModel);
  32441. var triggerEvent = axisModel.get('triggerEvent');
  32442. each$1(labels, function (labelItem, index) {
  32443. var tickValue = labelItem.tickValue;
  32444. var formattedLabel = labelItem.formattedLabel;
  32445. var rawLabel = labelItem.rawLabel;
  32446. var itemLabelModel = labelModel;
  32447. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  32448. itemLabelModel = new Model(rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel);
  32449. }
  32450. var textColor = itemLabelModel.getTextColor() || axisModel.get('axisLine.lineStyle.color');
  32451. var tickCoord = axis.dataToCoord(tickValue);
  32452. var pos = [tickCoord, opt.labelOffset + opt.labelDirection * labelMargin];
  32453. var textEl = new Text({
  32454. // Id for animation
  32455. anid: 'label_' + tickValue,
  32456. position: pos,
  32457. rotation: labelLayout.rotation,
  32458. silent: silent,
  32459. z2: 10
  32460. });
  32461. setTextStyle(textEl.style, itemLabelModel, {
  32462. text: formattedLabel,
  32463. textAlign: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  32464. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  32465. textFill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  32466. // index of axis.data. So tick should not be exposed to user
  32467. // in category axis.
  32468. // (2) Compatible with previous version, which always use formatted label as
  32469. // input. But in interval scale the formatted label is like '223,445', which
  32470. // maked user repalce ','. So we modify it to return original val but remain
  32471. // it as 'string' to avoid error in replacing.
  32472. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  32473. }); // Pack data for mouse event
  32474. if (triggerEvent) {
  32475. textEl.eventData = makeAxisEventDataBase(axisModel);
  32476. textEl.eventData.targetType = 'axisLabel';
  32477. textEl.eventData.value = rawLabel;
  32478. } // FIXME
  32479. axisBuilder._dumbGroup.add(textEl);
  32480. textEl.updateTransform();
  32481. labelEls.push(textEl);
  32482. axisBuilder.group.add(textEl);
  32483. textEl.decomposeTransform();
  32484. });
  32485. return labelEls;
  32486. }
  32487. /*
  32488. * Licensed to the Apache Software Foundation (ASF) under one
  32489. * or more contributor license agreements. See the NOTICE file
  32490. * distributed with this work for additional information
  32491. * regarding copyright ownership. The ASF licenses this file
  32492. * to you under the Apache License, Version 2.0 (the
  32493. * "License"); you may not use this file except in compliance
  32494. * with the License. You may obtain a copy of the License at
  32495. *
  32496. * http://www.apache.org/licenses/LICENSE-2.0
  32497. *
  32498. * Unless required by applicable law or agreed to in writing,
  32499. * software distributed under the License is distributed on an
  32500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32501. * KIND, either express or implied. See the License for the
  32502. * specific language governing permissions and limitations
  32503. * under the License.
  32504. */
  32505. var each$6 = each$1;
  32506. var curry$1 = curry; // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  32507. // allAxesInfo should be updated when setOption performed.
  32508. function collect(ecModel, api) {
  32509. var result = {
  32510. /**
  32511. * key: makeKey(axis.model)
  32512. * value: {
  32513. * axis,
  32514. * coordSys,
  32515. * axisPointerModel,
  32516. * triggerTooltip,
  32517. * involveSeries,
  32518. * snap,
  32519. * seriesModels,
  32520. * seriesDataCount
  32521. * }
  32522. */
  32523. axesInfo: {},
  32524. seriesInvolved: false,
  32525. /**
  32526. * key: makeKey(coordSys.model)
  32527. * value: Object: key makeKey(axis.model), value: axisInfo
  32528. */
  32529. coordSysAxesInfo: {},
  32530. coordSysMap: {}
  32531. };
  32532. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  32533. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  32534. return result;
  32535. }
  32536. function collectAxesInfo(result, ecModel, api) {
  32537. var globalTooltipModel = ecModel.getComponent('tooltip');
  32538. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  32539. var linksOption = globalAxisPointerModel.get('link', true) || [];
  32540. var linkGroups = []; // Collect axes info.
  32541. each$6(api.getCoordinateSystems(), function (coordSys) {
  32542. // Some coordinate system do not support axes, like geo.
  32543. if (!coordSys.axisPointerEnabled) {
  32544. return;
  32545. }
  32546. var coordSysKey = makeKey(coordSys.model);
  32547. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  32548. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  32549. // for user. So we enable seting tooltip on coordSys model.
  32550. var coordSysModel = coordSys.model;
  32551. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  32552. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  32553. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  32554. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  32555. // show but axisPointer will show as normal.
  32556. && baseTooltipModel.get('show')) {
  32557. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  32558. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  32559. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  32560. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  32561. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  32562. if (triggerAxis || cross) {
  32563. each$6(tooltipAxes.baseAxes, curry$1(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  32564. }
  32565. if (cross) {
  32566. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  32567. }
  32568. } // fromTooltip: true | false | 'cross'
  32569. // triggerTooltip: true | false | null
  32570. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  32571. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  32572. var axisPointerShow = axisPointerModel.get('show');
  32573. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  32574. return;
  32575. }
  32576. if (triggerTooltip == null) {
  32577. triggerTooltip = axisPointerModel.get('triggerTooltip');
  32578. }
  32579. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  32580. var snap = axisPointerModel.get('snap');
  32581. var key = makeKey(axis.model);
  32582. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  32583. var axisInfo = result.axesInfo[key] = {
  32584. key: key,
  32585. axis: axis,
  32586. coordSys: coordSys,
  32587. axisPointerModel: axisPointerModel,
  32588. triggerTooltip: triggerTooltip,
  32589. involveSeries: involveSeries,
  32590. snap: snap,
  32591. useHandle: isHandleTrigger(axisPointerModel),
  32592. seriesModels: []
  32593. };
  32594. axesInfoInCoordSys[key] = axisInfo;
  32595. result.seriesInvolved |= involveSeries;
  32596. var groupIndex = getLinkGroupIndex(linksOption, axis);
  32597. if (groupIndex != null) {
  32598. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  32599. axesInfo: {}
  32600. });
  32601. linkGroup.axesInfo[key] = axisInfo;
  32602. linkGroup.mapper = linksOption[groupIndex].mapper;
  32603. axisInfo.linkGroup = linkGroup;
  32604. }
  32605. }
  32606. });
  32607. }
  32608. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  32609. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  32610. var volatileOption = {};
  32611. each$6(['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'], function (field) {
  32612. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  32613. }); // category axis do not auto snap, otherwise some tick that do not
  32614. // has value can not be hovered. value/time/log axis default snap if
  32615. // triggered from tooltip and trigger tooltip.
  32616. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  32617. // Only these properties can be overrided from tooltip to axisPointer.
  32618. if (tooltipAxisPointerModel.get('type') === 'cross') {
  32619. volatileOption.type = 'line';
  32620. }
  32621. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  32622. labelOption.show == null && (labelOption.show = false);
  32623. if (fromTooltip === 'cross') {
  32624. // When 'cross', both axes show labels.
  32625. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  32626. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  32627. // (cross style is dashed by default)
  32628. if (!triggerTooltip) {
  32629. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  32630. crossStyle && defaults(labelOption, crossStyle.textStyle);
  32631. }
  32632. }
  32633. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  32634. }
  32635. function collectSeriesInfo(result, ecModel) {
  32636. // Prepare data for axis trigger
  32637. ecModel.eachSeries(function (seriesModel) {
  32638. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  32639. var coordSys = seriesModel.coordinateSystem;
  32640. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  32641. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  32642. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get('axisPointer.show', true) === false) {
  32643. return;
  32644. }
  32645. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  32646. var axis = axisInfo.axis;
  32647. if (coordSys.getAxis(axis.dim) === axis) {
  32648. axisInfo.seriesModels.push(seriesModel);
  32649. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  32650. axisInfo.seriesDataCount += seriesModel.getData().count();
  32651. }
  32652. });
  32653. }, this);
  32654. }
  32655. /**
  32656. * For example:
  32657. * {
  32658. * axisPointer: {
  32659. * links: [{
  32660. * xAxisIndex: [2, 4],
  32661. * yAxisIndex: 'all'
  32662. * }, {
  32663. * xAxisId: ['a5', 'a7'],
  32664. * xAxisName: 'xxx'
  32665. * }]
  32666. * }
  32667. * }
  32668. */
  32669. function getLinkGroupIndex(linksOption, axis) {
  32670. var axisModel = axis.model;
  32671. var dim = axis.dim;
  32672. for (var i = 0; i < linksOption.length; i++) {
  32673. var linkOption = linksOption[i] || {};
  32674. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  32675. return i;
  32676. }
  32677. }
  32678. }
  32679. function checkPropInLink(linkPropValue, axisPropValue) {
  32680. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  32681. }
  32682. function fixValue(axisModel) {
  32683. var axisInfo = getAxisInfo(axisModel);
  32684. if (!axisInfo) {
  32685. return;
  32686. }
  32687. var axisPointerModel = axisInfo.axisPointerModel;
  32688. var scale = axisInfo.axis.scale;
  32689. var option = axisPointerModel.option;
  32690. var status = axisPointerModel.get('status');
  32691. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  32692. if (value != null) {
  32693. value = scale.parse(value);
  32694. }
  32695. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  32696. // and status should be initialized.
  32697. if (status == null) {
  32698. option.status = useHandle ? 'show' : 'hide';
  32699. }
  32700. var extent = scale.getExtent().slice();
  32701. extent[0] > extent[1] && extent.reverse();
  32702. if ( // Pick a value on axis when initializing.
  32703. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  32704. // where we should re-pick a value to keep `handle` displaying normally.
  32705. || value > extent[1]) {
  32706. // Make handle displayed on the end of the axis when init, which looks better.
  32707. value = extent[1];
  32708. }
  32709. if (value < extent[0]) {
  32710. value = extent[0];
  32711. }
  32712. option.value = value;
  32713. if (useHandle) {
  32714. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  32715. }
  32716. }
  32717. function getAxisInfo(axisModel) {
  32718. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  32719. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  32720. }
  32721. function getAxisPointerModel(axisModel) {
  32722. var axisInfo = getAxisInfo(axisModel);
  32723. return axisInfo && axisInfo.axisPointerModel;
  32724. }
  32725. function isHandleTrigger(axisPointerModel) {
  32726. return !!axisPointerModel.get('handle.show');
  32727. }
  32728. /**
  32729. * @param {module:echarts/model/Model} model
  32730. * @return {string} unique key
  32731. */
  32732. function makeKey(model) {
  32733. return model.type + '||' + model.id;
  32734. }
  32735. /*
  32736. * Licensed to the Apache Software Foundation (ASF) under one
  32737. * or more contributor license agreements. See the NOTICE file
  32738. * distributed with this work for additional information
  32739. * regarding copyright ownership. The ASF licenses this file
  32740. * to you under the Apache License, Version 2.0 (the
  32741. * "License"); you may not use this file except in compliance
  32742. * with the License. You may obtain a copy of the License at
  32743. *
  32744. * http://www.apache.org/licenses/LICENSE-2.0
  32745. *
  32746. * Unless required by applicable law or agreed to in writing,
  32747. * software distributed under the License is distributed on an
  32748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32749. * KIND, either express or implied. See the License for the
  32750. * specific language governing permissions and limitations
  32751. * under the License.
  32752. */
  32753. /**
  32754. * Base class of AxisView.
  32755. */
  32756. var AxisView = extendComponentView({
  32757. type: 'axis',
  32758. /**
  32759. * @private
  32760. */
  32761. _axisPointer: null,
  32762. /**
  32763. * @protected
  32764. * @type {string}
  32765. */
  32766. axisPointerClass: null,
  32767. /**
  32768. * @override
  32769. */
  32770. render: function (axisModel, ecModel, api, payload) {
  32771. // FIXME
  32772. // This process should proformed after coordinate systems updated
  32773. // (axis scale updated), and should be performed each time update.
  32774. // So put it here temporarily, although it is not appropriate to
  32775. // put a model-writing procedure in `view`.
  32776. this.axisPointerClass && fixValue(axisModel);
  32777. AxisView.superApply(this, 'render', arguments);
  32778. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  32779. },
  32780. /**
  32781. * Action handler.
  32782. * @public
  32783. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  32784. * @param {module:echarts/model/Global} ecModel
  32785. * @param {module:echarts/ExtensionAPI} api
  32786. * @param {Object} payload
  32787. */
  32788. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  32789. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  32790. },
  32791. /**
  32792. * @override
  32793. */
  32794. remove: function (ecModel, api) {
  32795. var axisPointer = this._axisPointer;
  32796. axisPointer && axisPointer.remove(api);
  32797. AxisView.superApply(this, 'remove', arguments);
  32798. },
  32799. /**
  32800. * @override
  32801. */
  32802. dispose: function (ecModel, api) {
  32803. disposeAxisPointer(this, api);
  32804. AxisView.superApply(this, 'dispose', arguments);
  32805. }
  32806. });
  32807. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  32808. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  32809. if (!Clazz) {
  32810. return;
  32811. }
  32812. var axisPointerModel = getAxisPointerModel(axisModel);
  32813. axisPointerModel ? (axisView._axisPointer || (axisView._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : disposeAxisPointer(axisView, api);
  32814. }
  32815. function disposeAxisPointer(axisView, ecModel, api) {
  32816. var axisPointer = axisView._axisPointer;
  32817. axisPointer && axisPointer.dispose(ecModel, api);
  32818. axisView._axisPointer = null;
  32819. }
  32820. var axisPointerClazz = [];
  32821. AxisView.registerAxisPointerClass = function (type, clazz) {
  32822. axisPointerClazz[type] = clazz;
  32823. };
  32824. AxisView.getAxisPointerClass = function (type) {
  32825. return type && axisPointerClazz[type];
  32826. };
  32827. /*
  32828. * Licensed to the Apache Software Foundation (ASF) under one
  32829. * or more contributor license agreements. See the NOTICE file
  32830. * distributed with this work for additional information
  32831. * regarding copyright ownership. The ASF licenses this file
  32832. * to you under the Apache License, Version 2.0 (the
  32833. * "License"); you may not use this file except in compliance
  32834. * with the License. You may obtain a copy of the License at
  32835. *
  32836. * http://www.apache.org/licenses/LICENSE-2.0
  32837. *
  32838. * Unless required by applicable law or agreed to in writing,
  32839. * software distributed under the License is distributed on an
  32840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32841. * KIND, either express or implied. See the License for the
  32842. * specific language governing permissions and limitations
  32843. * under the License.
  32844. */
  32845. /**
  32846. * Can only be called after coordinate system creation stage.
  32847. * (Can be called before coordinate system update stage).
  32848. *
  32849. * @param {Object} opt {labelInside}
  32850. * @return {Object} {
  32851. * position, rotation, labelDirection, labelOffset,
  32852. * tickDirection, labelRotate, z2
  32853. * }
  32854. */
  32855. function layout$1(gridModel, axisModel, opt) {
  32856. opt = opt || {};
  32857. var grid = gridModel.coordinateSystem;
  32858. var axis = axisModel.axis;
  32859. var layout = {};
  32860. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  32861. var rawAxisPosition = axis.position;
  32862. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  32863. var axisDim = axis.dim;
  32864. var rect = grid.getRect();
  32865. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  32866. var idx = {
  32867. left: 0,
  32868. right: 1,
  32869. top: 0,
  32870. bottom: 1,
  32871. onZero: 2
  32872. };
  32873. var axisOffset = axisModel.get('offset') || 0;
  32874. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  32875. if (otherAxisOnZeroOf) {
  32876. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  32877. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  32878. } // Axis position
  32879. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  32880. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  32881. var dirMap = {
  32882. top: -1,
  32883. bottom: 1,
  32884. left: -1,
  32885. right: 1
  32886. };
  32887. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  32888. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  32889. if (axisModel.get('axisTick.inside')) {
  32890. layout.tickDirection = -layout.tickDirection;
  32891. }
  32892. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  32893. layout.labelDirection = -layout.labelDirection;
  32894. } // Special label rotation
  32895. var labelRotate = axisModel.get('axisLabel.rotate');
  32896. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  32897. layout.z2 = 1;
  32898. return layout;
  32899. }
  32900. /*
  32901. * Licensed to the Apache Software Foundation (ASF) under one
  32902. * or more contributor license agreements. See the NOTICE file
  32903. * distributed with this work for additional information
  32904. * regarding copyright ownership. The ASF licenses this file
  32905. * to you under the Apache License, Version 2.0 (the
  32906. * "License"); you may not use this file except in compliance
  32907. * with the License. You may obtain a copy of the License at
  32908. *
  32909. * http://www.apache.org/licenses/LICENSE-2.0
  32910. *
  32911. * Unless required by applicable law or agreed to in writing,
  32912. * software distributed under the License is distributed on an
  32913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32914. * KIND, either express or implied. See the License for the
  32915. * specific language governing permissions and limitations
  32916. * under the License.
  32917. */
  32918. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  32919. var axis = axisModel.axis;
  32920. if (axis.scale.isBlank()) {
  32921. return;
  32922. }
  32923. var splitAreaModel = axisModel.getModel('splitArea');
  32924. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  32925. var areaColors = areaStyleModel.get('color');
  32926. var gridRect = gridModel.coordinateSystem.getRect();
  32927. var ticksCoords = axis.getTicksCoords({
  32928. tickModel: splitAreaModel,
  32929. clamp: true
  32930. });
  32931. if (!ticksCoords.length) {
  32932. return;
  32933. } // For Making appropriate splitArea animation, the color and anid
  32934. // should be corresponding to previous one if possible.
  32935. var areaColorsLen = areaColors.length;
  32936. var lastSplitAreaColors = axisView.__splitAreaColors;
  32937. var newSplitAreaColors = createHashMap();
  32938. var colorIndex = 0;
  32939. if (lastSplitAreaColors) {
  32940. for (var i = 0; i < ticksCoords.length; i++) {
  32941. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  32942. if (cIndex != null) {
  32943. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  32944. break;
  32945. }
  32946. }
  32947. }
  32948. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  32949. var areaStyle = areaStyleModel.getAreaStyle();
  32950. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  32951. for (var i = 1; i < ticksCoords.length; i++) {
  32952. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  32953. var x;
  32954. var y;
  32955. var width;
  32956. var height;
  32957. if (axis.isHorizontal()) {
  32958. x = prev;
  32959. y = gridRect.y;
  32960. width = tickCoord - x;
  32961. height = gridRect.height;
  32962. prev = x + width;
  32963. } else {
  32964. x = gridRect.x;
  32965. y = prev;
  32966. width = gridRect.width;
  32967. height = tickCoord - y;
  32968. prev = y + height;
  32969. }
  32970. var tickValue = ticksCoords[i - 1].tickValue;
  32971. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  32972. axisGroup.add(new Rect({
  32973. anid: tickValue != null ? 'area_' + tickValue : null,
  32974. shape: {
  32975. x: x,
  32976. y: y,
  32977. width: width,
  32978. height: height
  32979. },
  32980. style: defaults({
  32981. fill: areaColors[colorIndex]
  32982. }, areaStyle),
  32983. silent: true
  32984. }));
  32985. colorIndex = (colorIndex + 1) % areaColorsLen;
  32986. }
  32987. axisView.__splitAreaColors = newSplitAreaColors;
  32988. }
  32989. function rectCoordAxisHandleRemove(axisView) {
  32990. axisView.__splitAreaColors = null;
  32991. }
  32992. /*
  32993. * Licensed to the Apache Software Foundation (ASF) under one
  32994. * or more contributor license agreements. See the NOTICE file
  32995. * distributed with this work for additional information
  32996. * regarding copyright ownership. The ASF licenses this file
  32997. * to you under the Apache License, Version 2.0 (the
  32998. * "License"); you may not use this file except in compliance
  32999. * with the License. You may obtain a copy of the License at
  33000. *
  33001. * http://www.apache.org/licenses/LICENSE-2.0
  33002. *
  33003. * Unless required by applicable law or agreed to in writing,
  33004. * software distributed under the License is distributed on an
  33005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33006. * KIND, either express or implied. See the License for the
  33007. * specific language governing permissions and limitations
  33008. * under the License.
  33009. */
  33010. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  33011. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  33012. var CartesianAxisView = AxisView.extend({
  33013. type: 'cartesianAxis',
  33014. axisPointerClass: 'CartesianAxisPointer',
  33015. /**
  33016. * @override
  33017. */
  33018. render: function (axisModel, ecModel, api, payload) {
  33019. this.group.removeAll();
  33020. var oldAxisGroup = this._axisGroup;
  33021. this._axisGroup = new Group();
  33022. this.group.add(this._axisGroup);
  33023. if (!axisModel.get('show')) {
  33024. return;
  33025. }
  33026. var gridModel = axisModel.getCoordSysModel();
  33027. var layout = layout$1(gridModel, axisModel);
  33028. var axisBuilder = new AxisBuilder(axisModel, layout);
  33029. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  33030. this._axisGroup.add(axisBuilder.getGroup());
  33031. each$1(selfBuilderAttrs, function (name) {
  33032. if (axisModel.get(name + '.show')) {
  33033. this['_' + name](axisModel, gridModel);
  33034. }
  33035. }, this);
  33036. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  33037. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  33038. },
  33039. remove: function () {
  33040. rectCoordAxisHandleRemove(this);
  33041. },
  33042. /**
  33043. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33044. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33045. * @private
  33046. */
  33047. _splitLine: function (axisModel, gridModel) {
  33048. var axis = axisModel.axis;
  33049. if (axis.scale.isBlank()) {
  33050. return;
  33051. }
  33052. var splitLineModel = axisModel.getModel('splitLine');
  33053. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33054. var lineColors = lineStyleModel.get('color');
  33055. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  33056. var gridRect = gridModel.coordinateSystem.getRect();
  33057. var isHorizontal = axis.isHorizontal();
  33058. var lineCount = 0;
  33059. var ticksCoords = axis.getTicksCoords({
  33060. tickModel: splitLineModel
  33061. });
  33062. var p1 = [];
  33063. var p2 = [];
  33064. var lineStyle = lineStyleModel.getLineStyle();
  33065. for (var i = 0; i < ticksCoords.length; i++) {
  33066. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33067. if (isHorizontal) {
  33068. p1[0] = tickCoord;
  33069. p1[1] = gridRect.y;
  33070. p2[0] = tickCoord;
  33071. p2[1] = gridRect.y + gridRect.height;
  33072. } else {
  33073. p1[0] = gridRect.x;
  33074. p1[1] = tickCoord;
  33075. p2[0] = gridRect.x + gridRect.width;
  33076. p2[1] = tickCoord;
  33077. }
  33078. var colorIndex = lineCount++ % lineColors.length;
  33079. var tickValue = ticksCoords[i].tickValue;
  33080. this._axisGroup.add(new Line({
  33081. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  33082. subPixelOptimize: true,
  33083. shape: {
  33084. x1: p1[0],
  33085. y1: p1[1],
  33086. x2: p2[0],
  33087. y2: p2[1]
  33088. },
  33089. style: defaults({
  33090. stroke: lineColors[colorIndex]
  33091. }, lineStyle),
  33092. silent: true
  33093. }));
  33094. }
  33095. },
  33096. /**
  33097. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33098. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33099. * @private
  33100. */
  33101. _minorSplitLine: function (axisModel, gridModel) {
  33102. var axis = axisModel.axis;
  33103. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  33104. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  33105. var gridRect = gridModel.coordinateSystem.getRect();
  33106. var isHorizontal = axis.isHorizontal();
  33107. var minorTicksCoords = axis.getMinorTicksCoords();
  33108. if (!minorTicksCoords.length) {
  33109. return;
  33110. }
  33111. var p1 = [];
  33112. var p2 = [];
  33113. var lineStyle = lineStyleModel.getLineStyle();
  33114. for (var i = 0; i < minorTicksCoords.length; i++) {
  33115. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  33116. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  33117. if (isHorizontal) {
  33118. p1[0] = tickCoord;
  33119. p1[1] = gridRect.y;
  33120. p2[0] = tickCoord;
  33121. p2[1] = gridRect.y + gridRect.height;
  33122. } else {
  33123. p1[0] = gridRect.x;
  33124. p1[1] = tickCoord;
  33125. p2[0] = gridRect.x + gridRect.width;
  33126. p2[1] = tickCoord;
  33127. }
  33128. this._axisGroup.add(new Line({
  33129. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  33130. subPixelOptimize: true,
  33131. shape: {
  33132. x1: p1[0],
  33133. y1: p1[1],
  33134. x2: p2[0],
  33135. y2: p2[1]
  33136. },
  33137. style: lineStyle,
  33138. silent: true
  33139. }));
  33140. }
  33141. }
  33142. },
  33143. /**
  33144. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33145. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33146. * @private
  33147. */
  33148. _splitArea: function (axisModel, gridModel) {
  33149. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  33150. }
  33151. });
  33152. CartesianAxisView.extend({
  33153. type: 'xAxis'
  33154. });
  33155. CartesianAxisView.extend({
  33156. type: 'yAxis'
  33157. });
  33158. /*
  33159. * Licensed to the Apache Software Foundation (ASF) under one
  33160. * or more contributor license agreements. See the NOTICE file
  33161. * distributed with this work for additional information
  33162. * regarding copyright ownership. The ASF licenses this file
  33163. * to you under the Apache License, Version 2.0 (the
  33164. * "License"); you may not use this file except in compliance
  33165. * with the License. You may obtain a copy of the License at
  33166. *
  33167. * http://www.apache.org/licenses/LICENSE-2.0
  33168. *
  33169. * Unless required by applicable law or agreed to in writing,
  33170. * software distributed under the License is distributed on an
  33171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33172. * KIND, either express or implied. See the License for the
  33173. * specific language governing permissions and limitations
  33174. * under the License.
  33175. */
  33176. /*
  33177. * Licensed to the Apache Software Foundation (ASF) under one
  33178. * or more contributor license agreements. See the NOTICE file
  33179. * distributed with this work for additional information
  33180. * regarding copyright ownership. The ASF licenses this file
  33181. * to you under the Apache License, Version 2.0 (the
  33182. * "License"); you may not use this file except in compliance
  33183. * with the License. You may obtain a copy of the License at
  33184. *
  33185. * http://www.apache.org/licenses/LICENSE-2.0
  33186. *
  33187. * Unless required by applicable law or agreed to in writing,
  33188. * software distributed under the License is distributed on an
  33189. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33190. * KIND, either express or implied. See the License for the
  33191. * specific language governing permissions and limitations
  33192. * under the License.
  33193. */
  33194. extendComponentView({
  33195. type: 'grid',
  33196. render: function (gridModel, ecModel) {
  33197. this.group.removeAll();
  33198. if (gridModel.get('show')) {
  33199. this.group.add(new Rect({
  33200. shape: gridModel.coordinateSystem.getRect(),
  33201. style: defaults({
  33202. fill: gridModel.get('backgroundColor')
  33203. }, gridModel.getItemStyle()),
  33204. silent: true,
  33205. z2: -1
  33206. }));
  33207. }
  33208. }
  33209. });
  33210. registerPreprocessor(function (option) {
  33211. // Only create grid when need
  33212. if (option.xAxis && option.yAxis && !option.grid) {
  33213. option.grid = {};
  33214. }
  33215. });
  33216. /*
  33217. * Licensed to the Apache Software Foundation (ASF) under one
  33218. * or more contributor license agreements. See the NOTICE file
  33219. * distributed with this work for additional information
  33220. * regarding copyright ownership. The ASF licenses this file
  33221. * to you under the Apache License, Version 2.0 (the
  33222. * "License"); you may not use this file except in compliance
  33223. * with the License. You may obtain a copy of the License at
  33224. *
  33225. * http://www.apache.org/licenses/LICENSE-2.0
  33226. *
  33227. * Unless required by applicable law or agreed to in writing,
  33228. * software distributed under the License is distributed on an
  33229. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33230. * KIND, either express or implied. See the License for the
  33231. * specific language governing permissions and limitations
  33232. * under the License.
  33233. */
  33234. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  33235. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  33236. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  33237. registerVisual({
  33238. seriesType: 'bar',
  33239. reset: function (seriesModel) {
  33240. // Visual coding for legend
  33241. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  33242. }
  33243. });
  33244. /*
  33245. * Licensed to the Apache Software Foundation (ASF) under one
  33246. * or more contributor license agreements. See the NOTICE file
  33247. * distributed with this work for additional information
  33248. * regarding copyright ownership. The ASF licenses this file
  33249. * to you under the Apache License, Version 2.0 (the
  33250. * "License"); you may not use this file except in compliance
  33251. * with the License. You may obtain a copy of the License at
  33252. *
  33253. * http://www.apache.org/licenses/LICENSE-2.0
  33254. *
  33255. * Unless required by applicable law or agreed to in writing,
  33256. * software distributed under the License is distributed on an
  33257. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33258. * KIND, either express or implied. See the License for the
  33259. * specific language governing permissions and limitations
  33260. * under the License.
  33261. */
  33262. SeriesModel.extend({
  33263. type: 'series.line',
  33264. dependencies: ['grid', 'polar'],
  33265. getInitialData: function (option, ecModel) {
  33266. return createListFromArray(this.getSource(), this, {
  33267. useEncodeDefaulter: true
  33268. });
  33269. },
  33270. defaultOption: {
  33271. zlevel: 0,
  33272. z: 2,
  33273. coordinateSystem: 'cartesian2d',
  33274. legendHoverLink: true,
  33275. hoverAnimation: true,
  33276. // stack: null
  33277. // xAxisIndex: 0,
  33278. // yAxisIndex: 0,
  33279. // polarIndex: 0,
  33280. // If clip the overflow value
  33281. clip: true,
  33282. // cursor: null,
  33283. label: {
  33284. position: 'top'
  33285. },
  33286. // itemStyle: {
  33287. // },
  33288. lineStyle: {
  33289. width: 2,
  33290. type: 'solid'
  33291. },
  33292. // areaStyle: {
  33293. // origin of areaStyle. Valid values:
  33294. // `'auto'/null/undefined`: from axisLine to data
  33295. // `'start'`: from min to data
  33296. // `'end'`: from data to max
  33297. // origin: 'auto'
  33298. // },
  33299. // false, 'start', 'end', 'middle'
  33300. step: false,
  33301. // Disabled if step is true
  33302. smooth: false,
  33303. smoothMonotone: null,
  33304. symbol: 'emptyCircle',
  33305. symbolSize: 4,
  33306. symbolRotate: null,
  33307. showSymbol: true,
  33308. // `false`: follow the label interval strategy.
  33309. // `true`: show all symbols.
  33310. // `'auto'`: If possible, show all symbols, otherwise
  33311. // follow the label interval strategy.
  33312. showAllSymbol: 'auto',
  33313. // Whether to connect break point.
  33314. connectNulls: false,
  33315. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  33316. sampling: 'none',
  33317. animationEasing: 'linear',
  33318. // Disable progressive
  33319. progressive: 0,
  33320. hoverLayerThreshold: Infinity
  33321. }
  33322. });
  33323. /*
  33324. * Licensed to the Apache Software Foundation (ASF) under one
  33325. * or more contributor license agreements. See the NOTICE file
  33326. * distributed with this work for additional information
  33327. * regarding copyright ownership. The ASF licenses this file
  33328. * to you under the Apache License, Version 2.0 (the
  33329. * "License"); you may not use this file except in compliance
  33330. * with the License. You may obtain a copy of the License at
  33331. *
  33332. * http://www.apache.org/licenses/LICENSE-2.0
  33333. *
  33334. * Unless required by applicable law or agreed to in writing,
  33335. * software distributed under the License is distributed on an
  33336. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33337. * KIND, either express or implied. See the License for the
  33338. * specific language governing permissions and limitations
  33339. * under the License.
  33340. */
  33341. /**
  33342. * @module echarts/chart/helper/Symbol
  33343. */
  33344. /**
  33345. * @constructor
  33346. * @alias {module:echarts/chart/helper/Symbol}
  33347. * @param {module:echarts/data/List} data
  33348. * @param {number} idx
  33349. * @extends {module:zrender/graphic/Group}
  33350. */
  33351. function SymbolClz$1(data, idx, seriesScope) {
  33352. Group.call(this);
  33353. this.updateData(data, idx, seriesScope);
  33354. }
  33355. var symbolProto = SymbolClz$1.prototype;
  33356. /**
  33357. * @public
  33358. * @static
  33359. * @param {module:echarts/data/List} data
  33360. * @param {number} dataIndex
  33361. * @return {Array.<number>} [width, height]
  33362. */
  33363. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  33364. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  33365. return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  33366. };
  33367. function getScale(symbolSize) {
  33368. return [symbolSize[0] / 2, symbolSize[1] / 2];
  33369. }
  33370. function driftSymbol(dx, dy) {
  33371. this.parent.drift(dx, dy);
  33372. }
  33373. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  33374. // Remove paths created before
  33375. this.removeAll();
  33376. var color = data.getItemVisual(idx, 'color'); // var symbolPath = createSymbol(
  33377. // symbolType, -0.5, -0.5, 1, 1, color
  33378. // );
  33379. // If width/height are set too small (e.g., set to 1) on ios10
  33380. // and macOS Sierra, a circle stroke become a rect, no matter what
  33381. // the scale is set. So we set width/height as 2. See #4150.
  33382. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, color, keepAspect);
  33383. symbolPath.attr({
  33384. z2: 100,
  33385. culling: true,
  33386. scale: getScale(symbolSize)
  33387. }); // Rewrite drift method
  33388. symbolPath.drift = driftSymbol;
  33389. this._symbolType = symbolType;
  33390. this.add(symbolPath);
  33391. };
  33392. /**
  33393. * Stop animation
  33394. * @param {boolean} toLastFrame
  33395. */
  33396. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  33397. this.childAt(0).stopAnimation(toLastFrame);
  33398. };
  33399. /**
  33400. * FIXME:
  33401. * Caution: This method breaks the encapsulation of this module,
  33402. * but it indeed brings convenience. So do not use the method
  33403. * unless you detailedly know all the implements of `Symbol`,
  33404. * especially animation.
  33405. *
  33406. * Get symbol path element.
  33407. */
  33408. symbolProto.getSymbolPath = function () {
  33409. return this.childAt(0);
  33410. };
  33411. /**
  33412. * Get scale(aka, current symbol size).
  33413. * Including the change caused by animation
  33414. */
  33415. symbolProto.getScale = function () {
  33416. return this.childAt(0).scale;
  33417. };
  33418. /**
  33419. * Highlight symbol
  33420. */
  33421. symbolProto.highlight = function () {
  33422. this.childAt(0).trigger('emphasis');
  33423. };
  33424. /**
  33425. * Downplay symbol
  33426. */
  33427. symbolProto.downplay = function () {
  33428. this.childAt(0).trigger('normal');
  33429. };
  33430. /**
  33431. * @param {number} zlevel
  33432. * @param {number} z
  33433. */
  33434. symbolProto.setZ = function (zlevel, z) {
  33435. var symbolPath = this.childAt(0);
  33436. symbolPath.zlevel = zlevel;
  33437. symbolPath.z = z;
  33438. };
  33439. symbolProto.setDraggable = function (draggable) {
  33440. var symbolPath = this.childAt(0);
  33441. symbolPath.draggable = draggable;
  33442. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  33443. };
  33444. /**
  33445. * Update symbol properties
  33446. * @param {module:echarts/data/List} data
  33447. * @param {number} idx
  33448. * @param {Object} [seriesScope]
  33449. * @param {Object} [seriesScope.itemStyle]
  33450. * @param {Object} [seriesScope.hoverItemStyle]
  33451. * @param {Object} [seriesScope.symbolRotate]
  33452. * @param {Object} [seriesScope.symbolOffset]
  33453. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  33454. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  33455. * @param {boolean} [seriesScope.hoverAnimation]
  33456. * @param {Object} [seriesScope.cursorStyle]
  33457. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  33458. * @param {string} [seriesScope.symbolInnerColor]
  33459. * @param {Object} [seriesScope.fadeIn=false]
  33460. */
  33461. symbolProto.updateData = function (data, idx, seriesScope) {
  33462. this.silent = false;
  33463. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33464. var seriesModel = data.hostModel;
  33465. var symbolSize = getSymbolSize(data, idx);
  33466. var isInit = symbolType !== this._symbolType;
  33467. if (isInit) {
  33468. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  33469. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  33470. } else {
  33471. var symbolPath = this.childAt(0);
  33472. symbolPath.silent = false;
  33473. updateProps(symbolPath, {
  33474. scale: getScale(symbolSize)
  33475. }, seriesModel, idx);
  33476. }
  33477. this._updateCommon(data, idx, symbolSize, seriesScope);
  33478. if (isInit) {
  33479. var symbolPath = this.childAt(0);
  33480. var fadeIn = seriesScope && seriesScope.fadeIn;
  33481. var target = {
  33482. scale: symbolPath.scale.slice()
  33483. };
  33484. fadeIn && (target.style = {
  33485. opacity: symbolPath.style.opacity
  33486. });
  33487. symbolPath.scale = [0, 0];
  33488. fadeIn && (symbolPath.style.opacity = 0);
  33489. initProps(symbolPath, target, seriesModel, idx);
  33490. }
  33491. this._seriesModel = seriesModel;
  33492. }; // Update common properties
  33493. var normalStyleAccessPath = ['itemStyle'];
  33494. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  33495. var normalLabelAccessPath = ['label'];
  33496. var emphasisLabelAccessPath = ['emphasis', 'label'];
  33497. /**
  33498. * @param {module:echarts/data/List} data
  33499. * @param {number} idx
  33500. * @param {Array.<number>} symbolSize
  33501. * @param {Object} [seriesScope]
  33502. */
  33503. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  33504. var symbolPath = this.childAt(0);
  33505. var seriesModel = data.hostModel;
  33506. var color = data.getItemVisual(idx, 'color'); // Reset style
  33507. if (symbolPath.type !== 'image') {
  33508. symbolPath.useStyle({
  33509. strokeNoScale: true
  33510. });
  33511. } else {
  33512. symbolPath.setStyle({
  33513. opacity: null,
  33514. shadowBlur: null,
  33515. shadowOffsetX: null,
  33516. shadowOffsetY: null,
  33517. shadowColor: null
  33518. });
  33519. }
  33520. var itemStyle = seriesScope && seriesScope.itemStyle;
  33521. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  33522. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  33523. var labelModel = seriesScope && seriesScope.labelModel;
  33524. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  33525. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  33526. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  33527. if (!seriesScope || data.hasItemOption) {
  33528. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx); // Color must be excluded.
  33529. // Because symbol provide setColor individually to set fill and stroke
  33530. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  33531. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  33532. symbolOffset = itemModel.getShallow('symbolOffset');
  33533. labelModel = itemModel.getModel(normalLabelAccessPath);
  33534. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  33535. hoverAnimation = itemModel.getShallow('hoverAnimation');
  33536. cursorStyle = itemModel.getShallow('cursor');
  33537. } else {
  33538. hoverItemStyle = extend({}, hoverItemStyle);
  33539. }
  33540. var elStyle = symbolPath.style;
  33541. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  33542. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  33543. if (symbolOffset) {
  33544. symbolPath.attr('position', [parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1])]);
  33545. }
  33546. cursorStyle && symbolPath.attr('cursor', cursorStyle); // PENDING setColor before setStyle!!!
  33547. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  33548. symbolPath.setStyle(itemStyle);
  33549. var opacity = data.getItemVisual(idx, 'opacity');
  33550. if (opacity != null) {
  33551. elStyle.opacity = opacity;
  33552. }
  33553. var liftZ = data.getItemVisual(idx, 'liftZ');
  33554. var z2Origin = symbolPath.__z2Origin;
  33555. if (liftZ != null) {
  33556. if (z2Origin == null) {
  33557. symbolPath.__z2Origin = symbolPath.z2;
  33558. symbolPath.z2 += liftZ;
  33559. }
  33560. } else if (z2Origin != null) {
  33561. symbolPath.z2 = z2Origin;
  33562. symbolPath.__z2Origin = null;
  33563. }
  33564. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  33565. setLabelStyle(elStyle, hoverItemStyle, labelModel, hoverLabelModel, {
  33566. labelFetcher: seriesModel,
  33567. labelDataIndex: idx,
  33568. defaultText: getLabelDefaultText,
  33569. isRectText: true,
  33570. autoColor: color
  33571. }); // Do not execute util needed.
  33572. function getLabelDefaultText(idx, opt) {
  33573. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  33574. }
  33575. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  33576. symbolPath.hoverStyle = hoverItemStyle;
  33577. symbolPath.highDownOnUpdate = hoverAnimation && seriesModel.isAnimationEnabled() ? highDownOnUpdate : null;
  33578. setHoverStyle(symbolPath);
  33579. };
  33580. function highDownOnUpdate(fromState, toState) {
  33581. // Do not support this hover animation util some scenario required.
  33582. // Animation can only be supported in hover layer when using `el.incremetal`.
  33583. if (this.incremental || this.useHoverLayer) {
  33584. return;
  33585. }
  33586. if (toState === 'emphasis') {
  33587. var scale = this.__symbolOriginalScale;
  33588. var ratio = scale[1] / scale[0];
  33589. var emphasisOpt = {
  33590. scale: [Math.max(scale[0] * 1.1, scale[0] + 3), Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)]
  33591. }; // FIXME
  33592. // modify it after support stop specified animation.
  33593. // toState === fromState
  33594. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  33595. this.animateTo(emphasisOpt, 400, 'elasticOut');
  33596. } else if (toState === 'normal') {
  33597. this.animateTo({
  33598. scale: this.__symbolOriginalScale
  33599. }, 400, 'elasticOut');
  33600. }
  33601. }
  33602. /**
  33603. * @param {Function} cb
  33604. * @param {Object} [opt]
  33605. * @param {Object} [opt.keepLabel=true]
  33606. */
  33607. symbolProto.fadeOut = function (cb, opt) {
  33608. var symbolPath = this.childAt(0); // Avoid mistaken hover when fading out
  33609. this.silent = symbolPath.silent = true; // Not show text when animating
  33610. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  33611. updateProps(symbolPath, {
  33612. style: {
  33613. opacity: 0
  33614. },
  33615. scale: [0, 0]
  33616. }, this._seriesModel, this.dataIndex, cb);
  33617. };
  33618. inherits(SymbolClz$1, Group);
  33619. /*
  33620. * Licensed to the Apache Software Foundation (ASF) under one
  33621. * or more contributor license agreements. See the NOTICE file
  33622. * distributed with this work for additional information
  33623. * regarding copyright ownership. The ASF licenses this file
  33624. * to you under the Apache License, Version 2.0 (the
  33625. * "License"); you may not use this file except in compliance
  33626. * with the License. You may obtain a copy of the License at
  33627. *
  33628. * http://www.apache.org/licenses/LICENSE-2.0
  33629. *
  33630. * Unless required by applicable law or agreed to in writing,
  33631. * software distributed under the License is distributed on an
  33632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33633. * KIND, either express or implied. See the License for the
  33634. * specific language governing permissions and limitations
  33635. * under the License.
  33636. */
  33637. /**
  33638. * @module echarts/chart/helper/SymbolDraw
  33639. */
  33640. /**
  33641. * @constructor
  33642. * @alias module:echarts/chart/helper/SymbolDraw
  33643. * @param {module:zrender/graphic/Group} [symbolCtor]
  33644. */
  33645. function SymbolDraw(symbolCtor) {
  33646. this.group = new Group();
  33647. this._symbolCtor = symbolCtor || SymbolClz$1;
  33648. }
  33649. var symbolDrawProto = SymbolDraw.prototype;
  33650. function symbolNeedsDraw(data, point, idx, opt) {
  33651. 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
  33652. // the symbol element shape. We use the same clip shape here as
  33653. // the line clip.
  33654. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  33655. }
  33656. /**
  33657. * Update symbols draw by new data
  33658. * @param {module:echarts/data/List} data
  33659. * @param {Object} [opt] Or isIgnore
  33660. * @param {Function} [opt.isIgnore]
  33661. * @param {Object} [opt.clipShape]
  33662. */
  33663. symbolDrawProto.updateData = function (data, opt) {
  33664. opt = normalizeUpdateOpt(opt);
  33665. var group = this.group;
  33666. var seriesModel = data.hostModel;
  33667. var oldData = this._data;
  33668. var SymbolCtor = this._symbolCtor;
  33669. var seriesScope = makeSeriesScope(data); // There is no oldLineData only when first rendering or switching from
  33670. // stream mode to normal mode, where previous elements should be removed.
  33671. if (!oldData) {
  33672. group.removeAll();
  33673. }
  33674. data.diff(oldData).add(function (newIdx) {
  33675. var point = data.getItemLayout(newIdx);
  33676. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33677. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  33678. symbolEl.attr('position', point);
  33679. data.setItemGraphicEl(newIdx, symbolEl);
  33680. group.add(symbolEl);
  33681. }
  33682. }).update(function (newIdx, oldIdx) {
  33683. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33684. var point = data.getItemLayout(newIdx);
  33685. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33686. group.remove(symbolEl);
  33687. return;
  33688. }
  33689. if (!symbolEl) {
  33690. symbolEl = new SymbolCtor(data, newIdx);
  33691. symbolEl.attr('position', point);
  33692. } else {
  33693. symbolEl.updateData(data, newIdx, seriesScope);
  33694. updateProps(symbolEl, {
  33695. position: point
  33696. }, seriesModel);
  33697. } // Add back
  33698. group.add(symbolEl);
  33699. data.setItemGraphicEl(newIdx, symbolEl);
  33700. }).remove(function (oldIdx) {
  33701. var el = oldData.getItemGraphicEl(oldIdx);
  33702. el && el.fadeOut(function () {
  33703. group.remove(el);
  33704. });
  33705. }).execute();
  33706. this._data = data;
  33707. };
  33708. symbolDrawProto.isPersistent = function () {
  33709. return true;
  33710. };
  33711. symbolDrawProto.updateLayout = function () {
  33712. var data = this._data;
  33713. if (data) {
  33714. // Not use animation
  33715. data.eachItemGraphicEl(function (el, idx) {
  33716. var point = data.getItemLayout(idx);
  33717. el.attr('position', point);
  33718. });
  33719. }
  33720. };
  33721. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33722. this._seriesScope = makeSeriesScope(data);
  33723. this._data = null;
  33724. this.group.removeAll();
  33725. };
  33726. /**
  33727. * Update symbols draw by new data
  33728. * @param {module:echarts/data/List} data
  33729. * @param {Object} [opt] Or isIgnore
  33730. * @param {Function} [opt.isIgnore]
  33731. * @param {Object} [opt.clipShape]
  33732. */
  33733. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33734. opt = normalizeUpdateOpt(opt);
  33735. function updateIncrementalAndHover(el) {
  33736. if (!el.isGroup) {
  33737. el.incremental = el.useHoverLayer = true;
  33738. }
  33739. }
  33740. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33741. var point = data.getItemLayout(idx);
  33742. if (symbolNeedsDraw(data, point, idx, opt)) {
  33743. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33744. el.traverse(updateIncrementalAndHover);
  33745. el.attr('position', point);
  33746. this.group.add(el);
  33747. data.setItemGraphicEl(idx, el);
  33748. }
  33749. }
  33750. };
  33751. function normalizeUpdateOpt(opt) {
  33752. if (opt != null && !isObject$1(opt)) {
  33753. opt = {
  33754. isIgnore: opt
  33755. };
  33756. }
  33757. return opt || {};
  33758. }
  33759. symbolDrawProto.remove = function (enableAnimation) {
  33760. var group = this.group;
  33761. var data = this._data; // Incremental model do not have this._data.
  33762. if (data && enableAnimation) {
  33763. data.eachItemGraphicEl(function (el) {
  33764. el.fadeOut(function () {
  33765. group.remove(el);
  33766. });
  33767. });
  33768. } else {
  33769. group.removeAll();
  33770. }
  33771. };
  33772. function makeSeriesScope(data) {
  33773. var seriesModel = data.hostModel;
  33774. return {
  33775. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33776. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33777. symbolRotate: seriesModel.get('symbolRotate'),
  33778. symbolOffset: seriesModel.get('symbolOffset'),
  33779. hoverAnimation: seriesModel.get('hoverAnimation'),
  33780. labelModel: seriesModel.getModel('label'),
  33781. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33782. cursorStyle: seriesModel.get('cursor')
  33783. };
  33784. }
  33785. /*
  33786. * Licensed to the Apache Software Foundation (ASF) under one
  33787. * or more contributor license agreements. See the NOTICE file
  33788. * distributed with this work for additional information
  33789. * regarding copyright ownership. The ASF licenses this file
  33790. * to you under the Apache License, Version 2.0 (the
  33791. * "License"); you may not use this file except in compliance
  33792. * with the License. You may obtain a copy of the License at
  33793. *
  33794. * http://www.apache.org/licenses/LICENSE-2.0
  33795. *
  33796. * Unless required by applicable law or agreed to in writing,
  33797. * software distributed under the License is distributed on an
  33798. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33799. * KIND, either express or implied. See the License for the
  33800. * specific language governing permissions and limitations
  33801. * under the License.
  33802. */
  33803. /**
  33804. * @param {Object} coordSys
  33805. * @param {module:echarts/data/List} data
  33806. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33807. */
  33808. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33809. var baseAxis = coordSys.getBaseAxis();
  33810. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33811. var valueStart = getValueStart(valueAxis, valueOrigin);
  33812. var baseAxisDim = baseAxis.dim;
  33813. var valueAxisDim = valueAxis.dim;
  33814. var valueDim = data.mapDimension(valueAxisDim);
  33815. var baseDim = data.mapDimension(baseAxisDim);
  33816. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33817. var dims = map(coordSys.dimensions, function (coordDim) {
  33818. return data.mapDimension(coordDim);
  33819. });
  33820. var stacked;
  33821. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33822. if (stacked |= isDimensionStacked(data, dims[0]
  33823. /*, dims[1]*/
  33824. )) {
  33825. // jshint ignore:line
  33826. dims[0] = stackResultDim;
  33827. }
  33828. if (stacked |= isDimensionStacked(data, dims[1]
  33829. /*, dims[0]*/
  33830. )) {
  33831. // jshint ignore:line
  33832. dims[1] = stackResultDim;
  33833. }
  33834. return {
  33835. dataDimsForPoint: dims,
  33836. valueStart: valueStart,
  33837. valueAxisDim: valueAxisDim,
  33838. baseAxisDim: baseAxisDim,
  33839. stacked: !!stacked,
  33840. valueDim: valueDim,
  33841. baseDim: baseDim,
  33842. baseDataOffset: baseDataOffset,
  33843. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33844. };
  33845. }
  33846. function getValueStart(valueAxis, valueOrigin) {
  33847. var valueStart = 0;
  33848. var extent = valueAxis.scale.getExtent();
  33849. if (valueOrigin === 'start') {
  33850. valueStart = extent[0];
  33851. } else if (valueOrigin === 'end') {
  33852. valueStart = extent[1];
  33853. } // auto
  33854. else {
  33855. // Both positive
  33856. if (extent[0] > 0) {
  33857. valueStart = extent[0];
  33858. } // Both negative
  33859. else if (extent[1] < 0) {
  33860. valueStart = extent[1];
  33861. } // If is one positive, and one negative, onZero shall be true
  33862. }
  33863. return valueStart;
  33864. }
  33865. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  33866. var value = NaN;
  33867. if (dataCoordInfo.stacked) {
  33868. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  33869. }
  33870. if (isNaN(value)) {
  33871. value = dataCoordInfo.valueStart;
  33872. }
  33873. var baseDataOffset = dataCoordInfo.baseDataOffset;
  33874. var stackedData = [];
  33875. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  33876. stackedData[1 - baseDataOffset] = value;
  33877. return coordSys.dataToPoint(stackedData);
  33878. }
  33879. /*
  33880. * Licensed to the Apache Software Foundation (ASF) under one
  33881. * or more contributor license agreements. See the NOTICE file
  33882. * distributed with this work for additional information
  33883. * regarding copyright ownership. The ASF licenses this file
  33884. * to you under the Apache License, Version 2.0 (the
  33885. * "License"); you may not use this file except in compliance
  33886. * with the License. You may obtain a copy of the License at
  33887. *
  33888. * http://www.apache.org/licenses/LICENSE-2.0
  33889. *
  33890. * Unless required by applicable law or agreed to in writing,
  33891. * software distributed under the License is distributed on an
  33892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33893. * KIND, either express or implied. See the License for the
  33894. * specific language governing permissions and limitations
  33895. * under the License.
  33896. */
  33897. // 'zrender/src/core/arrayDiff' has been used before, but it did
  33898. // not do well in performance when roam with fixed dataZoom window.
  33899. // function convertToIntId(newIdList, oldIdList) {
  33900. // // Generate int id instead of string id.
  33901. // // Compare string maybe slow in score function of arrDiff
  33902. // // Assume id in idList are all unique
  33903. // var idIndicesMap = {};
  33904. // var idx = 0;
  33905. // for (var i = 0; i < newIdList.length; i++) {
  33906. // idIndicesMap[newIdList[i]] = idx;
  33907. // newIdList[i] = idx++;
  33908. // }
  33909. // for (var i = 0; i < oldIdList.length; i++) {
  33910. // var oldId = oldIdList[i];
  33911. // // Same with newIdList
  33912. // if (idIndicesMap[oldId]) {
  33913. // oldIdList[i] = idIndicesMap[oldId];
  33914. // }
  33915. // else {
  33916. // oldIdList[i] = idx++;
  33917. // }
  33918. // }
  33919. // }
  33920. function diffData(oldData, newData) {
  33921. var diffResult = [];
  33922. newData.diff(oldData).add(function (idx) {
  33923. diffResult.push({
  33924. cmd: '+',
  33925. idx: idx
  33926. });
  33927. }).update(function (newIdx, oldIdx) {
  33928. diffResult.push({
  33929. cmd: '=',
  33930. idx: oldIdx,
  33931. idx1: newIdx
  33932. });
  33933. }).remove(function (idx) {
  33934. diffResult.push({
  33935. cmd: '-',
  33936. idx: idx
  33937. });
  33938. }).execute();
  33939. return diffResult;
  33940. }
  33941. var lineAnimationDiff = function (oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  33942. var diff = diffData(oldData, newData); // var newIdList = newData.mapArray(newData.getId);
  33943. // var oldIdList = oldData.mapArray(oldData.getId);
  33944. // convertToIntId(newIdList, oldIdList);
  33945. // // FIXME One data ?
  33946. // diff = arrayDiff(oldIdList, newIdList);
  33947. var currPoints = [];
  33948. var nextPoints = []; // Points for stacking base line
  33949. var currStackedPoints = [];
  33950. var nextStackedPoints = [];
  33951. var status = [];
  33952. var sortedIndices = [];
  33953. var rawIndices = [];
  33954. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  33955. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  33956. for (var i = 0; i < diff.length; i++) {
  33957. var diffItem = diff[i];
  33958. var pointAdded = true; // FIXME, animation is not so perfect when dataZoom window moves fast
  33959. // Which is in case remvoing or add more than one data in the tail or head
  33960. switch (diffItem.cmd) {
  33961. case '=':
  33962. var currentPt = oldData.getItemLayout(diffItem.idx);
  33963. var nextPt = newData.getItemLayout(diffItem.idx1); // If previous data is NaN, use next point directly
  33964. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  33965. currentPt = nextPt.slice();
  33966. }
  33967. currPoints.push(currentPt);
  33968. nextPoints.push(nextPt);
  33969. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  33970. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  33971. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  33972. break;
  33973. case '+':
  33974. var idx = diffItem.idx;
  33975. currPoints.push(oldCoordSys.dataToPoint([newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx), newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)]));
  33976. nextPoints.push(newData.getItemLayout(idx).slice());
  33977. currStackedPoints.push(getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx));
  33978. nextStackedPoints.push(newStackedOnPoints[idx]);
  33979. rawIndices.push(newData.getRawIndex(idx));
  33980. break;
  33981. case '-':
  33982. var idx = diffItem.idx;
  33983. var rawIndex = oldData.getRawIndex(idx); // Data is replaced. In the case of dynamic data queue
  33984. // FIXME FIXME FIXME
  33985. if (rawIndex !== idx) {
  33986. currPoints.push(oldData.getItemLayout(idx));
  33987. nextPoints.push(newCoordSys.dataToPoint([oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx), oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)]));
  33988. currStackedPoints.push(oldStackedOnPoints[idx]);
  33989. nextStackedPoints.push(getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx));
  33990. rawIndices.push(rawIndex);
  33991. } else {
  33992. pointAdded = false;
  33993. }
  33994. } // Original indices
  33995. if (pointAdded) {
  33996. status.push(diffItem);
  33997. sortedIndices.push(sortedIndices.length);
  33998. }
  33999. } // Diff result may be crossed if all items are changed
  34000. // Sort by data index
  34001. sortedIndices.sort(function (a, b) {
  34002. return rawIndices[a] - rawIndices[b];
  34003. });
  34004. var sortedCurrPoints = [];
  34005. var sortedNextPoints = [];
  34006. var sortedCurrStackedPoints = [];
  34007. var sortedNextStackedPoints = [];
  34008. var sortedStatus = [];
  34009. for (var i = 0; i < sortedIndices.length; i++) {
  34010. var idx = sortedIndices[i];
  34011. sortedCurrPoints[i] = currPoints[idx];
  34012. sortedNextPoints[i] = nextPoints[idx];
  34013. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  34014. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  34015. sortedStatus[i] = status[idx];
  34016. }
  34017. return {
  34018. current: sortedCurrPoints,
  34019. next: sortedNextPoints,
  34020. stackedOnCurrent: sortedCurrStackedPoints,
  34021. stackedOnNext: sortedNextStackedPoints,
  34022. status: sortedStatus
  34023. };
  34024. };
  34025. /*
  34026. * Licensed to the Apache Software Foundation (ASF) under one
  34027. * or more contributor license agreements. See the NOTICE file
  34028. * distributed with this work for additional information
  34029. * regarding copyright ownership. The ASF licenses this file
  34030. * to you under the Apache License, Version 2.0 (the
  34031. * "License"); you may not use this file except in compliance
  34032. * with the License. You may obtain a copy of the License at
  34033. *
  34034. * http://www.apache.org/licenses/LICENSE-2.0
  34035. *
  34036. * Unless required by applicable law or agreed to in writing,
  34037. * software distributed under the License is distributed on an
  34038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34039. * KIND, either express or implied. See the License for the
  34040. * specific language governing permissions and limitations
  34041. * under the License.
  34042. */
  34043. // Poly path support NaN point
  34044. var vec2Min = min;
  34045. var vec2Max = max;
  34046. var scaleAndAdd$1 = scaleAndAdd;
  34047. var v2Copy = copy; // Temporary variable
  34048. var v = [];
  34049. var cp0 = [];
  34050. var cp1 = [];
  34051. function isPointNull(p) {
  34052. return isNaN(p[0]) || isNaN(p[1]);
  34053. }
  34054. function drawSegment(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34055. // if (smoothMonotone == null) {
  34056. // if (isMono(points, 'x')) {
  34057. // return drawMono(ctx, points, start, segLen, allLen,
  34058. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  34059. // }
  34060. // else if (isMono(points, 'y')) {
  34061. // return drawMono(ctx, points, start, segLen, allLen,
  34062. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  34063. // }
  34064. // else {
  34065. // return drawNonMono.apply(this, arguments);
  34066. // }
  34067. // }
  34068. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  34069. // return drawMono.apply(this, arguments);
  34070. // }
  34071. // else {
  34072. // return drawNonMono.apply(this, arguments);
  34073. // }
  34074. if (smoothMonotone === 'none' || !smoothMonotone) {
  34075. return drawNonMono.apply(this, arguments);
  34076. } else {
  34077. return drawMono.apply(this, arguments);
  34078. }
  34079. }
  34080. /**
  34081. * Check if points is in monotone.
  34082. *
  34083. * @param {number[][]} points Array of points which is in [x, y] form
  34084. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  34085. * dimension that is checking.
  34086. * If is 'none', `drawNonMono` should be
  34087. * called.
  34088. * If is undefined, either being monotone
  34089. * in 'x' or 'y' will call `drawMono`.
  34090. */
  34091. // function isMono(points, smoothMonotone) {
  34092. // if (points.length <= 1) {
  34093. // return true;
  34094. // }
  34095. // var dim = smoothMonotone === 'x' ? 0 : 1;
  34096. // var last = points[0][dim];
  34097. // var lastDiff = 0;
  34098. // for (var i = 1; i < points.length; ++i) {
  34099. // var diff = points[i][dim] - last;
  34100. // if (!isNaN(diff) && !isNaN(lastDiff)
  34101. // && diff !== 0 && lastDiff !== 0
  34102. // && ((diff >= 0) !== (lastDiff >= 0))
  34103. // ) {
  34104. // return false;
  34105. // }
  34106. // if (!isNaN(diff) && diff !== 0) {
  34107. // lastDiff = diff;
  34108. // last = points[i][dim];
  34109. // }
  34110. // }
  34111. // return true;
  34112. // }
  34113. /**
  34114. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  34115. * control points will be used. This should be used when points are monotone
  34116. * either in x or y dimension.
  34117. */
  34118. function drawMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34119. var prevIdx = 0;
  34120. var idx = start;
  34121. for (var k = 0; k < segLen; k++) {
  34122. var p = points[idx];
  34123. if (idx >= allLen || idx < 0) {
  34124. break;
  34125. }
  34126. if (isPointNull(p)) {
  34127. if (connectNulls) {
  34128. idx += dir;
  34129. continue;
  34130. }
  34131. break;
  34132. }
  34133. if (idx === start) {
  34134. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  34135. } else {
  34136. if (smooth > 0) {
  34137. var prevP = points[prevIdx];
  34138. var dim = smoothMonotone === 'y' ? 1 : 0; // Length of control point to p, either in x or y, but not both
  34139. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  34140. v2Copy(cp0, prevP);
  34141. cp0[dim] = prevP[dim] + ctrlLen;
  34142. v2Copy(cp1, p);
  34143. cp1[dim] = p[dim] - ctrlLen;
  34144. ctx.bezierCurveTo(cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1]);
  34145. } else {
  34146. ctx.lineTo(p[0], p[1]);
  34147. }
  34148. }
  34149. prevIdx = idx;
  34150. idx += dir;
  34151. }
  34152. return k;
  34153. }
  34154. /**
  34155. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  34156. * situations. This should be used when points are non-monotone neither in x or
  34157. * y dimension.
  34158. */
  34159. function drawNonMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34160. var prevIdx = 0;
  34161. var idx = start;
  34162. for (var k = 0; k < segLen; k++) {
  34163. var p = points[idx];
  34164. if (idx >= allLen || idx < 0) {
  34165. break;
  34166. }
  34167. if (isPointNull(p)) {
  34168. if (connectNulls) {
  34169. idx += dir;
  34170. continue;
  34171. }
  34172. break;
  34173. }
  34174. if (idx === start) {
  34175. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  34176. v2Copy(cp0, p);
  34177. } else {
  34178. if (smooth > 0) {
  34179. var nextIdx = idx + dir;
  34180. var nextP = points[nextIdx];
  34181. if (connectNulls) {
  34182. // Find next point not null
  34183. while (nextP && isPointNull(points[nextIdx])) {
  34184. nextIdx += dir;
  34185. nextP = points[nextIdx];
  34186. }
  34187. }
  34188. var ratioNextSeg = 0.5;
  34189. var prevP = points[prevIdx];
  34190. var nextP = points[nextIdx]; // Last point
  34191. if (!nextP || isPointNull(nextP)) {
  34192. v2Copy(cp1, p);
  34193. } else {
  34194. // If next data is null in not connect case
  34195. if (isPointNull(nextP) && !connectNulls) {
  34196. nextP = p;
  34197. }
  34198. sub(v, nextP, prevP);
  34199. var lenPrevSeg;
  34200. var lenNextSeg;
  34201. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  34202. var dim = smoothMonotone === 'x' ? 0 : 1;
  34203. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  34204. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  34205. } else {
  34206. lenPrevSeg = dist(p, prevP);
  34207. lenNextSeg = dist(p, nextP);
  34208. } // Use ratio of seg length
  34209. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  34210. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  34211. } // Smooth constraint
  34212. vec2Min(cp0, cp0, smoothMax);
  34213. vec2Max(cp0, cp0, smoothMin);
  34214. vec2Min(cp1, cp1, smoothMax);
  34215. vec2Max(cp1, cp1, smoothMin);
  34216. ctx.bezierCurveTo(cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1]); // cp0 of next segment
  34217. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  34218. } else {
  34219. ctx.lineTo(p[0], p[1]);
  34220. }
  34221. }
  34222. prevIdx = idx;
  34223. idx += dir;
  34224. }
  34225. return k;
  34226. }
  34227. function getBoundingBox(points, smoothConstraint) {
  34228. var ptMin = [Infinity, Infinity];
  34229. var ptMax = [-Infinity, -Infinity];
  34230. if (smoothConstraint) {
  34231. for (var i = 0; i < points.length; i++) {
  34232. var pt = points[i];
  34233. if (pt[0] < ptMin[0]) {
  34234. ptMin[0] = pt[0];
  34235. }
  34236. if (pt[1] < ptMin[1]) {
  34237. ptMin[1] = pt[1];
  34238. }
  34239. if (pt[0] > ptMax[0]) {
  34240. ptMax[0] = pt[0];
  34241. }
  34242. if (pt[1] > ptMax[1]) {
  34243. ptMax[1] = pt[1];
  34244. }
  34245. }
  34246. }
  34247. return {
  34248. min: smoothConstraint ? ptMin : ptMax,
  34249. max: smoothConstraint ? ptMax : ptMin
  34250. };
  34251. }
  34252. var Polyline$1 = Path.extend({
  34253. type: 'ec-polyline',
  34254. shape: {
  34255. points: [],
  34256. smooth: 0,
  34257. smoothConstraint: true,
  34258. smoothMonotone: null,
  34259. connectNulls: false
  34260. },
  34261. style: {
  34262. fill: null,
  34263. stroke: '#000'
  34264. },
  34265. brush: fixClipWithShadow(Path.prototype.brush),
  34266. buildPath: function (ctx, shape) {
  34267. var points = shape.points;
  34268. var i = 0;
  34269. var len$$1 = points.length;
  34270. var result = getBoundingBox(points, shape.smoothConstraint);
  34271. if (shape.connectNulls) {
  34272. // Must remove first and last null values avoid draw error in polygon
  34273. for (; len$$1 > 0; len$$1--) {
  34274. if (!isPointNull(points[len$$1 - 1])) {
  34275. break;
  34276. }
  34277. }
  34278. for (; i < len$$1; i++) {
  34279. if (!isPointNull(points[i])) {
  34280. break;
  34281. }
  34282. }
  34283. }
  34284. while (i < len$$1) {
  34285. i += drawSegment(ctx, points, i, len$$1, len$$1, 1, result.min, result.max, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  34286. }
  34287. }
  34288. });
  34289. var Polygon$1 = Path.extend({
  34290. type: 'ec-polygon',
  34291. shape: {
  34292. points: [],
  34293. // Offset between stacked base points and points
  34294. stackedOnPoints: [],
  34295. smooth: 0,
  34296. stackedOnSmooth: 0,
  34297. smoothConstraint: true,
  34298. smoothMonotone: null,
  34299. connectNulls: false
  34300. },
  34301. brush: fixClipWithShadow(Path.prototype.brush),
  34302. buildPath: function (ctx, shape) {
  34303. var points = shape.points;
  34304. var stackedOnPoints = shape.stackedOnPoints;
  34305. var i = 0;
  34306. var len$$1 = points.length;
  34307. var smoothMonotone = shape.smoothMonotone;
  34308. var bbox = getBoundingBox(points, shape.smoothConstraint);
  34309. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  34310. if (shape.connectNulls) {
  34311. // Must remove first and last null values avoid draw error in polygon
  34312. for (; len$$1 > 0; len$$1--) {
  34313. if (!isPointNull(points[len$$1 - 1])) {
  34314. break;
  34315. }
  34316. }
  34317. for (; i < len$$1; i++) {
  34318. if (!isPointNull(points[i])) {
  34319. break;
  34320. }
  34321. }
  34322. }
  34323. while (i < len$$1) {
  34324. var k = drawSegment(ctx, points, i, len$$1, len$$1, 1, bbox.min, bbox.max, shape.smooth, smoothMonotone, shape.connectNulls);
  34325. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len$$1, -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  34326. i += k + 1;
  34327. ctx.closePath();
  34328. }
  34329. }
  34330. });
  34331. /*
  34332. * Licensed to the Apache Software Foundation (ASF) under one
  34333. * or more contributor license agreements. See the NOTICE file
  34334. * distributed with this work for additional information
  34335. * regarding copyright ownership. The ASF licenses this file
  34336. * to you under the Apache License, Version 2.0 (the
  34337. * "License"); you may not use this file except in compliance
  34338. * with the License. You may obtain a copy of the License at
  34339. *
  34340. * http://www.apache.org/licenses/LICENSE-2.0
  34341. *
  34342. * Unless required by applicable law or agreed to in writing,
  34343. * software distributed under the License is distributed on an
  34344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34345. * KIND, either express or implied. See the License for the
  34346. * specific language governing permissions and limitations
  34347. * under the License.
  34348. */
  34349. // FIXME step not support polar
  34350. function isPointsSame(points1, points2) {
  34351. if (points1.length !== points2.length) {
  34352. return;
  34353. }
  34354. for (var i = 0; i < points1.length; i++) {
  34355. var p1 = points1[i];
  34356. var p2 = points2[i];
  34357. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  34358. return;
  34359. }
  34360. }
  34361. return true;
  34362. }
  34363. function getBoundingDiff(points1, points2) {
  34364. var min1 = [];
  34365. var max1 = [];
  34366. var min2 = [];
  34367. var max2 = [];
  34368. fromPoints(points1, min1, max1);
  34369. fromPoints(points2, min2, max2); // Get a max value from each corner of two boundings.
  34370. 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]));
  34371. }
  34372. function getSmooth(smooth) {
  34373. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  34374. }
  34375. /**
  34376. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  34377. * @param {module:echarts/data/List} data
  34378. * @param {Object} dataCoordInfo
  34379. * @param {Array.<Array.<number>>} points
  34380. */
  34381. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  34382. if (!dataCoordInfo.valueDim) {
  34383. return [];
  34384. }
  34385. var points = [];
  34386. for (var idx = 0, len = data.count(); idx < len; idx++) {
  34387. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  34388. }
  34389. return points;
  34390. }
  34391. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  34392. var baseAxis = coordSys.getBaseAxis();
  34393. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  34394. var stepPoints = [];
  34395. for (var i = 0; i < points.length - 1; i++) {
  34396. var nextPt = points[i + 1];
  34397. var pt = points[i];
  34398. stepPoints.push(pt);
  34399. var stepPt = [];
  34400. switch (stepTurnAt) {
  34401. case 'end':
  34402. stepPt[baseIndex] = nextPt[baseIndex];
  34403. stepPt[1 - baseIndex] = pt[1 - baseIndex]; // default is start
  34404. stepPoints.push(stepPt);
  34405. break;
  34406. case 'middle':
  34407. // default is start
  34408. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  34409. var stepPt2 = [];
  34410. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  34411. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34412. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  34413. stepPoints.push(stepPt);
  34414. stepPoints.push(stepPt2);
  34415. break;
  34416. default:
  34417. stepPt[baseIndex] = pt[baseIndex];
  34418. stepPt[1 - baseIndex] = nextPt[1 - baseIndex]; // default is start
  34419. stepPoints.push(stepPt);
  34420. }
  34421. } // Last points
  34422. points[i] && stepPoints.push(points[i]);
  34423. return stepPoints;
  34424. }
  34425. function getVisualGradient(data, coordSys) {
  34426. var visualMetaList = data.getVisual('visualMeta');
  34427. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  34428. // When data.count() is 0, gradient range can not be calculated.
  34429. return;
  34430. }
  34431. if (coordSys.type !== 'cartesian2d') {
  34432. return;
  34433. }
  34434. var coordDim;
  34435. var visualMeta;
  34436. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  34437. var dimIndex = visualMetaList[i].dimension;
  34438. var dimName = data.dimensions[dimIndex];
  34439. var dimInfo = data.getDimensionInfo(dimName);
  34440. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  34441. if (coordDim === 'x' || coordDim === 'y') {
  34442. visualMeta = visualMetaList[i];
  34443. break;
  34444. }
  34445. }
  34446. if (!visualMeta) {
  34447. return;
  34448. } // If the area to be rendered is bigger than area defined by LinearGradient,
  34449. // the canvas spec prescribes that the color of the first stop and the last
  34450. // stop should be used. But if two stops are added at offset 0, in effect
  34451. // browsers use the color of the second stop to render area outside
  34452. // LinearGradient. So we can only infinitesimally extend area defined in
  34453. // LinearGradient to render `outerColors`.
  34454. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic.
  34455. var colorStops = map(visualMeta.stops, function (stop) {
  34456. return {
  34457. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34458. color: stop.color
  34459. };
  34460. });
  34461. var stopLen = colorStops.length;
  34462. var outerColors = visualMeta.outerColors.slice();
  34463. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34464. colorStops.reverse();
  34465. outerColors.reverse();
  34466. }
  34467. var tinyExtent = 10; // Arbitrary value: 10px
  34468. var minCoord = colorStops[0].coord - tinyExtent;
  34469. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  34470. var coordSpan = maxCoord - minCoord;
  34471. if (coordSpan < 1e-3) {
  34472. return 'transparent';
  34473. }
  34474. each$1(colorStops, function (stop) {
  34475. stop.offset = (stop.coord - minCoord) / coordSpan;
  34476. });
  34477. colorStops.push({
  34478. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  34479. color: outerColors[1] || 'transparent'
  34480. });
  34481. colorStops.unshift({
  34482. // notice colorStops.length have been changed.
  34483. offset: stopLen ? colorStops[0].offset : 0.5,
  34484. color: outerColors[0] || 'transparent'
  34485. }); // zrUtil.each(colorStops, function (colorStop) {
  34486. // // Make sure each offset has rounded px to avoid not sharp edge
  34487. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  34488. // });
  34489. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  34490. gradient[coordDim] = minCoord;
  34491. gradient[coordDim + '2'] = maxCoord;
  34492. return gradient;
  34493. }
  34494. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34495. var showAllSymbol = seriesModel.get('showAllSymbol');
  34496. var isAuto = showAllSymbol === 'auto';
  34497. if (showAllSymbol && !isAuto) {
  34498. return;
  34499. }
  34500. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34501. if (!categoryAxis) {
  34502. return;
  34503. } // Note that category label interval strategy might bring some weird effect
  34504. // in some scenario: users may wonder why some of the symbols are not
  34505. // displayed. So we show all symbols as possible as we can.
  34506. if (isAuto // Simplify the logic, do not determine label overlap here.
  34507. && canShowAllSymbolForCategory(categoryAxis, data)) {
  34508. return;
  34509. } // Otherwise follow the label interval strategy on category axis.
  34510. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34511. var labelMap = {};
  34512. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  34513. labelMap[labelItem.tickValue] = 1;
  34514. });
  34515. return function (dataIndex) {
  34516. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34517. };
  34518. }
  34519. function canShowAllSymbolForCategory(categoryAxis, data) {
  34520. // In mose cases, line is monotonous on category axis, and the label size
  34521. // is close with each other. So we check the symbol size and some of the
  34522. // label size alone with the category axis to estimate whether all symbol
  34523. // can be shown without overlap.
  34524. var axisExtent = categoryAxis.getExtent();
  34525. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34526. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34527. // Sampling some points, max 5.
  34528. var dataLen = data.count();
  34529. var step = Math.max(1, Math.round(dataLen / 5));
  34530. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34531. if (SymbolClz$1.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  34532. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  34533. * 1.5 > availSize) {
  34534. return false;
  34535. }
  34536. }
  34537. return true;
  34538. }
  34539. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  34540. if (coordSys.type === 'cartesian2d') {
  34541. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34542. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel); // Expand clip shape to avoid clipping when line value exceeds axis
  34543. if (!seriesModel.get('clip', true)) {
  34544. var rectShape = clipPath.shape;
  34545. var expandSize = Math.max(rectShape.width, rectShape.height);
  34546. if (isHorizontal) {
  34547. rectShape.y -= expandSize;
  34548. rectShape.height += expandSize * 2;
  34549. } else {
  34550. rectShape.x -= expandSize;
  34551. rectShape.width += expandSize * 2;
  34552. }
  34553. }
  34554. return clipPath;
  34555. } else {
  34556. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34557. }
  34558. }
  34559. Chart.extend({
  34560. type: 'line',
  34561. init: function () {
  34562. var lineGroup = new Group();
  34563. var symbolDraw = new SymbolDraw();
  34564. this.group.add(symbolDraw.group);
  34565. this._symbolDraw = symbolDraw;
  34566. this._lineGroup = lineGroup;
  34567. },
  34568. render: function (seriesModel, ecModel, api) {
  34569. var coordSys = seriesModel.coordinateSystem;
  34570. var group = this.group;
  34571. var data = seriesModel.getData();
  34572. var lineStyleModel = seriesModel.getModel('lineStyle');
  34573. var areaStyleModel = seriesModel.getModel('areaStyle');
  34574. var points = data.mapArray(data.getItemLayout);
  34575. var isCoordSysPolar = coordSys.type === 'polar';
  34576. var prevCoordSys = this._coordSys;
  34577. var symbolDraw = this._symbolDraw;
  34578. var polyline = this._polyline;
  34579. var polygon = this._polygon;
  34580. var lineGroup = this._lineGroup;
  34581. var hasAnimation = seriesModel.get('animation');
  34582. var isAreaChart = !areaStyleModel.isEmpty();
  34583. var valueOrigin = areaStyleModel.get('origin');
  34584. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34585. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34586. var showSymbol = seriesModel.get('showSymbol');
  34587. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  34588. var oldData = this._data;
  34589. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34590. if (el.__temp) {
  34591. group.remove(el);
  34592. oldData.setItemGraphicEl(idx, null);
  34593. }
  34594. }); // Remove previous created symbols if showSymbol changed to false
  34595. if (!showSymbol) {
  34596. symbolDraw.remove();
  34597. }
  34598. group.add(lineGroup); // FIXME step not support polar
  34599. var step = !isCoordSysPolar && seriesModel.get('step');
  34600. var clipShapeForSymbol;
  34601. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34602. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  34603. // See #7913 and `test/dataZoom-clip.html`.
  34604. if (clipShapeForSymbol.width != null) {
  34605. clipShapeForSymbol.x -= 0.1;
  34606. clipShapeForSymbol.y -= 0.1;
  34607. clipShapeForSymbol.width += 0.2;
  34608. clipShapeForSymbol.height += 0.2;
  34609. } else if (clipShapeForSymbol.r0) {
  34610. clipShapeForSymbol.r0 -= 0.5;
  34611. clipShapeForSymbol.r1 += 0.5;
  34612. }
  34613. }
  34614. this._clipShapeForSymbol = clipShapeForSymbol; // Initialization animation or coordinate system changed
  34615. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  34616. showSymbol && symbolDraw.updateData(data, {
  34617. isIgnore: isIgnoreFunc,
  34618. clipShape: clipShapeForSymbol
  34619. });
  34620. if (step) {
  34621. // TODO If stacked series is not step
  34622. points = turnPointsIntoStep(points, coordSys, step);
  34623. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34624. }
  34625. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34626. if (isAreaChart) {
  34627. polygon = this._newPolygon(points, stackedOnPoints, coordSys, hasAnimation);
  34628. }
  34629. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34630. } else {
  34631. if (isAreaChart && !polygon) {
  34632. // If areaStyle is added
  34633. polygon = this._newPolygon(points, stackedOnPoints, coordSys, hasAnimation);
  34634. } else if (polygon && !isAreaChart) {
  34635. // If areaStyle is removed
  34636. lineGroup.remove(polygon);
  34637. polygon = this._polygon = null;
  34638. } // Update clipPath
  34639. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  34640. // because points are not changed
  34641. showSymbol && symbolDraw.updateData(data, {
  34642. isIgnore: isIgnoreFunc,
  34643. clipShape: clipShapeForSymbol
  34644. }); // Stop symbol animation and sync with line points
  34645. // FIXME performance?
  34646. data.eachItemGraphicEl(function (el) {
  34647. el.stopAnimation(true);
  34648. }); // In the case data zoom triggerred refreshing frequently
  34649. // Data may not change if line has a category axis. So it should animate nothing
  34650. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  34651. if (hasAnimation) {
  34652. this._updateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  34653. } else {
  34654. // Not do it in update with animation
  34655. if (step) {
  34656. // TODO If stacked series is not step
  34657. points = turnPointsIntoStep(points, coordSys, step);
  34658. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34659. }
  34660. polyline.setShape({
  34661. points: points
  34662. });
  34663. polygon && polygon.setShape({
  34664. points: points,
  34665. stackedOnPoints: stackedOnPoints
  34666. });
  34667. }
  34668. }
  34669. }
  34670. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34671. polyline.useStyle(defaults( // Use color in lineStyle first
  34672. lineStyleModel.getLineStyle(), {
  34673. fill: 'none',
  34674. stroke: visualColor,
  34675. lineJoin: 'bevel'
  34676. }));
  34677. var smooth = seriesModel.get('smooth');
  34678. smooth = getSmooth(seriesModel.get('smooth'));
  34679. polyline.setShape({
  34680. smooth: smooth,
  34681. smoothMonotone: seriesModel.get('smoothMonotone'),
  34682. connectNulls: seriesModel.get('connectNulls')
  34683. });
  34684. if (polygon) {
  34685. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34686. var stackedOnSmooth = 0;
  34687. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  34688. fill: visualColor,
  34689. opacity: 0.7,
  34690. lineJoin: 'bevel'
  34691. }));
  34692. if (stackedOnSeries) {
  34693. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34694. }
  34695. polygon.setShape({
  34696. smooth: smooth,
  34697. stackedOnSmooth: stackedOnSmooth,
  34698. smoothMonotone: seriesModel.get('smoothMonotone'),
  34699. connectNulls: seriesModel.get('connectNulls')
  34700. });
  34701. }
  34702. this._data = data; // Save the coordinate system for transition animation when data changed
  34703. this._coordSys = coordSys;
  34704. this._stackedOnPoints = stackedOnPoints;
  34705. this._points = points;
  34706. this._step = step;
  34707. this._valueOrigin = valueOrigin;
  34708. },
  34709. dispose: function () {},
  34710. highlight: function (seriesModel, ecModel, api, payload) {
  34711. var data = seriesModel.getData();
  34712. var dataIndex = queryDataIndex(data, payload);
  34713. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34714. var symbol = data.getItemGraphicEl(dataIndex);
  34715. if (!symbol) {
  34716. // Create a temporary symbol if it is not exists
  34717. var pt = data.getItemLayout(dataIndex);
  34718. if (!pt) {
  34719. // Null data
  34720. return;
  34721. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  34722. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34723. return;
  34724. }
  34725. symbol = new SymbolClz$1(data, dataIndex);
  34726. symbol.position = pt;
  34727. symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z'));
  34728. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34729. symbol.__temp = true;
  34730. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  34731. symbol.stopSymbolAnimation(true);
  34732. this.group.add(symbol);
  34733. }
  34734. symbol.highlight();
  34735. } else {
  34736. // Highlight whole series
  34737. Chart.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  34738. }
  34739. },
  34740. downplay: function (seriesModel, ecModel, api, payload) {
  34741. var data = seriesModel.getData();
  34742. var dataIndex = queryDataIndex(data, payload);
  34743. if (dataIndex != null && dataIndex >= 0) {
  34744. var symbol = data.getItemGraphicEl(dataIndex);
  34745. if (symbol) {
  34746. if (symbol.__temp) {
  34747. data.setItemGraphicEl(dataIndex, null);
  34748. this.group.remove(symbol);
  34749. } else {
  34750. symbol.downplay();
  34751. }
  34752. }
  34753. } else {
  34754. // FIXME
  34755. // can not downplay completely.
  34756. // Downplay whole series
  34757. Chart.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  34758. }
  34759. },
  34760. /**
  34761. * @param {module:zrender/container/Group} group
  34762. * @param {Array.<Array.<number>>} points
  34763. * @private
  34764. */
  34765. _newPolyline: function (points) {
  34766. var polyline = this._polyline; // Remove previous created polyline
  34767. if (polyline) {
  34768. this._lineGroup.remove(polyline);
  34769. }
  34770. polyline = new Polyline$1({
  34771. shape: {
  34772. points: points
  34773. },
  34774. silent: true,
  34775. z2: 10
  34776. });
  34777. this._lineGroup.add(polyline);
  34778. this._polyline = polyline;
  34779. return polyline;
  34780. },
  34781. /**
  34782. * @param {module:zrender/container/Group} group
  34783. * @param {Array.<Array.<number>>} stackedOnPoints
  34784. * @param {Array.<Array.<number>>} points
  34785. * @private
  34786. */
  34787. _newPolygon: function (points, stackedOnPoints) {
  34788. var polygon = this._polygon; // Remove previous created polygon
  34789. if (polygon) {
  34790. this._lineGroup.remove(polygon);
  34791. }
  34792. polygon = new Polygon$1({
  34793. shape: {
  34794. points: points,
  34795. stackedOnPoints: stackedOnPoints
  34796. },
  34797. silent: true
  34798. });
  34799. this._lineGroup.add(polygon);
  34800. this._polygon = polygon;
  34801. return polygon;
  34802. },
  34803. /**
  34804. * @private
  34805. */
  34806. // FIXME Two value axis
  34807. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34808. var polyline = this._polyline;
  34809. var polygon = this._polygon;
  34810. var seriesModel = data.hostModel;
  34811. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin);
  34812. var current = diff.current;
  34813. var stackedOnCurrent = diff.stackedOnCurrent;
  34814. var next = diff.next;
  34815. var stackedOnNext = diff.stackedOnNext;
  34816. if (step) {
  34817. // TODO If stacked series is not step
  34818. current = turnPointsIntoStep(diff.current, coordSys, step);
  34819. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34820. next = turnPointsIntoStep(diff.next, coordSys, step);
  34821. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34822. } // Don't apply animation if diff is large.
  34823. // For better result and avoid memory explosion problems like
  34824. // https://github.com/apache/incubator-echarts/issues/12229
  34825. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  34826. polyline.setShape({
  34827. points: next
  34828. });
  34829. if (polygon) {
  34830. polygon.setShape({
  34831. points: next,
  34832. stackedOnPoints: stackedOnNext
  34833. });
  34834. }
  34835. return;
  34836. } // `diff.current` is subset of `current` (which should be ensured by
  34837. // turnPointsIntoStep), so points in `__points` can be updated when
  34838. // points in `current` are update during animation.
  34839. polyline.shape.__points = diff.current;
  34840. polyline.shape.points = current;
  34841. updateProps(polyline, {
  34842. shape: {
  34843. points: next
  34844. }
  34845. }, seriesModel);
  34846. if (polygon) {
  34847. polygon.setShape({
  34848. points: current,
  34849. stackedOnPoints: stackedOnCurrent
  34850. });
  34851. updateProps(polygon, {
  34852. shape: {
  34853. points: next,
  34854. stackedOnPoints: stackedOnNext
  34855. }
  34856. }, seriesModel);
  34857. }
  34858. var updatedDataInfo = [];
  34859. var diffStatus = diff.status;
  34860. for (var i = 0; i < diffStatus.length; i++) {
  34861. var cmd = diffStatus[i].cmd;
  34862. if (cmd === '=') {
  34863. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  34864. if (el) {
  34865. updatedDataInfo.push({
  34866. el: el,
  34867. ptIdx: i // Index of points
  34868. });
  34869. }
  34870. }
  34871. }
  34872. if (polyline.animators && polyline.animators.length) {
  34873. polyline.animators[0].during(function () {
  34874. for (var i = 0; i < updatedDataInfo.length; i++) {
  34875. var el = updatedDataInfo[i].el;
  34876. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  34877. }
  34878. });
  34879. }
  34880. },
  34881. remove: function (ecModel) {
  34882. var group = this.group;
  34883. var oldData = this._data;
  34884. this._lineGroup.removeAll();
  34885. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  34886. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34887. if (el.__temp) {
  34888. group.remove(el);
  34889. oldData.setItemGraphicEl(idx, null);
  34890. }
  34891. });
  34892. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._data = null;
  34893. }
  34894. });
  34895. /*
  34896. * Licensed to the Apache Software Foundation (ASF) under one
  34897. * or more contributor license agreements. See the NOTICE file
  34898. * distributed with this work for additional information
  34899. * regarding copyright ownership. The ASF licenses this file
  34900. * to you under the Apache License, Version 2.0 (the
  34901. * "License"); you may not use this file except in compliance
  34902. * with the License. You may obtain a copy of the License at
  34903. *
  34904. * http://www.apache.org/licenses/LICENSE-2.0
  34905. *
  34906. * Unless required by applicable law or agreed to in writing,
  34907. * software distributed under the License is distributed on an
  34908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34909. * KIND, either express or implied. See the License for the
  34910. * specific language governing permissions and limitations
  34911. * under the License.
  34912. */
  34913. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  34914. // Encoding visual for all series include which is filtered for legend drawing
  34915. return {
  34916. seriesType: seriesType,
  34917. // For legend.
  34918. performRawSeries: true,
  34919. reset: function (seriesModel, ecModel, api) {
  34920. var data = seriesModel.getData();
  34921. var symbolType = seriesModel.get('symbol');
  34922. var symbolSize = seriesModel.get('symbolSize');
  34923. var keepAspect = seriesModel.get('symbolKeepAspect');
  34924. var symbolRotate = seriesModel.get('symbolRotate');
  34925. var hasSymbolTypeCallback = isFunction$1(symbolType);
  34926. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  34927. var hasSymbolRotateCallback = isFunction$1(symbolRotate);
  34928. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  34929. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : defaultSymbolType;
  34930. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  34931. data.setVisual({
  34932. legendSymbol: legendSymbol || seriesSymbol,
  34933. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  34934. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  34935. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  34936. // some cases but generally it is not recommanded.
  34937. symbol: seriesSymbol,
  34938. symbolSize: seriesSymbolSize,
  34939. symbolKeepAspect: keepAspect,
  34940. symbolRotate: symbolRotate
  34941. }); // Only visible series has each data be visual encoded
  34942. if (ecModel.isSeriesFiltered(seriesModel)) {
  34943. return;
  34944. }
  34945. function dataEach(data, idx) {
  34946. if (hasCallback) {
  34947. var rawValue = seriesModel.getRawValue(idx);
  34948. var params = seriesModel.getDataParams(idx);
  34949. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  34950. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  34951. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  34952. }
  34953. if (data.hasItemOption) {
  34954. var itemModel = data.getItemModel(idx);
  34955. var itemSymbolType = itemModel.getShallow('symbol', true);
  34956. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  34957. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  34958. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  34959. if (itemSymbolType != null) {
  34960. data.setItemVisual(idx, 'symbol', itemSymbolType);
  34961. }
  34962. if (itemSymbolSize != null) {
  34963. // PENDING Transform symbolSize ?
  34964. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  34965. }
  34966. if (itemSymbolRotate != null) {
  34967. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  34968. }
  34969. if (itemSymbolKeepAspect != null) {
  34970. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  34971. }
  34972. }
  34973. }
  34974. return {
  34975. dataEach: data.hasItemOption || hasCallback ? dataEach : null
  34976. };
  34977. }
  34978. };
  34979. };
  34980. /*
  34981. * Licensed to the Apache Software Foundation (ASF) under one
  34982. * or more contributor license agreements. See the NOTICE file
  34983. * distributed with this work for additional information
  34984. * regarding copyright ownership. The ASF licenses this file
  34985. * to you under the Apache License, Version 2.0 (the
  34986. * "License"); you may not use this file except in compliance
  34987. * with the License. You may obtain a copy of the License at
  34988. *
  34989. * http://www.apache.org/licenses/LICENSE-2.0
  34990. *
  34991. * Unless required by applicable law or agreed to in writing,
  34992. * software distributed under the License is distributed on an
  34993. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34994. * KIND, either express or implied. See the License for the
  34995. * specific language governing permissions and limitations
  34996. * under the License.
  34997. */
  34998. /* global Float32Array */
  34999. var layoutPoints = function (seriesType) {
  35000. return {
  35001. seriesType: seriesType,
  35002. plan: createRenderPlanner(),
  35003. reset: function (seriesModel) {
  35004. var data = seriesModel.getData();
  35005. var coordSys = seriesModel.coordinateSystem;
  35006. var pipelineContext = seriesModel.pipelineContext;
  35007. var isLargeRender = pipelineContext.large;
  35008. if (!coordSys) {
  35009. return;
  35010. }
  35011. var dims = map(coordSys.dimensions, function (dim) {
  35012. return data.mapDimension(dim);
  35013. }).slice(0, 2);
  35014. var dimLen = dims.length;
  35015. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35016. if (isDimensionStacked(data, dims[0]
  35017. /*, dims[1]*/
  35018. )) {
  35019. dims[0] = stackResultDim;
  35020. }
  35021. if (isDimensionStacked(data, dims[1]
  35022. /*, dims[0]*/
  35023. )) {
  35024. dims[1] = stackResultDim;
  35025. }
  35026. function progress(params, data) {
  35027. var segCount = params.end - params.start;
  35028. var points = isLargeRender && new Float32Array(segCount * dimLen);
  35029. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  35030. var point;
  35031. if (dimLen === 1) {
  35032. var x = data.get(dims[0], i);
  35033. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  35034. } else {
  35035. var x = tmpIn[0] = data.get(dims[0], i);
  35036. var y = tmpIn[1] = data.get(dims[1], i); // Also {Array.<number>}, not undefined to avoid if...else... statement
  35037. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  35038. }
  35039. if (isLargeRender) {
  35040. points[offset++] = point ? point[0] : NaN;
  35041. points[offset++] = point ? point[1] : NaN;
  35042. } else {
  35043. data.setItemLayout(i, point && point.slice() || [NaN, NaN]);
  35044. }
  35045. }
  35046. isLargeRender && data.setLayout('symbolPoints', points);
  35047. }
  35048. return dimLen && {
  35049. progress: progress
  35050. };
  35051. }
  35052. };
  35053. };
  35054. /*
  35055. * Licensed to the Apache Software Foundation (ASF) under one
  35056. * or more contributor license agreements. See the NOTICE file
  35057. * distributed with this work for additional information
  35058. * regarding copyright ownership. The ASF licenses this file
  35059. * to you under the Apache License, Version 2.0 (the
  35060. * "License"); you may not use this file except in compliance
  35061. * with the License. You may obtain a copy of the License at
  35062. *
  35063. * http://www.apache.org/licenses/LICENSE-2.0
  35064. *
  35065. * Unless required by applicable law or agreed to in writing,
  35066. * software distributed under the License is distributed on an
  35067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35068. * KIND, either express or implied. See the License for the
  35069. * specific language governing permissions and limitations
  35070. * under the License.
  35071. */
  35072. var samplers = {
  35073. average: function (frame) {
  35074. var sum = 0;
  35075. var count = 0;
  35076. for (var i = 0; i < frame.length; i++) {
  35077. if (!isNaN(frame[i])) {
  35078. sum += frame[i];
  35079. count++;
  35080. }
  35081. } // Return NaN if count is 0
  35082. return count === 0 ? NaN : sum / count;
  35083. },
  35084. sum: function (frame) {
  35085. var sum = 0;
  35086. for (var i = 0; i < frame.length; i++) {
  35087. // Ignore NaN
  35088. sum += frame[i] || 0;
  35089. }
  35090. return sum;
  35091. },
  35092. max: function (frame) {
  35093. var max = -Infinity;
  35094. for (var i = 0; i < frame.length; i++) {
  35095. frame[i] > max && (max = frame[i]);
  35096. } // NaN will cause illegal axis extent.
  35097. return isFinite(max) ? max : NaN;
  35098. },
  35099. min: function (frame) {
  35100. var min = Infinity;
  35101. for (var i = 0; i < frame.length; i++) {
  35102. frame[i] < min && (min = frame[i]);
  35103. } // NaN will cause illegal axis extent.
  35104. return isFinite(min) ? min : NaN;
  35105. },
  35106. // TODO
  35107. // Median
  35108. nearest: function (frame) {
  35109. return frame[0];
  35110. }
  35111. };
  35112. var indexSampler = function (frame, value) {
  35113. return Math.round(frame.length / 2);
  35114. };
  35115. var dataSample = function (seriesType) {
  35116. return {
  35117. seriesType: seriesType,
  35118. modifyOutputEnd: true,
  35119. reset: function (seriesModel, ecModel, api) {
  35120. var data = seriesModel.getData();
  35121. var sampling = seriesModel.get('sampling');
  35122. var coordSys = seriesModel.coordinateSystem; // Only cartesian2d support down sampling
  35123. if (coordSys.type === 'cartesian2d' && sampling) {
  35124. var baseAxis = coordSys.getBaseAxis();
  35125. var valueAxis = coordSys.getOtherAxis(baseAxis);
  35126. var extent = baseAxis.getExtent(); // Coordinste system has been resized
  35127. var size = extent[1] - extent[0];
  35128. var rate = Math.round(data.count() / size);
  35129. if (rate > 1) {
  35130. var sampler;
  35131. if (typeof sampling === 'string') {
  35132. sampler = samplers[sampling];
  35133. } else if (typeof sampling === 'function') {
  35134. sampler = sampling;
  35135. }
  35136. if (sampler) {
  35137. // Only support sample the first dim mapped from value axis.
  35138. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  35139. }
  35140. }
  35141. }
  35142. }
  35143. };
  35144. };
  35145. /*
  35146. * Licensed to the Apache Software Foundation (ASF) under one
  35147. * or more contributor license agreements. See the NOTICE file
  35148. * distributed with this work for additional information
  35149. * regarding copyright ownership. The ASF licenses this file
  35150. * to you under the Apache License, Version 2.0 (the
  35151. * "License"); you may not use this file except in compliance
  35152. * with the License. You may obtain a copy of the License at
  35153. *
  35154. * http://www.apache.org/licenses/LICENSE-2.0
  35155. *
  35156. * Unless required by applicable law or agreed to in writing,
  35157. * software distributed under the License is distributed on an
  35158. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35159. * KIND, either express or implied. See the License for the
  35160. * specific language governing permissions and limitations
  35161. * under the License.
  35162. */
  35163. registerVisual(visualSymbol('line', 'circle', 'line'));
  35164. registerLayout(layoutPoints('line')); // Down sample after filter
  35165. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  35166. /*
  35167. * Licensed to the Apache Software Foundation (ASF) under one
  35168. * or more contributor license agreements. See the NOTICE file
  35169. * distributed with this work for additional information
  35170. * regarding copyright ownership. The ASF licenses this file
  35171. * to you under the Apache License, Version 2.0 (the
  35172. * "License"); you may not use this file except in compliance
  35173. * with the License. You may obtain a copy of the License at
  35174. *
  35175. * http://www.apache.org/licenses/LICENSE-2.0
  35176. *
  35177. * Unless required by applicable law or agreed to in writing,
  35178. * software distributed under the License is distributed on an
  35179. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35180. * KIND, either express or implied. See the License for the
  35181. * specific language governing permissions and limitations
  35182. * under the License.
  35183. */
  35184. /**
  35185. * [Usage]:
  35186. * (1)
  35187. * createListSimply(seriesModel, ['value']);
  35188. * (2)
  35189. * createListSimply(seriesModel, {
  35190. * coordDimensions: ['value'],
  35191. * dimensionsCount: 5
  35192. * });
  35193. *
  35194. * @param {module:echarts/model/Series} seriesModel
  35195. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  35196. * The options in opt, see `echarts/data/helper/createDimensions`
  35197. * @param {Array.<string>} [nameList]
  35198. * @return {module:echarts/data/List}
  35199. */
  35200. var createListSimply = function (seriesModel, opt, nameList) {
  35201. opt = isArray(opt) && {
  35202. coordDimensions: opt
  35203. } || extend({}, opt);
  35204. var source = seriesModel.getSource();
  35205. var dimensionsInfo = createDimensions(source, opt);
  35206. var list = new List(dimensionsInfo, seriesModel);
  35207. list.initData(source, nameList);
  35208. return list;
  35209. };
  35210. /*
  35211. * Licensed to the Apache Software Foundation (ASF) under one
  35212. * or more contributor license agreements. See the NOTICE file
  35213. * distributed with this work for additional information
  35214. * regarding copyright ownership. The ASF licenses this file
  35215. * to you under the Apache License, Version 2.0 (the
  35216. * "License"); you may not use this file except in compliance
  35217. * with the License. You may obtain a copy of the License at
  35218. *
  35219. * http://www.apache.org/licenses/LICENSE-2.0
  35220. *
  35221. * Unless required by applicable law or agreed to in writing,
  35222. * software distributed under the License is distributed on an
  35223. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35224. * KIND, either express or implied. See the License for the
  35225. * specific language governing permissions and limitations
  35226. * under the License.
  35227. */
  35228. /**
  35229. * Data selectable mixin for chart series.
  35230. * To eanble data select, option of series must have `selectedMode`.
  35231. * And each data item will use `selected` to toggle itself selected status
  35232. */
  35233. var dataSelectableMixin = {
  35234. /**
  35235. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  35236. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  35237. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  35238. */
  35239. updateSelectedMap: function (targetList) {
  35240. this._targetList = isArray(targetList) ? targetList.slice() : [];
  35241. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  35242. targetMap.set(target.name, target);
  35243. return targetMap;
  35244. }, createHashMap());
  35245. },
  35246. /**
  35247. * Either name or id should be passed as input here.
  35248. * If both of them are defined, id is used.
  35249. *
  35250. * @param {string|undefined} name name of data
  35251. * @param {number|undefined} id dataIndex of data
  35252. */
  35253. // PENGING If selectedMode is null ?
  35254. select: function (name, id) {
  35255. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35256. var selectedMode = this.get('selectedMode');
  35257. if (selectedMode === 'single') {
  35258. this._selectTargetMap.each(function (target) {
  35259. target.selected = false;
  35260. });
  35261. }
  35262. target && (target.selected = true);
  35263. },
  35264. /**
  35265. * Either name or id should be passed as input here.
  35266. * If both of them are defined, id is used.
  35267. *
  35268. * @param {string|undefined} name name of data
  35269. * @param {number|undefined} id dataIndex of data
  35270. */
  35271. unSelect: function (name, id) {
  35272. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); // var selectedMode = this.get('selectedMode');
  35273. // selectedMode !== 'single' && target && (target.selected = false);
  35274. target && (target.selected = false);
  35275. },
  35276. /**
  35277. * Either name or id should be passed as input here.
  35278. * If both of them are defined, id is used.
  35279. *
  35280. * @param {string|undefined} name name of data
  35281. * @param {number|undefined} id dataIndex of data
  35282. */
  35283. toggleSelected: function (name, id) {
  35284. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35285. if (target != null) {
  35286. this[target.selected ? 'unSelect' : 'select'](name, id);
  35287. return target.selected;
  35288. }
  35289. },
  35290. /**
  35291. * Either name or id should be passed as input here.
  35292. * If both of them are defined, id is used.
  35293. *
  35294. * @param {string|undefined} name name of data
  35295. * @param {number|undefined} id dataIndex of data
  35296. */
  35297. isSelected: function (name, id) {
  35298. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35299. return target && target.selected;
  35300. }
  35301. };
  35302. /*
  35303. * Licensed to the Apache Software Foundation (ASF) under one
  35304. * or more contributor license agreements. See the NOTICE file
  35305. * distributed with this work for additional information
  35306. * regarding copyright ownership. The ASF licenses this file
  35307. * to you under the Apache License, Version 2.0 (the
  35308. * "License"); you may not use this file except in compliance
  35309. * with the License. You may obtain a copy of the License at
  35310. *
  35311. * http://www.apache.org/licenses/LICENSE-2.0
  35312. *
  35313. * Unless required by applicable law or agreed to in writing,
  35314. * software distributed under the License is distributed on an
  35315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35316. * KIND, either express or implied. See the License for the
  35317. * specific language governing permissions and limitations
  35318. * under the License.
  35319. */
  35320. /**
  35321. * LegendVisualProvider is an bridge that pick encoded color from data and
  35322. * provide to the legend component.
  35323. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  35324. * @param {Function} getRawData Function to get raw data before filtered.
  35325. */
  35326. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  35327. this.getAllNames = function () {
  35328. var rawData = getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  35329. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  35330. return rawData.mapArray(rawData.getName);
  35331. };
  35332. this.containName = function (name) {
  35333. var rawData = getRawData();
  35334. return rawData.indexOfName(name) >= 0;
  35335. };
  35336. this.indexOfName = function (name) {
  35337. // Only get data when necessary.
  35338. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  35339. // Invoking Series#getData immediately will throw an error.
  35340. var dataWithEncodedVisual = getDataWithEncodedVisual();
  35341. return dataWithEncodedVisual.indexOfName(name);
  35342. };
  35343. this.getItemVisual = function (dataIndex, key) {
  35344. // Get encoded visual properties from final filtered data.
  35345. var dataWithEncodedVisual = getDataWithEncodedVisual();
  35346. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  35347. };
  35348. }
  35349. /*
  35350. * Licensed to the Apache Software Foundation (ASF) under one
  35351. * or more contributor license agreements. See the NOTICE file
  35352. * distributed with this work for additional information
  35353. * regarding copyright ownership. The ASF licenses this file
  35354. * to you under the Apache License, Version 2.0 (the
  35355. * "License"); you may not use this file except in compliance
  35356. * with the License. You may obtain a copy of the License at
  35357. *
  35358. * http://www.apache.org/licenses/LICENSE-2.0
  35359. *
  35360. * Unless required by applicable law or agreed to in writing,
  35361. * software distributed under the License is distributed on an
  35362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35363. * KIND, either express or implied. See the License for the
  35364. * specific language governing permissions and limitations
  35365. * under the License.
  35366. */
  35367. var PieSeries = extendSeriesModel({
  35368. type: 'series.pie',
  35369. // Overwrite
  35370. init: function (option) {
  35371. PieSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item
  35372. // Use a function instead of direct access because data reference may changed
  35373. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  35374. this.updateSelectedMap(this._createSelectableList());
  35375. this._defaultLabelLine(option);
  35376. },
  35377. // Overwrite
  35378. mergeOption: function (newOption) {
  35379. PieSeries.superCall(this, 'mergeOption', newOption);
  35380. this.updateSelectedMap(this._createSelectableList());
  35381. },
  35382. getInitialData: function (option, ecModel) {
  35383. return createListSimply(this, {
  35384. coordDimensions: ['value'],
  35385. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  35386. });
  35387. },
  35388. _createSelectableList: function () {
  35389. var data = this.getRawData();
  35390. var valueDim = data.mapDimension('value');
  35391. var targetList = [];
  35392. for (var i = 0, len = data.count(); i < len; i++) {
  35393. targetList.push({
  35394. name: data.getName(i),
  35395. value: data.get(valueDim, i),
  35396. selected: retrieveRawAttr(data, i, 'selected')
  35397. });
  35398. }
  35399. return targetList;
  35400. },
  35401. // Overwrite
  35402. getDataParams: function (dataIndex) {
  35403. var data = this.getData();
  35404. var params = PieSeries.superCall(this, 'getDataParams', dataIndex); // FIXME toFixed?
  35405. var valueList = [];
  35406. data.each(data.mapDimension('value'), function (value) {
  35407. valueList.push(value);
  35408. });
  35409. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  35410. params.$vars.push('percent');
  35411. return params;
  35412. },
  35413. _defaultLabelLine: function (option) {
  35414. // Extend labelLine emphasis
  35415. defaultEmphasis(option, 'labelLine', ['show']);
  35416. var labelLineNormalOpt = option.labelLine;
  35417. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  35418. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  35419. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  35420. },
  35421. defaultOption: {
  35422. zlevel: 0,
  35423. z: 2,
  35424. legendHoverLink: true,
  35425. hoverAnimation: true,
  35426. // 默认全局居中
  35427. center: ['50%', '50%'],
  35428. radius: [0, '75%'],
  35429. // 默认顺时针
  35430. clockwise: true,
  35431. startAngle: 90,
  35432. // 最小角度改为0
  35433. minAngle: 0,
  35434. // If the angle of a sector less than `minShowLabelAngle`,
  35435. // the label will not be displayed.
  35436. minShowLabelAngle: 0,
  35437. // 选中时扇区偏移量
  35438. selectedOffset: 10,
  35439. // 高亮扇区偏移量
  35440. hoverOffset: 10,
  35441. // If use strategy to avoid label overlapping
  35442. avoidLabelOverlap: true,
  35443. // 选择模式,默认关闭,可选single,multiple
  35444. // selectedMode: false,
  35445. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  35446. // roseType: null,
  35447. percentPrecision: 2,
  35448. // If still show when all data zero.
  35449. stillShowZeroSum: true,
  35450. // cursor: null,
  35451. left: 0,
  35452. top: 0,
  35453. right: 0,
  35454. bottom: 0,
  35455. width: null,
  35456. height: null,
  35457. label: {
  35458. // If rotate around circle
  35459. rotate: false,
  35460. show: true,
  35461. // 'outer', 'inside', 'center'
  35462. position: 'outer',
  35463. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  35464. alignTo: 'none',
  35465. // Closest distance between label and chart edge.
  35466. // Works only position is 'outer' and alignTo is 'edge'.
  35467. margin: '25%',
  35468. // Works only position is 'outer' and alignTo is not 'edge'.
  35469. bleedMargin: 10,
  35470. // Distance between text and label line.
  35471. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35472. // 默认使用全局文本样式,详见TEXTSTYLE
  35473. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  35474. },
  35475. // Enabled when label.normal.position is 'outer'
  35476. labelLine: {
  35477. show: true,
  35478. // 引导线两段中的第一段长度
  35479. length: 15,
  35480. // 引导线两段中的第二段长度
  35481. length2: 15,
  35482. smooth: false,
  35483. lineStyle: {
  35484. // color: 各异,
  35485. width: 1,
  35486. type: 'solid'
  35487. }
  35488. },
  35489. itemStyle: {
  35490. borderWidth: 1
  35491. },
  35492. // Animation type. Valid values: expansion, scale
  35493. animationType: 'expansion',
  35494. // Animation type when update. Valid values: transition, expansion
  35495. animationTypeUpdate: 'transition',
  35496. animationEasing: 'cubicOut'
  35497. }
  35498. });
  35499. mixin(PieSeries, dataSelectableMixin);
  35500. /*
  35501. * Licensed to the Apache Software Foundation (ASF) under one
  35502. * or more contributor license agreements. See the NOTICE file
  35503. * distributed with this work for additional information
  35504. * regarding copyright ownership. The ASF licenses this file
  35505. * to you under the Apache License, Version 2.0 (the
  35506. * "License"); you may not use this file except in compliance
  35507. * with the License. You may obtain a copy of the License at
  35508. *
  35509. * http://www.apache.org/licenses/LICENSE-2.0
  35510. *
  35511. * Unless required by applicable law or agreed to in writing,
  35512. * software distributed under the License is distributed on an
  35513. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35514. * KIND, either express or implied. See the License for the
  35515. * specific language governing permissions and limitations
  35516. * under the License.
  35517. */
  35518. /**
  35519. * @param {module:echarts/model/Series} seriesModel
  35520. * @param {boolean} hasAnimation
  35521. * @inner
  35522. */
  35523. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  35524. var data = seriesModel.getData();
  35525. var dataIndex = this.dataIndex;
  35526. var name = data.getName(dataIndex);
  35527. var selectedOffset = seriesModel.get('selectedOffset');
  35528. api.dispatchAction({
  35529. type: 'pieToggleSelect',
  35530. from: uid,
  35531. name: name,
  35532. seriesId: seriesModel.id
  35533. });
  35534. data.each(function (idx) {
  35535. toggleItemSelected(data.getItemGraphicEl(idx), data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), selectedOffset, hasAnimation);
  35536. });
  35537. }
  35538. /**
  35539. * @param {module:zrender/graphic/Sector} el
  35540. * @param {Object} layout
  35541. * @param {boolean} isSelected
  35542. * @param {number} selectedOffset
  35543. * @param {boolean} hasAnimation
  35544. * @inner
  35545. */
  35546. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  35547. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35548. var dx = Math.cos(midAngle);
  35549. var dy = Math.sin(midAngle);
  35550. var offset = isSelected ? selectedOffset : 0;
  35551. var position = [dx * offset, dy * offset];
  35552. hasAnimation // animateTo will stop revious animation like update transition
  35553. ? el.animate().when(200, {
  35554. position: position
  35555. }).start('bounceOut') : el.attr('position', position);
  35556. }
  35557. /**
  35558. * Piece of pie including Sector, Label, LabelLine
  35559. * @constructor
  35560. * @extends {module:zrender/graphic/Group}
  35561. */
  35562. function PiePiece(data, idx) {
  35563. Group.call(this);
  35564. var sector = new Sector({
  35565. z2: 2
  35566. });
  35567. var polyline = new Polyline();
  35568. var text = new Text();
  35569. this.add(sector);
  35570. this.add(polyline);
  35571. this.add(text);
  35572. this.updateData(data, idx, true);
  35573. }
  35574. var piePieceProto = PiePiece.prototype;
  35575. piePieceProto.updateData = function (data, idx, firstCreate) {
  35576. var sector = this.childAt(0);
  35577. var labelLine = this.childAt(1);
  35578. var labelText = this.childAt(2);
  35579. var seriesModel = data.hostModel;
  35580. var itemModel = data.getItemModel(idx);
  35581. var layout = data.getItemLayout(idx);
  35582. var sectorShape = extend({}, layout);
  35583. sectorShape.label = null;
  35584. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  35585. if (firstCreate) {
  35586. sector.setShape(sectorShape);
  35587. var animationType = seriesModel.getShallow('animationType');
  35588. if (animationType === 'scale') {
  35589. sector.shape.r = layout.r0;
  35590. initProps(sector, {
  35591. shape: {
  35592. r: layout.r
  35593. }
  35594. }, seriesModel, idx);
  35595. } // Expansion
  35596. else {
  35597. sector.shape.endAngle = layout.startAngle;
  35598. updateProps(sector, {
  35599. shape: {
  35600. endAngle: layout.endAngle
  35601. }
  35602. }, seriesModel, idx);
  35603. }
  35604. } else {
  35605. if (animationTypeUpdate === 'expansion') {
  35606. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  35607. sector.setShape(sectorShape);
  35608. } else {
  35609. // Transition animation from the old shape
  35610. updateProps(sector, {
  35611. shape: sectorShape
  35612. }, seriesModel, idx);
  35613. }
  35614. } // Update common style
  35615. var visualColor = data.getItemVisual(idx, 'color');
  35616. sector.useStyle(defaults({
  35617. lineJoin: 'bevel',
  35618. fill: visualColor
  35619. }, itemModel.getModel('itemStyle').getItemStyle()));
  35620. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  35621. var cursorStyle = itemModel.getShallow('cursor');
  35622. cursorStyle && sector.attr('cursor', cursorStyle); // Toggle selected
  35623. toggleItemSelected(this, data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), seriesModel.get('selectedOffset'), seriesModel.get('animation')); // Label and text animation should be applied only for transition type animation when update
  35624. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  35625. this._updateLabel(data, idx, withAnimation);
  35626. this.highDownOnUpdate = !seriesModel.get('silent') ? function (fromState, toState) {
  35627. var hasAnimation = seriesModel.isAnimationEnabled() && itemModel.get('hoverAnimation');
  35628. if (toState === 'emphasis') {
  35629. labelLine.ignore = labelLine.hoverIgnore;
  35630. labelText.ignore = labelText.hoverIgnore; // Sector may has animation of updating data. Force to move to the last frame
  35631. // Or it may stopped on the wrong shape
  35632. if (hasAnimation) {
  35633. sector.stopAnimation(true);
  35634. sector.animateTo({
  35635. shape: {
  35636. r: layout.r + seriesModel.get('hoverOffset')
  35637. }
  35638. }, 300, 'elasticOut');
  35639. }
  35640. } else {
  35641. labelLine.ignore = labelLine.normalIgnore;
  35642. labelText.ignore = labelText.normalIgnore;
  35643. if (hasAnimation) {
  35644. sector.stopAnimation(true);
  35645. sector.animateTo({
  35646. shape: {
  35647. r: layout.r
  35648. }
  35649. }, 300, 'elasticOut');
  35650. }
  35651. }
  35652. } : null;
  35653. setHoverStyle(this);
  35654. };
  35655. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  35656. var labelLine = this.childAt(1);
  35657. var labelText = this.childAt(2);
  35658. var seriesModel = data.hostModel;
  35659. var itemModel = data.getItemModel(idx);
  35660. var layout = data.getItemLayout(idx);
  35661. var labelLayout = layout.label;
  35662. var visualColor = data.getItemVisual(idx, 'color');
  35663. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  35664. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore = labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  35665. return;
  35666. }
  35667. var targetLineShape = {
  35668. points: labelLayout.linePoints || [[labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]]
  35669. };
  35670. var targetTextStyle = {
  35671. x: labelLayout.x,
  35672. y: labelLayout.y
  35673. };
  35674. if (withAnimation) {
  35675. updateProps(labelLine, {
  35676. shape: targetLineShape
  35677. }, seriesModel, idx);
  35678. updateProps(labelText, {
  35679. style: targetTextStyle
  35680. }, seriesModel, idx);
  35681. } else {
  35682. labelLine.attr({
  35683. shape: targetLineShape
  35684. });
  35685. labelText.attr({
  35686. style: targetTextStyle
  35687. });
  35688. }
  35689. labelText.attr({
  35690. rotation: labelLayout.rotation,
  35691. origin: [labelLayout.x, labelLayout.y],
  35692. z2: 10
  35693. });
  35694. var labelModel = itemModel.getModel('label');
  35695. var labelHoverModel = itemModel.getModel('emphasis.label');
  35696. var labelLineModel = itemModel.getModel('labelLine');
  35697. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35698. var visualColor = data.getItemVisual(idx, 'color');
  35699. setLabelStyle(labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel, {
  35700. labelFetcher: data.hostModel,
  35701. labelDataIndex: idx,
  35702. defaultText: labelLayout.text,
  35703. autoColor: visualColor,
  35704. useInsideStyle: !!labelLayout.inside
  35705. }, {
  35706. textAlign: labelLayout.textAlign,
  35707. textVerticalAlign: labelLayout.verticalAlign,
  35708. opacity: data.getItemVisual(idx, 'opacity')
  35709. });
  35710. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35711. labelText.hoverIgnore = !labelHoverModel.get('show');
  35712. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35713. labelLine.hoverIgnore = !labelLineHoverModel.get('show'); // Default use item visual color
  35714. labelLine.setStyle({
  35715. stroke: visualColor,
  35716. opacity: data.getItemVisual(idx, 'opacity')
  35717. });
  35718. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35719. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35720. var smooth = labelLineModel.get('smooth');
  35721. if (smooth && smooth === true) {
  35722. smooth = 0.4;
  35723. }
  35724. labelLine.setShape({
  35725. smooth: smooth
  35726. });
  35727. };
  35728. inherits(PiePiece, Group); // Pie view
  35729. var PieView = Chart.extend({
  35730. type: 'pie',
  35731. init: function () {
  35732. var sectorGroup = new Group();
  35733. this._sectorGroup = sectorGroup;
  35734. },
  35735. render: function (seriesModel, ecModel, api, payload) {
  35736. if (payload && payload.from === this.uid) {
  35737. return;
  35738. }
  35739. var data = seriesModel.getData();
  35740. var oldData = this._data;
  35741. var group = this.group;
  35742. var hasAnimation = ecModel.get('animation');
  35743. var isFirstRender = !oldData;
  35744. var animationType = seriesModel.get('animationType');
  35745. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  35746. var onSectorClick = curry(updateDataSelected, this.uid, seriesModel, hasAnimation, api);
  35747. var selectedMode = seriesModel.get('selectedMode');
  35748. data.diff(oldData).add(function (idx) {
  35749. var piePiece = new PiePiece(data, idx); // Default expansion animation
  35750. if (isFirstRender && animationType !== 'scale') {
  35751. piePiece.eachChild(function (child) {
  35752. child.stopAnimation(true);
  35753. });
  35754. }
  35755. selectedMode && piePiece.on('click', onSectorClick);
  35756. data.setItemGraphicEl(idx, piePiece);
  35757. group.add(piePiece);
  35758. }).update(function (newIdx, oldIdx) {
  35759. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35760. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  35761. piePiece.eachChild(function (child) {
  35762. child.stopAnimation(true);
  35763. });
  35764. }
  35765. piePiece.updateData(data, newIdx);
  35766. piePiece.off('click');
  35767. selectedMode && piePiece.on('click', onSectorClick);
  35768. group.add(piePiece);
  35769. data.setItemGraphicEl(newIdx, piePiece);
  35770. }).remove(function (idx) {
  35771. var piePiece = oldData.getItemGraphicEl(idx);
  35772. group.remove(piePiece);
  35773. }).execute();
  35774. if (hasAnimation && data.count() > 0 && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')) {
  35775. var shape = data.getItemLayout(0);
  35776. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  35777. shape = data.getItemLayout(s);
  35778. }
  35779. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35780. var removeClipPath = bind(group.removeClipPath, group);
  35781. group.setClipPath(this._createClipPath(shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender));
  35782. } else {
  35783. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  35784. group.removeClipPath();
  35785. }
  35786. this._data = data;
  35787. },
  35788. dispose: function () {},
  35789. _createClipPath: function (cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender) {
  35790. var clipPath = new Sector({
  35791. shape: {
  35792. cx: cx,
  35793. cy: cy,
  35794. r0: 0,
  35795. r: r,
  35796. startAngle: startAngle,
  35797. endAngle: startAngle,
  35798. clockwise: clockwise
  35799. }
  35800. });
  35801. var initOrUpdate = isFirstRender ? initProps : updateProps;
  35802. initOrUpdate(clipPath, {
  35803. shape: {
  35804. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35805. }
  35806. }, seriesModel, cb);
  35807. return clipPath;
  35808. },
  35809. /**
  35810. * @implement
  35811. */
  35812. containPoint: function (point, seriesModel) {
  35813. var data = seriesModel.getData();
  35814. var itemLayout = data.getItemLayout(0);
  35815. if (itemLayout) {
  35816. var dx = point[0] - itemLayout.cx;
  35817. var dy = point[1] - itemLayout.cy;
  35818. var radius = Math.sqrt(dx * dx + dy * dy);
  35819. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35820. }
  35821. }
  35822. });
  35823. /*
  35824. * Licensed to the Apache Software Foundation (ASF) under one
  35825. * or more contributor license agreements. See the NOTICE file
  35826. * distributed with this work for additional information
  35827. * regarding copyright ownership. The ASF licenses this file
  35828. * to you under the Apache License, Version 2.0 (the
  35829. * "License"); you may not use this file except in compliance
  35830. * with the License. You may obtain a copy of the License at
  35831. *
  35832. * http://www.apache.org/licenses/LICENSE-2.0
  35833. *
  35834. * Unless required by applicable law or agreed to in writing,
  35835. * software distributed under the License is distributed on an
  35836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35837. * KIND, either express or implied. See the License for the
  35838. * specific language governing permissions and limitations
  35839. * under the License.
  35840. */
  35841. var createDataSelectAction = function (seriesType, actionInfos) {
  35842. each$1(actionInfos, function (actionInfo) {
  35843. actionInfo.update = 'updateView';
  35844. /**
  35845. * @payload
  35846. * @property {string} seriesName
  35847. * @property {string} name
  35848. */
  35849. registerAction(actionInfo, function (payload, ecModel) {
  35850. var selected = {};
  35851. ecModel.eachComponent({
  35852. mainType: 'series',
  35853. subType: seriesType,
  35854. query: payload
  35855. }, function (seriesModel) {
  35856. if (seriesModel[actionInfo.method]) {
  35857. seriesModel[actionInfo.method](payload.name, payload.dataIndex);
  35858. }
  35859. var data = seriesModel.getData(); // Create selected map
  35860. data.each(function (idx) {
  35861. var name = data.getName(idx);
  35862. selected[name] = seriesModel.isSelected(name) || false;
  35863. });
  35864. });
  35865. return {
  35866. name: payload.name,
  35867. selected: selected,
  35868. seriesId: payload.seriesId
  35869. };
  35870. });
  35871. });
  35872. };
  35873. /*
  35874. * Licensed to the Apache Software Foundation (ASF) under one
  35875. * or more contributor license agreements. See the NOTICE file
  35876. * distributed with this work for additional information
  35877. * regarding copyright ownership. The ASF licenses this file
  35878. * to you under the Apache License, Version 2.0 (the
  35879. * "License"); you may not use this file except in compliance
  35880. * with the License. You may obtain a copy of the License at
  35881. *
  35882. * http://www.apache.org/licenses/LICENSE-2.0
  35883. *
  35884. * Unless required by applicable law or agreed to in writing,
  35885. * software distributed under the License is distributed on an
  35886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35887. * KIND, either express or implied. See the License for the
  35888. * specific language governing permissions and limitations
  35889. * under the License.
  35890. */
  35891. // Pick color from palette for each data item.
  35892. // Applicable for charts that require applying color palette
  35893. // in data level (like pie, funnel, chord).
  35894. var dataColor = function (seriesType) {
  35895. return {
  35896. getTargetSeries: function (ecModel) {
  35897. // Pie and funnel may use diferrent scope
  35898. var paletteScope = {};
  35899. var seiresModelMap = createHashMap();
  35900. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35901. seriesModel.__paletteScope = paletteScope;
  35902. seiresModelMap.set(seriesModel.uid, seriesModel);
  35903. });
  35904. return seiresModelMap;
  35905. },
  35906. reset: function (seriesModel, ecModel) {
  35907. var dataAll = seriesModel.getRawData();
  35908. var idxMap = {};
  35909. var data = seriesModel.getData();
  35910. data.each(function (idx) {
  35911. var rawIdx = data.getRawIndex(idx);
  35912. idxMap[rawIdx] = idx;
  35913. });
  35914. dataAll.each(function (rawIdx) {
  35915. var filteredIdx = idxMap[rawIdx]; // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35916. var singleDataColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'color', true);
  35917. var singleDataBorderColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'borderColor', true);
  35918. var itemModel;
  35919. if (!singleDataColor || !singleDataBorderColor) {
  35920. // FIXME Performance
  35921. itemModel = dataAll.getItemModel(rawIdx);
  35922. }
  35923. if (!singleDataColor) {
  35924. var color = itemModel.get('itemStyle.color') || seriesModel.getColorFromPalette(dataAll.getName(rawIdx) || rawIdx + '', seriesModel.__paletteScope, dataAll.count()); // Data is not filtered
  35925. if (filteredIdx != null) {
  35926. data.setItemVisual(filteredIdx, 'color', color);
  35927. }
  35928. }
  35929. if (!singleDataBorderColor) {
  35930. var borderColor = itemModel.get('itemStyle.borderColor'); // Data is not filtered
  35931. if (filteredIdx != null) {
  35932. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  35933. }
  35934. }
  35935. });
  35936. }
  35937. };
  35938. };
  35939. /*
  35940. * Licensed to the Apache Software Foundation (ASF) under one
  35941. * or more contributor license agreements. See the NOTICE file
  35942. * distributed with this work for additional information
  35943. * regarding copyright ownership. The ASF licenses this file
  35944. * to you under the Apache License, Version 2.0 (the
  35945. * "License"); you may not use this file except in compliance
  35946. * with the License. You may obtain a copy of the License at
  35947. *
  35948. * http://www.apache.org/licenses/LICENSE-2.0
  35949. *
  35950. * Unless required by applicable law or agreed to in writing,
  35951. * software distributed under the License is distributed on an
  35952. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35953. * KIND, either express or implied. See the License for the
  35954. * specific language governing permissions and limitations
  35955. * under the License.
  35956. */
  35957. // FIXME emphasis label position is not same with normal label position
  35958. var RADIAN$1 = Math.PI / 180;
  35959. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  35960. list.sort(function (a, b) {
  35961. return a.y - b.y;
  35962. });
  35963. function shiftDown(start, end, delta, dir) {
  35964. for (var j = start; j < end; j++) {
  35965. if (list[j].y + delta > viewTop + viewHeight) {
  35966. break;
  35967. }
  35968. list[j].y += delta;
  35969. if (j > start && j + 1 < end && list[j + 1].y > list[j].y + list[j].height) {
  35970. shiftUp(j, delta / 2);
  35971. return;
  35972. }
  35973. }
  35974. shiftUp(end - 1, delta / 2);
  35975. }
  35976. function shiftUp(end, delta) {
  35977. for (var j = end; j >= 0; j--) {
  35978. if (list[j].y - delta < viewTop) {
  35979. break;
  35980. }
  35981. list[j].y -= delta;
  35982. if (j > 0 && list[j].y > list[j - 1].y + list[j - 1].height) {
  35983. break;
  35984. }
  35985. }
  35986. }
  35987. function changeX(list, isDownList, cx, cy, r, dir) {
  35988. var lastDeltaX = dir > 0 ? isDownList // right-side
  35989. ? Number.MAX_VALUE // down
  35990. : 0 // up
  35991. : isDownList // left-side
  35992. ? Number.MAX_VALUE // down
  35993. : 0; // up
  35994. for (var i = 0, l = list.length; i < l; i++) {
  35995. if (list[i].labelAlignTo !== 'none') {
  35996. continue;
  35997. }
  35998. var deltaY = Math.abs(list[i].y - cy);
  35999. var length = list[i].len;
  36000. var length2 = list[i].len2;
  36001. var deltaX = deltaY < r + length ? Math.sqrt((r + length + length2) * (r + length + length2) - deltaY * deltaY) : Math.abs(list[i].x - cx);
  36002. if (isDownList && deltaX >= lastDeltaX) {
  36003. // right-down, left-down
  36004. deltaX = lastDeltaX - 10;
  36005. }
  36006. if (!isDownList && deltaX <= lastDeltaX) {
  36007. // right-up, left-up
  36008. deltaX = lastDeltaX + 10;
  36009. }
  36010. list[i].x = cx + deltaX * dir;
  36011. lastDeltaX = deltaX;
  36012. }
  36013. }
  36014. var lastY = 0;
  36015. var delta;
  36016. var len = list.length;
  36017. var upList = [];
  36018. var downList = [];
  36019. for (var i = 0; i < len; i++) {
  36020. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  36021. var dx = list[i].x - farthestX;
  36022. list[i].linePoints[1][0] += dx;
  36023. list[i].x = farthestX;
  36024. }
  36025. delta = list[i].y - lastY;
  36026. if (delta < 0) {
  36027. shiftDown(i, len, -delta, dir);
  36028. }
  36029. lastY = list[i].y + list[i].height;
  36030. }
  36031. if (viewHeight - lastY < 0) {
  36032. shiftUp(len - 1, lastY - viewHeight);
  36033. }
  36034. for (var i = 0; i < len; i++) {
  36035. if (list[i].y >= cy) {
  36036. downList.push(list[i]);
  36037. } else {
  36038. upList.push(list[i]);
  36039. }
  36040. }
  36041. changeX(upList, false, cx, cy, r, dir);
  36042. changeX(downList, true, cx, cy, r, dir);
  36043. }
  36044. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  36045. var leftList = [];
  36046. var rightList = [];
  36047. var leftmostX = Number.MAX_VALUE;
  36048. var rightmostX = -Number.MAX_VALUE;
  36049. for (var i = 0; i < labelLayoutList.length; i++) {
  36050. if (isPositionCenter(labelLayoutList[i])) {
  36051. continue;
  36052. }
  36053. if (labelLayoutList[i].x < cx) {
  36054. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  36055. leftList.push(labelLayoutList[i]);
  36056. } else {
  36057. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  36058. rightList.push(labelLayoutList[i]);
  36059. }
  36060. }
  36061. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  36062. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  36063. for (var i = 0; i < labelLayoutList.length; i++) {
  36064. var layout = labelLayoutList[i];
  36065. if (isPositionCenter(layout)) {
  36066. continue;
  36067. }
  36068. var linePoints = layout.linePoints;
  36069. if (linePoints) {
  36070. var isAlignToEdge = layout.labelAlignTo === 'edge';
  36071. var realTextWidth = layout.textRect.width;
  36072. var targetTextWidth;
  36073. if (isAlignToEdge) {
  36074. if (layout.x < cx) {
  36075. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.labelMargin;
  36076. } else {
  36077. targetTextWidth = viewLeft + viewWidth - layout.labelMargin - linePoints[2][0] - layout.labelDistance;
  36078. }
  36079. } else {
  36080. if (layout.x < cx) {
  36081. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  36082. } else {
  36083. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  36084. }
  36085. }
  36086. if (targetTextWidth < layout.textRect.width) {
  36087. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  36088. if (layout.labelAlignTo === 'edge') {
  36089. realTextWidth = getWidth(layout.text, layout.font);
  36090. }
  36091. }
  36092. var dist = linePoints[1][0] - linePoints[2][0];
  36093. if (isAlignToEdge) {
  36094. if (layout.x < cx) {
  36095. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  36096. } else {
  36097. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin - realTextWidth - layout.labelDistance;
  36098. }
  36099. } else {
  36100. if (layout.x < cx) {
  36101. linePoints[2][0] = layout.x + layout.labelDistance;
  36102. } else {
  36103. linePoints[2][0] = layout.x - layout.labelDistance;
  36104. }
  36105. linePoints[1][0] = linePoints[2][0] + dist;
  36106. }
  36107. linePoints[1][1] = linePoints[2][1] = layout.y;
  36108. }
  36109. }
  36110. }
  36111. function isPositionCenter(layout) {
  36112. // Not change x for center label
  36113. return layout.position === 'center';
  36114. }
  36115. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  36116. var data = seriesModel.getData();
  36117. var labelLayoutList = [];
  36118. var cx;
  36119. var cy;
  36120. var hasLabelRotate = false;
  36121. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  36122. data.each(function (idx) {
  36123. var layout = data.getItemLayout(idx);
  36124. var itemModel = data.getItemModel(idx);
  36125. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  36126. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  36127. var labelDistance = labelModel.get('distanceToLabelLine');
  36128. var labelAlignTo = labelModel.get('alignTo');
  36129. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  36130. var bleedMargin = labelModel.get('bleedMargin');
  36131. var font = labelModel.getFont();
  36132. var labelLineModel = itemModel.getModel('labelLine');
  36133. var labelLineLen = labelLineModel.get('length');
  36134. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  36135. var labelLineLen2 = labelLineModel.get('length2');
  36136. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  36137. if (layout.angle < minShowLabelRadian) {
  36138. return;
  36139. }
  36140. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36141. var dx = Math.cos(midAngle);
  36142. var dy = Math.sin(midAngle);
  36143. var textX;
  36144. var textY;
  36145. var linePoints;
  36146. var textAlign;
  36147. cx = layout.cx;
  36148. cy = layout.cy;
  36149. var text = seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx);
  36150. var textRect = getBoundingRect(text, font, textAlign, 'top');
  36151. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  36152. if (labelPosition === 'center') {
  36153. textX = layout.cx;
  36154. textY = layout.cy;
  36155. textAlign = 'center';
  36156. } else {
  36157. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  36158. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  36159. textX = x1 + dx * 3;
  36160. textY = y1 + dy * 3;
  36161. if (!isLabelInside) {
  36162. // For roseType
  36163. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  36164. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  36165. var x3 = x2 + (dx < 0 ? -1 : 1) * labelLineLen2;
  36166. var y3 = y2;
  36167. if (labelAlignTo === 'edge') {
  36168. // Adjust textX because text align of edge is opposite
  36169. textX = dx < 0 ? viewLeft + labelMargin : viewLeft + viewWidth - labelMargin;
  36170. } else {
  36171. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  36172. }
  36173. textY = y3;
  36174. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  36175. }
  36176. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? dx > 0 ? 'right' : 'left' : dx > 0 ? 'left' : 'right';
  36177. }
  36178. var labelRotate;
  36179. var rotate = labelModel.get('rotate');
  36180. if (typeof rotate === 'number') {
  36181. labelRotate = rotate * (Math.PI / 180);
  36182. } else {
  36183. labelRotate = rotate ? dx < 0 ? -midAngle + Math.PI : -midAngle : 0;
  36184. }
  36185. hasLabelRotate = !!labelRotate;
  36186. layout.label = {
  36187. x: textX,
  36188. y: textY,
  36189. position: labelPosition,
  36190. height: textRect.height,
  36191. len: labelLineLen,
  36192. len2: labelLineLen2,
  36193. linePoints: linePoints,
  36194. textAlign: textAlign,
  36195. verticalAlign: 'middle',
  36196. rotation: labelRotate,
  36197. inside: isLabelInside,
  36198. labelDistance: labelDistance,
  36199. labelAlignTo: labelAlignTo,
  36200. labelMargin: labelMargin,
  36201. bleedMargin: bleedMargin,
  36202. textRect: textRect,
  36203. text: text,
  36204. font: font
  36205. }; // Not layout the inside label
  36206. if (!isLabelInside) {
  36207. labelLayoutList.push(layout.label);
  36208. }
  36209. });
  36210. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  36211. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  36212. }
  36213. };
  36214. /*
  36215. * Licensed to the Apache Software Foundation (ASF) under one
  36216. * or more contributor license agreements. See the NOTICE file
  36217. * distributed with this work for additional information
  36218. * regarding copyright ownership. The ASF licenses this file
  36219. * to you under the Apache License, Version 2.0 (the
  36220. * "License"); you may not use this file except in compliance
  36221. * with the License. You may obtain a copy of the License at
  36222. *
  36223. * http://www.apache.org/licenses/LICENSE-2.0
  36224. *
  36225. * Unless required by applicable law or agreed to in writing,
  36226. * software distributed under the License is distributed on an
  36227. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36228. * KIND, either express or implied. See the License for the
  36229. * specific language governing permissions and limitations
  36230. * under the License.
  36231. */
  36232. var PI2$4 = Math.PI * 2;
  36233. var RADIAN = Math.PI / 180;
  36234. function getViewRect(seriesModel, api) {
  36235. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  36236. width: api.getWidth(),
  36237. height: api.getHeight()
  36238. });
  36239. }
  36240. var pieLayout = function (seriesType, ecModel, api, payload) {
  36241. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36242. var data = seriesModel.getData();
  36243. var valueDim = data.mapDimension('value');
  36244. var viewRect = getViewRect(seriesModel, api);
  36245. var center = seriesModel.get('center');
  36246. var radius = seriesModel.get('radius');
  36247. if (!isArray(radius)) {
  36248. radius = [0, radius];
  36249. }
  36250. if (!isArray(center)) {
  36251. center = [center, center];
  36252. }
  36253. var width = parsePercent$1(viewRect.width, api.getWidth());
  36254. var height = parsePercent$1(viewRect.height, api.getHeight());
  36255. var size = Math.min(width, height);
  36256. var cx = parsePercent$1(center[0], width) + viewRect.x;
  36257. var cy = parsePercent$1(center[1], height) + viewRect.y;
  36258. var r0 = parsePercent$1(radius[0], size / 2);
  36259. var r = parsePercent$1(radius[1], size / 2);
  36260. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36261. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36262. var validDataCount = 0;
  36263. data.each(valueDim, function (value) {
  36264. !isNaN(value) && validDataCount++;
  36265. });
  36266. var sum = data.getSum(valueDim); // Sum may be 0
  36267. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36268. var clockwise = seriesModel.get('clockwise');
  36269. var roseType = seriesModel.get('roseType');
  36270. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  36271. var extent = data.getDataExtent(valueDim);
  36272. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  36273. var restAngle = PI2$4;
  36274. var valueSumLargerThanMinAngle = 0;
  36275. var currentAngle = startAngle;
  36276. var dir = clockwise ? 1 : -1;
  36277. data.each(valueDim, function (value, idx) {
  36278. var angle;
  36279. if (isNaN(value)) {
  36280. data.setItemLayout(idx, {
  36281. angle: NaN,
  36282. startAngle: NaN,
  36283. endAngle: NaN,
  36284. clockwise: clockwise,
  36285. cx: cx,
  36286. cy: cy,
  36287. r0: r0,
  36288. r: roseType ? NaN : r,
  36289. viewRect: viewRect
  36290. });
  36291. return;
  36292. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36293. if (roseType !== 'area') {
  36294. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  36295. } else {
  36296. angle = PI2$4 / validDataCount;
  36297. }
  36298. if (angle < minAngle) {
  36299. angle = minAngle;
  36300. restAngle -= minAngle;
  36301. } else {
  36302. valueSumLargerThanMinAngle += value;
  36303. }
  36304. var endAngle = currentAngle + dir * angle;
  36305. data.setItemLayout(idx, {
  36306. angle: angle,
  36307. startAngle: currentAngle,
  36308. endAngle: endAngle,
  36309. clockwise: clockwise,
  36310. cx: cx,
  36311. cy: cy,
  36312. r0: r0,
  36313. r: roseType ? linearMap(value, extent, [r0, r]) : r,
  36314. viewRect: viewRect
  36315. });
  36316. currentAngle = endAngle;
  36317. }); // Some sector is constrained by minAngle
  36318. // Rest sectors needs recalculate angle
  36319. if (restAngle < PI2$4 && validDataCount) {
  36320. // Average the angle if rest angle is not enough after all angles is
  36321. // Constrained by minAngle
  36322. if (restAngle <= 1e-3) {
  36323. var angle = PI2$4 / validDataCount;
  36324. data.each(valueDim, function (value, idx) {
  36325. if (!isNaN(value)) {
  36326. var layout = data.getItemLayout(idx);
  36327. layout.angle = angle;
  36328. layout.startAngle = startAngle + dir * idx * angle;
  36329. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  36330. }
  36331. });
  36332. } else {
  36333. unitRadian = restAngle / valueSumLargerThanMinAngle;
  36334. currentAngle = startAngle;
  36335. data.each(valueDim, function (value, idx) {
  36336. if (!isNaN(value)) {
  36337. var layout = data.getItemLayout(idx);
  36338. var angle = layout.angle === minAngle ? minAngle : value * unitRadian;
  36339. layout.startAngle = currentAngle;
  36340. layout.endAngle = currentAngle + dir * angle;
  36341. currentAngle += dir * angle;
  36342. }
  36343. });
  36344. }
  36345. }
  36346. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  36347. });
  36348. };
  36349. /*
  36350. * Licensed to the Apache Software Foundation (ASF) under one
  36351. * or more contributor license agreements. See the NOTICE file
  36352. * distributed with this work for additional information
  36353. * regarding copyright ownership. The ASF licenses this file
  36354. * to you under the Apache License, Version 2.0 (the
  36355. * "License"); you may not use this file except in compliance
  36356. * with the License. You may obtain a copy of the License at
  36357. *
  36358. * http://www.apache.org/licenses/LICENSE-2.0
  36359. *
  36360. * Unless required by applicable law or agreed to in writing,
  36361. * software distributed under the License is distributed on an
  36362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36363. * KIND, either express or implied. See the License for the
  36364. * specific language governing permissions and limitations
  36365. * under the License.
  36366. */
  36367. var dataFilter = function (seriesType) {
  36368. return {
  36369. seriesType: seriesType,
  36370. reset: function (seriesModel, ecModel) {
  36371. var legendModels = ecModel.findComponents({
  36372. mainType: 'legend'
  36373. });
  36374. if (!legendModels || !legendModels.length) {
  36375. return;
  36376. }
  36377. var data = seriesModel.getData();
  36378. data.filterSelf(function (idx) {
  36379. var name = data.getName(idx); // If in any legend component the status is not selected.
  36380. for (var i = 0; i < legendModels.length; i++) {
  36381. if (!legendModels[i].isSelected(name)) {
  36382. return false;
  36383. }
  36384. }
  36385. return true;
  36386. });
  36387. }
  36388. };
  36389. };
  36390. /*
  36391. * Licensed to the Apache Software Foundation (ASF) under one
  36392. * or more contributor license agreements. See the NOTICE file
  36393. * distributed with this work for additional information
  36394. * regarding copyright ownership. The ASF licenses this file
  36395. * to you under the Apache License, Version 2.0 (the
  36396. * "License"); you may not use this file except in compliance
  36397. * with the License. You may obtain a copy of the License at
  36398. *
  36399. * http://www.apache.org/licenses/LICENSE-2.0
  36400. *
  36401. * Unless required by applicable law or agreed to in writing,
  36402. * software distributed under the License is distributed on an
  36403. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36404. * KIND, either express or implied. See the License for the
  36405. * specific language governing permissions and limitations
  36406. * under the License.
  36407. */
  36408. createDataSelectAction('pie', [{
  36409. type: 'pieToggleSelect',
  36410. event: 'pieselectchanged',
  36411. method: 'toggleSelected'
  36412. }, {
  36413. type: 'pieSelect',
  36414. event: 'pieselected',
  36415. method: 'select'
  36416. }, {
  36417. type: 'pieUnSelect',
  36418. event: 'pieunselected',
  36419. method: 'unSelect'
  36420. }]);
  36421. registerVisual(dataColor('pie'));
  36422. registerLayout(curry(pieLayout, 'pie'));
  36423. registerProcessor(dataFilter('pie'));
  36424. /*
  36425. * Licensed to the Apache Software Foundation (ASF) under one
  36426. * or more contributor license agreements. See the NOTICE file
  36427. * distributed with this work for additional information
  36428. * regarding copyright ownership. The ASF licenses this file
  36429. * to you under the Apache License, Version 2.0 (the
  36430. * "License"); you may not use this file except in compliance
  36431. * with the License. You may obtain a copy of the License at
  36432. *
  36433. * http://www.apache.org/licenses/LICENSE-2.0
  36434. *
  36435. * Unless required by applicable law or agreed to in writing,
  36436. * software distributed under the License is distributed on an
  36437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36438. * KIND, either express or implied. See the License for the
  36439. * specific language governing permissions and limitations
  36440. * under the License.
  36441. */
  36442. extendComponentModel({
  36443. type: 'title',
  36444. layoutMode: {
  36445. type: 'box',
  36446. ignoreSize: true
  36447. },
  36448. defaultOption: {
  36449. // 一级层叠
  36450. zlevel: 0,
  36451. // 二级层叠
  36452. z: 6,
  36453. show: true,
  36454. text: '',
  36455. // 超链接跳转
  36456. // link: null,
  36457. // 仅支持self | blank
  36458. target: 'blank',
  36459. subtext: '',
  36460. // 超链接跳转
  36461. // sublink: null,
  36462. // 仅支持self | blank
  36463. subtarget: 'blank',
  36464. // 'center' ¦ 'left' ¦ 'right'
  36465. // ¦ {number}(x坐标,单位px)
  36466. left: 0,
  36467. // 'top' ¦ 'bottom' ¦ 'center'
  36468. // ¦ {number}(y坐标,单位px)
  36469. top: 0,
  36470. // 水平对齐
  36471. // 'auto' | 'left' | 'right' | 'center'
  36472. // 默认根据 left 的位置判断是左对齐还是右对齐
  36473. // textAlign: null
  36474. //
  36475. // 垂直对齐
  36476. // 'auto' | 'top' | 'bottom' | 'middle'
  36477. // 默认根据 top 位置判断是上对齐还是下对齐
  36478. // textVerticalAlign: null
  36479. // textBaseline: null // The same as textVerticalAlign.
  36480. backgroundColor: 'rgba(0,0,0,0)',
  36481. // 标题边框颜色
  36482. borderColor: '#ccc',
  36483. // 标题边框线宽,单位px,默认为0(无边框)
  36484. borderWidth: 0,
  36485. // 标题内边距,单位px,默认各方向内边距为5,
  36486. // 接受数组分别设定上右下左边距,同css
  36487. padding: 5,
  36488. // 主副标题纵向间隔,单位px,默认为10,
  36489. itemGap: 10,
  36490. textStyle: {
  36491. fontSize: 18,
  36492. fontWeight: 'bolder',
  36493. color: '#333'
  36494. },
  36495. subtextStyle: {
  36496. color: '#aaa'
  36497. }
  36498. }
  36499. }); // View
  36500. extendComponentView({
  36501. type: 'title',
  36502. render: function (titleModel, ecModel, api) {
  36503. this.group.removeAll();
  36504. if (!titleModel.get('show')) {
  36505. return;
  36506. }
  36507. var group = this.group;
  36508. var textStyleModel = titleModel.getModel('textStyle');
  36509. var subtextStyleModel = titleModel.getModel('subtextStyle');
  36510. var textAlign = titleModel.get('textAlign');
  36511. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  36512. var textEl = new Text({
  36513. style: setTextStyle({}, textStyleModel, {
  36514. text: titleModel.get('text'),
  36515. textFill: textStyleModel.getTextColor()
  36516. }, {
  36517. disableBox: true
  36518. }),
  36519. z2: 10
  36520. });
  36521. var textRect = textEl.getBoundingRect();
  36522. var subText = titleModel.get('subtext');
  36523. var subTextEl = new Text({
  36524. style: setTextStyle({}, subtextStyleModel, {
  36525. text: subText,
  36526. textFill: subtextStyleModel.getTextColor(),
  36527. y: textRect.height + titleModel.get('itemGap'),
  36528. textVerticalAlign: 'top'
  36529. }, {
  36530. disableBox: true
  36531. }),
  36532. z2: 10
  36533. });
  36534. var link = titleModel.get('link');
  36535. var sublink = titleModel.get('sublink');
  36536. var triggerEvent = titleModel.get('triggerEvent', true);
  36537. textEl.silent = !link && !triggerEvent;
  36538. subTextEl.silent = !sublink && !triggerEvent;
  36539. if (link) {
  36540. textEl.on('click', function () {
  36541. windowOpen(link, '_' + titleModel.get('target'));
  36542. });
  36543. }
  36544. if (sublink) {
  36545. subTextEl.on('click', function () {
  36546. windowOpen(link, '_' + titleModel.get('subtarget'));
  36547. });
  36548. }
  36549. textEl.eventData = subTextEl.eventData = triggerEvent ? {
  36550. componentType: 'title',
  36551. componentIndex: titleModel.componentIndex
  36552. } : null;
  36553. group.add(textEl);
  36554. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  36555. var groupRect = group.getBoundingRect();
  36556. var layoutOption = titleModel.getBoxLayoutParams();
  36557. layoutOption.width = groupRect.width;
  36558. layoutOption.height = groupRect.height;
  36559. var layoutRect = getLayoutRect(layoutOption, {
  36560. width: api.getWidth(),
  36561. height: api.getHeight()
  36562. }, titleModel.get('padding')); // Adjust text align based on position
  36563. if (!textAlign) {
  36564. // Align left if title is on the left. center and right is same
  36565. textAlign = titleModel.get('left') || titleModel.get('right');
  36566. if (textAlign === 'middle') {
  36567. textAlign = 'center';
  36568. } // Adjust layout by text align
  36569. if (textAlign === 'right') {
  36570. layoutRect.x += layoutRect.width;
  36571. } else if (textAlign === 'center') {
  36572. layoutRect.x += layoutRect.width / 2;
  36573. }
  36574. }
  36575. if (!textVerticalAlign) {
  36576. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  36577. if (textVerticalAlign === 'center') {
  36578. textVerticalAlign = 'middle';
  36579. }
  36580. if (textVerticalAlign === 'bottom') {
  36581. layoutRect.y += layoutRect.height;
  36582. } else if (textVerticalAlign === 'middle') {
  36583. layoutRect.y += layoutRect.height / 2;
  36584. }
  36585. textVerticalAlign = textVerticalAlign || 'top';
  36586. }
  36587. group.attr('position', [layoutRect.x, layoutRect.y]);
  36588. var alignStyle = {
  36589. textAlign: textAlign,
  36590. textVerticalAlign: textVerticalAlign
  36591. };
  36592. textEl.setStyle(alignStyle);
  36593. subTextEl.setStyle(alignStyle); // Render background
  36594. // Get groupRect again because textAlign has been changed
  36595. groupRect = group.getBoundingRect();
  36596. var padding = layoutRect.margin;
  36597. var style = titleModel.getItemStyle(['color', 'opacity']);
  36598. style.fill = titleModel.get('backgroundColor');
  36599. var rect = new Rect({
  36600. shape: {
  36601. x: groupRect.x - padding[3],
  36602. y: groupRect.y - padding[0],
  36603. width: groupRect.width + padding[1] + padding[3],
  36604. height: groupRect.height + padding[0] + padding[2],
  36605. r: titleModel.get('borderRadius')
  36606. },
  36607. style: style,
  36608. subPixelOptimize: true,
  36609. silent: true
  36610. });
  36611. group.add(rect);
  36612. }
  36613. });
  36614. /*
  36615. * Licensed to the Apache Software Foundation (ASF) under one
  36616. * or more contributor license agreements. See the NOTICE file
  36617. * distributed with this work for additional information
  36618. * regarding copyright ownership. The ASF licenses this file
  36619. * to you under the Apache License, Version 2.0 (the
  36620. * "License"); you may not use this file except in compliance
  36621. * with the License. You may obtain a copy of the License at
  36622. *
  36623. * http://www.apache.org/licenses/LICENSE-2.0
  36624. *
  36625. * Unless required by applicable law or agreed to in writing,
  36626. * software distributed under the License is distributed on an
  36627. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36628. * KIND, either express or implied. See the License for the
  36629. * specific language governing permissions and limitations
  36630. * under the License.
  36631. */
  36632. var langSelector = lang.legend.selector;
  36633. var defaultSelectorOption = {
  36634. all: {
  36635. type: 'all',
  36636. title: clone(langSelector.all)
  36637. },
  36638. inverse: {
  36639. type: 'inverse',
  36640. title: clone(langSelector.inverse)
  36641. }
  36642. };
  36643. var LegendModel = extendComponentModel({
  36644. type: 'legend.plain',
  36645. dependencies: ['series'],
  36646. layoutMode: {
  36647. type: 'box',
  36648. // legend.width/height are maxWidth/maxHeight actually,
  36649. // whereas realy width/height is calculated by its content.
  36650. // (Setting {left: 10, right: 10} does not make sense).
  36651. // So consider the case:
  36652. // `setOption({legend: {left: 10});`
  36653. // then `setOption({legend: {right: 10});`
  36654. // The previous `left` should be cleared by setting `ignoreSize`.
  36655. ignoreSize: true
  36656. },
  36657. init: function (option, parentModel, ecModel) {
  36658. this.mergeDefaultAndTheme(option, ecModel);
  36659. option.selected = option.selected || {};
  36660. this._updateSelector(option);
  36661. },
  36662. mergeOption: function (option) {
  36663. LegendModel.superCall(this, 'mergeOption', option);
  36664. this._updateSelector(option);
  36665. },
  36666. _updateSelector: function (option) {
  36667. var selector = option.selector;
  36668. if (selector === true) {
  36669. selector = option.selector = ['all', 'inverse'];
  36670. }
  36671. if (isArray(selector)) {
  36672. each$1(selector, function (item, index) {
  36673. isString(item) && (item = {
  36674. type: item
  36675. });
  36676. selector[index] = merge(item, defaultSelectorOption[item.type]);
  36677. });
  36678. }
  36679. },
  36680. optionUpdated: function () {
  36681. this._updateData(this.ecModel);
  36682. var legendData = this._data; // If selectedMode is single, try to select one
  36683. if (legendData[0] && this.get('selectedMode') === 'single') {
  36684. var hasSelected = false; // If has any selected in option.selected
  36685. for (var i = 0; i < legendData.length; i++) {
  36686. var name = legendData[i].get('name');
  36687. if (this.isSelected(name)) {
  36688. // Force to unselect others
  36689. this.select(name);
  36690. hasSelected = true;
  36691. break;
  36692. }
  36693. } // Try select the first if selectedMode is single
  36694. !hasSelected && this.select(legendData[0].get('name'));
  36695. }
  36696. },
  36697. _updateData: function (ecModel) {
  36698. var potentialData = [];
  36699. var availableNames = [];
  36700. ecModel.eachRawSeries(function (seriesModel) {
  36701. var seriesName = seriesModel.name;
  36702. availableNames.push(seriesName);
  36703. var isPotential;
  36704. if (seriesModel.legendVisualProvider) {
  36705. var provider = seriesModel.legendVisualProvider;
  36706. var names = provider.getAllNames();
  36707. if (!ecModel.isSeriesFiltered(seriesModel)) {
  36708. availableNames = availableNames.concat(names);
  36709. }
  36710. if (names.length) {
  36711. potentialData = potentialData.concat(names);
  36712. } else {
  36713. isPotential = true;
  36714. }
  36715. } else {
  36716. isPotential = true;
  36717. }
  36718. if (isPotential && isNameSpecified(seriesModel)) {
  36719. potentialData.push(seriesModel.name);
  36720. }
  36721. });
  36722. /**
  36723. * @type {Array.<string>}
  36724. * @private
  36725. */
  36726. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  36727. // which is convinient for user preparing option.
  36728. var rawData = this.get('data') || potentialData;
  36729. var legendData = map(rawData, function (dataItem) {
  36730. // Can be string or number
  36731. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  36732. dataItem = {
  36733. name: dataItem
  36734. };
  36735. }
  36736. return new Model(dataItem, this, this.ecModel);
  36737. }, this);
  36738. /**
  36739. * @type {Array.<module:echarts/model/Model>}
  36740. * @private
  36741. */
  36742. this._data = legendData;
  36743. },
  36744. /**
  36745. * @return {Array.<module:echarts/model/Model>}
  36746. */
  36747. getData: function () {
  36748. return this._data;
  36749. },
  36750. /**
  36751. * @param {string} name
  36752. */
  36753. select: function (name) {
  36754. var selected = this.option.selected;
  36755. var selectedMode = this.get('selectedMode');
  36756. if (selectedMode === 'single') {
  36757. var data = this._data;
  36758. each$1(data, function (dataItem) {
  36759. selected[dataItem.get('name')] = false;
  36760. });
  36761. }
  36762. selected[name] = true;
  36763. },
  36764. /**
  36765. * @param {string} name
  36766. */
  36767. unSelect: function (name) {
  36768. if (this.get('selectedMode') !== 'single') {
  36769. this.option.selected[name] = false;
  36770. }
  36771. },
  36772. /**
  36773. * @param {string} name
  36774. */
  36775. toggleSelected: function (name) {
  36776. var selected = this.option.selected; // Default is true
  36777. if (!selected.hasOwnProperty(name)) {
  36778. selected[name] = true;
  36779. }
  36780. this[selected[name] ? 'unSelect' : 'select'](name);
  36781. },
  36782. allSelect: function () {
  36783. var data = this._data;
  36784. var selected = this.option.selected;
  36785. each$1(data, function (dataItem) {
  36786. selected[dataItem.get('name', true)] = true;
  36787. });
  36788. },
  36789. inverseSelect: function () {
  36790. var data = this._data;
  36791. var selected = this.option.selected;
  36792. each$1(data, function (dataItem) {
  36793. var name = dataItem.get('name', true); // Initially, default value is true
  36794. if (!selected.hasOwnProperty(name)) {
  36795. selected[name] = true;
  36796. }
  36797. selected[name] = !selected[name];
  36798. });
  36799. },
  36800. /**
  36801. * @param {string} name
  36802. */
  36803. isSelected: function (name) {
  36804. var selected = this.option.selected;
  36805. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  36806. },
  36807. getOrient: function () {
  36808. return this.get('orient') === 'vertical' ? {
  36809. index: 1,
  36810. name: 'vertical'
  36811. } : {
  36812. index: 0,
  36813. name: 'horizontal'
  36814. };
  36815. },
  36816. defaultOption: {
  36817. // 一级层叠
  36818. zlevel: 0,
  36819. // 二级层叠
  36820. z: 4,
  36821. show: true,
  36822. // 布局方式,默认为水平布局,可选为:
  36823. // 'horizontal' | 'vertical'
  36824. orient: 'horizontal',
  36825. left: 'center',
  36826. // right: 'center',
  36827. top: 0,
  36828. // bottom: null,
  36829. // 水平对齐
  36830. // 'auto' | 'left' | 'right'
  36831. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  36832. align: 'auto',
  36833. backgroundColor: 'rgba(0,0,0,0)',
  36834. // 图例边框颜色
  36835. borderColor: '#ccc',
  36836. borderRadius: 0,
  36837. // 图例边框线宽,单位px,默认为0(无边框)
  36838. borderWidth: 0,
  36839. // 图例内边距,单位px,默认各方向内边距为5,
  36840. // 接受数组分别设定上右下左边距,同css
  36841. padding: 5,
  36842. // 各个item之间的间隔,单位px,默认为10,
  36843. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  36844. itemGap: 10,
  36845. // the width of legend symbol
  36846. itemWidth: 25,
  36847. // the height of legend symbol
  36848. itemHeight: 14,
  36849. // the color of unselected legend symbol
  36850. inactiveColor: '#ccc',
  36851. // the borderColor of unselected legend symbol
  36852. inactiveBorderColor: '#ccc',
  36853. itemStyle: {
  36854. // the default borderWidth of legend symbol
  36855. borderWidth: 0
  36856. },
  36857. textStyle: {
  36858. // 图例文字颜色
  36859. color: '#333'
  36860. },
  36861. // formatter: '',
  36862. // 选择模式,默认开启图例开关
  36863. selectedMode: true,
  36864. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  36865. // selected: null,
  36866. // 图例内容(详见legend.data,数组中每一项代表一个item
  36867. // data: [],
  36868. // Usage:
  36869. // selector: [{type: 'all or inverse', title: xxx}]
  36870. // or
  36871. // selector: true
  36872. // or
  36873. // selector: ['all', 'inverse']
  36874. selector: false,
  36875. selectorLabel: {
  36876. show: true,
  36877. borderRadius: 10,
  36878. padding: [3, 5, 3, 5],
  36879. fontSize: 12,
  36880. fontFamily: ' sans-serif',
  36881. color: '#666',
  36882. borderWidth: 1,
  36883. borderColor: '#666'
  36884. },
  36885. emphasis: {
  36886. selectorLabel: {
  36887. show: true,
  36888. color: '#eee',
  36889. backgroundColor: '#666'
  36890. }
  36891. },
  36892. // Value can be 'start' or 'end'
  36893. selectorPosition: 'auto',
  36894. selectorItemGap: 7,
  36895. selectorButtonGap: 10,
  36896. // Tooltip 相关配置
  36897. tooltip: {
  36898. show: false
  36899. }
  36900. }
  36901. });
  36902. /*
  36903. * Licensed to the Apache Software Foundation (ASF) under one
  36904. * or more contributor license agreements. See the NOTICE file
  36905. * distributed with this work for additional information
  36906. * regarding copyright ownership. The ASF licenses this file
  36907. * to you under the Apache License, Version 2.0 (the
  36908. * "License"); you may not use this file except in compliance
  36909. * with the License. You may obtain a copy of the License at
  36910. *
  36911. * http://www.apache.org/licenses/LICENSE-2.0
  36912. *
  36913. * Unless required by applicable law or agreed to in writing,
  36914. * software distributed under the License is distributed on an
  36915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36916. * KIND, either express or implied. See the License for the
  36917. * specific language governing permissions and limitations
  36918. * under the License.
  36919. */
  36920. function legendSelectActionHandler(methodName, payload, ecModel) {
  36921. var selectedMap = {};
  36922. var isToggleSelect = methodName === 'toggleSelected';
  36923. var isSelected; // Update all legend components
  36924. ecModel.eachComponent('legend', function (legendModel) {
  36925. if (isToggleSelect && isSelected != null) {
  36926. // Force other legend has same selected status
  36927. // Or the first is toggled to true and other are toggled to false
  36928. // In the case one legend has some item unSelected in option. And if other legend
  36929. // doesn't has the item, they will assume it is selected.
  36930. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  36931. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  36932. legendModel[methodName]();
  36933. } else {
  36934. legendModel[methodName](payload.name);
  36935. isSelected = legendModel.isSelected(payload.name);
  36936. }
  36937. var legendData = legendModel.getData();
  36938. each$1(legendData, function (model) {
  36939. var name = model.get('name'); // Wrap element
  36940. if (name === '\n' || name === '') {
  36941. return;
  36942. }
  36943. var isItemSelected = legendModel.isSelected(name);
  36944. if (selectedMap.hasOwnProperty(name)) {
  36945. // Unselected if any legend is unselected
  36946. selectedMap[name] = selectedMap[name] && isItemSelected;
  36947. } else {
  36948. selectedMap[name] = isItemSelected;
  36949. }
  36950. });
  36951. }); // Return the event explicitly
  36952. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  36953. selected: selectedMap
  36954. } : {
  36955. name: payload.name,
  36956. selected: selectedMap
  36957. };
  36958. }
  36959. /**
  36960. * @event legendToggleSelect
  36961. * @type {Object}
  36962. * @property {string} type 'legendToggleSelect'
  36963. * @property {string} [from]
  36964. * @property {string} name Series name or data item name
  36965. */
  36966. registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  36967. registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  36968. registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  36969. /**
  36970. * @event legendSelect
  36971. * @type {Object}
  36972. * @property {string} type 'legendSelect'
  36973. * @property {string} name Series name or data item name
  36974. */
  36975. registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  36976. /**
  36977. * @event legendUnSelect
  36978. * @type {Object}
  36979. * @property {string} type 'legendUnSelect'
  36980. * @property {string} name Series name or data item name
  36981. */
  36982. registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  36983. /*
  36984. * Licensed to the Apache Software Foundation (ASF) under one
  36985. * or more contributor license agreements. See the NOTICE file
  36986. * distributed with this work for additional information
  36987. * regarding copyright ownership. The ASF licenses this file
  36988. * to you under the Apache License, Version 2.0 (the
  36989. * "License"); you may not use this file except in compliance
  36990. * with the License. You may obtain a copy of the License at
  36991. *
  36992. * http://www.apache.org/licenses/LICENSE-2.0
  36993. *
  36994. * Unless required by applicable law or agreed to in writing,
  36995. * software distributed under the License is distributed on an
  36996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36997. * KIND, either express or implied. See the License for the
  36998. * specific language governing permissions and limitations
  36999. * under the License.
  37000. */
  37001. /**
  37002. * Layout list like component.
  37003. * It will box layout each items in group of component and then position the whole group in the viewport
  37004. * @param {module:zrender/group/Group} group
  37005. * @param {module:echarts/model/Component} componentModel
  37006. * @param {module:echarts/ExtensionAPI}
  37007. */
  37008. function makeBackground(rect, componentModel) {
  37009. var padding = normalizeCssArray$1(componentModel.get('padding'));
  37010. var style = componentModel.getItemStyle(['color', 'opacity']);
  37011. style.fill = componentModel.get('backgroundColor');
  37012. var rect = new Rect({
  37013. shape: {
  37014. x: rect.x - padding[3],
  37015. y: rect.y - padding[0],
  37016. width: rect.width + padding[1] + padding[3],
  37017. height: rect.height + padding[0] + padding[2],
  37018. r: componentModel.get('borderRadius')
  37019. },
  37020. style: style,
  37021. silent: true,
  37022. z2: -1
  37023. }); // FIXME
  37024. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  37025. // and background rect when setting like `left: 0`, `top: 0`.
  37026. // graphic.subPixelOptimizeRect(rect);
  37027. return rect;
  37028. }
  37029. /*
  37030. * Licensed to the Apache Software Foundation (ASF) under one
  37031. * or more contributor license agreements. See the NOTICE file
  37032. * distributed with this work for additional information
  37033. * regarding copyright ownership. The ASF licenses this file
  37034. * to you under the Apache License, Version 2.0 (the
  37035. * "License"); you may not use this file except in compliance
  37036. * with the License. You may obtain a copy of the License at
  37037. *
  37038. * http://www.apache.org/licenses/LICENSE-2.0
  37039. *
  37040. * Unless required by applicable law or agreed to in writing,
  37041. * software distributed under the License is distributed on an
  37042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37043. * KIND, either express or implied. See the License for the
  37044. * specific language governing permissions and limitations
  37045. * under the License.
  37046. */
  37047. var curry$2 = curry;
  37048. var each$7 = each$1;
  37049. var Group$2 = Group;
  37050. var LegendView = extendComponentView({
  37051. type: 'legend.plain',
  37052. newlineDisabled: false,
  37053. /**
  37054. * @override
  37055. */
  37056. init: function () {
  37057. /**
  37058. * @private
  37059. * @type {module:zrender/container/Group}
  37060. */
  37061. this.group.add(this._contentGroup = new Group$2());
  37062. /**
  37063. * @private
  37064. * @type {module:zrender/Element}
  37065. */
  37066. this._backgroundEl;
  37067. /**
  37068. * @private
  37069. * @type {module:zrender/container/Group}
  37070. */
  37071. this.group.add(this._selectorGroup = new Group$2());
  37072. /**
  37073. * If first rendering, `contentGroup.position` is [0, 0], which
  37074. * does not make sense and may cause unexepcted animation if adopted.
  37075. * @private
  37076. * @type {boolean}
  37077. */
  37078. this._isFirstRender = true;
  37079. },
  37080. /**
  37081. * @protected
  37082. */
  37083. getContentGroup: function () {
  37084. return this._contentGroup;
  37085. },
  37086. /**
  37087. * @protected
  37088. */
  37089. getSelectorGroup: function () {
  37090. return this._selectorGroup;
  37091. },
  37092. /**
  37093. * @override
  37094. */
  37095. render: function (legendModel, ecModel, api) {
  37096. var isFirstRender = this._isFirstRender;
  37097. this._isFirstRender = false;
  37098. this.resetInner();
  37099. if (!legendModel.get('show', true)) {
  37100. return;
  37101. }
  37102. var itemAlign = legendModel.get('align');
  37103. var orient = legendModel.get('orient');
  37104. if (!itemAlign || itemAlign === 'auto') {
  37105. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  37106. }
  37107. var selector = legendModel.get('selector', true);
  37108. var selectorPosition = legendModel.get('selectorPosition', true);
  37109. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  37110. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  37111. }
  37112. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  37113. var positionInfo = legendModel.getBoxLayoutParams();
  37114. var viewportSize = {
  37115. width: api.getWidth(),
  37116. height: api.getHeight()
  37117. };
  37118. var padding = legendModel.get('padding');
  37119. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  37120. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  37121. var layoutRect = getLayoutRect(defaults({
  37122. width: mainRect.width,
  37123. height: mainRect.height
  37124. }, positionInfo), viewportSize, padding);
  37125. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]); // Render background after group is layout.
  37126. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  37127. },
  37128. /**
  37129. * @protected
  37130. */
  37131. resetInner: function () {
  37132. this.getContentGroup().removeAll();
  37133. this._backgroundEl && this.group.remove(this._backgroundEl);
  37134. this.getSelectorGroup().removeAll();
  37135. },
  37136. /**
  37137. * @protected
  37138. */
  37139. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  37140. var contentGroup = this.getContentGroup();
  37141. var legendDrawnMap = createHashMap();
  37142. var selectMode = legendModel.get('selectedMode');
  37143. var excludeSeriesId = [];
  37144. ecModel.eachRawSeries(function (seriesModel) {
  37145. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  37146. });
  37147. each$7(legendModel.getData(), function (itemModel, dataIndex) {
  37148. var name = itemModel.get('name'); // Use empty string or \n as a newline string
  37149. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  37150. contentGroup.add(new Group$2({
  37151. newline: true
  37152. }));
  37153. return;
  37154. } // Representitive series.
  37155. var seriesModel = ecModel.getSeriesByName(name)[0];
  37156. if (legendDrawnMap.get(name)) {
  37157. // Have been drawed
  37158. return;
  37159. } // Legend to control series.
  37160. if (seriesModel) {
  37161. var data = seriesModel.getData();
  37162. var color = data.getVisual('color');
  37163. var borderColor = data.getVisual('borderColor'); // If color is a callback function
  37164. if (typeof color === 'function') {
  37165. // Use the first data
  37166. color = color(seriesModel.getDataParams(0));
  37167. } // If borderColor is a callback function
  37168. if (typeof borderColor === 'function') {
  37169. // Use the first data
  37170. borderColor = borderColor(seriesModel.getDataParams(0));
  37171. } // Using rect symbol defaultly
  37172. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  37173. var symbolType = data.getVisual('symbol');
  37174. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, selectMode);
  37175. itemGroup.on('click', curry$2(dispatchSelectAction, name, null, api, excludeSeriesId)).on('mouseover', curry$2(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)).on('mouseout', curry$2(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  37176. legendDrawnMap.set(name, true);
  37177. } else {
  37178. // Legend to control data. In pie and funnel.
  37179. ecModel.eachRawSeries(function (seriesModel) {
  37180. // In case multiple series has same data name
  37181. if (legendDrawnMap.get(name)) {
  37182. return;
  37183. }
  37184. if (seriesModel.legendVisualProvider) {
  37185. var provider = seriesModel.legendVisualProvider;
  37186. if (!provider.containName(name)) {
  37187. return;
  37188. }
  37189. var idx = provider.indexOfName(name);
  37190. var color = provider.getItemVisual(idx, 'color');
  37191. var borderColor = provider.getItemVisual(idx, 'borderColor');
  37192. var legendSymbolType = 'roundRect';
  37193. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, null, itemAlign, color, borderColor, selectMode); // FIXME: consider different series has items with the same name.
  37194. itemGroup.on('click', curry$2(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  37195. // more than one pie series.
  37196. .on('mouseover', curry$2(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$2(dispatchDownplayAction, null, name, api, excludeSeriesId));
  37197. legendDrawnMap.set(name, true);
  37198. }
  37199. }, this);
  37200. }
  37201. }, this);
  37202. if (selector) {
  37203. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  37204. }
  37205. },
  37206. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  37207. var selectorGroup = this.getSelectorGroup();
  37208. each$7(selector, function (selectorItem) {
  37209. createSelectorButton(selectorItem);
  37210. });
  37211. function createSelectorButton(selectorItem) {
  37212. var type = selectorItem.type;
  37213. var labelText = new Text({
  37214. style: {
  37215. x: 0,
  37216. y: 0,
  37217. align: 'center',
  37218. verticalAlign: 'middle'
  37219. },
  37220. onclick: function () {
  37221. api.dispatchAction({
  37222. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  37223. });
  37224. }
  37225. });
  37226. selectorGroup.add(labelText);
  37227. var labelModel = legendModel.getModel('selectorLabel');
  37228. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  37229. setLabelStyle(labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel, {
  37230. defaultText: selectorItem.title,
  37231. isRectText: false
  37232. });
  37233. setHoverStyle(labelText);
  37234. }
  37235. },
  37236. _createItem: function (name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, selectMode) {
  37237. var itemWidth = legendModel.get('itemWidth');
  37238. var itemHeight = legendModel.get('itemHeight');
  37239. var inactiveColor = legendModel.get('inactiveColor');
  37240. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  37241. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  37242. var legendModelItemStyle = legendModel.getModel('itemStyle');
  37243. var isSelected = legendModel.isSelected(name);
  37244. var itemGroup = new Group$2();
  37245. var textStyleModel = itemModel.getModel('textStyle');
  37246. var itemIcon = itemModel.get('icon');
  37247. var tooltipModel = itemModel.getModel('tooltip');
  37248. var legendGlobalTooltipModel = tooltipModel.parentModel; // Use user given icon first
  37249. legendSymbolType = itemIcon || legendSymbolType;
  37250. var legendSymbol = createSymbol(legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  37251. symbolKeepAspect == null ? true : symbolKeepAspect);
  37252. itemGroup.add(setSymbolStyle(legendSymbol, legendSymbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected)); // Compose symbols
  37253. // PENDING
  37254. if (!itemIcon && symbolType // At least show one symbol, can't be all none
  37255. && (symbolType !== legendSymbolType || symbolType === 'none')) {
  37256. var size = itemHeight * 0.8;
  37257. if (symbolType === 'none') {
  37258. symbolType = 'circle';
  37259. }
  37260. var legendSymbolCenter = createSymbol(symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  37261. symbolKeepAspect == null ? true : symbolKeepAspect); // Put symbol in the center
  37262. itemGroup.add(setSymbolStyle(legendSymbolCenter, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected));
  37263. }
  37264. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  37265. var textAlign = itemAlign;
  37266. var formatter = legendModel.get('formatter');
  37267. var content = name;
  37268. if (typeof formatter === 'string' && formatter) {
  37269. content = formatter.replace('{name}', name != null ? name : '');
  37270. } else if (typeof formatter === 'function') {
  37271. content = formatter(name);
  37272. }
  37273. itemGroup.add(new Text({
  37274. style: setTextStyle({}, textStyleModel, {
  37275. text: content,
  37276. x: textX,
  37277. y: itemHeight / 2,
  37278. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  37279. textAlign: textAlign,
  37280. textVerticalAlign: 'middle'
  37281. })
  37282. })); // Add a invisible rect to increase the area of mouse hover
  37283. var hitRect = new Rect({
  37284. shape: itemGroup.getBoundingRect(),
  37285. invisible: true,
  37286. tooltip: tooltipModel.get('show') ? extend({
  37287. content: name,
  37288. // Defaul formatter
  37289. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  37290. return name;
  37291. },
  37292. formatterParams: {
  37293. componentType: 'legend',
  37294. legendIndex: legendModel.componentIndex,
  37295. name: name,
  37296. $vars: ['name']
  37297. }
  37298. }, tooltipModel.option) : null
  37299. });
  37300. itemGroup.add(hitRect);
  37301. itemGroup.eachChild(function (child) {
  37302. child.silent = true;
  37303. });
  37304. hitRect.silent = !selectMode;
  37305. this.getContentGroup().add(itemGroup);
  37306. setHoverStyle(itemGroup);
  37307. itemGroup.__legendDataIndex = dataIndex;
  37308. return itemGroup;
  37309. },
  37310. /**
  37311. * @protected
  37312. */
  37313. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  37314. var contentGroup = this.getContentGroup();
  37315. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  37316. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  37317. var contentRect = contentGroup.getBoundingRect();
  37318. var contentPos = [-contentRect.x, -contentRect.y];
  37319. if (selector) {
  37320. // Place buttons in selectorGroup
  37321. box( // Buttons in selectorGroup always layout horizontally
  37322. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  37323. var selectorRect = selectorGroup.getBoundingRect();
  37324. var selectorPos = [-selectorRect.x, -selectorRect.y];
  37325. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  37326. var orientIdx = legendModel.getOrient().index;
  37327. var wh = orientIdx === 0 ? 'width' : 'height';
  37328. var hw = orientIdx === 0 ? 'height' : 'width';
  37329. var yx = orientIdx === 0 ? 'y' : 'x';
  37330. if (selectorPosition === 'end') {
  37331. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  37332. } else {
  37333. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  37334. } //Always align selector to content as 'middle'
  37335. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  37336. selectorGroup.attr('position', selectorPos);
  37337. contentGroup.attr('position', contentPos);
  37338. var mainRect = {
  37339. x: 0,
  37340. y: 0
  37341. };
  37342. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  37343. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  37344. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  37345. return mainRect;
  37346. } else {
  37347. contentGroup.attr('position', contentPos);
  37348. return this.group.getBoundingRect();
  37349. }
  37350. },
  37351. /**
  37352. * @protected
  37353. */
  37354. remove: function () {
  37355. this.getContentGroup().removeAll();
  37356. this._isFirstRender = true;
  37357. }
  37358. });
  37359. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  37360. var itemStyle;
  37361. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  37362. itemStyle = legendModelItemStyle.getItemStyle();
  37363. symbol.style.stroke = borderColor;
  37364. if (!isSelected) {
  37365. itemStyle.stroke = inactiveBorderColor;
  37366. }
  37367. } else {
  37368. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  37369. }
  37370. return symbol.setStyle(itemStyle);
  37371. }
  37372. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  37373. // downplay before unselect
  37374. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  37375. api.dispatchAction({
  37376. type: 'legendToggleSelect',
  37377. name: seriesName != null ? seriesName : dataName
  37378. }); // highlight after select
  37379. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  37380. }
  37381. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  37382. // If element hover will move to a hoverLayer.
  37383. var el = api.getZr().storage.getDisplayList()[0];
  37384. if (!(el && el.useHoverLayer)) {
  37385. api.dispatchAction({
  37386. type: 'highlight',
  37387. seriesName: seriesName,
  37388. name: dataName,
  37389. excludeSeriesId: excludeSeriesId
  37390. });
  37391. }
  37392. }
  37393. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  37394. // If element hover will move to a hoverLayer.
  37395. var el = api.getZr().storage.getDisplayList()[0];
  37396. if (!(el && el.useHoverLayer)) {
  37397. api.dispatchAction({
  37398. type: 'downplay',
  37399. seriesName: seriesName,
  37400. name: dataName,
  37401. excludeSeriesId: excludeSeriesId
  37402. });
  37403. }
  37404. }
  37405. /*
  37406. * Licensed to the Apache Software Foundation (ASF) under one
  37407. * or more contributor license agreements. See the NOTICE file
  37408. * distributed with this work for additional information
  37409. * regarding copyright ownership. The ASF licenses this file
  37410. * to you under the Apache License, Version 2.0 (the
  37411. * "License"); you may not use this file except in compliance
  37412. * with the License. You may obtain a copy of the License at
  37413. *
  37414. * http://www.apache.org/licenses/LICENSE-2.0
  37415. *
  37416. * Unless required by applicable law or agreed to in writing,
  37417. * software distributed under the License is distributed on an
  37418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37419. * KIND, either express or implied. See the License for the
  37420. * specific language governing permissions and limitations
  37421. * under the License.
  37422. */
  37423. var legendFilter = function (ecModel) {
  37424. var legendModels = ecModel.findComponents({
  37425. mainType: 'legend'
  37426. });
  37427. if (legendModels && legendModels.length) {
  37428. ecModel.filterSeries(function (series) {
  37429. // If in any legend component the status is not selected.
  37430. // Because in legend series is assumed selected when it is not in the legend data.
  37431. for (var i = 0; i < legendModels.length; i++) {
  37432. if (!legendModels[i].isSelected(series.name)) {
  37433. return false;
  37434. }
  37435. }
  37436. return true;
  37437. });
  37438. }
  37439. };
  37440. /*
  37441. * Licensed to the Apache Software Foundation (ASF) under one
  37442. * or more contributor license agreements. See the NOTICE file
  37443. * distributed with this work for additional information
  37444. * regarding copyright ownership. The ASF licenses this file
  37445. * to you under the Apache License, Version 2.0 (the
  37446. * "License"); you may not use this file except in compliance
  37447. * with the License. You may obtain a copy of the License at
  37448. *
  37449. * http://www.apache.org/licenses/LICENSE-2.0
  37450. *
  37451. * Unless required by applicable law or agreed to in writing,
  37452. * software distributed under the License is distributed on an
  37453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37454. * KIND, either express or implied. See the License for the
  37455. * specific language governing permissions and limitations
  37456. * under the License.
  37457. */
  37458. // Do not contain scrollable legend, for sake of file size.
  37459. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  37460. ComponentModel.registerSubTypeDefaulter('legend', function () {
  37461. // Default 'plain' when no type specified.
  37462. return 'plain';
  37463. });
  37464. /*
  37465. * Licensed to the Apache Software Foundation (ASF) under one
  37466. * or more contributor license agreements. See the NOTICE file
  37467. * distributed with this work for additional information
  37468. * regarding copyright ownership. The ASF licenses this file
  37469. * to you under the Apache License, Version 2.0 (the
  37470. * "License"); you may not use this file except in compliance
  37471. * with the License. You may obtain a copy of the License at
  37472. *
  37473. * http://www.apache.org/licenses/LICENSE-2.0
  37474. *
  37475. * Unless required by applicable law or agreed to in writing,
  37476. * software distributed under the License is distributed on an
  37477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37478. * KIND, either express or implied. See the License for the
  37479. * specific language governing permissions and limitations
  37480. * under the License.
  37481. */
  37482. var ScrollableLegendModel = LegendModel.extend({
  37483. type: 'legend.scroll',
  37484. /**
  37485. * @param {number} scrollDataIndex
  37486. */
  37487. setScrollDataIndex: function (scrollDataIndex) {
  37488. this.option.scrollDataIndex = scrollDataIndex;
  37489. },
  37490. defaultOption: {
  37491. scrollDataIndex: 0,
  37492. pageButtonItemGap: 5,
  37493. pageButtonGap: null,
  37494. pageButtonPosition: 'end',
  37495. // 'start' or 'end'
  37496. pageFormatter: '{current}/{total}',
  37497. // If null/undefined, do not show page.
  37498. pageIcons: {
  37499. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  37500. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  37501. },
  37502. pageIconColor: '#2f4554',
  37503. pageIconInactiveColor: '#aaa',
  37504. pageIconSize: 15,
  37505. // Can be [10, 3], which represents [width, height]
  37506. pageTextStyle: {
  37507. color: '#333'
  37508. },
  37509. animationDurationUpdate: 800
  37510. },
  37511. /**
  37512. * @override
  37513. */
  37514. init: function (option, parentModel, ecModel, extraOpt) {
  37515. var inputPositionParams = getLayoutParams(option);
  37516. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  37517. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  37518. },
  37519. /**
  37520. * @override
  37521. */
  37522. mergeOption: function (option, extraOpt) {
  37523. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  37524. mergeAndNormalizeLayoutParams(this, this.option, option);
  37525. }
  37526. }); // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  37527. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  37528. var orient = legendModel.getOrient();
  37529. var ignoreSize = [1, 1];
  37530. ignoreSize[orient.index] = 0;
  37531. mergeLayoutParam(target, raw, {
  37532. type: 'box',
  37533. ignoreSize: ignoreSize
  37534. });
  37535. }
  37536. /*
  37537. * Licensed to the Apache Software Foundation (ASF) under one
  37538. * or more contributor license agreements. See the NOTICE file
  37539. * distributed with this work for additional information
  37540. * regarding copyright ownership. The ASF licenses this file
  37541. * to you under the Apache License, Version 2.0 (the
  37542. * "License"); you may not use this file except in compliance
  37543. * with the License. You may obtain a copy of the License at
  37544. *
  37545. * http://www.apache.org/licenses/LICENSE-2.0
  37546. *
  37547. * Unless required by applicable law or agreed to in writing,
  37548. * software distributed under the License is distributed on an
  37549. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37550. * KIND, either express or implied. See the License for the
  37551. * specific language governing permissions and limitations
  37552. * under the License.
  37553. */
  37554. /**
  37555. * Separate legend and scrollable legend to reduce package size.
  37556. */
  37557. var Group$3 = Group;
  37558. var WH = ['width', 'height'];
  37559. var XY = ['x', 'y'];
  37560. var ScrollableLegendView = LegendView.extend({
  37561. type: 'legend.scroll',
  37562. newlineDisabled: true,
  37563. init: function () {
  37564. ScrollableLegendView.superCall(this, 'init');
  37565. /**
  37566. * @private
  37567. * @type {number} For `scroll`.
  37568. */
  37569. this._currentIndex = 0;
  37570. /**
  37571. * @private
  37572. * @type {module:zrender/container/Group}
  37573. */
  37574. this.group.add(this._containerGroup = new Group$3());
  37575. this._containerGroup.add(this.getContentGroup());
  37576. /**
  37577. * @private
  37578. * @type {module:zrender/container/Group}
  37579. */
  37580. this.group.add(this._controllerGroup = new Group$3());
  37581. /**
  37582. *
  37583. * @private
  37584. */
  37585. this._showController;
  37586. },
  37587. /**
  37588. * @override
  37589. */
  37590. resetInner: function () {
  37591. ScrollableLegendView.superCall(this, 'resetInner');
  37592. this._controllerGroup.removeAll();
  37593. this._containerGroup.removeClipPath();
  37594. this._containerGroup.__rectSize = null;
  37595. },
  37596. /**
  37597. * @override
  37598. */
  37599. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  37600. var me = this; // Render content items.
  37601. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  37602. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  37603. // e.g., '3/12345' should not overlap with the control arrow button.
  37604. var pageIconSize = legendModel.get('pageIconSize', true);
  37605. if (!isArray(pageIconSize)) {
  37606. pageIconSize = [pageIconSize, pageIconSize];
  37607. }
  37608. createPageButton('pagePrev', 0);
  37609. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  37610. controllerGroup.add(new Text({
  37611. name: 'pageText',
  37612. style: {
  37613. textFill: pageTextStyleModel.getTextColor(),
  37614. font: pageTextStyleModel.getFont(),
  37615. textVerticalAlign: 'middle',
  37616. textAlign: 'center'
  37617. },
  37618. silent: true
  37619. }));
  37620. createPageButton('pageNext', 1);
  37621. function createPageButton(name, iconIdx) {
  37622. var pageDataIndexName = name + 'DataIndex';
  37623. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  37624. // Buttons will be created in each render, so we do not need
  37625. // to worry about avoiding using legendModel kept in scope.
  37626. onclick: bind(me._pageGo, me, pageDataIndexName, legendModel, api)
  37627. }, {
  37628. x: -pageIconSize[0] / 2,
  37629. y: -pageIconSize[1] / 2,
  37630. width: pageIconSize[0],
  37631. height: pageIconSize[1]
  37632. });
  37633. icon.name = name;
  37634. controllerGroup.add(icon);
  37635. }
  37636. },
  37637. /**
  37638. * @override
  37639. */
  37640. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  37641. var selectorGroup = this.getSelectorGroup();
  37642. var orientIdx = legendModel.getOrient().index;
  37643. var wh = WH[orientIdx];
  37644. var xy = XY[orientIdx];
  37645. var hw = WH[1 - orientIdx];
  37646. var yx = XY[1 - orientIdx];
  37647. selector && box( // Buttons in selectorGroup always layout horizontally
  37648. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  37649. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  37650. var selectorRect = selectorGroup.getBoundingRect();
  37651. var selectorPos = [-selectorRect.x, -selectorRect.y];
  37652. var processMaxSize = clone(maxSize);
  37653. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  37654. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx);
  37655. if (selector) {
  37656. if (selectorPosition === 'end') {
  37657. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  37658. } else {
  37659. var offset = selectorRect[wh] + selectorButtonGap;
  37660. selectorPos[orientIdx] -= offset;
  37661. mainRect[xy] -= offset;
  37662. }
  37663. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  37664. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  37665. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  37666. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  37667. selectorGroup.attr('position', selectorPos);
  37668. }
  37669. return mainRect;
  37670. },
  37671. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  37672. var contentGroup = this.getContentGroup();
  37673. var containerGroup = this._containerGroup;
  37674. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  37675. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  37676. box( // Buttons in controller are layout always horizontally.
  37677. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  37678. var contentRect = contentGroup.getBoundingRect();
  37679. var controllerRect = controllerGroup.getBoundingRect();
  37680. var showController = this._showController = contentRect[wh] > maxSize[wh];
  37681. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  37682. // If first rendering, `contentGroup.position` is [0, 0], which
  37683. // does not make sense and may cause unexepcted animation if adopted.
  37684. if (!isFirstRender) {
  37685. contentPos[orientIdx] = contentGroup.position[orientIdx];
  37686. } // Layout container group based on 0.
  37687. var containerPos = [0, 0];
  37688. var controllerPos = [-controllerRect.x, -controllerRect.y];
  37689. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  37690. if (showController) {
  37691. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  37692. if (pageButtonPosition === 'end') {
  37693. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  37694. } // controller is on the left / top.
  37695. else {
  37696. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  37697. }
  37698. } // Always align controller to content as 'middle'.
  37699. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  37700. contentGroup.attr('position', contentPos);
  37701. containerGroup.attr('position', containerPos);
  37702. controllerGroup.attr('position', controllerPos); // Calculate `mainRect` and set `clipPath`.
  37703. // mainRect should not be calculated by `this.group.getBoundingRect()`
  37704. // for sake of the overflow.
  37705. var mainRect = {
  37706. x: 0,
  37707. y: 0
  37708. }; // Consider content may be overflow (should be clipped).
  37709. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  37710. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  37711. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  37712. containerGroup.__rectSize = maxSize[wh];
  37713. if (showController) {
  37714. var clipShape = {
  37715. x: 0,
  37716. y: 0
  37717. };
  37718. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  37719. clipShape[hw] = mainRect[hw];
  37720. containerGroup.setClipPath(new Rect({
  37721. shape: clipShape
  37722. })); // Consider content may be larger than container, container rect
  37723. // can not be obtained from `containerGroup.getBoundingRect()`.
  37724. containerGroup.__rectSize = clipShape[wh];
  37725. } else {
  37726. // Do not remove or ignore controller. Keep them set as placeholders.
  37727. controllerGroup.eachChild(function (child) {
  37728. child.attr({
  37729. invisible: true,
  37730. silent: true
  37731. });
  37732. });
  37733. } // Content translate animation.
  37734. var pageInfo = this._getPageInfo(legendModel);
  37735. pageInfo.pageIndex != null && updateProps(contentGroup, {
  37736. position: pageInfo.contentPosition
  37737. }, // When switch from "show controller" to "not show controller", view should be
  37738. // updated immediately without animation, otherwise causes weird effect.
  37739. showController ? legendModel : false);
  37740. this._updatePageInfoView(legendModel, pageInfo);
  37741. return mainRect;
  37742. },
  37743. _pageGo: function (to, legendModel, api) {
  37744. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  37745. scrollDataIndex != null && api.dispatchAction({
  37746. type: 'legendScroll',
  37747. scrollDataIndex: scrollDataIndex,
  37748. legendId: legendModel.id
  37749. });
  37750. },
  37751. _updatePageInfoView: function (legendModel, pageInfo) {
  37752. var controllerGroup = this._controllerGroup;
  37753. each$1(['pagePrev', 'pageNext'], function (name) {
  37754. var canJump = pageInfo[name + 'DataIndex'] != null;
  37755. var icon = controllerGroup.childOfName(name);
  37756. if (icon) {
  37757. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  37758. icon.cursor = canJump ? 'pointer' : 'default';
  37759. }
  37760. });
  37761. var pageText = controllerGroup.childOfName('pageText');
  37762. var pageFormatter = legendModel.get('pageFormatter');
  37763. var pageIndex = pageInfo.pageIndex;
  37764. var current = pageIndex != null ? pageIndex + 1 : 0;
  37765. var total = pageInfo.pageCount;
  37766. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current).replace('{total}', total) : pageFormatter({
  37767. current: current,
  37768. total: total
  37769. }));
  37770. },
  37771. /**
  37772. * @param {module:echarts/model/Model} legendModel
  37773. * @return {Object} {
  37774. * contentPosition: Array.<number>, null when data item not found.
  37775. * pageIndex: number, null when data item not found.
  37776. * pageCount: number, always be a number, can be 0.
  37777. * pagePrevDataIndex: number, null when no previous page.
  37778. * pageNextDataIndex: number, null when no next page.
  37779. * }
  37780. */
  37781. _getPageInfo: function (legendModel) {
  37782. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  37783. var contentGroup = this.getContentGroup();
  37784. var containerRectSize = this._containerGroup.__rectSize;
  37785. var orientIdx = legendModel.getOrient().index;
  37786. var wh = WH[orientIdx];
  37787. var xy = XY[orientIdx];
  37788. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  37789. var children = contentGroup.children();
  37790. var targetItem = children[targetItemIndex];
  37791. var itemCount = children.length;
  37792. var pCount = !itemCount ? 0 : 1;
  37793. var result = {
  37794. contentPosition: contentGroup.position.slice(),
  37795. pageCount: pCount,
  37796. pageIndex: pCount - 1,
  37797. pagePrevDataIndex: null,
  37798. pageNextDataIndex: null
  37799. };
  37800. if (!targetItem) {
  37801. return result;
  37802. }
  37803. var targetItemInfo = getItemInfo(targetItem);
  37804. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  37805. // (1) Always align based on the left/top most item.
  37806. // (2) It is user-friendly that the last item shown in the
  37807. // current window is shown at the begining of next window.
  37808. // Otherwise if half of the last item is cut by the window,
  37809. // it will have no chance to display entirely.
  37810. // (3) Consider that item size probably be different, we
  37811. // have calculate pageIndex by size rather than item index,
  37812. // and we can not get page index directly by division.
  37813. // (4) The window is to narrow to contain more than
  37814. // one item, we should make sure that the page can be fliped.
  37815. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  37816. currItemInfo = getItemInfo(children[i]);
  37817. if ( // Half of the last item is out of the window.
  37818. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  37819. // can be started at the current item or the last item.
  37820. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  37821. if (winEndItemInfo.i > winStartItemInfo.i) {
  37822. winStartItemInfo = winEndItemInfo;
  37823. } else {
  37824. // e.g., when page size is smaller than item size.
  37825. winStartItemInfo = currItemInfo;
  37826. }
  37827. if (winStartItemInfo) {
  37828. if (result.pageNextDataIndex == null) {
  37829. result.pageNextDataIndex = winStartItemInfo.i;
  37830. }
  37831. ++result.pageCount;
  37832. }
  37833. }
  37834. winEndItemInfo = currItemInfo;
  37835. }
  37836. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  37837. currItemInfo = getItemInfo(children[i]);
  37838. if ( // If the the end item does not intersect with the window started
  37839. // from the current item, a page can be settled.
  37840. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  37841. winStartItemInfo.i < winEndItemInfo.i) {
  37842. winEndItemInfo = winStartItemInfo;
  37843. if (result.pagePrevDataIndex == null) {
  37844. result.pagePrevDataIndex = winStartItemInfo.i;
  37845. }
  37846. ++result.pageCount;
  37847. ++result.pageIndex;
  37848. }
  37849. winStartItemInfo = currItemInfo;
  37850. }
  37851. return result;
  37852. function getItemInfo(el) {
  37853. if (el) {
  37854. var itemRect = el.getBoundingRect();
  37855. var start = itemRect[xy] + el.position[orientIdx];
  37856. return {
  37857. s: start,
  37858. e: start + itemRect[wh],
  37859. i: el.__legendDataIndex
  37860. };
  37861. }
  37862. }
  37863. function intersect(itemInfo, winStart) {
  37864. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  37865. }
  37866. },
  37867. _findTargetItemIndex: function (targetDataIndex) {
  37868. if (!this._showController) {
  37869. return 0;
  37870. }
  37871. var index;
  37872. var contentGroup = this.getContentGroup();
  37873. var defaultIndex;
  37874. contentGroup.eachChild(function (child, idx) {
  37875. var legendDataIdx = child.__legendDataIndex; // FIXME
  37876. // If the given targetDataIndex (from model) is illegal,
  37877. // we use defualtIndex. But the index on the legend model and
  37878. // action payload is still illegal. That case will not be
  37879. // changed until some scenario requires.
  37880. if (defaultIndex == null && legendDataIdx != null) {
  37881. defaultIndex = idx;
  37882. }
  37883. if (legendDataIdx === targetDataIndex) {
  37884. index = idx;
  37885. }
  37886. });
  37887. return index != null ? index : defaultIndex;
  37888. }
  37889. });
  37890. /*
  37891. * Licensed to the Apache Software Foundation (ASF) under one
  37892. * or more contributor license agreements. See the NOTICE file
  37893. * distributed with this work for additional information
  37894. * regarding copyright ownership. The ASF licenses this file
  37895. * to you under the Apache License, Version 2.0 (the
  37896. * "License"); you may not use this file except in compliance
  37897. * with the License. You may obtain a copy of the License at
  37898. *
  37899. * http://www.apache.org/licenses/LICENSE-2.0
  37900. *
  37901. * Unless required by applicable law or agreed to in writing,
  37902. * software distributed under the License is distributed on an
  37903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37904. * KIND, either express or implied. See the License for the
  37905. * specific language governing permissions and limitations
  37906. * under the License.
  37907. */
  37908. /**
  37909. * @event legendScroll
  37910. * @type {Object}
  37911. * @property {string} type 'legendScroll'
  37912. * @property {string} scrollDataIndex
  37913. */
  37914. registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  37915. var scrollDataIndex = payload.scrollDataIndex;
  37916. scrollDataIndex != null && ecModel.eachComponent({
  37917. mainType: 'legend',
  37918. subType: 'scroll',
  37919. query: payload
  37920. }, function (legendModel) {
  37921. legendModel.setScrollDataIndex(scrollDataIndex);
  37922. });
  37923. });
  37924. /*
  37925. * Licensed to the Apache Software Foundation (ASF) under one
  37926. * or more contributor license agreements. See the NOTICE file
  37927. * distributed with this work for additional information
  37928. * regarding copyright ownership. The ASF licenses this file
  37929. * to you under the Apache License, Version 2.0 (the
  37930. * "License"); you may not use this file except in compliance
  37931. * with the License. You may obtain a copy of the License at
  37932. *
  37933. * http://www.apache.org/licenses/LICENSE-2.0
  37934. *
  37935. * Unless required by applicable law or agreed to in writing,
  37936. * software distributed under the License is distributed on an
  37937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37938. * KIND, either express or implied. See the License for the
  37939. * specific language governing permissions and limitations
  37940. * under the License.
  37941. */
  37942. /**
  37943. * Legend component entry file8
  37944. */
  37945. /*
  37946. * Licensed to the Apache Software Foundation (ASF) under one
  37947. * or more contributor license agreements. See the NOTICE file
  37948. * distributed with this work for additional information
  37949. * regarding copyright ownership. The ASF licenses this file
  37950. * to you under the Apache License, Version 2.0 (the
  37951. * "License"); you may not use this file except in compliance
  37952. * with the License. You may obtain a copy of the License at
  37953. *
  37954. * http://www.apache.org/licenses/LICENSE-2.0
  37955. *
  37956. * Unless required by applicable law or agreed to in writing,
  37957. * software distributed under the License is distributed on an
  37958. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37959. * KIND, either express or implied. See the License for the
  37960. * specific language governing permissions and limitations
  37961. * under the License.
  37962. */
  37963. /**
  37964. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  37965. * @param {module:echarts/model/Global} ecModel
  37966. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  37967. */
  37968. var findPointFromSeries = function (finder, ecModel) {
  37969. var point = [];
  37970. var seriesIndex = finder.seriesIndex;
  37971. var seriesModel;
  37972. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  37973. return {
  37974. point: []
  37975. };
  37976. }
  37977. var data = seriesModel.getData();
  37978. var dataIndex = queryDataIndex(data, finder);
  37979. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  37980. return {
  37981. point: []
  37982. };
  37983. }
  37984. var el = data.getItemGraphicEl(dataIndex);
  37985. var coordSys = seriesModel.coordinateSystem;
  37986. if (seriesModel.getTooltipPosition) {
  37987. point = seriesModel.getTooltipPosition(dataIndex) || [];
  37988. } else if (coordSys && coordSys.dataToPoint) {
  37989. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  37990. return data.mapDimension(dim);
  37991. }), dataIndex, true)) || [];
  37992. } else if (el) {
  37993. // Use graphic bounding rect
  37994. var rect = el.getBoundingRect().clone();
  37995. rect.applyTransform(el.transform);
  37996. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  37997. }
  37998. return {
  37999. point: point,
  38000. el: el
  38001. };
  38002. };
  38003. /*
  38004. * Licensed to the Apache Software Foundation (ASF) under one
  38005. * or more contributor license agreements. See the NOTICE file
  38006. * distributed with this work for additional information
  38007. * regarding copyright ownership. The ASF licenses this file
  38008. * to you under the Apache License, Version 2.0 (the
  38009. * "License"); you may not use this file except in compliance
  38010. * with the License. You may obtain a copy of the License at
  38011. *
  38012. * http://www.apache.org/licenses/LICENSE-2.0
  38013. *
  38014. * Unless required by applicable law or agreed to in writing,
  38015. * software distributed under the License is distributed on an
  38016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38017. * KIND, either express or implied. See the License for the
  38018. * specific language governing permissions and limitations
  38019. * under the License.
  38020. */
  38021. var each$8 = each$1;
  38022. var curry$3 = curry;
  38023. var inner$7 = makeInner();
  38024. /**
  38025. * Basic logic: check all axis, if they do not demand show/highlight,
  38026. * then hide/downplay them.
  38027. *
  38028. * @param {Object} coordSysAxesInfo
  38029. * @param {Object} payload
  38030. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  38031. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  38032. * trigger axisPointer and tooltip.
  38033. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  38034. * trigger axisPointer and tooltip.
  38035. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  38036. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  38037. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  38038. * [{
  38039. * axisDim: 'x'|'y'|'angle'|...,
  38040. * axisIndex: ...,
  38041. * value: ...
  38042. * }, ...]
  38043. * @param {Function} [payload.dispatchAction]
  38044. * @param {Object} [payload.tooltipOption]
  38045. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  38046. * which can be specified in dispatchAction
  38047. * @param {module:echarts/model/Global} ecModel
  38048. * @param {module:echarts/ExtensionAPI} api
  38049. * @return {Object} content of event obj for echarts.connect.
  38050. */
  38051. var axisTrigger = function (payload, ecModel, api) {
  38052. var currTrigger = payload.currTrigger;
  38053. var point = [payload.x, payload.y];
  38054. var finder = payload;
  38055. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  38056. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  38057. // See #6121. But we are not able to reproduce it yet.
  38058. if (!coordSysAxesInfo) {
  38059. return;
  38060. }
  38061. if (illegalPoint(point)) {
  38062. // Used in the default behavior of `connection`: use the sample seriesIndex
  38063. // and dataIndex. And also used in the tooltipView trigger.
  38064. point = findPointFromSeries({
  38065. seriesIndex: finder.seriesIndex,
  38066. // Do not use dataIndexInside from other ec instance.
  38067. // FIXME: auto detect it?
  38068. dataIndex: finder.dataIndex
  38069. }, ecModel).point;
  38070. }
  38071. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  38072. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  38073. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  38074. // and dataIndex.
  38075. var inputAxesInfo = finder.axesInfo;
  38076. var axesInfo = coordSysAxesInfo.axesInfo;
  38077. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  38078. var outputFinder = {};
  38079. var showValueMap = {};
  38080. var dataByCoordSys = {
  38081. list: [],
  38082. map: {}
  38083. };
  38084. var updaters = {
  38085. showPointer: curry$3(showPointer, showValueMap),
  38086. showTooltip: curry$3(showTooltip, dataByCoordSys)
  38087. }; // Process for triggered axes.
  38088. each$8(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  38089. // If a point given, it must be contained by the coordinate system.
  38090. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  38091. each$8(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  38092. var axis = axisInfo.axis;
  38093. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  38094. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  38095. var val = inputAxisInfo && inputAxisInfo.value;
  38096. if (val == null && !isIllegalPoint) {
  38097. val = axis.pointToData(point);
  38098. }
  38099. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  38100. }
  38101. });
  38102. }); // Process for linked axes.
  38103. var linkTriggers = {};
  38104. each$8(axesInfo, function (tarAxisInfo, tarKey) {
  38105. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  38106. if (linkGroup && !showValueMap[tarKey]) {
  38107. each$8(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  38108. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  38109. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  38110. var val = srcValItem.value;
  38111. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  38112. linkTriggers[tarAxisInfo.key] = val;
  38113. }
  38114. });
  38115. }
  38116. });
  38117. each$8(linkTriggers, function (val, tarKey) {
  38118. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  38119. });
  38120. updateModelActually(showValueMap, axesInfo, outputFinder);
  38121. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  38122. dispatchHighDownActually(axesInfo, dispatchAction, api);
  38123. return outputFinder;
  38124. };
  38125. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  38126. var axis = axisInfo.axis;
  38127. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  38128. return;
  38129. }
  38130. if (!axisInfo.involveSeries) {
  38131. updaters.showPointer(axisInfo, newValue);
  38132. return;
  38133. } // Heavy calculation. So put it after axis.containData checking.
  38134. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  38135. var payloadBatch = payloadInfo.payloadBatch;
  38136. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  38137. // By defualt use the first involved series data as a sample to connect.
  38138. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  38139. extend(outputFinder, payloadBatch[0]);
  38140. } // If no linkSource input, this process is for collecting link
  38141. // target, where snap should not be accepted.
  38142. if (!dontSnap && axisInfo.snap) {
  38143. if (axis.containData(snapToValue) && snapToValue != null) {
  38144. newValue = snapToValue;
  38145. }
  38146. }
  38147. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder); // Tooltip should always be snapToValue, otherwise there will be
  38148. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  38149. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  38150. }
  38151. function buildPayloadsBySeries(value, axisInfo) {
  38152. var axis = axisInfo.axis;
  38153. var dim = axis.dim;
  38154. var snapToValue = value;
  38155. var payloadBatch = [];
  38156. var minDist = Number.MAX_VALUE;
  38157. var minDiff = -1;
  38158. each$8(axisInfo.seriesModels, function (series, idx) {
  38159. var dataDim = series.getData().mapDimension(dim, true);
  38160. var seriesNestestValue;
  38161. var dataIndices;
  38162. if (series.getAxisTooltipData) {
  38163. var result = series.getAxisTooltipData(dataDim, value, axis);
  38164. dataIndices = result.dataIndices;
  38165. seriesNestestValue = result.nestestValue;
  38166. } else {
  38167. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  38168. // when data length is not same.
  38169. // false,
  38170. axis.type === 'category' ? 0.5 : null);
  38171. if (!dataIndices.length) {
  38172. return;
  38173. }
  38174. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  38175. }
  38176. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  38177. return;
  38178. }
  38179. var diff = value - seriesNestestValue;
  38180. var dist = Math.abs(diff); // Consider category case
  38181. if (dist <= minDist) {
  38182. if (dist < minDist || diff >= 0 && minDiff < 0) {
  38183. minDist = dist;
  38184. minDiff = diff;
  38185. snapToValue = seriesNestestValue;
  38186. payloadBatch.length = 0;
  38187. }
  38188. each$8(dataIndices, function (dataIndex) {
  38189. payloadBatch.push({
  38190. seriesIndex: series.seriesIndex,
  38191. dataIndexInside: dataIndex,
  38192. dataIndex: series.getData().getRawIndex(dataIndex)
  38193. });
  38194. });
  38195. }
  38196. });
  38197. return {
  38198. payloadBatch: payloadBatch,
  38199. snapToValue: snapToValue
  38200. };
  38201. }
  38202. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  38203. showValueMap[axisInfo.key] = {
  38204. value: value,
  38205. payloadBatch: payloadBatch
  38206. };
  38207. }
  38208. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  38209. var payloadBatch = payloadInfo.payloadBatch;
  38210. var axis = axisInfo.axis;
  38211. var axisModel = axis.model;
  38212. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  38213. // whose length will be used to judge whether dispatch action.
  38214. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  38215. return;
  38216. }
  38217. var coordSysModel = axisInfo.coordSys.model;
  38218. var coordSysKey = makeKey(coordSysModel);
  38219. var coordSysItem = dataByCoordSys.map[coordSysKey];
  38220. if (!coordSysItem) {
  38221. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  38222. coordSysId: coordSysModel.id,
  38223. coordSysIndex: coordSysModel.componentIndex,
  38224. coordSysType: coordSysModel.type,
  38225. coordSysMainType: coordSysModel.mainType,
  38226. dataByAxis: []
  38227. };
  38228. dataByCoordSys.list.push(coordSysItem);
  38229. }
  38230. coordSysItem.dataByAxis.push({
  38231. axisDim: axis.dim,
  38232. axisIndex: axisModel.componentIndex,
  38233. axisType: axisModel.type,
  38234. axisId: axisModel.id,
  38235. value: value,
  38236. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  38237. // depends that all models have been updated. So it should not be performed
  38238. // here. Considering axisPointerModel used here is volatile, which is hard
  38239. // to be retrieve in TooltipView, we prepare parameters here.
  38240. valueLabelOpt: {
  38241. precision: axisPointerModel.get('label.precision'),
  38242. formatter: axisPointerModel.get('label.formatter')
  38243. },
  38244. seriesDataIndices: payloadBatch.slice()
  38245. });
  38246. }
  38247. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  38248. var outputAxesInfo = outputFinder.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  38249. each$8(axesInfo, function (axisInfo, key) {
  38250. var option = axisInfo.axisPointerModel.option;
  38251. var valItem = showValueMap[key];
  38252. if (valItem) {
  38253. !axisInfo.useHandle && (option.status = 'show');
  38254. option.value = valItem.value; // For label formatter param and highlight.
  38255. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  38256. } // When always show (e.g., handle used), remain
  38257. // original value and status.
  38258. else {
  38259. // If hide, value still need to be set, consider
  38260. // click legend to toggle axis blank.
  38261. !axisInfo.useHandle && (option.status = 'hide');
  38262. } // If status is 'hide', should be no info in payload.
  38263. option.status === 'show' && outputAxesInfo.push({
  38264. axisDim: axisInfo.axis.dim,
  38265. axisIndex: axisInfo.axis.model.componentIndex,
  38266. value: option.value
  38267. });
  38268. });
  38269. }
  38270. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  38271. // Basic logic: If no showTip required, hideTip will be dispatched.
  38272. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  38273. dispatchAction({
  38274. type: 'hideTip'
  38275. });
  38276. return;
  38277. } // In most case only one axis (or event one series is used). It is
  38278. // convinient to fetch payload.seriesIndex and payload.dataIndex
  38279. // dirtectly. So put the first seriesIndex and dataIndex of the first
  38280. // axis on the payload.
  38281. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  38282. dispatchAction({
  38283. type: 'showTip',
  38284. escapeConnect: true,
  38285. x: point[0],
  38286. y: point[1],
  38287. tooltipOption: payload.tooltipOption,
  38288. position: payload.position,
  38289. dataIndexInside: sampleItem.dataIndexInside,
  38290. dataIndex: sampleItem.dataIndex,
  38291. seriesIndex: sampleItem.seriesIndex,
  38292. dataByCoordSys: dataByCoordSys.list
  38293. });
  38294. }
  38295. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  38296. // FIXME
  38297. // highlight status modification shoule be a stage of main process?
  38298. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  38299. var zr = api.getZr();
  38300. var highDownKey = 'axisPointerLastHighlights';
  38301. var lastHighlights = inner$7(zr)[highDownKey] || {};
  38302. var newHighlights = inner$7(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  38303. // Build hash map and remove duplicate incidentally.
  38304. each$8(axesInfo, function (axisInfo, key) {
  38305. var option = axisInfo.axisPointerModel.option;
  38306. option.status === 'show' && each$8(option.seriesDataIndices, function (batchItem) {
  38307. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  38308. newHighlights[key] = batchItem;
  38309. });
  38310. }); // Diff.
  38311. var toHighlight = [];
  38312. var toDownplay = [];
  38313. each$1(lastHighlights, function (batchItem, key) {
  38314. !newHighlights[key] && toDownplay.push(batchItem);
  38315. });
  38316. each$1(newHighlights, function (batchItem, key) {
  38317. !lastHighlights[key] && toHighlight.push(batchItem);
  38318. });
  38319. toDownplay.length && api.dispatchAction({
  38320. type: 'downplay',
  38321. escapeConnect: true,
  38322. batch: toDownplay
  38323. });
  38324. toHighlight.length && api.dispatchAction({
  38325. type: 'highlight',
  38326. escapeConnect: true,
  38327. batch: toHighlight
  38328. });
  38329. }
  38330. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  38331. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  38332. var inputAxisInfo = inputAxesInfo[i];
  38333. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  38334. return inputAxisInfo;
  38335. }
  38336. }
  38337. }
  38338. function makeMapperParam(axisInfo) {
  38339. var axisModel = axisInfo.axis.model;
  38340. var item = {};
  38341. var dim = item.axisDim = axisInfo.axis.dim;
  38342. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  38343. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  38344. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  38345. return item;
  38346. }
  38347. function illegalPoint(point) {
  38348. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  38349. }
  38350. /*
  38351. * Licensed to the Apache Software Foundation (ASF) under one
  38352. * or more contributor license agreements. See the NOTICE file
  38353. * distributed with this work for additional information
  38354. * regarding copyright ownership. The ASF licenses this file
  38355. * to you under the Apache License, Version 2.0 (the
  38356. * "License"); you may not use this file except in compliance
  38357. * with the License. You may obtain a copy of the License at
  38358. *
  38359. * http://www.apache.org/licenses/LICENSE-2.0
  38360. *
  38361. * Unless required by applicable law or agreed to in writing,
  38362. * software distributed under the License is distributed on an
  38363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38364. * KIND, either express or implied. See the License for the
  38365. * specific language governing permissions and limitations
  38366. * under the License.
  38367. */
  38368. var AxisPointerModel = extendComponentModel({
  38369. type: 'axisPointer',
  38370. coordSysAxesInfo: null,
  38371. defaultOption: {
  38372. // 'auto' means that show when triggered by tooltip or handle.
  38373. show: 'auto',
  38374. // 'click' | 'mousemove' | 'none'
  38375. triggerOn: null,
  38376. // set default in AxisPonterView.js
  38377. zlevel: 0,
  38378. z: 50,
  38379. type: 'line',
  38380. // 'line' 'shadow' 'cross' 'none'.
  38381. // axispointer triggered by tootip determine snap automatically,
  38382. // see `modelHelper`.
  38383. snap: false,
  38384. triggerTooltip: true,
  38385. value: null,
  38386. status: null,
  38387. // Init value depends on whether handle is used.
  38388. // [group0, group1, ...]
  38389. // Each group can be: {
  38390. // mapper: function () {},
  38391. // singleTooltip: 'multiple', // 'multiple' or 'single'
  38392. // xAxisId: ...,
  38393. // yAxisName: ...,
  38394. // angleAxisIndex: ...
  38395. // }
  38396. // mapper: can be ignored.
  38397. // input: {axisInfo, value}
  38398. // output: {axisInfo, value}
  38399. link: [],
  38400. // Do not set 'auto' here, otherwise global animation: false
  38401. // will not effect at this axispointer.
  38402. animation: null,
  38403. animationDurationUpdate: 200,
  38404. lineStyle: {
  38405. color: '#aaa',
  38406. width: 1,
  38407. type: 'solid'
  38408. },
  38409. shadowStyle: {
  38410. color: 'rgba(150,150,150,0.3)'
  38411. },
  38412. label: {
  38413. show: true,
  38414. formatter: null,
  38415. // string | Function
  38416. precision: 'auto',
  38417. // Or a number like 0, 1, 2 ...
  38418. margin: 3,
  38419. color: '#fff',
  38420. padding: [5, 7, 5, 7],
  38421. backgroundColor: 'auto',
  38422. // default: axis line color
  38423. borderColor: null,
  38424. borderWidth: 0,
  38425. shadowBlur: 3,
  38426. shadowColor: '#aaa' // Considering applicability, common style should
  38427. // better not have shadowOffset.
  38428. // shadowOffsetX: 0,
  38429. // shadowOffsetY: 2
  38430. },
  38431. handle: {
  38432. show: false,
  38433. /* eslint-disable */
  38434. 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',
  38435. // jshint ignore:line
  38436. /* eslint-enable */
  38437. size: 45,
  38438. // handle margin is from symbol center to axis, which is stable when circular move.
  38439. margin: 50,
  38440. // color: '#1b8bbd'
  38441. // color: '#2f4554'
  38442. color: '#333',
  38443. shadowBlur: 3,
  38444. shadowColor: '#aaa',
  38445. shadowOffsetX: 0,
  38446. shadowOffsetY: 2,
  38447. // For mobile performance
  38448. throttle: 40
  38449. }
  38450. }
  38451. });
  38452. /*
  38453. * Licensed to the Apache Software Foundation (ASF) under one
  38454. * or more contributor license agreements. See the NOTICE file
  38455. * distributed with this work for additional information
  38456. * regarding copyright ownership. The ASF licenses this file
  38457. * to you under the Apache License, Version 2.0 (the
  38458. * "License"); you may not use this file except in compliance
  38459. * with the License. You may obtain a copy of the License at
  38460. *
  38461. * http://www.apache.org/licenses/LICENSE-2.0
  38462. *
  38463. * Unless required by applicable law or agreed to in writing,
  38464. * software distributed under the License is distributed on an
  38465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38466. * KIND, either express or implied. See the License for the
  38467. * specific language governing permissions and limitations
  38468. * under the License.
  38469. */
  38470. var inner$8 = makeInner();
  38471. var each$9 = each$1;
  38472. /**
  38473. * @param {string} key
  38474. * @param {module:echarts/ExtensionAPI} api
  38475. * @param {Function} handler
  38476. * param: {string} currTrigger
  38477. * param: {Array.<number>} point
  38478. */
  38479. function register(key, api, handler) {
  38480. if (env$1.node) {
  38481. return;
  38482. }
  38483. var zr = api.getZr();
  38484. inner$8(zr).records || (inner$8(zr).records = {});
  38485. initGlobalListeners(zr, api);
  38486. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  38487. record.handler = handler;
  38488. }
  38489. function initGlobalListeners(zr, api) {
  38490. if (inner$8(zr).initialized) {
  38491. return;
  38492. }
  38493. inner$8(zr).initialized = true;
  38494. useHandler('click', curry(doEnter, 'click'));
  38495. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  38496. useHandler('globalout', onLeave);
  38497. function useHandler(eventType, cb) {
  38498. zr.on(eventType, function (e) {
  38499. var dis = makeDispatchAction(api);
  38500. each$9(inner$8(zr).records, function (record) {
  38501. record && cb(record, e, dis.dispatchAction);
  38502. });
  38503. dispatchTooltipFinally(dis.pendings, api);
  38504. });
  38505. }
  38506. }
  38507. function dispatchTooltipFinally(pendings, api) {
  38508. var showLen = pendings.showTip.length;
  38509. var hideLen = pendings.hideTip.length;
  38510. var actuallyPayload;
  38511. if (showLen) {
  38512. actuallyPayload = pendings.showTip[showLen - 1];
  38513. } else if (hideLen) {
  38514. actuallyPayload = pendings.hideTip[hideLen - 1];
  38515. }
  38516. if (actuallyPayload) {
  38517. actuallyPayload.dispatchAction = null;
  38518. api.dispatchAction(actuallyPayload);
  38519. }
  38520. }
  38521. function onLeave(record, e, dispatchAction) {
  38522. record.handler('leave', null, dispatchAction);
  38523. }
  38524. function doEnter(currTrigger, record, e, dispatchAction) {
  38525. record.handler(currTrigger, e, dispatchAction);
  38526. }
  38527. function makeDispatchAction(api) {
  38528. var pendings = {
  38529. showTip: [],
  38530. hideTip: []
  38531. }; // FIXME
  38532. // better approach?
  38533. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  38534. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  38535. // So we have to add "final stage" to merge those dispatched actions.
  38536. var dispatchAction = function (payload) {
  38537. var pendingList = pendings[payload.type];
  38538. if (pendingList) {
  38539. pendingList.push(payload);
  38540. } else {
  38541. payload.dispatchAction = dispatchAction;
  38542. api.dispatchAction(payload);
  38543. }
  38544. };
  38545. return {
  38546. dispatchAction: dispatchAction,
  38547. pendings: pendings
  38548. };
  38549. }
  38550. /**
  38551. * @param {string} key
  38552. * @param {module:echarts/ExtensionAPI} api
  38553. */
  38554. function unregister(key, api) {
  38555. if (env$1.node) {
  38556. return;
  38557. }
  38558. var zr = api.getZr();
  38559. var record = (inner$8(zr).records || {})[key];
  38560. if (record) {
  38561. inner$8(zr).records[key] = null;
  38562. }
  38563. }
  38564. /*
  38565. * Licensed to the Apache Software Foundation (ASF) under one
  38566. * or more contributor license agreements. See the NOTICE file
  38567. * distributed with this work for additional information
  38568. * regarding copyright ownership. The ASF licenses this file
  38569. * to you under the Apache License, Version 2.0 (the
  38570. * "License"); you may not use this file except in compliance
  38571. * with the License. You may obtain a copy of the License at
  38572. *
  38573. * http://www.apache.org/licenses/LICENSE-2.0
  38574. *
  38575. * Unless required by applicable law or agreed to in writing,
  38576. * software distributed under the License is distributed on an
  38577. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38578. * KIND, either express or implied. See the License for the
  38579. * specific language governing permissions and limitations
  38580. * under the License.
  38581. */
  38582. var AxisPointerView = extendComponentView({
  38583. type: 'axisPointer',
  38584. render: function (globalAxisPointerModel, ecModel, api) {
  38585. var globalTooltipModel = ecModel.getComponent('tooltip');
  38586. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  38587. // AxisPointerView to be independent to Tooltip.
  38588. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  38589. // If 'none', it is not controlled by mouse totally.
  38590. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  38591. dispatchAction({
  38592. type: 'updateAxisPointer',
  38593. currTrigger: currTrigger,
  38594. x: e && e.offsetX,
  38595. y: e && e.offsetY
  38596. });
  38597. }
  38598. });
  38599. },
  38600. /**
  38601. * @override
  38602. */
  38603. remove: function (ecModel, api) {
  38604. unregister(api.getZr(), 'axisPointer');
  38605. AxisPointerView.superApply(this._model, 'remove', arguments);
  38606. },
  38607. /**
  38608. * @override
  38609. */
  38610. dispose: function (ecModel, api) {
  38611. unregister('axisPointer', api);
  38612. AxisPointerView.superApply(this._model, 'dispose', arguments);
  38613. }
  38614. });
  38615. /*
  38616. * Licensed to the Apache Software Foundation (ASF) under one
  38617. * or more contributor license agreements. See the NOTICE file
  38618. * distributed with this work for additional information
  38619. * regarding copyright ownership. The ASF licenses this file
  38620. * to you under the Apache License, Version 2.0 (the
  38621. * "License"); you may not use this file except in compliance
  38622. * with the License. You may obtain a copy of the License at
  38623. *
  38624. * http://www.apache.org/licenses/LICENSE-2.0
  38625. *
  38626. * Unless required by applicable law or agreed to in writing,
  38627. * software distributed under the License is distributed on an
  38628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38629. * KIND, either express or implied. See the License for the
  38630. * specific language governing permissions and limitations
  38631. * under the License.
  38632. */
  38633. var inner$9 = makeInner();
  38634. var clone$4 = clone;
  38635. var bind$1 = bind;
  38636. /**
  38637. * Base axis pointer class in 2D.
  38638. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  38639. */
  38640. function BaseAxisPointer() {}
  38641. BaseAxisPointer.prototype = {
  38642. /**
  38643. * @private
  38644. */
  38645. _group: null,
  38646. /**
  38647. * @private
  38648. */
  38649. _lastGraphicKey: null,
  38650. /**
  38651. * @private
  38652. */
  38653. _handle: null,
  38654. /**
  38655. * @private
  38656. */
  38657. _dragging: false,
  38658. /**
  38659. * @private
  38660. */
  38661. _lastValue: null,
  38662. /**
  38663. * @private
  38664. */
  38665. _lastStatus: null,
  38666. /**
  38667. * @private
  38668. */
  38669. _payloadInfo: null,
  38670. /**
  38671. * In px, arbitrary value. Do not set too small,
  38672. * no animation is ok for most cases.
  38673. * @protected
  38674. */
  38675. animationThreshold: 15,
  38676. /**
  38677. * @implement
  38678. */
  38679. render: function (axisModel, axisPointerModel, api, forceRender) {
  38680. var value = axisPointerModel.get('value');
  38681. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  38682. // be replaced when user calling setOption in not merge mode.
  38683. this._axisModel = axisModel;
  38684. this._axisPointerModel = axisPointerModel;
  38685. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  38686. // So it is power consuming if performing `render` each time,
  38687. // especially on mobile device.
  38688. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  38689. return;
  38690. }
  38691. this._lastValue = value;
  38692. this._lastStatus = status;
  38693. var group = this._group;
  38694. var handle = this._handle;
  38695. if (!status || status === 'hide') {
  38696. // Do not clear here, for animation better.
  38697. group && group.hide();
  38698. handle && handle.hide();
  38699. return;
  38700. }
  38701. group && group.show();
  38702. handle && handle.show(); // Otherwise status is 'show'
  38703. var elOption = {};
  38704. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  38705. var graphicKey = elOption.graphicKey;
  38706. if (graphicKey !== this._lastGraphicKey) {
  38707. this.clear(api);
  38708. }
  38709. this._lastGraphicKey = graphicKey;
  38710. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  38711. if (!group) {
  38712. group = this._group = new Group();
  38713. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  38714. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  38715. api.getZr().add(group);
  38716. } else {
  38717. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  38718. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  38719. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  38720. }
  38721. updateMandatoryProps(group, axisPointerModel, true);
  38722. this._renderHandle(value);
  38723. },
  38724. /**
  38725. * @implement
  38726. */
  38727. remove: function (api) {
  38728. this.clear(api);
  38729. },
  38730. /**
  38731. * @implement
  38732. */
  38733. dispose: function (api) {
  38734. this.clear(api);
  38735. },
  38736. /**
  38737. * @protected
  38738. */
  38739. determineAnimation: function (axisModel, axisPointerModel) {
  38740. var animation = axisPointerModel.get('animation');
  38741. var axis = axisModel.axis;
  38742. var isCategoryAxis = axis.type === 'category';
  38743. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  38744. if (!useSnap && !isCategoryAxis) {
  38745. return false;
  38746. }
  38747. if (animation === 'auto' || animation == null) {
  38748. var animationThreshold = this.animationThreshold;
  38749. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  38750. return true;
  38751. } // It is important to auto animation when snap used. Consider if there is
  38752. // a dataZoom, animation will be disabled when too many points exist, while
  38753. // it will be enabled for better visual effect when little points exist.
  38754. if (useSnap) {
  38755. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  38756. var axisExtent = axis.getExtent(); // Approximate band width
  38757. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  38758. }
  38759. return false;
  38760. }
  38761. return animation === true;
  38762. },
  38763. /**
  38764. * add {pointer, label, graphicKey} to elOption
  38765. * @protected
  38766. */
  38767. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  38768. },
  38769. /**
  38770. * @protected
  38771. */
  38772. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  38773. var pointerOption = elOption.pointer;
  38774. if (pointerOption) {
  38775. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](clone$4(elOption.pointer));
  38776. group.add(pointerEl);
  38777. }
  38778. },
  38779. /**
  38780. * @protected
  38781. */
  38782. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  38783. if (elOption.label) {
  38784. var labelEl = inner$9(group).labelEl = new Rect(clone$4(elOption.label));
  38785. group.add(labelEl);
  38786. updateLabelShowHide(labelEl, axisPointerModel);
  38787. }
  38788. },
  38789. /**
  38790. * @protected
  38791. */
  38792. updatePointerEl: function (group, elOption, updateProps$$1) {
  38793. var pointerEl = inner$9(group).pointerEl;
  38794. if (pointerEl && elOption.pointer) {
  38795. pointerEl.setStyle(elOption.pointer.style);
  38796. updateProps$$1(pointerEl, {
  38797. shape: elOption.pointer.shape
  38798. });
  38799. }
  38800. },
  38801. /**
  38802. * @protected
  38803. */
  38804. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  38805. var labelEl = inner$9(group).labelEl;
  38806. if (labelEl) {
  38807. labelEl.setStyle(elOption.label.style);
  38808. updateProps$$1(labelEl, {
  38809. // Consider text length change in vertical axis, animation should
  38810. // be used on shape, otherwise the effect will be weird.
  38811. shape: elOption.label.shape,
  38812. position: elOption.label.position
  38813. });
  38814. updateLabelShowHide(labelEl, axisPointerModel);
  38815. }
  38816. },
  38817. /**
  38818. * @private
  38819. */
  38820. _renderHandle: function (value) {
  38821. if (this._dragging || !this.updateHandleTransform) {
  38822. return;
  38823. }
  38824. var axisPointerModel = this._axisPointerModel;
  38825. var zr = this._api.getZr();
  38826. var handle = this._handle;
  38827. var handleModel = axisPointerModel.getModel('handle');
  38828. var status = axisPointerModel.get('status');
  38829. if (!handleModel.get('show') || !status || status === 'hide') {
  38830. handle && zr.remove(handle);
  38831. this._handle = null;
  38832. return;
  38833. }
  38834. var isInit;
  38835. if (!this._handle) {
  38836. isInit = true;
  38837. handle = this._handle = createIcon(handleModel.get('icon'), {
  38838. cursor: 'move',
  38839. draggable: true,
  38840. onmousemove: function (e) {
  38841. // Fot mobile devicem, prevent screen slider on the button.
  38842. stop(e.event);
  38843. },
  38844. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  38845. drift: bind$1(this._onHandleDragMove, this),
  38846. ondragend: bind$1(this._onHandleDragEnd, this)
  38847. });
  38848. zr.add(handle);
  38849. }
  38850. updateMandatoryProps(handle, axisPointerModel, false); // update style
  38851. var includeStyles = ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  38852. handle.setStyle(handleModel.getItemStyle(null, includeStyles)); // update position
  38853. var handleSize = handleModel.get('size');
  38854. if (!isArray(handleSize)) {
  38855. handleSize = [handleSize, handleSize];
  38856. }
  38857. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  38858. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  38859. this._moveHandleToValue(value, isInit);
  38860. },
  38861. /**
  38862. * @private
  38863. */
  38864. _moveHandleToValue: function (value, isInit) {
  38865. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  38866. },
  38867. /**
  38868. * @private
  38869. */
  38870. _onHandleDragMove: function (dx, dy) {
  38871. var handle = this._handle;
  38872. if (!handle) {
  38873. return;
  38874. }
  38875. this._dragging = true; // Persistent for throttle.
  38876. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  38877. this._payloadInfo = trans;
  38878. handle.stopAnimation();
  38879. handle.attr(getHandleTransProps(trans));
  38880. inner$9(handle).lastProp = null;
  38881. this._doDispatchAxisPointer();
  38882. },
  38883. /**
  38884. * Throttled method.
  38885. * @private
  38886. */
  38887. _doDispatchAxisPointer: function () {
  38888. var handle = this._handle;
  38889. if (!handle) {
  38890. return;
  38891. }
  38892. var payloadInfo = this._payloadInfo;
  38893. var axisModel = this._axisModel;
  38894. this._api.dispatchAction({
  38895. type: 'updateAxisPointer',
  38896. x: payloadInfo.cursorPoint[0],
  38897. y: payloadInfo.cursorPoint[1],
  38898. tooltipOption: payloadInfo.tooltipOption,
  38899. axesInfo: [{
  38900. axisDim: axisModel.axis.dim,
  38901. axisIndex: axisModel.componentIndex
  38902. }]
  38903. });
  38904. },
  38905. /**
  38906. * @private
  38907. */
  38908. _onHandleDragEnd: function (moveAnimation) {
  38909. this._dragging = false;
  38910. var handle = this._handle;
  38911. if (!handle) {
  38912. return;
  38913. }
  38914. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  38915. // axisPointer. So move handle to align the exact value position when
  38916. // drag ended.
  38917. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  38918. // button, and will be hidden after finger left handle button.
  38919. this._api.dispatchAction({
  38920. type: 'hideTip'
  38921. });
  38922. },
  38923. /**
  38924. * Should be implemenented by sub-class if support `handle`.
  38925. * @protected
  38926. * @param {number} value
  38927. * @param {module:echarts/model/Model} axisModel
  38928. * @param {module:echarts/model/Model} axisPointerModel
  38929. * @return {Object} {position: [x, y], rotation: 0}
  38930. */
  38931. getHandleTransform: null,
  38932. /**
  38933. * * Should be implemenented by sub-class if support `handle`.
  38934. * @protected
  38935. * @param {Object} transform {position, rotation}
  38936. * @param {Array.<number>} delta [dx, dy]
  38937. * @param {module:echarts/model/Model} axisModel
  38938. * @param {module:echarts/model/Model} axisPointerModel
  38939. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  38940. */
  38941. updateHandleTransform: null,
  38942. /**
  38943. * @private
  38944. */
  38945. clear: function (api) {
  38946. this._lastValue = null;
  38947. this._lastStatus = null;
  38948. var zr = api.getZr();
  38949. var group = this._group;
  38950. var handle = this._handle;
  38951. if (zr && group) {
  38952. this._lastGraphicKey = null;
  38953. group && zr.remove(group);
  38954. handle && zr.remove(handle);
  38955. this._group = null;
  38956. this._handle = null;
  38957. this._payloadInfo = null;
  38958. }
  38959. },
  38960. /**
  38961. * @protected
  38962. */
  38963. doClear: function () {// Implemented by sub-class if necessary.
  38964. },
  38965. /**
  38966. * @protected
  38967. * @param {Array.<number>} xy
  38968. * @param {Array.<number>} wh
  38969. * @param {number} [xDimIndex=0] or 1
  38970. */
  38971. buildLabel: function (xy, wh, xDimIndex) {
  38972. xDimIndex = xDimIndex || 0;
  38973. return {
  38974. x: xy[xDimIndex],
  38975. y: xy[1 - xDimIndex],
  38976. width: wh[xDimIndex],
  38977. height: wh[1 - xDimIndex]
  38978. };
  38979. }
  38980. };
  38981. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  38982. function updateProps$1(animationModel, moveAnimation, el, props) {
  38983. // Animation optimize.
  38984. if (!propsEqual(inner$9(el).lastProp, props)) {
  38985. inner$9(el).lastProp = props;
  38986. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  38987. }
  38988. }
  38989. function propsEqual(lastProps, newProps) {
  38990. if (isObject$1(lastProps) && isObject$1(newProps)) {
  38991. var equals = true;
  38992. each$1(newProps, function (item, key) {
  38993. equals = equals && propsEqual(lastProps[key], item);
  38994. });
  38995. return !!equals;
  38996. } else {
  38997. return lastProps === newProps;
  38998. }
  38999. }
  39000. function updateLabelShowHide(labelEl, axisPointerModel) {
  39001. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  39002. }
  39003. function getHandleTransProps(trans) {
  39004. return {
  39005. position: trans.position.slice(),
  39006. rotation: trans.rotation || 0
  39007. };
  39008. }
  39009. function updateMandatoryProps(group, axisPointerModel, silent) {
  39010. var z = axisPointerModel.get('z');
  39011. var zlevel = axisPointerModel.get('zlevel');
  39012. group && group.traverse(function (el) {
  39013. if (el.type !== 'group') {
  39014. z != null && (el.z = z);
  39015. zlevel != null && (el.zlevel = zlevel);
  39016. el.silent = silent;
  39017. }
  39018. });
  39019. }
  39020. enableClassExtend(BaseAxisPointer);
  39021. /*
  39022. * Licensed to the Apache Software Foundation (ASF) under one
  39023. * or more contributor license agreements. See the NOTICE file
  39024. * distributed with this work for additional information
  39025. * regarding copyright ownership. The ASF licenses this file
  39026. * to you under the Apache License, Version 2.0 (the
  39027. * "License"); you may not use this file except in compliance
  39028. * with the License. You may obtain a copy of the License at
  39029. *
  39030. * http://www.apache.org/licenses/LICENSE-2.0
  39031. *
  39032. * Unless required by applicable law or agreed to in writing,
  39033. * software distributed under the License is distributed on an
  39034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39035. * KIND, either express or implied. See the License for the
  39036. * specific language governing permissions and limitations
  39037. * under the License.
  39038. */
  39039. /**
  39040. * @param {module:echarts/model/Model} axisPointerModel
  39041. */
  39042. function buildElStyle(axisPointerModel) {
  39043. var axisPointerType = axisPointerModel.get('type');
  39044. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  39045. var style;
  39046. if (axisPointerType === 'line') {
  39047. style = styleModel.getLineStyle();
  39048. style.fill = null;
  39049. } else if (axisPointerType === 'shadow') {
  39050. style = styleModel.getAreaStyle();
  39051. style.stroke = null;
  39052. }
  39053. return style;
  39054. }
  39055. /**
  39056. * @param {Function} labelPos {align, verticalAlign, position}
  39057. */
  39058. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  39059. var value = axisPointerModel.get('value');
  39060. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  39061. precision: axisPointerModel.get('label.precision'),
  39062. formatter: axisPointerModel.get('label.formatter')
  39063. });
  39064. var labelModel = axisPointerModel.getModel('label');
  39065. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  39066. var font = labelModel.getFont();
  39067. var textRect = getBoundingRect(text, font);
  39068. var position = labelPos.position;
  39069. var width = textRect.width + paddings[1] + paddings[3];
  39070. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  39071. var align = labelPos.align;
  39072. align === 'right' && (position[0] -= width);
  39073. align === 'center' && (position[0] -= width / 2);
  39074. var verticalAlign = labelPos.verticalAlign;
  39075. verticalAlign === 'bottom' && (position[1] -= height);
  39076. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  39077. confineInContainer(position, width, height, api);
  39078. var bgColor = labelModel.get('backgroundColor');
  39079. if (!bgColor || bgColor === 'auto') {
  39080. bgColor = axisModel.get('axisLine.lineStyle.color');
  39081. }
  39082. elOption.label = {
  39083. shape: {
  39084. x: 0,
  39085. y: 0,
  39086. width: width,
  39087. height: height,
  39088. r: labelModel.get('borderRadius')
  39089. },
  39090. position: position.slice(),
  39091. // TODO: rich
  39092. style: {
  39093. text: text,
  39094. textFont: font,
  39095. textFill: labelModel.getTextColor(),
  39096. textPosition: 'inside',
  39097. textPadding: paddings,
  39098. fill: bgColor,
  39099. stroke: labelModel.get('borderColor') || 'transparent',
  39100. lineWidth: labelModel.get('borderWidth') || 0,
  39101. shadowBlur: labelModel.get('shadowBlur'),
  39102. shadowColor: labelModel.get('shadowColor'),
  39103. shadowOffsetX: labelModel.get('shadowOffsetX'),
  39104. shadowOffsetY: labelModel.get('shadowOffsetY')
  39105. },
  39106. // Lable should be over axisPointer.
  39107. z2: 10
  39108. };
  39109. } // Do not overflow ec container
  39110. function confineInContainer(position, width, height, api) {
  39111. var viewWidth = api.getWidth();
  39112. var viewHeight = api.getHeight();
  39113. position[0] = Math.min(position[0] + width, viewWidth) - width;
  39114. position[1] = Math.min(position[1] + height, viewHeight) - height;
  39115. position[0] = Math.max(position[0], 0);
  39116. position[1] = Math.max(position[1], 0);
  39117. }
  39118. /**
  39119. * @param {number} value
  39120. * @param {module:echarts/coord/Axis} axis
  39121. * @param {module:echarts/model/Global} ecModel
  39122. * @param {Object} opt
  39123. * @param {Array.<Object>} seriesDataIndices
  39124. * @param {number|string} opt.precision 'auto' or a number
  39125. * @param {string|Function} opt.formatter label formatter
  39126. */
  39127. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  39128. value = axis.scale.parse(value);
  39129. var text = axis.scale.getLabel( // If `precision` is set, width can be fixed (like '12.00500'), which
  39130. // helps to debounce when when moving label.
  39131. value, {
  39132. precision: opt.precision
  39133. });
  39134. var formatter = opt.formatter;
  39135. if (formatter) {
  39136. var params = {
  39137. value: getAxisRawValue(axis, value),
  39138. axisDimension: axis.dim,
  39139. axisIndex: axis.index,
  39140. seriesData: []
  39141. };
  39142. each$1(seriesDataIndices, function (idxItem) {
  39143. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  39144. var dataIndex = idxItem.dataIndexInside;
  39145. var dataParams = series && series.getDataParams(dataIndex);
  39146. dataParams && params.seriesData.push(dataParams);
  39147. });
  39148. if (isString(formatter)) {
  39149. text = formatter.replace('{value}', text);
  39150. } else if (isFunction$1(formatter)) {
  39151. text = formatter(params);
  39152. }
  39153. }
  39154. return text;
  39155. }
  39156. /**
  39157. * @param {module:echarts/coord/Axis} axis
  39158. * @param {number} value
  39159. * @param {Object} layoutInfo {
  39160. * rotation, position, labelOffset, labelDirection, labelMargin
  39161. * }
  39162. */
  39163. function getTransformedPosition(axis, value, layoutInfo) {
  39164. var transform = create$1();
  39165. rotate(transform, transform, layoutInfo.rotation);
  39166. translate(transform, transform, layoutInfo.position);
  39167. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  39168. }
  39169. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  39170. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  39171. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  39172. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  39173. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  39174. align: textLayout.textAlign,
  39175. verticalAlign: textLayout.textVerticalAlign
  39176. });
  39177. }
  39178. /**
  39179. * @param {Array.<number>} p1
  39180. * @param {Array.<number>} p2
  39181. * @param {number} [xDimIndex=0] or 1
  39182. */
  39183. function makeLineShape(p1, p2, xDimIndex) {
  39184. xDimIndex = xDimIndex || 0;
  39185. return {
  39186. x1: p1[xDimIndex],
  39187. y1: p1[1 - xDimIndex],
  39188. x2: p2[xDimIndex],
  39189. y2: p2[1 - xDimIndex]
  39190. };
  39191. }
  39192. /**
  39193. * @param {Array.<number>} xy
  39194. * @param {Array.<number>} wh
  39195. * @param {number} [xDimIndex=0] or 1
  39196. */
  39197. function makeRectShape(xy, wh, xDimIndex) {
  39198. xDimIndex = xDimIndex || 0;
  39199. return {
  39200. x: xy[xDimIndex],
  39201. y: xy[1 - xDimIndex],
  39202. width: wh[xDimIndex],
  39203. height: wh[1 - xDimIndex]
  39204. };
  39205. }
  39206. /*
  39207. * Licensed to the Apache Software Foundation (ASF) under one
  39208. * or more contributor license agreements. See the NOTICE file
  39209. * distributed with this work for additional information
  39210. * regarding copyright ownership. The ASF licenses this file
  39211. * to you under the Apache License, Version 2.0 (the
  39212. * "License"); you may not use this file except in compliance
  39213. * with the License. You may obtain a copy of the License at
  39214. *
  39215. * http://www.apache.org/licenses/LICENSE-2.0
  39216. *
  39217. * Unless required by applicable law or agreed to in writing,
  39218. * software distributed under the License is distributed on an
  39219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39220. * KIND, either express or implied. See the License for the
  39221. * specific language governing permissions and limitations
  39222. * under the License.
  39223. */
  39224. var CartesianAxisPointer = BaseAxisPointer.extend({
  39225. /**
  39226. * @override
  39227. */
  39228. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  39229. var axis = axisModel.axis;
  39230. var grid = axis.grid;
  39231. var axisPointerType = axisPointerModel.get('type');
  39232. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  39233. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  39234. if (axisPointerType && axisPointerType !== 'none') {
  39235. var elStyle = buildElStyle(axisPointerModel);
  39236. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  39237. pointerOption.style = elStyle;
  39238. elOption.graphicKey = pointerOption.type;
  39239. elOption.pointer = pointerOption;
  39240. }
  39241. var layoutInfo = layout$1(grid.model, axisModel);
  39242. buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  39243. },
  39244. /**
  39245. * @override
  39246. */
  39247. getHandleTransform: function (value, axisModel, axisPointerModel) {
  39248. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  39249. labelInside: false
  39250. });
  39251. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  39252. return {
  39253. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  39254. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  39255. };
  39256. },
  39257. /**
  39258. * @override
  39259. */
  39260. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  39261. var axis = axisModel.axis;
  39262. var grid = axis.grid;
  39263. var axisExtent = axis.getGlobalExtent(true);
  39264. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  39265. var dimIndex = axis.dim === 'x' ? 0 : 1;
  39266. var currPosition = transform.position;
  39267. currPosition[dimIndex] += delta[dimIndex];
  39268. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  39269. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  39270. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  39271. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  39272. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  39273. var tooltipOptions = [{
  39274. verticalAlign: 'middle'
  39275. }, {
  39276. align: 'center'
  39277. }];
  39278. return {
  39279. position: currPosition,
  39280. rotation: transform.rotation,
  39281. cursorPoint: cursorPoint,
  39282. tooltipOption: tooltipOptions[dimIndex]
  39283. };
  39284. }
  39285. });
  39286. function getCartesian(grid, axis) {
  39287. var opt = {};
  39288. opt[axis.dim + 'AxisIndex'] = axis.index;
  39289. return grid.getCartesian(opt);
  39290. }
  39291. var pointerShapeBuilder = {
  39292. line: function (axis, pixelValue, otherExtent) {
  39293. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  39294. return {
  39295. type: 'Line',
  39296. subPixelOptimize: true,
  39297. shape: targetShape
  39298. };
  39299. },
  39300. shadow: function (axis, pixelValue, otherExtent) {
  39301. var bandWidth = Math.max(1, axis.getBandWidth());
  39302. var span = otherExtent[1] - otherExtent[0];
  39303. return {
  39304. type: 'Rect',
  39305. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  39306. };
  39307. }
  39308. };
  39309. function getAxisDimIndex(axis) {
  39310. return axis.dim === 'x' ? 0 : 1;
  39311. }
  39312. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  39313. /*
  39314. * Licensed to the Apache Software Foundation (ASF) under one
  39315. * or more contributor license agreements. See the NOTICE file
  39316. * distributed with this work for additional information
  39317. * regarding copyright ownership. The ASF licenses this file
  39318. * to you under the Apache License, Version 2.0 (the
  39319. * "License"); you may not use this file except in compliance
  39320. * with the License. You may obtain a copy of the License at
  39321. *
  39322. * http://www.apache.org/licenses/LICENSE-2.0
  39323. *
  39324. * Unless required by applicable law or agreed to in writing,
  39325. * software distributed under the License is distributed on an
  39326. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39327. * KIND, either express or implied. See the License for the
  39328. * specific language governing permissions and limitations
  39329. * under the License.
  39330. */
  39331. // echarts.simple.js and online build tooltip, which only require gridSimple,
  39332. // CartesianAxisPointer should be able to required somewhere.
  39333. registerPreprocessor(function (option) {
  39334. // Always has a global axisPointerModel for default setting.
  39335. if (option) {
  39336. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  39337. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  39338. // is not set, remain null/undefined, otherwise it will
  39339. // override existent link setting.
  39340. if (link && !isArray(link)) {
  39341. option.axisPointer.link = [link];
  39342. }
  39343. }
  39344. }); // This process should proformed after coordinate systems created
  39345. // and series data processed. So put it on statistic processing stage.
  39346. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  39347. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  39348. // allAxesInfo should be updated when setOption performed.
  39349. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  39350. }); // Broadcast to all views.
  39351. registerAction({
  39352. type: 'updateAxisPointer',
  39353. event: 'updateAxisPointer',
  39354. update: ':updateAxisPointer'
  39355. }, axisTrigger);
  39356. /*
  39357. * Licensed to the Apache Software Foundation (ASF) under one
  39358. * or more contributor license agreements. See the NOTICE file
  39359. * distributed with this work for additional information
  39360. * regarding copyright ownership. The ASF licenses this file
  39361. * to you under the Apache License, Version 2.0 (the
  39362. * "License"); you may not use this file except in compliance
  39363. * with the License. You may obtain a copy of the License at
  39364. *
  39365. * http://www.apache.org/licenses/LICENSE-2.0
  39366. *
  39367. * Unless required by applicable law or agreed to in writing,
  39368. * software distributed under the License is distributed on an
  39369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39370. * KIND, either express or implied. See the License for the
  39371. * specific language governing permissions and limitations
  39372. * under the License.
  39373. */
  39374. extendComponentModel({
  39375. type: 'tooltip',
  39376. dependencies: ['axisPointer'],
  39377. defaultOption: {
  39378. zlevel: 0,
  39379. z: 60,
  39380. show: true,
  39381. // tooltip主体内容
  39382. showContent: true,
  39383. // 'trigger' only works on coordinate system.
  39384. // 'item' | 'axis' | 'none'
  39385. trigger: 'item',
  39386. // 'click' | 'mousemove' | 'none'
  39387. triggerOn: 'mousemove|click',
  39388. alwaysShowContent: false,
  39389. displayMode: 'single',
  39390. // 'single' | 'multipleByCoordSys'
  39391. renderMode: 'auto',
  39392. // 'auto' | 'html' | 'richText'
  39393. // 'auto': use html by default, and use non-html if `document` is not defined
  39394. // 'html': use html for tooltip
  39395. // 'richText': use canvas, svg, and etc. for tooltip
  39396. // 位置 {Array} | {Function}
  39397. // position: null
  39398. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  39399. // align: null,
  39400. // verticalAlign: null,
  39401. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  39402. confine: false,
  39403. // 内容格式器:{string}(Template) ¦ {Function}
  39404. // formatter: null
  39405. showDelay: 0,
  39406. // 隐藏延迟,单位ms
  39407. hideDelay: 100,
  39408. // 动画变换时间,单位s
  39409. transitionDuration: 0.4,
  39410. enterable: false,
  39411. // 提示背景颜色,默认为透明度为0.7的黑色
  39412. backgroundColor: 'rgba(50,50,50,0.7)',
  39413. // 提示边框颜色
  39414. borderColor: '#333',
  39415. // 提示边框圆角,单位px,默认为4
  39416. borderRadius: 4,
  39417. // 提示边框线宽,单位px,默认为0(无边框)
  39418. borderWidth: 0,
  39419. // 提示内边距,单位px,默认各方向内边距为5,
  39420. // 接受数组分别设定上右下左边距,同css
  39421. padding: 5,
  39422. // Extra css text
  39423. extraCssText: '',
  39424. // 坐标轴指示器,坐标轴触发有效
  39425. axisPointer: {
  39426. // 默认为直线
  39427. // 可选为:'line' | 'shadow' | 'cross'
  39428. type: 'line',
  39429. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  39430. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  39431. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  39432. // 极坐标系会默认选择 angle 轴
  39433. axis: 'auto',
  39434. animation: 'auto',
  39435. animationDurationUpdate: 200,
  39436. animationEasingUpdate: 'exponentialOut',
  39437. crossStyle: {
  39438. color: '#999',
  39439. width: 1,
  39440. type: 'dashed',
  39441. // TODO formatter
  39442. textStyle: {} // lineStyle and shadowStyle should not be specified here,
  39443. // otherwise it will always override those styles on option.axisPointer.
  39444. }
  39445. },
  39446. textStyle: {
  39447. color: '#fff',
  39448. fontSize: 14
  39449. }
  39450. }
  39451. });
  39452. /*
  39453. * Licensed to the Apache Software Foundation (ASF) under one
  39454. * or more contributor license agreements. See the NOTICE file
  39455. * distributed with this work for additional information
  39456. * regarding copyright ownership. The ASF licenses this file
  39457. * to you under the Apache License, Version 2.0 (the
  39458. * "License"); you may not use this file except in compliance
  39459. * with the License. You may obtain a copy of the License at
  39460. *
  39461. * http://www.apache.org/licenses/LICENSE-2.0
  39462. *
  39463. * Unless required by applicable law or agreed to in writing,
  39464. * software distributed under the License is distributed on an
  39465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39466. * KIND, either express or implied. See the License for the
  39467. * specific language governing permissions and limitations
  39468. * under the License.
  39469. */
  39470. var each$11 = each$1;
  39471. var toCamelCase$1 = toCamelCase;
  39472. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  39473. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  39474. /**
  39475. * @param {number} duration
  39476. * @return {string}
  39477. * @inner
  39478. */
  39479. function assembleTransition(duration) {
  39480. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  39481. var transitionText = 'left ' + duration + 's ' + transitionCurve + ',' + 'top ' + duration + 's ' + transitionCurve;
  39482. return map(vendors, function (vendorPrefix) {
  39483. return vendorPrefix + 'transition:' + transitionText;
  39484. }).join(';');
  39485. }
  39486. /**
  39487. * @param {Object} textStyle
  39488. * @return {string}
  39489. * @inner
  39490. */
  39491. function assembleFont(textStyleModel) {
  39492. var cssText = [];
  39493. var fontSize = textStyleModel.get('fontSize');
  39494. var color = textStyleModel.getTextColor();
  39495. color && cssText.push('color:' + color);
  39496. cssText.push('font:' + textStyleModel.getFont());
  39497. fontSize && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  39498. each$11(['decoration', 'align'], function (name) {
  39499. var val = textStyleModel.get(name);
  39500. val && cssText.push('text-' + name + ':' + val);
  39501. });
  39502. return cssText.join(';');
  39503. }
  39504. /**
  39505. * @param {Object} tooltipModel
  39506. * @return {string}
  39507. * @inner
  39508. */
  39509. function assembleCssText(tooltipModel) {
  39510. var cssText = [];
  39511. var transitionDuration = tooltipModel.get('transitionDuration');
  39512. var backgroundColor = tooltipModel.get('backgroundColor');
  39513. var textStyleModel = tooltipModel.getModel('textStyle');
  39514. var padding = tooltipModel.get('padding'); // Animation transition. Do not animate when transitionDuration is 0.
  39515. transitionDuration && cssText.push(assembleTransition(transitionDuration));
  39516. if (backgroundColor) {
  39517. if (env$1.canvasSupported) {
  39518. cssText.push('background-Color:' + backgroundColor);
  39519. } else {
  39520. // for ie
  39521. cssText.push('background-Color:#' + toHex(backgroundColor));
  39522. cssText.push('filter:alpha(opacity=70)');
  39523. }
  39524. } // Border style
  39525. each$11(['width', 'color', 'radius'], function (name) {
  39526. var borderName = 'border-' + name;
  39527. var camelCase = toCamelCase$1(borderName);
  39528. var val = tooltipModel.get(camelCase);
  39529. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  39530. }); // Text style
  39531. cssText.push(assembleFont(textStyleModel)); // Padding
  39532. if (padding != null) {
  39533. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  39534. }
  39535. return cssText.join(';') + ';';
  39536. } // If not able to make, do not modify the input `out`.
  39537. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  39538. var zrPainter = zr && zr.painter;
  39539. if (appendToBody) {
  39540. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  39541. if (zrViewportRoot) {
  39542. // Some APPs might use scale on body, so we support CSS transform here.
  39543. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  39544. }
  39545. } else {
  39546. out[0] = zrX;
  39547. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  39548. // the sibling of canvas root. So padding of ec container
  39549. // should be considered here.
  39550. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  39551. if (viewportRootOffset) {
  39552. out[0] += viewportRootOffset.offsetLeft;
  39553. out[1] += viewportRootOffset.offsetTop;
  39554. }
  39555. }
  39556. }
  39557. /**
  39558. * @alias module:echarts/component/tooltip/TooltipContent
  39559. * @param {HTMLElement} container
  39560. * @param {ExtensionAPI} api
  39561. * @param {Object} [opt]
  39562. * @param {boolean} [opt.appendToBody]
  39563. * `false`: the DOM element will be inside the container. Default value.
  39564. * `true`: the DOM element will be appended to HTML body, which avoid
  39565. * some overflow clip but intrude outside of the container.
  39566. * @constructor
  39567. */
  39568. function TooltipContent(container, api, opt) {
  39569. if (env$1.wxa) {
  39570. return null;
  39571. }
  39572. var el = document.createElement('div');
  39573. el.domBelongToZr = true;
  39574. this.el = el;
  39575. var zr = this._zr = api.getZr();
  39576. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  39577. this._styleCoord = [0, 0];
  39578. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  39579. if (appendToBody) {
  39580. document.body.appendChild(el);
  39581. } else {
  39582. container.appendChild(el);
  39583. }
  39584. this._container = container;
  39585. this._show = false;
  39586. /**
  39587. * @private
  39588. */
  39589. this._hideTimeout; // FIXME
  39590. // Is it needed to trigger zr event manually if
  39591. // the browser do not support `pointer-events: none`.
  39592. var self = this;
  39593. el.onmouseenter = function () {
  39594. // clear the timeout in hideLater and keep showing tooltip
  39595. if (self._enterable) {
  39596. clearTimeout(self._hideTimeout);
  39597. self._show = true;
  39598. }
  39599. self._inContent = true;
  39600. };
  39601. el.onmousemove = function (e) {
  39602. e = e || window.event;
  39603. if (!self._enterable) {
  39604. // `pointer-events: none` is set to tooltip content div
  39605. // if `enterable` is set as `false`, and `el.onmousemove`
  39606. // can not be triggered. But in browser that do not
  39607. // support `pointer-events`, we need to do this:
  39608. // Try trigger zrender event to avoid mouse
  39609. // in and out shape too frequently
  39610. var handler = zr.handler;
  39611. var zrViewportRoot = zr.painter.getViewportRoot();
  39612. normalizeEvent(zrViewportRoot, e, true);
  39613. handler.dispatch('mousemove', e);
  39614. }
  39615. };
  39616. el.onmouseleave = function () {
  39617. if (self._enterable) {
  39618. if (self._show) {
  39619. self.hideLater(self._hideDelay);
  39620. }
  39621. }
  39622. self._inContent = false;
  39623. };
  39624. }
  39625. TooltipContent.prototype = {
  39626. constructor: TooltipContent,
  39627. /**
  39628. * @private
  39629. * @type {boolean}
  39630. */
  39631. _enterable: true,
  39632. /**
  39633. * Update when tooltip is rendered
  39634. */
  39635. update: function () {
  39636. // FIXME
  39637. // Move this logic to ec main?
  39638. var container = this._container;
  39639. var stl = container.currentStyle || document.defaultView.getComputedStyle(container);
  39640. var domStyle = container.style;
  39641. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  39642. domStyle.position = 'relative';
  39643. } // Hide the tooltip
  39644. // PENDING
  39645. // this.hide();
  39646. },
  39647. show: function (tooltipModel) {
  39648. clearTimeout(this._hideTimeout);
  39649. var el = this.el;
  39650. var styleCoord = this._styleCoord;
  39651. el.style.cssText = gCssText + assembleCssText(tooltipModel) // Because of the reason described in:
  39652. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  39653. // we should set initial value to `left` and `top`.
  39654. + ';left:' + styleCoord[0] + 'px;top:' + styleCoord[1] + 'px;' + (tooltipModel.get('extraCssText') || '');
  39655. el.style.display = el.innerHTML ? 'block' : 'none'; // If mouse occsionally move over the tooltip, a mouseout event will be
  39656. // triggered by canvas, and cuase some unexpectable result like dragging
  39657. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  39658. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  39659. // scenario.
  39660. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  39661. this._show = true;
  39662. },
  39663. setContent: function (content) {
  39664. this.el.innerHTML = content == null ? '' : content;
  39665. },
  39666. setEnterable: function (enterable) {
  39667. this._enterable = enterable;
  39668. },
  39669. getSize: function () {
  39670. var el = this.el;
  39671. return [el.clientWidth, el.clientHeight];
  39672. },
  39673. moveTo: function (zrX, zrY) {
  39674. var styleCoord = this._styleCoord;
  39675. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  39676. var style = this.el.style;
  39677. style.left = styleCoord[0] + 'px';
  39678. style.top = styleCoord[1] + 'px';
  39679. },
  39680. hide: function () {
  39681. this.el.style.display = 'none';
  39682. this._show = false;
  39683. },
  39684. hideLater: function (time) {
  39685. if (this._show && !(this._inContent && this._enterable)) {
  39686. if (time) {
  39687. this._hideDelay = time; // Set show false to avoid invoke hideLater mutiple times
  39688. this._show = false;
  39689. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  39690. } else {
  39691. this.hide();
  39692. }
  39693. }
  39694. },
  39695. isShow: function () {
  39696. return this._show;
  39697. },
  39698. dispose: function () {
  39699. this.el.parentNode.removeChild(this.el);
  39700. },
  39701. getOuterSize: function () {
  39702. var width = this.el.clientWidth;
  39703. var height = this.el.clientHeight; // Consider browser compatibility.
  39704. // IE8 does not support getComputedStyle.
  39705. if (document.defaultView && document.defaultView.getComputedStyle) {
  39706. var stl = document.defaultView.getComputedStyle(this.el);
  39707. if (stl) {
  39708. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  39709. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  39710. }
  39711. }
  39712. return {
  39713. width: width,
  39714. height: height
  39715. };
  39716. }
  39717. };
  39718. /*
  39719. * Licensed to the Apache Software Foundation (ASF) under one
  39720. * or more contributor license agreements. See the NOTICE file
  39721. * distributed with this work for additional information
  39722. * regarding copyright ownership. The ASF licenses this file
  39723. * to you under the Apache License, Version 2.0 (the
  39724. * "License"); you may not use this file except in compliance
  39725. * with the License. You may obtain a copy of the License at
  39726. *
  39727. * http://www.apache.org/licenses/LICENSE-2.0
  39728. *
  39729. * Unless required by applicable law or agreed to in writing,
  39730. * software distributed under the License is distributed on an
  39731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39732. * KIND, either express or implied. See the License for the
  39733. * specific language governing permissions and limitations
  39734. * under the License.
  39735. */
  39736. /**
  39737. * @alias module:echarts/component/tooltip/TooltipRichContent
  39738. * @constructor
  39739. */
  39740. function TooltipRichContent(api) {
  39741. this._zr = api.getZr();
  39742. this._show = false;
  39743. /**
  39744. * @private
  39745. */
  39746. this._hideTimeout;
  39747. }
  39748. TooltipRichContent.prototype = {
  39749. constructor: TooltipRichContent,
  39750. /**
  39751. * @private
  39752. * @type {boolean}
  39753. */
  39754. _enterable: true,
  39755. /**
  39756. * Update when tooltip is rendered
  39757. */
  39758. update: function () {// noop
  39759. },
  39760. show: function (tooltipModel) {
  39761. if (this._hideTimeout) {
  39762. clearTimeout(this._hideTimeout);
  39763. }
  39764. this.el.attr('show', true);
  39765. this._show = true;
  39766. },
  39767. /**
  39768. * Set tooltip content
  39769. *
  39770. * @param {string} content rich text string of content
  39771. * @param {Object} markerRich rich text style
  39772. * @param {Object} tooltipModel tooltip model
  39773. */
  39774. setContent: function (content, markerRich, tooltipModel) {
  39775. if (this.el) {
  39776. this._zr.remove(this.el);
  39777. }
  39778. var markers = {};
  39779. var text = content;
  39780. var prefix = '{marker';
  39781. var suffix = '|}';
  39782. var startId = text.indexOf(prefix);
  39783. while (startId >= 0) {
  39784. var endId = text.indexOf(suffix);
  39785. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  39786. if (name.indexOf('sub') > -1) {
  39787. markers['marker' + name] = {
  39788. textWidth: 4,
  39789. textHeight: 4,
  39790. textBorderRadius: 2,
  39791. textBackgroundColor: markerRich[name],
  39792. // TODO: textOffset is not implemented for rich text
  39793. textOffset: [3, 0]
  39794. };
  39795. } else {
  39796. markers['marker' + name] = {
  39797. textWidth: 10,
  39798. textHeight: 10,
  39799. textBorderRadius: 5,
  39800. textBackgroundColor: markerRich[name]
  39801. };
  39802. }
  39803. text = text.substr(endId + 1);
  39804. startId = text.indexOf('{marker');
  39805. }
  39806. this.el = new Text({
  39807. style: {
  39808. rich: markers,
  39809. text: content,
  39810. textLineHeight: 20,
  39811. textBackgroundColor: tooltipModel.get('backgroundColor'),
  39812. textBorderRadius: tooltipModel.get('borderRadius'),
  39813. textFill: tooltipModel.get('textStyle.color'),
  39814. textPadding: tooltipModel.get('padding')
  39815. },
  39816. z: tooltipModel.get('z')
  39817. });
  39818. this._zr.add(this.el);
  39819. var self = this;
  39820. this.el.on('mouseover', function () {
  39821. // clear the timeout in hideLater and keep showing tooltip
  39822. if (self._enterable) {
  39823. clearTimeout(self._hideTimeout);
  39824. self._show = true;
  39825. }
  39826. self._inContent = true;
  39827. });
  39828. this.el.on('mouseout', function () {
  39829. if (self._enterable) {
  39830. if (self._show) {
  39831. self.hideLater(self._hideDelay);
  39832. }
  39833. }
  39834. self._inContent = false;
  39835. });
  39836. },
  39837. setEnterable: function (enterable) {
  39838. this._enterable = enterable;
  39839. },
  39840. getSize: function () {
  39841. var bounding = this.el.getBoundingRect();
  39842. return [bounding.width, bounding.height];
  39843. },
  39844. moveTo: function (x, y) {
  39845. if (this.el) {
  39846. this.el.attr('position', [x, y]);
  39847. }
  39848. },
  39849. hide: function () {
  39850. if (this.el) {
  39851. this.el.hide();
  39852. }
  39853. this._show = false;
  39854. },
  39855. hideLater: function (time) {
  39856. if (this._show && !(this._inContent && this._enterable)) {
  39857. if (time) {
  39858. this._hideDelay = time; // Set show false to avoid invoke hideLater mutiple times
  39859. this._show = false;
  39860. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  39861. } else {
  39862. this.hide();
  39863. }
  39864. }
  39865. },
  39866. isShow: function () {
  39867. return this._show;
  39868. },
  39869. getOuterSize: function () {
  39870. var size = this.getSize();
  39871. return {
  39872. width: size[0],
  39873. height: size[1]
  39874. };
  39875. }
  39876. };
  39877. /*
  39878. * Licensed to the Apache Software Foundation (ASF) under one
  39879. * or more contributor license agreements. See the NOTICE file
  39880. * distributed with this work for additional information
  39881. * regarding copyright ownership. The ASF licenses this file
  39882. * to you under the Apache License, Version 2.0 (the
  39883. * "License"); you may not use this file except in compliance
  39884. * with the License. You may obtain a copy of the License at
  39885. *
  39886. * http://www.apache.org/licenses/LICENSE-2.0
  39887. *
  39888. * Unless required by applicable law or agreed to in writing,
  39889. * software distributed under the License is distributed on an
  39890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39891. * KIND, either express or implied. See the License for the
  39892. * specific language governing permissions and limitations
  39893. * under the License.
  39894. */
  39895. var bind$2 = bind;
  39896. var each$10 = each$1;
  39897. var parsePercent$2 = parsePercent$1;
  39898. var proxyRect = new Rect({
  39899. shape: {
  39900. x: -1,
  39901. y: -1,
  39902. width: 2,
  39903. height: 2
  39904. }
  39905. });
  39906. extendComponentView({
  39907. type: 'tooltip',
  39908. init: function (ecModel, api) {
  39909. if (env$1.node) {
  39910. return;
  39911. }
  39912. var tooltipModel = ecModel.getComponent('tooltip');
  39913. var renderMode = tooltipModel.get('renderMode');
  39914. this._renderMode = getTooltipRenderMode(renderMode);
  39915. var tooltipContent;
  39916. if (this._renderMode === 'html') {
  39917. tooltipContent = new TooltipContent(api.getDom(), api, {
  39918. appendToBody: tooltipModel.get('appendToBody', true)
  39919. });
  39920. this._newLine = '<br/>';
  39921. } else {
  39922. tooltipContent = new TooltipRichContent(api);
  39923. this._newLine = '\n';
  39924. }
  39925. this._tooltipContent = tooltipContent;
  39926. },
  39927. render: function (tooltipModel, ecModel, api) {
  39928. if (env$1.node) {
  39929. return;
  39930. } // Reset
  39931. this.group.removeAll();
  39932. /**
  39933. * @private
  39934. * @type {module:echarts/component/tooltip/TooltipModel}
  39935. */
  39936. this._tooltipModel = tooltipModel;
  39937. /**
  39938. * @private
  39939. * @type {module:echarts/model/Global}
  39940. */
  39941. this._ecModel = ecModel;
  39942. /**
  39943. * @private
  39944. * @type {module:echarts/ExtensionAPI}
  39945. */
  39946. this._api = api;
  39947. /**
  39948. * Should be cleaned when render.
  39949. * @private
  39950. * @type {Array.<Array.<Object>>}
  39951. */
  39952. this._lastDataByCoordSys = null;
  39953. /**
  39954. * @private
  39955. * @type {boolean}
  39956. */
  39957. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  39958. var tooltipContent = this._tooltipContent;
  39959. tooltipContent.update();
  39960. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  39961. this._initGlobalListener();
  39962. this._keepShow();
  39963. },
  39964. _initGlobalListener: function () {
  39965. var tooltipModel = this._tooltipModel;
  39966. var triggerOn = tooltipModel.get('triggerOn');
  39967. register('itemTooltip', this._api, bind$2(function (currTrigger, e, dispatchAction) {
  39968. // If 'none', it is not controlled by mouse totally.
  39969. if (triggerOn !== 'none') {
  39970. if (triggerOn.indexOf(currTrigger) >= 0) {
  39971. this._tryShow(e, dispatchAction);
  39972. } else if (currTrigger === 'leave') {
  39973. this._hide(dispatchAction);
  39974. }
  39975. }
  39976. }, this));
  39977. },
  39978. _keepShow: function () {
  39979. var tooltipModel = this._tooltipModel;
  39980. var ecModel = this._ecModel;
  39981. var api = this._api; // Try to keep the tooltip show when refreshing
  39982. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  39983. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  39984. // which is not expected.
  39985. && tooltipModel.get('triggerOn') !== 'none') {
  39986. var self = this;
  39987. clearTimeout(this._refreshUpdateTimeout);
  39988. this._refreshUpdateTimeout = setTimeout(function () {
  39989. // Show tip next tick after other charts are rendered
  39990. // In case highlight action has wrong result
  39991. // FIXME
  39992. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  39993. x: self._lastX,
  39994. y: self._lastY
  39995. });
  39996. });
  39997. }
  39998. },
  39999. /**
  40000. * Show tip manually by
  40001. * dispatchAction({
  40002. * type: 'showTip',
  40003. * x: 10,
  40004. * y: 10
  40005. * });
  40006. * Or
  40007. * dispatchAction({
  40008. * type: 'showTip',
  40009. * seriesIndex: 0,
  40010. * dataIndex or dataIndexInside or name
  40011. * });
  40012. *
  40013. * TODO Batch
  40014. */
  40015. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  40016. if (payload.from === this.uid || env$1.node) {
  40017. return;
  40018. }
  40019. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  40020. this._ticket = ''; // When triggered from axisPointer.
  40021. var dataByCoordSys = payload.dataByCoordSys;
  40022. if (payload.tooltip && payload.x != null && payload.y != null) {
  40023. var el = proxyRect;
  40024. el.position = [payload.x, payload.y];
  40025. el.update();
  40026. el.tooltip = payload.tooltip; // Manually show tooltip while view is not using zrender elements.
  40027. this._tryShow({
  40028. offsetX: payload.x,
  40029. offsetY: payload.y,
  40030. target: el
  40031. }, dispatchAction);
  40032. } else if (dataByCoordSys) {
  40033. this._tryShow({
  40034. offsetX: payload.x,
  40035. offsetY: payload.y,
  40036. position: payload.position,
  40037. dataByCoordSys: payload.dataByCoordSys,
  40038. tooltipOption: payload.tooltipOption
  40039. }, dispatchAction);
  40040. } else if (payload.seriesIndex != null) {
  40041. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  40042. return;
  40043. }
  40044. var pointInfo = findPointFromSeries(payload, ecModel);
  40045. var cx = pointInfo.point[0];
  40046. var cy = pointInfo.point[1];
  40047. if (cx != null && cy != null) {
  40048. this._tryShow({
  40049. offsetX: cx,
  40050. offsetY: cy,
  40051. position: payload.position,
  40052. target: pointInfo.el
  40053. }, dispatchAction);
  40054. }
  40055. } else if (payload.x != null && payload.y != null) {
  40056. // FIXME
  40057. // should wrap dispatchAction like `axisPointer/globalListener` ?
  40058. api.dispatchAction({
  40059. type: 'updateAxisPointer',
  40060. x: payload.x,
  40061. y: payload.y
  40062. });
  40063. this._tryShow({
  40064. offsetX: payload.x,
  40065. offsetY: payload.y,
  40066. position: payload.position,
  40067. target: api.getZr().findHover(payload.x, payload.y).target
  40068. }, dispatchAction);
  40069. }
  40070. },
  40071. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  40072. var tooltipContent = this._tooltipContent;
  40073. if (!this._alwaysShowContent && this._tooltipModel) {
  40074. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  40075. }
  40076. this._lastX = this._lastY = null;
  40077. if (payload.from !== this.uid) {
  40078. this._hide(makeDispatchAction$1(payload, api));
  40079. }
  40080. },
  40081. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  40082. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  40083. // and tooltip.
  40084. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  40085. var seriesIndex = payload.seriesIndex;
  40086. var dataIndex = payload.dataIndex;
  40087. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  40088. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  40089. return;
  40090. }
  40091. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  40092. if (!seriesModel) {
  40093. return;
  40094. }
  40095. var data = seriesModel.getData();
  40096. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model, tooltipModel]);
  40097. if (tooltipModel.get('trigger') !== 'axis') {
  40098. return;
  40099. }
  40100. api.dispatchAction({
  40101. type: 'updateAxisPointer',
  40102. seriesIndex: seriesIndex,
  40103. dataIndex: dataIndex,
  40104. position: payload.position
  40105. });
  40106. return true;
  40107. },
  40108. _tryShow: function (e, dispatchAction) {
  40109. var el = e.target;
  40110. var tooltipModel = this._tooltipModel;
  40111. if (!tooltipModel) {
  40112. return;
  40113. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  40114. this._lastX = e.offsetX;
  40115. this._lastY = e.offsetY;
  40116. var dataByCoordSys = e.dataByCoordSys;
  40117. if (dataByCoordSys && dataByCoordSys.length) {
  40118. this._showAxisTooltip(dataByCoordSys, e);
  40119. } // Always show item tooltip if mouse is on the element with dataIndex
  40120. else if (el && el.dataIndex != null) {
  40121. this._lastDataByCoordSys = null;
  40122. this._showSeriesItemTooltip(e, el, dispatchAction);
  40123. } // Tooltip provided directly. Like legend.
  40124. else if (el && el.tooltip) {
  40125. this._lastDataByCoordSys = null;
  40126. this._showComponentItemTooltip(e, el, dispatchAction);
  40127. } else {
  40128. this._lastDataByCoordSys = null;
  40129. this._hide(dispatchAction);
  40130. }
  40131. },
  40132. _showOrMove: function (tooltipModel, cb) {
  40133. // showDelay is used in this case: tooltip.enterable is set
  40134. // as true. User intent to move mouse into tooltip and click
  40135. // something. `showDelay` makes it easyer to enter the content
  40136. // but tooltip do not move immediately.
  40137. var delay = tooltipModel.get('showDelay');
  40138. cb = bind(cb, this);
  40139. clearTimeout(this._showTimout);
  40140. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  40141. },
  40142. _showAxisTooltip: function (dataByCoordSys, e) {
  40143. var ecModel = this._ecModel;
  40144. var globalTooltipModel = this._tooltipModel;
  40145. var point = [e.offsetX, e.offsetY];
  40146. var singleDefaultHTML = [];
  40147. var singleParamsList = [];
  40148. var singleTooltipModel = buildTooltipModel([e.tooltipOption, globalTooltipModel]);
  40149. var renderMode = this._renderMode;
  40150. var newLine = this._newLine;
  40151. var markers = {};
  40152. each$10(dataByCoordSys, function (itemCoordSys) {
  40153. // var coordParamList = [];
  40154. // var coordDefaultHTML = [];
  40155. // var coordTooltipModel = buildTooltipModel([
  40156. // e.tooltipOption,
  40157. // itemCoordSys.tooltipOption,
  40158. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  40159. // globalTooltipModel
  40160. // ]);
  40161. // var displayMode = coordTooltipModel.get('displayMode');
  40162. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  40163. each$10(itemCoordSys.dataByAxis, function (item) {
  40164. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  40165. var axisValue = item.value;
  40166. var seriesDefaultHTML = [];
  40167. if (!axisModel || axisValue == null) {
  40168. return;
  40169. }
  40170. var valueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, item.seriesDataIndices, item.valueLabelOpt);
  40171. each$1(item.seriesDataIndices, function (idxItem) {
  40172. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  40173. var dataIndex = idxItem.dataIndexInside;
  40174. var dataParams = series && series.getDataParams(dataIndex);
  40175. dataParams.axisDim = item.axisDim;
  40176. dataParams.axisIndex = item.axisIndex;
  40177. dataParams.axisType = item.axisType;
  40178. dataParams.axisId = item.axisId;
  40179. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  40180. dataParams.axisValueLabel = valueLabel;
  40181. if (dataParams) {
  40182. singleParamsList.push(dataParams);
  40183. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  40184. var html;
  40185. if (isObject$1(seriesTooltip)) {
  40186. html = seriesTooltip.html;
  40187. var newMarkers = seriesTooltip.markers;
  40188. merge(markers, newMarkers);
  40189. } else {
  40190. html = seriesTooltip;
  40191. }
  40192. seriesDefaultHTML.push(html);
  40193. }
  40194. }); // Default tooltip content
  40195. // FIXME
  40196. // (1) shold be the first data which has name?
  40197. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  40198. var firstLine = valueLabel;
  40199. if (renderMode !== 'html') {
  40200. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  40201. } else {
  40202. singleDefaultHTML.push((firstLine ? encodeHTML(firstLine) + newLine : '') + seriesDefaultHTML.join(newLine));
  40203. }
  40204. });
  40205. }, this); // In most case, the second axis is shown upper than the first one.
  40206. singleDefaultHTML.reverse();
  40207. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  40208. var positionExpr = e.position;
  40209. this._showOrMove(singleTooltipModel, function () {
  40210. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  40211. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, singleParamsList);
  40212. } else {
  40213. this._showTooltipContent(singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(), point[0], point[1], positionExpr, undefined, markers);
  40214. }
  40215. }); // Do not trigger events here, because this branch only be entered
  40216. // from dispatchAction.
  40217. },
  40218. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  40219. var ecModel = this._ecModel; // Use dataModel in element if possible
  40220. // Used when mouseover on a element like markPoint or edge
  40221. // In which case, the data is not main data in series.
  40222. var seriesIndex = el.seriesIndex;
  40223. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  40224. var dataModel = el.dataModel || seriesModel;
  40225. var dataIndex = el.dataIndex;
  40226. var dataType = el.dataType;
  40227. var data = dataModel.getData(dataType);
  40228. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model, this._tooltipModel]);
  40229. var tooltipTrigger = tooltipModel.get('trigger');
  40230. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  40231. return;
  40232. }
  40233. var params = dataModel.getDataParams(dataIndex, dataType);
  40234. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  40235. var defaultHtml;
  40236. var markers;
  40237. if (isObject$1(seriesTooltip)) {
  40238. defaultHtml = seriesTooltip.html;
  40239. markers = seriesTooltip.markers;
  40240. } else {
  40241. defaultHtml = seriesTooltip;
  40242. markers = null;
  40243. }
  40244. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  40245. this._showOrMove(tooltipModel, function () {
  40246. this._showTooltipContent(tooltipModel, defaultHtml, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markers);
  40247. }); // FIXME
  40248. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  40249. dispatchAction({
  40250. type: 'showTip',
  40251. dataIndexInside: dataIndex,
  40252. dataIndex: data.getRawIndex(dataIndex),
  40253. seriesIndex: seriesIndex,
  40254. from: this.uid
  40255. });
  40256. },
  40257. _showComponentItemTooltip: function (e, el, dispatchAction) {
  40258. var tooltipOpt = el.tooltip;
  40259. if (typeof tooltipOpt === 'string') {
  40260. var content = tooltipOpt;
  40261. tooltipOpt = {
  40262. content: content,
  40263. // Fixed formatter
  40264. formatter: content
  40265. };
  40266. }
  40267. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  40268. var defaultHtml = subTooltipModel.get('content');
  40269. var asyncTicket = Math.random(); // Do not check whether `trigger` is 'none' here, because `trigger`
  40270. // only works on cooridinate system. In fact, we have not found case
  40271. // that requires setting `trigger` nothing on component yet.
  40272. this._showOrMove(subTooltipModel, function () {
  40273. this._showTooltipContent(subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {}, asyncTicket, e.offsetX, e.offsetY, e.position, el);
  40274. }); // If not dispatch showTip, tip may be hide triggered by axis.
  40275. dispatchAction({
  40276. type: 'showTip',
  40277. from: this.uid
  40278. });
  40279. },
  40280. _showTooltipContent: function (tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers) {
  40281. // Reset ticket
  40282. this._ticket = '';
  40283. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  40284. return;
  40285. }
  40286. var tooltipContent = this._tooltipContent;
  40287. var formatter = tooltipModel.get('formatter');
  40288. positionExpr = positionExpr || tooltipModel.get('position');
  40289. var html = defaultHtml;
  40290. if (formatter && typeof formatter === 'string') {
  40291. html = formatTpl(formatter, params, true);
  40292. } else if (typeof formatter === 'function') {
  40293. var callback = bind$2(function (cbTicket, html) {
  40294. if (cbTicket === this._ticket) {
  40295. tooltipContent.setContent(html, markers, tooltipModel);
  40296. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  40297. }
  40298. }, this);
  40299. this._ticket = asyncTicket;
  40300. html = formatter(params, asyncTicket, callback);
  40301. }
  40302. tooltipContent.setContent(html, markers, tooltipModel);
  40303. tooltipContent.show(tooltipModel);
  40304. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  40305. },
  40306. /**
  40307. * @param {string|Function|Array.<number>|Object} positionExpr
  40308. * @param {number} x Mouse x
  40309. * @param {number} y Mouse y
  40310. * @param {boolean} confine Whether confine tooltip content in view rect.
  40311. * @param {Object|<Array.<Object>} params
  40312. * @param {module:zrender/Element} el target element
  40313. * @param {module:echarts/ExtensionAPI} api
  40314. * @return {Array.<number>}
  40315. */
  40316. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  40317. var viewWidth = this._api.getWidth();
  40318. var viewHeight = this._api.getHeight();
  40319. positionExpr = positionExpr || tooltipModel.get('position');
  40320. var contentSize = content.getSize();
  40321. var align = tooltipModel.get('align');
  40322. var vAlign = tooltipModel.get('verticalAlign');
  40323. var rect = el && el.getBoundingRect().clone();
  40324. el && rect.applyTransform(el.transform);
  40325. if (typeof positionExpr === 'function') {
  40326. // Callback of position can be an array or a string specify the position
  40327. positionExpr = positionExpr([x, y], params, content.el, rect, {
  40328. viewSize: [viewWidth, viewHeight],
  40329. contentSize: contentSize.slice()
  40330. });
  40331. }
  40332. if (isArray(positionExpr)) {
  40333. x = parsePercent$2(positionExpr[0], viewWidth);
  40334. y = parsePercent$2(positionExpr[1], viewHeight);
  40335. } else if (isObject$1(positionExpr)) {
  40336. positionExpr.width = contentSize[0];
  40337. positionExpr.height = contentSize[1];
  40338. var layoutRect = getLayoutRect(positionExpr, {
  40339. width: viewWidth,
  40340. height: viewHeight
  40341. });
  40342. x = layoutRect.x;
  40343. y = layoutRect.y;
  40344. align = null; // When positionExpr is left/top/right/bottom,
  40345. // align and verticalAlign will not work.
  40346. vAlign = null;
  40347. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  40348. else if (typeof positionExpr === 'string' && el) {
  40349. var pos = calcTooltipPosition(positionExpr, rect, contentSize);
  40350. x = pos[0];
  40351. y = pos[1];
  40352. } else {
  40353. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  40354. x = pos[0];
  40355. y = pos[1];
  40356. }
  40357. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  40358. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  40359. if (tooltipModel.get('confine')) {
  40360. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  40361. x = pos[0];
  40362. y = pos[1];
  40363. }
  40364. content.moveTo(x, y);
  40365. },
  40366. // FIXME
  40367. // Should we remove this but leave this to user?
  40368. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  40369. var lastCoordSys = this._lastDataByCoordSys;
  40370. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  40371. contentNotChanged && each$10(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  40372. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  40373. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  40374. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  40375. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  40376. contentNotChanged && each$10(lastDataByAxis, function (lastItem, indexAxis) {
  40377. var thisItem = thisDataByAxis[indexAxis] || {};
  40378. var lastIndices = lastItem.seriesDataIndices || [];
  40379. var newIndices = thisItem.seriesDataIndices || [];
  40380. contentNotChanged &= lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  40381. contentNotChanged && each$10(lastIndices, function (lastIdxItem, j) {
  40382. var newIdxItem = newIndices[j];
  40383. contentNotChanged &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  40384. });
  40385. });
  40386. });
  40387. this._lastDataByCoordSys = dataByCoordSys;
  40388. return !!contentNotChanged;
  40389. },
  40390. _hide: function (dispatchAction) {
  40391. // Do not directly hideLater here, because this behavior may be prevented
  40392. // in dispatchAction when showTip is dispatched.
  40393. // FIXME
  40394. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  40395. this._lastDataByCoordSys = null;
  40396. dispatchAction({
  40397. type: 'hideTip',
  40398. from: this.uid
  40399. });
  40400. },
  40401. dispose: function (ecModel, api) {
  40402. if (env$1.node) {
  40403. return;
  40404. }
  40405. this._tooltipContent.dispose();
  40406. unregister('itemTooltip', api);
  40407. }
  40408. });
  40409. /**
  40410. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  40411. * From top to bottom. (the last one should be globalTooltipModel);
  40412. */
  40413. function buildTooltipModel(modelCascade) {
  40414. var resultModel = modelCascade.pop();
  40415. while (modelCascade.length) {
  40416. var tooltipOpt = modelCascade.pop();
  40417. if (tooltipOpt) {
  40418. if (Model.isInstance(tooltipOpt)) {
  40419. tooltipOpt = tooltipOpt.get('tooltip', true);
  40420. } // In each data item tooltip can be simply write:
  40421. // {
  40422. // value: 10,
  40423. // tooltip: 'Something you need to know'
  40424. // }
  40425. if (typeof tooltipOpt === 'string') {
  40426. tooltipOpt = {
  40427. formatter: tooltipOpt
  40428. };
  40429. }
  40430. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  40431. }
  40432. }
  40433. return resultModel;
  40434. }
  40435. function makeDispatchAction$1(payload, api) {
  40436. return payload.dispatchAction || bind(api.dispatchAction, api);
  40437. }
  40438. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  40439. var size = content.getOuterSize();
  40440. var width = size.width;
  40441. var height = size.height;
  40442. if (gapH != null) {
  40443. if (x + width + gapH > viewWidth) {
  40444. x -= width + gapH;
  40445. } else {
  40446. x += gapH;
  40447. }
  40448. }
  40449. if (gapV != null) {
  40450. if (y + height + gapV > viewHeight) {
  40451. y -= height + gapV;
  40452. } else {
  40453. y += gapV;
  40454. }
  40455. }
  40456. return [x, y];
  40457. }
  40458. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  40459. var size = content.getOuterSize();
  40460. var width = size.width;
  40461. var height = size.height;
  40462. x = Math.min(x + width, viewWidth) - width;
  40463. y = Math.min(y + height, viewHeight) - height;
  40464. x = Math.max(x, 0);
  40465. y = Math.max(y, 0);
  40466. return [x, y];
  40467. }
  40468. function calcTooltipPosition(position, rect, contentSize) {
  40469. var domWidth = contentSize[0];
  40470. var domHeight = contentSize[1];
  40471. var gap = 5;
  40472. var x = 0;
  40473. var y = 0;
  40474. var rectWidth = rect.width;
  40475. var rectHeight = rect.height;
  40476. switch (position) {
  40477. case 'inside':
  40478. x = rect.x + rectWidth / 2 - domWidth / 2;
  40479. y = rect.y + rectHeight / 2 - domHeight / 2;
  40480. break;
  40481. case 'top':
  40482. x = rect.x + rectWidth / 2 - domWidth / 2;
  40483. y = rect.y - domHeight - gap;
  40484. break;
  40485. case 'bottom':
  40486. x = rect.x + rectWidth / 2 - domWidth / 2;
  40487. y = rect.y + rectHeight + gap;
  40488. break;
  40489. case 'left':
  40490. x = rect.x - domWidth - gap;
  40491. y = rect.y + rectHeight / 2 - domHeight / 2;
  40492. break;
  40493. case 'right':
  40494. x = rect.x + rectWidth + gap;
  40495. y = rect.y + rectHeight / 2 - domHeight / 2;
  40496. }
  40497. return [x, y];
  40498. }
  40499. function isCenterAlign(align) {
  40500. return align === 'center' || align === 'middle';
  40501. }
  40502. /*
  40503. * Licensed to the Apache Software Foundation (ASF) under one
  40504. * or more contributor license agreements. See the NOTICE file
  40505. * distributed with this work for additional information
  40506. * regarding copyright ownership. The ASF licenses this file
  40507. * to you under the Apache License, Version 2.0 (the
  40508. * "License"); you may not use this file except in compliance
  40509. * with the License. You may obtain a copy of the License at
  40510. *
  40511. * http://www.apache.org/licenses/LICENSE-2.0
  40512. *
  40513. * Unless required by applicable law or agreed to in writing,
  40514. * software distributed under the License is distributed on an
  40515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40516. * KIND, either express or implied. See the License for the
  40517. * specific language governing permissions and limitations
  40518. * under the License.
  40519. */
  40520. // FIXME Better way to pack data in graphic element
  40521. /**
  40522. * @action
  40523. * @property {string} type
  40524. * @property {number} seriesIndex
  40525. * @property {number} dataIndex
  40526. * @property {number} [x]
  40527. * @property {number} [y]
  40528. */
  40529. registerAction({
  40530. type: 'showTip',
  40531. event: 'showTip',
  40532. update: 'tooltip:manuallyShowTip'
  40533. }, // noop
  40534. function () {});
  40535. registerAction({
  40536. type: 'hideTip',
  40537. event: 'hideTip',
  40538. update: 'tooltip:manuallyHideTip'
  40539. }, // noop
  40540. function () {});
  40541. exports.version = version;
  40542. exports.dependencies = dependencies;
  40543. exports.PRIORITY = PRIORITY;
  40544. exports.init = init;
  40545. exports.connect = connect;
  40546. exports.disConnect = disConnect;
  40547. exports.disconnect = disconnect;
  40548. exports.dispose = dispose;
  40549. exports.getInstanceByDom = getInstanceByDom;
  40550. exports.getInstanceById = getInstanceById;
  40551. exports.registerTheme = registerTheme;
  40552. exports.registerPreprocessor = registerPreprocessor;
  40553. exports.registerProcessor = registerProcessor;
  40554. exports.registerPostUpdate = registerPostUpdate;
  40555. exports.registerAction = registerAction;
  40556. exports.registerCoordinateSystem = registerCoordinateSystem;
  40557. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  40558. exports.registerLayout = registerLayout;
  40559. exports.registerVisual = registerVisual;
  40560. exports.registerLoading = registerLoading;
  40561. exports.extendComponentModel = extendComponentModel;
  40562. exports.extendComponentView = extendComponentView;
  40563. exports.extendSeriesModel = extendSeriesModel;
  40564. exports.extendChartView = extendChartView;
  40565. exports.setCanvasCreator = setCanvasCreator;
  40566. exports.registerMap = registerMap;
  40567. exports.getMap = getMap;
  40568. exports.dataTool = dataTool;
  40569. exports.zrender = zrender;
  40570. exports.number = number;
  40571. exports.format = format;
  40572. exports.throttle = throttle;
  40573. exports.helper = helper;
  40574. exports.matrix = matrix;
  40575. exports.vector = vector;
  40576. exports.color = color;
  40577. exports.parseGeoJSON = parseGeoJSON;
  40578. exports.parseGeoJson = parseGeoJson;
  40579. exports.util = ecUtil;
  40580. exports.graphic = graphic$1;
  40581. exports.List = List;
  40582. exports.Model = Model;
  40583. exports.Axis = Axis;
  40584. exports.env = env$1;
  40585. })));