echarts-en.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523
  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. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  7. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  8. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  9. // declaration is behind of the using position (for example in `Model.extent`,
  10. // And tools like rollup can not analysis the dependency if not import).
  11. var dev;
  12. // In browser
  13. if (typeof window !== 'undefined') {
  14. dev = window.__DEV__;
  15. }
  16. // In node
  17. else if (typeof global !== 'undefined') {
  18. dev = global.__DEV__;
  19. }
  20. if (typeof dev === 'undefined') {
  21. dev = true;
  22. }
  23. var __DEV__ = dev;
  24. /**
  25. * zrender: 生成唯一id
  26. *
  27. * @author errorrik (errorrik@gmail.com)
  28. */
  29. var idStart = 0x0907;
  30. var guid = function () {
  31. return idStart++;
  32. };
  33. /**
  34. * echarts设备环境识别
  35. *
  36. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  37. * @author firede[firede@firede.us]
  38. * @desc thanks zepto.
  39. */
  40. var env = {};
  41. if (typeof wx !== 'undefined') {
  42. // In Weixin Application
  43. env = {
  44. browser: {},
  45. os: {},
  46. node: false,
  47. wxa: true, // Weixin Application
  48. canvasSupported: true,
  49. svgSupported: false,
  50. touchEventsSupported: true
  51. };
  52. }
  53. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  54. // In worker
  55. env = {
  56. browser: {},
  57. os: {},
  58. node: false,
  59. worker: true,
  60. canvasSupported: true
  61. };
  62. }
  63. else if (typeof navigator === 'undefined') {
  64. // In node
  65. env = {
  66. browser: {},
  67. os: {},
  68. node: true,
  69. worker: false,
  70. // Assume canvas is supported
  71. canvasSupported: true,
  72. svgSupported: true
  73. };
  74. }
  75. else {
  76. env = detect(navigator.userAgent);
  77. }
  78. var env$1 = env;
  79. // Zepto.js
  80. // (c) 2010-2013 Thomas Fuchs
  81. // Zepto.js may be freely distributed under the MIT license.
  82. function detect(ua) {
  83. var os = {};
  84. var browser = {};
  85. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  86. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  87. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  88. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  89. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  90. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  91. // var touchpad = webos && ua.match(/TouchPad/);
  92. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  93. // var silk = ua.match(/Silk\/([\d._]+)/);
  94. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  95. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  96. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  97. // var playbook = ua.match(/PlayBook/);
  98. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  99. var firefox = ua.match(/Firefox\/([\d.]+)/);
  100. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  101. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  102. var ie = ua.match(/MSIE\s([\d.]+)/)
  103. // IE 11 Trident/7.0; rv:11.0
  104. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  105. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  106. var weChat = (/micromessenger/i).test(ua);
  107. // Todo: clean this up with a better OS/browser seperation:
  108. // - discern (more) between multiple browsers on android
  109. // - decide if kindle fire in silk mode is android or not
  110. // - Firefox on Android doesn't specify the Android version
  111. // - possibly devide in os, device and browser hashes
  112. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  113. // if (android) os.android = true, os.version = android[2];
  114. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  115. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  116. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  117. // if (webos) os.webos = true, os.version = webos[2];
  118. // if (touchpad) os.touchpad = true;
  119. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  120. // if (bb10) os.bb10 = true, os.version = bb10[2];
  121. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  122. // if (playbook) browser.playbook = true;
  123. // if (kindle) os.kindle = true, os.version = kindle[1];
  124. // if (silk) browser.silk = true, browser.version = silk[1];
  125. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  126. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  127. if (firefox) {
  128. browser.firefox = true;
  129. browser.version = firefox[1];
  130. }
  131. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  132. // if (webview) browser.webview = true;
  133. if (ie) {
  134. browser.ie = true;
  135. browser.version = ie[1];
  136. }
  137. if (edge) {
  138. browser.edge = true;
  139. browser.version = edge[1];
  140. }
  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. }
  146. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  147. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  148. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  149. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  150. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  151. return {
  152. browser: browser,
  153. os: os,
  154. node: false,
  155. // 原生canvas支持,改极端点了
  156. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  157. canvasSupported: !!document.createElement('canvas').getContext,
  158. svgSupported: typeof SVGRect !== 'undefined',
  159. // works on most browsers
  160. // IE10/11 does not support touch event, and MS Edge supports them but not by
  161. // default, so we dont check navigator.maxTouchPoints for them here.
  162. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  163. // <http://caniuse.com/#search=pointer%20event>.
  164. pointerEventsSupported: 'onpointerdown' in window
  165. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  166. // events currently. So we dont use that on other browsers unless tested sufficiently.
  167. // Although IE 10 supports pointer event, it use old style and is different from the
  168. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  169. && (browser.edge || (browser.ie && browser.version >= 11))
  170. };
  171. }
  172. /**
  173. * @module zrender/core/util
  174. */
  175. // 用于处理merge时无法遍历Date等对象的问题
  176. var BUILTIN_OBJECT = {
  177. '[object Function]': 1,
  178. '[object RegExp]': 1,
  179. '[object Date]': 1,
  180. '[object Error]': 1,
  181. '[object CanvasGradient]': 1,
  182. '[object CanvasPattern]': 1,
  183. // For node-canvas
  184. '[object Image]': 1,
  185. '[object Canvas]': 1
  186. };
  187. var TYPED_ARRAY = {
  188. '[object Int8Array]': 1,
  189. '[object Uint8Array]': 1,
  190. '[object Uint8ClampedArray]': 1,
  191. '[object Int16Array]': 1,
  192. '[object Uint16Array]': 1,
  193. '[object Int32Array]': 1,
  194. '[object Uint32Array]': 1,
  195. '[object Float32Array]': 1,
  196. '[object Float64Array]': 1
  197. };
  198. var objToString = Object.prototype.toString;
  199. var arrayProto = Array.prototype;
  200. var nativeForEach = arrayProto.forEach;
  201. var nativeFilter = arrayProto.filter;
  202. var nativeSlice = arrayProto.slice;
  203. var nativeMap = arrayProto.map;
  204. var nativeReduce = arrayProto.reduce;
  205. // Avoid assign to an exported variable, for transforming to cjs.
  206. var methods = {};
  207. function $override(name, fn) {
  208. // Clear ctx instance for different environment
  209. if (name === 'createCanvas') {
  210. _ctx = null;
  211. }
  212. methods[name] = fn;
  213. }
  214. /**
  215. * Those data types can be cloned:
  216. * Plain object, Array, TypedArray, number, string, null, undefined.
  217. * Those data types will be assgined using the orginal data:
  218. * BUILTIN_OBJECT
  219. * Instance of user defined class will be cloned to a plain object, without
  220. * properties in prototype.
  221. * Other data types is not supported (not sure what will happen).
  222. *
  223. * Caution: do not support clone Date, for performance consideration.
  224. * (There might be a large number of date in `series.data`).
  225. * So date should not be modified in and out of echarts.
  226. *
  227. * @param {*} source
  228. * @return {*} new
  229. */
  230. function clone(source) {
  231. if (source == null || typeof source != 'object') {
  232. return source;
  233. }
  234. var result = source;
  235. var typeStr = objToString.call(source);
  236. if (typeStr === '[object Array]') {
  237. if (!isPrimitive(source)) {
  238. result = [];
  239. for (var i = 0, len = source.length; i < len; i++) {
  240. result[i] = clone(source[i]);
  241. }
  242. }
  243. }
  244. else if (TYPED_ARRAY[typeStr]) {
  245. if (!isPrimitive(source)) {
  246. var Ctor = source.constructor;
  247. if (source.constructor.from) {
  248. result = Ctor.from(source);
  249. }
  250. else {
  251. result = new Ctor(source.length);
  252. for (var i = 0, len = source.length; i < len; i++) {
  253. result[i] = clone(source[i]);
  254. }
  255. }
  256. }
  257. }
  258. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  259. result = {};
  260. for (var key in source) {
  261. if (source.hasOwnProperty(key)) {
  262. result[key] = clone(source[key]);
  263. }
  264. }
  265. }
  266. return result;
  267. }
  268. /**
  269. * @memberOf module:zrender/core/util
  270. * @param {*} target
  271. * @param {*} source
  272. * @param {boolean} [overwrite=false]
  273. */
  274. function merge(target, source, overwrite) {
  275. // We should escapse that source is string
  276. // and enter for ... in ...
  277. if (!isObject$1(source) || !isObject$1(target)) {
  278. return overwrite ? clone(source) : target;
  279. }
  280. for (var key in source) {
  281. if (source.hasOwnProperty(key)) {
  282. var targetProp = target[key];
  283. var sourceProp = source[key];
  284. if (isObject$1(sourceProp)
  285. && isObject$1(targetProp)
  286. && !isArray(sourceProp)
  287. && !isArray(targetProp)
  288. && !isDom(sourceProp)
  289. && !isDom(targetProp)
  290. && !isBuiltInObject(sourceProp)
  291. && !isBuiltInObject(targetProp)
  292. && !isPrimitive(sourceProp)
  293. && !isPrimitive(targetProp)
  294. ) {
  295. // 如果需要递归覆盖,就递归调用merge
  296. merge(targetProp, sourceProp, overwrite);
  297. }
  298. else if (overwrite || !(key in target)) {
  299. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  300. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  301. target[key] = clone(source[key], true);
  302. }
  303. }
  304. }
  305. return target;
  306. }
  307. /**
  308. * @param {Array} targetAndSources The first item is target, and the rests are source.
  309. * @param {boolean} [overwrite=false]
  310. * @return {*} target
  311. */
  312. function mergeAll(targetAndSources, overwrite) {
  313. var result = targetAndSources[0];
  314. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  315. result = merge(result, targetAndSources[i], overwrite);
  316. }
  317. return result;
  318. }
  319. /**
  320. * @param {*} target
  321. * @param {*} source
  322. * @memberOf module:zrender/core/util
  323. */
  324. function extend(target, source) {
  325. for (var key in source) {
  326. if (source.hasOwnProperty(key)) {
  327. target[key] = source[key];
  328. }
  329. }
  330. return target;
  331. }
  332. /**
  333. * @param {*} target
  334. * @param {*} source
  335. * @param {boolean} [overlay=false]
  336. * @memberOf module:zrender/core/util
  337. */
  338. function defaults(target, source, overlay) {
  339. for (var key in source) {
  340. if (source.hasOwnProperty(key)
  341. && (overlay ? source[key] != null : target[key] == null)
  342. ) {
  343. target[key] = source[key];
  344. }
  345. }
  346. return target;
  347. }
  348. var createCanvas = function () {
  349. return methods.createCanvas();
  350. };
  351. methods.createCanvas = function () {
  352. return document.createElement('canvas');
  353. };
  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. clazz.prototype[prop] = clazzPrototype[prop];
  395. }
  396. clazz.prototype.constructor = clazz;
  397. clazz.superClass = baseClazz;
  398. }
  399. /**
  400. * @memberOf module:zrender/core/util
  401. * @param {Object|Function} target
  402. * @param {Object|Function} sorce
  403. * @param {boolean} overlay
  404. */
  405. function mixin(target, source, overlay) {
  406. target = 'prototype' in target ? target.prototype : target;
  407. source = 'prototype' in source ? source.prototype : source;
  408. defaults(target, source, overlay);
  409. }
  410. /**
  411. * Consider typed array.
  412. * @param {Array|TypedArray} data
  413. */
  414. function isArrayLike(data) {
  415. if (! data) {
  416. return;
  417. }
  418. if (typeof data == 'string') {
  419. return false;
  420. }
  421. return typeof data.length == 'number';
  422. }
  423. /**
  424. * 数组或对象遍历
  425. * @memberOf module:zrender/core/util
  426. * @param {Object|Array} obj
  427. * @param {Function} cb
  428. * @param {*} [context]
  429. */
  430. function each$1(obj, cb, context) {
  431. if (!(obj && cb)) {
  432. return;
  433. }
  434. if (obj.forEach && obj.forEach === nativeForEach) {
  435. obj.forEach(cb, context);
  436. }
  437. else if (obj.length === +obj.length) {
  438. for (var i = 0, len = obj.length; i < len; i++) {
  439. cb.call(context, obj[i], i, obj);
  440. }
  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. }
  465. else {
  466. var result = [];
  467. for (var i = 0, len = obj.length; i < len; i++) {
  468. result.push(cb.call(context, obj[i], i, obj));
  469. }
  470. return result;
  471. }
  472. }
  473. /**
  474. * @memberOf module:zrender/core/util
  475. * @param {Array} obj
  476. * @param {Function} cb
  477. * @param {Object} [memo]
  478. * @param {*} [context]
  479. * @return {Array}
  480. */
  481. function reduce(obj, cb, memo, context) {
  482. if (!(obj && cb)) {
  483. return;
  484. }
  485. if (obj.reduce && obj.reduce === nativeReduce) {
  486. return obj.reduce(cb, memo, context);
  487. }
  488. else {
  489. for (var i = 0, len = obj.length; i < len; i++) {
  490. memo = cb.call(context, memo, obj[i], i, obj);
  491. }
  492. return memo;
  493. }
  494. }
  495. /**
  496. * 数组过滤
  497. * @memberOf module:zrender/core/util
  498. * @param {Array} obj
  499. * @param {Function} cb
  500. * @param {*} [context]
  501. * @return {Array}
  502. */
  503. function filter(obj, cb, context) {
  504. if (!(obj && cb)) {
  505. return;
  506. }
  507. if (obj.filter && obj.filter === nativeFilter) {
  508. return obj.filter(cb, context);
  509. }
  510. else {
  511. var result = [];
  512. for (var i = 0, len = obj.length; i < len; i++) {
  513. if (cb.call(context, obj[i], i, obj)) {
  514. result.push(obj[i]);
  515. }
  516. }
  517. return result;
  518. }
  519. }
  520. /**
  521. * 数组项查找
  522. * @memberOf module:zrender/core/util
  523. * @param {Array} obj
  524. * @param {Function} cb
  525. * @param {*} [context]
  526. * @return {*}
  527. */
  528. function find(obj, cb, context) {
  529. if (!(obj && cb)) {
  530. return;
  531. }
  532. for (var i = 0, len = obj.length; i < len; i++) {
  533. if (cb.call(context, obj[i], i, obj)) {
  534. return obj[i];
  535. }
  536. }
  537. }
  538. /**
  539. * @memberOf module:zrender/core/util
  540. * @param {Function} func
  541. * @param {*} context
  542. * @return {Function}
  543. */
  544. function bind(func, context) {
  545. var args = nativeSlice.call(arguments, 2);
  546. return function () {
  547. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  548. };
  549. }
  550. /**
  551. * @memberOf module:zrender/core/util
  552. * @param {Function} func
  553. * @return {Function}
  554. */
  555. function curry(func) {
  556. var args = nativeSlice.call(arguments, 1);
  557. return function () {
  558. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  559. };
  560. }
  561. /**
  562. * @memberOf module:zrender/core/util
  563. * @param {*} value
  564. * @return {boolean}
  565. */
  566. function isArray(value) {
  567. return objToString.call(value) === '[object Array]';
  568. }
  569. /**
  570. * @memberOf module:zrender/core/util
  571. * @param {*} value
  572. * @return {boolean}
  573. */
  574. function isFunction$1(value) {
  575. return typeof value === 'function';
  576. }
  577. /**
  578. * @memberOf module:zrender/core/util
  579. * @param {*} value
  580. * @return {boolean}
  581. */
  582. function isString(value) {
  583. return objToString.call(value) === '[object String]';
  584. }
  585. /**
  586. * @memberOf module:zrender/core/util
  587. * @param {*} value
  588. * @return {boolean}
  589. */
  590. function isObject$1(value) {
  591. // Avoid a V8 JIT bug in Chrome 19-20.
  592. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  593. var type = typeof value;
  594. return type === 'function' || (!!value && type == 'object');
  595. }
  596. /**
  597. * @memberOf module:zrender/core/util
  598. * @param {*} value
  599. * @return {boolean}
  600. */
  601. function isBuiltInObject(value) {
  602. return !!BUILTIN_OBJECT[objToString.call(value)];
  603. }
  604. /**
  605. * @memberOf module:zrender/core/util
  606. * @param {*} value
  607. * @return {boolean}
  608. */
  609. function isTypedArray(value) {
  610. return !!TYPED_ARRAY[objToString.call(value)];
  611. }
  612. /**
  613. * @memberOf module:zrender/core/util
  614. * @param {*} value
  615. * @return {boolean}
  616. */
  617. function isDom(value) {
  618. return typeof value === 'object'
  619. && typeof value.nodeType === 'number'
  620. && typeof value.ownerDocument === 'object';
  621. }
  622. /**
  623. * Whether is exactly NaN. Notice isNaN('a') returns true.
  624. * @param {*} value
  625. * @return {boolean}
  626. */
  627. function eqNaN(value) {
  628. return value !== value;
  629. }
  630. /**
  631. * If value1 is not null, then return value1, otherwise judget rest of values.
  632. * Low performance.
  633. * @memberOf module:zrender/core/util
  634. * @return {*} Final value
  635. */
  636. function retrieve(values) {
  637. for (var i = 0, len = arguments.length; i < len; i++) {
  638. if (arguments[i] != null) {
  639. return arguments[i];
  640. }
  641. }
  642. }
  643. function retrieve2(value0, value1) {
  644. return value0 != null
  645. ? value0
  646. : value1;
  647. }
  648. function retrieve3(value0, value1, value2) {
  649. return value0 != null
  650. ? value0
  651. : value1 != null
  652. ? value1
  653. : value2;
  654. }
  655. /**
  656. * @memberOf module:zrender/core/util
  657. * @param {Array} arr
  658. * @param {number} startIndex
  659. * @param {number} endIndex
  660. * @return {Array}
  661. */
  662. function slice() {
  663. return Function.call.apply(nativeSlice, arguments);
  664. }
  665. /**
  666. * Normalize css liked array configuration
  667. * e.g.
  668. * 3 => [3, 3, 3, 3]
  669. * [4, 2] => [4, 2, 4, 2]
  670. * [4, 3, 2] => [4, 3, 2, 3]
  671. * @param {number|Array.<number>} val
  672. * @return {Array.<number>}
  673. */
  674. function normalizeCssArray(val) {
  675. if (typeof (val) === 'number') {
  676. return [val, val, val, val];
  677. }
  678. var len = val.length;
  679. if (len === 2) {
  680. // vertical | horizontal
  681. return [val[0], val[1], val[0], val[1]];
  682. }
  683. else if (len === 3) {
  684. // top | horizontal | bottom
  685. return [val[0], val[1], val[2], val[1]];
  686. }
  687. return val;
  688. }
  689. /**
  690. * @memberOf module:zrender/core/util
  691. * @param {boolean} condition
  692. * @param {string} message
  693. */
  694. function assert$1(condition, message) {
  695. if (!condition) {
  696. throw new Error(message);
  697. }
  698. }
  699. /**
  700. * @memberOf module:zrender/core/util
  701. * @param {string} str string to be trimed
  702. * @return {string} trimed string
  703. */
  704. function trim(str) {
  705. if (str == null) {
  706. return null;
  707. }
  708. else if (typeof str.trim === 'function') {
  709. return str.trim();
  710. }
  711. else {
  712. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  713. }
  714. }
  715. var primitiveKey = '__ec_primitive__';
  716. /**
  717. * Set an object as primitive to be ignored traversing children in clone or merge
  718. */
  719. function setAsPrimitive(obj) {
  720. obj[primitiveKey] = true;
  721. }
  722. function isPrimitive(obj) {
  723. return obj[primitiveKey];
  724. }
  725. /**
  726. * @constructor
  727. * @param {Object} obj Only apply `ownProperty`.
  728. */
  729. function HashMap(obj) {
  730. var isArr = isArray(obj);
  731. var thisMap = this;
  732. (obj instanceof HashMap)
  733. ? obj.each(visit)
  734. : (obj && each$1(obj, visit));
  735. function visit(value, key) {
  736. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  737. }
  738. }
  739. // Add prefix to avoid conflict with Object.prototype.
  740. HashMap.prototype = {
  741. constructor: HashMap,
  742. // Do not provide `has` method to avoid defining what is `has`.
  743. // (We usually treat `null` and `undefined` as the same, different
  744. // from ES6 Map).
  745. get: function (key) {
  746. return this.hasOwnProperty(key) ? this[key] : null;
  747. },
  748. set: function (key, value) {
  749. // Comparing with invocation chaining, `return value` is more commonly
  750. // used in this case: `var someVal = map.set('a', genVal());`
  751. return (this[key] = value);
  752. },
  753. // Although util.each can be performed on this hashMap directly, user
  754. // should not use the exposed keys, who are prefixed.
  755. each: function (cb, context) {
  756. context !== void 0 && (cb = bind(cb, context));
  757. for (var key in this) {
  758. this.hasOwnProperty(key) && cb(this[key], key);
  759. }
  760. },
  761. // Do not use this method if performance sensitive.
  762. removeKey: function (key) {
  763. delete this[key];
  764. }
  765. };
  766. function createHashMap(obj) {
  767. return new HashMap(obj);
  768. }
  769. function concatArray(a, b) {
  770. var newArray = new a.constructor(a.length + b.length);
  771. for (var i = 0; i < a.length; i++) {
  772. newArray[i] = a[i];
  773. }
  774. var offset = a.length;
  775. for (i = 0; i < b.length; i++) {
  776. newArray[i + offset] = b[i];
  777. }
  778. return newArray;
  779. }
  780. function noop() {}
  781. var zrUtil = (Object.freeze || Object)({
  782. $override: $override,
  783. clone: clone,
  784. merge: merge,
  785. mergeAll: mergeAll,
  786. extend: extend,
  787. defaults: defaults,
  788. createCanvas: createCanvas,
  789. getContext: getContext,
  790. indexOf: indexOf,
  791. inherits: inherits,
  792. mixin: mixin,
  793. isArrayLike: isArrayLike,
  794. each: each$1,
  795. map: map,
  796. reduce: reduce,
  797. filter: filter,
  798. find: find,
  799. bind: bind,
  800. curry: curry,
  801. isArray: isArray,
  802. isFunction: isFunction$1,
  803. isString: isString,
  804. isObject: isObject$1,
  805. isBuiltInObject: isBuiltInObject,
  806. isTypedArray: isTypedArray,
  807. isDom: isDom,
  808. eqNaN: eqNaN,
  809. retrieve: retrieve,
  810. retrieve2: retrieve2,
  811. retrieve3: retrieve3,
  812. slice: slice,
  813. normalizeCssArray: normalizeCssArray,
  814. assert: assert$1,
  815. trim: trim,
  816. setAsPrimitive: setAsPrimitive,
  817. isPrimitive: isPrimitive,
  818. createHashMap: createHashMap,
  819. concatArray: concatArray,
  820. noop: noop
  821. });
  822. var ArrayCtor = typeof Float32Array === 'undefined'
  823. ? Array
  824. : Float32Array;
  825. /**
  826. * 创建一个向量
  827. * @param {number} [x=0]
  828. * @param {number} [y=0]
  829. * @return {Vector2}
  830. */
  831. function create(x, y) {
  832. var out = new ArrayCtor(2);
  833. if (x == null) {
  834. x = 0;
  835. }
  836. if (y == null) {
  837. y = 0;
  838. }
  839. out[0] = x;
  840. out[1] = y;
  841. return out;
  842. }
  843. /**
  844. * 复制向量数据
  845. * @param {Vector2} out
  846. * @param {Vector2} v
  847. * @return {Vector2}
  848. */
  849. function copy(out, v) {
  850. out[0] = v[0];
  851. out[1] = v[1];
  852. return out;
  853. }
  854. /**
  855. * 克隆一个向量
  856. * @param {Vector2} v
  857. * @return {Vector2}
  858. */
  859. function clone$1(v) {
  860. var out = new ArrayCtor(2);
  861. out[0] = v[0];
  862. out[1] = v[1];
  863. return out;
  864. }
  865. /**
  866. * 设置向量的两个项
  867. * @param {Vector2} out
  868. * @param {number} a
  869. * @param {number} b
  870. * @return {Vector2} 结果
  871. */
  872. function set(out, a, b) {
  873. out[0] = a;
  874. out[1] = b;
  875. return out;
  876. }
  877. /**
  878. * 向量相加
  879. * @param {Vector2} out
  880. * @param {Vector2} v1
  881. * @param {Vector2} v2
  882. */
  883. function add(out, v1, v2) {
  884. out[0] = v1[0] + v2[0];
  885. out[1] = v1[1] + v2[1];
  886. return out;
  887. }
  888. /**
  889. * 向量缩放后相加
  890. * @param {Vector2} out
  891. * @param {Vector2} v1
  892. * @param {Vector2} v2
  893. * @param {number} a
  894. */
  895. function scaleAndAdd(out, v1, v2, a) {
  896. out[0] = v1[0] + v2[0] * a;
  897. out[1] = v1[1] + v2[1] * a;
  898. return out;
  899. }
  900. /**
  901. * 向量相减
  902. * @param {Vector2} out
  903. * @param {Vector2} v1
  904. * @param {Vector2} v2
  905. */
  906. function sub(out, v1, v2) {
  907. out[0] = v1[0] - v2[0];
  908. out[1] = v1[1] - v2[1];
  909. return out;
  910. }
  911. /**
  912. * 向量长度
  913. * @param {Vector2} v
  914. * @return {number}
  915. */
  916. function len(v) {
  917. return Math.sqrt(lenSquare(v));
  918. }
  919. var length = len; // jshint ignore:line
  920. /**
  921. * 向量长度平方
  922. * @param {Vector2} v
  923. * @return {number}
  924. */
  925. function lenSquare(v) {
  926. return v[0] * v[0] + v[1] * v[1];
  927. }
  928. var lengthSquare = lenSquare;
  929. /**
  930. * 向量乘法
  931. * @param {Vector2} out
  932. * @param {Vector2} v1
  933. * @param {Vector2} v2
  934. */
  935. function mul(out, v1, v2) {
  936. out[0] = v1[0] * v2[0];
  937. out[1] = v1[1] * v2[1];
  938. return out;
  939. }
  940. /**
  941. * 向量除法
  942. * @param {Vector2} out
  943. * @param {Vector2} v1
  944. * @param {Vector2} v2
  945. */
  946. function div(out, v1, v2) {
  947. out[0] = v1[0] / v2[0];
  948. out[1] = v1[1] / v2[1];
  949. return out;
  950. }
  951. /**
  952. * 向量点乘
  953. * @param {Vector2} v1
  954. * @param {Vector2} v2
  955. * @return {number}
  956. */
  957. function dot(v1, v2) {
  958. return v1[0] * v2[0] + v1[1] * v2[1];
  959. }
  960. /**
  961. * 向量缩放
  962. * @param {Vector2} out
  963. * @param {Vector2} v
  964. * @param {number} s
  965. */
  966. function scale(out, v, s) {
  967. out[0] = v[0] * s;
  968. out[1] = v[1] * s;
  969. return out;
  970. }
  971. /**
  972. * 向量归一化
  973. * @param {Vector2} out
  974. * @param {Vector2} v
  975. */
  976. function normalize(out, v) {
  977. var d = len(v);
  978. if (d === 0) {
  979. out[0] = 0;
  980. out[1] = 0;
  981. }
  982. else {
  983. out[0] = v[0] / d;
  984. out[1] = v[1] / d;
  985. }
  986. return out;
  987. }
  988. /**
  989. * 计算向量间距离
  990. * @param {Vector2} v1
  991. * @param {Vector2} v2
  992. * @return {number}
  993. */
  994. function distance(v1, v2) {
  995. return Math.sqrt(
  996. (v1[0] - v2[0]) * (v1[0] - v2[0])
  997. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  998. );
  999. }
  1000. var dist = distance;
  1001. /**
  1002. * 向量距离平方
  1003. * @param {Vector2} v1
  1004. * @param {Vector2} v2
  1005. * @return {number}
  1006. */
  1007. function distanceSquare(v1, v2) {
  1008. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1009. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1010. }
  1011. var distSquare = distanceSquare;
  1012. /**
  1013. * 求负向量
  1014. * @param {Vector2} out
  1015. * @param {Vector2} v
  1016. */
  1017. function negate(out, v) {
  1018. out[0] = -v[0];
  1019. out[1] = -v[1];
  1020. return out;
  1021. }
  1022. /**
  1023. * 插值两个点
  1024. * @param {Vector2} out
  1025. * @param {Vector2} v1
  1026. * @param {Vector2} v2
  1027. * @param {number} t
  1028. */
  1029. function lerp(out, v1, v2, t) {
  1030. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1031. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1032. return out;
  1033. }
  1034. /**
  1035. * 矩阵左乘向量
  1036. * @param {Vector2} out
  1037. * @param {Vector2} v
  1038. * @param {Vector2} m
  1039. */
  1040. function applyTransform(out, v, m) {
  1041. var x = v[0];
  1042. var y = v[1];
  1043. out[0] = m[0] * x + m[2] * y + m[4];
  1044. out[1] = m[1] * x + m[3] * y + m[5];
  1045. return out;
  1046. }
  1047. /**
  1048. * 求两个向量最小值
  1049. * @param {Vector2} out
  1050. * @param {Vector2} v1
  1051. * @param {Vector2} v2
  1052. */
  1053. function min(out, v1, v2) {
  1054. out[0] = Math.min(v1[0], v2[0]);
  1055. out[1] = Math.min(v1[1], v2[1]);
  1056. return out;
  1057. }
  1058. /**
  1059. * 求两个向量最大值
  1060. * @param {Vector2} out
  1061. * @param {Vector2} v1
  1062. * @param {Vector2} v2
  1063. */
  1064. function max(out, v1, v2) {
  1065. out[0] = Math.max(v1[0], v2[0]);
  1066. out[1] = Math.max(v1[1], v2[1]);
  1067. return out;
  1068. }
  1069. var vector = (Object.freeze || Object)({
  1070. create: create,
  1071. copy: copy,
  1072. clone: clone$1,
  1073. set: set,
  1074. add: add,
  1075. scaleAndAdd: scaleAndAdd,
  1076. sub: sub,
  1077. len: len,
  1078. length: length,
  1079. lenSquare: lenSquare,
  1080. lengthSquare: lengthSquare,
  1081. mul: mul,
  1082. div: div,
  1083. dot: dot,
  1084. scale: scale,
  1085. normalize: normalize,
  1086. distance: distance,
  1087. dist: dist,
  1088. distanceSquare: distanceSquare,
  1089. distSquare: distSquare,
  1090. negate: negate,
  1091. lerp: lerp,
  1092. applyTransform: applyTransform,
  1093. min: min,
  1094. max: max
  1095. });
  1096. // TODO Draggable for group
  1097. // FIXME Draggable on element which has parent rotation or scale
  1098. function Draggable() {
  1099. this.on('mousedown', this._dragStart, this);
  1100. this.on('mousemove', this._drag, this);
  1101. this.on('mouseup', this._dragEnd, this);
  1102. this.on('globalout', this._dragEnd, this);
  1103. // this._dropTarget = null;
  1104. // this._draggingTarget = null;
  1105. // this._x = 0;
  1106. // this._y = 0;
  1107. }
  1108. Draggable.prototype = {
  1109. constructor: Draggable,
  1110. _dragStart: function (e) {
  1111. var draggingTarget = e.target;
  1112. if (draggingTarget && draggingTarget.draggable) {
  1113. this._draggingTarget = draggingTarget;
  1114. draggingTarget.dragging = true;
  1115. this._x = e.offsetX;
  1116. this._y = e.offsetY;
  1117. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1118. }
  1119. },
  1120. _drag: function (e) {
  1121. var draggingTarget = this._draggingTarget;
  1122. if (draggingTarget) {
  1123. var x = e.offsetX;
  1124. var y = e.offsetY;
  1125. var dx = x - this._x;
  1126. var dy = y - this._y;
  1127. this._x = x;
  1128. this._y = y;
  1129. draggingTarget.drift(dx, dy, e);
  1130. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1131. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1132. var lastDropTarget = this._dropTarget;
  1133. this._dropTarget = dropTarget;
  1134. if (draggingTarget !== dropTarget) {
  1135. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1136. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1137. }
  1138. if (dropTarget && dropTarget !== lastDropTarget) {
  1139. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1140. }
  1141. }
  1142. }
  1143. },
  1144. _dragEnd: function (e) {
  1145. var draggingTarget = this._draggingTarget;
  1146. if (draggingTarget) {
  1147. draggingTarget.dragging = false;
  1148. }
  1149. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1150. if (this._dropTarget) {
  1151. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1152. }
  1153. this._draggingTarget = null;
  1154. this._dropTarget = null;
  1155. }
  1156. };
  1157. function param(target, e) {
  1158. return {target: target, topTarget: e && e.topTarget};
  1159. }
  1160. /**
  1161. * 事件扩展
  1162. * @module zrender/mixin/Eventful
  1163. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1164. * pissang (https://www.github.com/pissang)
  1165. */
  1166. var arrySlice = Array.prototype.slice;
  1167. /**
  1168. * 事件分发器
  1169. * @alias module:zrender/mixin/Eventful
  1170. * @constructor
  1171. */
  1172. var Eventful = function () {
  1173. this._$handlers = {};
  1174. };
  1175. Eventful.prototype = {
  1176. constructor: Eventful,
  1177. /**
  1178. * 单次触发绑定,trigger后销毁
  1179. *
  1180. * @param {string} event 事件名
  1181. * @param {Function} handler 响应函数
  1182. * @param {Object} context
  1183. */
  1184. one: function (event, handler, context) {
  1185. var _h = this._$handlers;
  1186. if (!handler || !event) {
  1187. return this;
  1188. }
  1189. if (!_h[event]) {
  1190. _h[event] = [];
  1191. }
  1192. for (var i = 0; i < _h[event].length; i++) {
  1193. if (_h[event][i].h === handler) {
  1194. return this;
  1195. }
  1196. }
  1197. _h[event].push({
  1198. h: handler,
  1199. one: true,
  1200. ctx: context || this
  1201. });
  1202. return this;
  1203. },
  1204. /**
  1205. * 绑定事件
  1206. * @param {string} event 事件名
  1207. * @param {Function} handler 事件处理函数
  1208. * @param {Object} [context]
  1209. */
  1210. on: function (event, handler, context) {
  1211. var _h = this._$handlers;
  1212. if (!handler || !event) {
  1213. return this;
  1214. }
  1215. if (!_h[event]) {
  1216. _h[event] = [];
  1217. }
  1218. for (var i = 0; i < _h[event].length; i++) {
  1219. if (_h[event][i].h === handler) {
  1220. return this;
  1221. }
  1222. }
  1223. _h[event].push({
  1224. h: handler,
  1225. one: false,
  1226. ctx: context || this
  1227. });
  1228. return this;
  1229. },
  1230. /**
  1231. * 是否绑定了事件
  1232. * @param {string} event
  1233. * @return {boolean}
  1234. */
  1235. isSilent: function (event) {
  1236. var _h = this._$handlers;
  1237. return _h[event] && _h[event].length;
  1238. },
  1239. /**
  1240. * 解绑事件
  1241. * @param {string} event 事件名
  1242. * @param {Function} [handler] 事件处理函数
  1243. */
  1244. off: function (event, handler) {
  1245. var _h = this._$handlers;
  1246. if (!event) {
  1247. this._$handlers = {};
  1248. return this;
  1249. }
  1250. if (handler) {
  1251. if (_h[event]) {
  1252. var newList = [];
  1253. for (var i = 0, l = _h[event].length; i < l; i++) {
  1254. if (_h[event][i]['h'] != handler) {
  1255. newList.push(_h[event][i]);
  1256. }
  1257. }
  1258. _h[event] = newList;
  1259. }
  1260. if (_h[event] && _h[event].length === 0) {
  1261. delete _h[event];
  1262. }
  1263. }
  1264. else {
  1265. delete _h[event];
  1266. }
  1267. return this;
  1268. },
  1269. /**
  1270. * 事件分发
  1271. *
  1272. * @param {string} type 事件类型
  1273. */
  1274. trigger: function (type) {
  1275. if (this._$handlers[type]) {
  1276. var args = arguments;
  1277. var argLen = args.length;
  1278. if (argLen > 3) {
  1279. args = arrySlice.call(args, 1);
  1280. }
  1281. var _h = this._$handlers[type];
  1282. var len = _h.length;
  1283. for (var i = 0; i < len;) {
  1284. // Optimize advise from backbone
  1285. switch (argLen) {
  1286. case 1:
  1287. _h[i]['h'].call(_h[i]['ctx']);
  1288. break;
  1289. case 2:
  1290. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1291. break;
  1292. case 3:
  1293. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1294. break;
  1295. default:
  1296. // have more than 2 given arguments
  1297. _h[i]['h'].apply(_h[i]['ctx'], args);
  1298. break;
  1299. }
  1300. if (_h[i]['one']) {
  1301. _h.splice(i, 1);
  1302. len--;
  1303. }
  1304. else {
  1305. i++;
  1306. }
  1307. }
  1308. }
  1309. return this;
  1310. },
  1311. /**
  1312. * 带有context的事件分发, 最后一个参数是事件回调的context
  1313. * @param {string} type 事件类型
  1314. */
  1315. triggerWithContext: function (type) {
  1316. if (this._$handlers[type]) {
  1317. var args = arguments;
  1318. var argLen = args.length;
  1319. if (argLen > 4) {
  1320. args = arrySlice.call(args, 1, args.length - 1);
  1321. }
  1322. var ctx = args[args.length - 1];
  1323. var _h = this._$handlers[type];
  1324. var len = _h.length;
  1325. for (var i = 0; i < len;) {
  1326. // Optimize advise from backbone
  1327. switch (argLen) {
  1328. case 1:
  1329. _h[i]['h'].call(ctx);
  1330. break;
  1331. case 2:
  1332. _h[i]['h'].call(ctx, args[1]);
  1333. break;
  1334. case 3:
  1335. _h[i]['h'].call(ctx, args[1], args[2]);
  1336. break;
  1337. default:
  1338. // have more than 2 given arguments
  1339. _h[i]['h'].apply(ctx, args);
  1340. break;
  1341. }
  1342. if (_h[i]['one']) {
  1343. _h.splice(i, 1);
  1344. len--;
  1345. }
  1346. else {
  1347. i++;
  1348. }
  1349. }
  1350. }
  1351. return this;
  1352. }
  1353. };
  1354. var SILENT = 'silent';
  1355. function makeEventPacket(eveType, targetInfo, event) {
  1356. return {
  1357. type: eveType,
  1358. event: event,
  1359. // target can only be an element that is not silent.
  1360. target: targetInfo.target,
  1361. // topTarget can be a silent element.
  1362. topTarget: targetInfo.topTarget,
  1363. cancelBubble: false,
  1364. offsetX: event.zrX,
  1365. offsetY: event.zrY,
  1366. gestureEvent: event.gestureEvent,
  1367. pinchX: event.pinchX,
  1368. pinchY: event.pinchY,
  1369. pinchScale: event.pinchScale,
  1370. wheelDelta: event.zrDelta,
  1371. zrByTouch: event.zrByTouch,
  1372. which: event.which
  1373. };
  1374. }
  1375. function EmptyProxy () {}
  1376. EmptyProxy.prototype.dispose = function () {};
  1377. var handlerNames = [
  1378. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1379. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1380. ];
  1381. /**
  1382. * @alias module:zrender/Handler
  1383. * @constructor
  1384. * @extends module:zrender/mixin/Eventful
  1385. * @param {module:zrender/Storage} storage Storage instance.
  1386. * @param {module:zrender/Painter} painter Painter instance.
  1387. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1388. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1389. */
  1390. var Handler = function(storage, painter, proxy, painterRoot) {
  1391. Eventful.call(this);
  1392. this.storage = storage;
  1393. this.painter = painter;
  1394. this.painterRoot = painterRoot;
  1395. proxy = proxy || new EmptyProxy();
  1396. /**
  1397. * Proxy of event. can be Dom, WebGLSurface, etc.
  1398. */
  1399. this.proxy = null;
  1400. /**
  1401. * {target, topTarget, x, y}
  1402. * @private
  1403. * @type {Object}
  1404. */
  1405. this._hovered = {};
  1406. /**
  1407. * @private
  1408. * @type {Date}
  1409. */
  1410. this._lastTouchMoment;
  1411. /**
  1412. * @private
  1413. * @type {number}
  1414. */
  1415. this._lastX;
  1416. /**
  1417. * @private
  1418. * @type {number}
  1419. */
  1420. this._lastY;
  1421. Draggable.call(this);
  1422. this.setHandlerProxy(proxy);
  1423. };
  1424. Handler.prototype = {
  1425. constructor: Handler,
  1426. setHandlerProxy: function (proxy) {
  1427. if (this.proxy) {
  1428. this.proxy.dispose();
  1429. }
  1430. if (proxy) {
  1431. each$1(handlerNames, function (name) {
  1432. proxy.on && proxy.on(name, this[name], this);
  1433. }, this);
  1434. // Attach handler
  1435. proxy.handler = this;
  1436. }
  1437. this.proxy = proxy;
  1438. },
  1439. mousemove: function (event) {
  1440. var x = event.zrX;
  1441. var y = event.zrY;
  1442. var lastHovered = this._hovered;
  1443. var lastHoveredTarget = lastHovered.target;
  1444. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1445. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1446. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1447. // See #6198.
  1448. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1449. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1450. lastHoveredTarget = lastHovered.target;
  1451. }
  1452. var hovered = this._hovered = this.findHover(x, y);
  1453. var hoveredTarget = hovered.target;
  1454. var proxy = this.proxy;
  1455. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1456. // Mouse out on previous hovered element
  1457. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1458. this.dispatchToElement(lastHovered, 'mouseout', event);
  1459. }
  1460. // Mouse moving on one element
  1461. this.dispatchToElement(hovered, 'mousemove', event);
  1462. // Mouse over on a new element
  1463. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1464. this.dispatchToElement(hovered, 'mouseover', event);
  1465. }
  1466. },
  1467. mouseout: function (event) {
  1468. this.dispatchToElement(this._hovered, 'mouseout', event);
  1469. // There might be some doms created by upper layer application
  1470. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1471. // dom created by echarts), where 'globalout' event should not
  1472. // be triggered when mouse enters these doms. (But 'mouseout'
  1473. // should be triggered at the original hovered element as usual).
  1474. var element = event.toElement || event.relatedTarget;
  1475. var innerDom;
  1476. do {
  1477. element = element && element.parentNode;
  1478. }
  1479. while (element && element.nodeType != 9 && !(
  1480. innerDom = element === this.painterRoot
  1481. ));
  1482. !innerDom && this.trigger('globalout', {event: event});
  1483. },
  1484. /**
  1485. * Resize
  1486. */
  1487. resize: function (event) {
  1488. this._hovered = {};
  1489. },
  1490. /**
  1491. * Dispatch event
  1492. * @param {string} eventName
  1493. * @param {event=} eventArgs
  1494. */
  1495. dispatch: function (eventName, eventArgs) {
  1496. var handler = this[eventName];
  1497. handler && handler.call(this, eventArgs);
  1498. },
  1499. /**
  1500. * Dispose
  1501. */
  1502. dispose: function () {
  1503. this.proxy.dispose();
  1504. this.storage =
  1505. this.proxy =
  1506. this.painter = null;
  1507. },
  1508. /**
  1509. * 设置默认的cursor style
  1510. * @param {string} [cursorStyle='default'] 例如 crosshair
  1511. */
  1512. setCursorStyle: function (cursorStyle) {
  1513. var proxy = this.proxy;
  1514. proxy.setCursor && proxy.setCursor(cursorStyle);
  1515. },
  1516. /**
  1517. * 事件分发代理
  1518. *
  1519. * @private
  1520. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1521. * @param {string} eventName 事件名称
  1522. * @param {Object} event 事件对象
  1523. */
  1524. dispatchToElement: function (targetInfo, eventName, event) {
  1525. targetInfo = targetInfo || {};
  1526. var el = targetInfo.target;
  1527. if (el && el.silent) {
  1528. return;
  1529. }
  1530. var eventHandler = 'on' + eventName;
  1531. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1532. while (el) {
  1533. el[eventHandler]
  1534. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1535. el.trigger(eventName, eventPacket);
  1536. el = el.parent;
  1537. if (eventPacket.cancelBubble) {
  1538. break;
  1539. }
  1540. }
  1541. if (!eventPacket.cancelBubble) {
  1542. // 冒泡到顶级 zrender 对象
  1543. this.trigger(eventName, eventPacket);
  1544. // 分发事件到用户自定义层
  1545. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1546. this.painter && this.painter.eachOtherLayer(function (layer) {
  1547. if (typeof(layer[eventHandler]) == 'function') {
  1548. layer[eventHandler].call(layer, eventPacket);
  1549. }
  1550. if (layer.trigger) {
  1551. layer.trigger(eventName, eventPacket);
  1552. }
  1553. });
  1554. }
  1555. },
  1556. /**
  1557. * @private
  1558. * @param {number} x
  1559. * @param {number} y
  1560. * @param {module:zrender/graphic/Displayable} exclude
  1561. * @return {model:zrender/Element}
  1562. * @method
  1563. */
  1564. findHover: function(x, y, exclude) {
  1565. var list = this.storage.getDisplayList();
  1566. var out = {x: x, y: y};
  1567. for (var i = list.length - 1; i >= 0 ; i--) {
  1568. var hoverCheckResult;
  1569. if (list[i] !== exclude
  1570. // getDisplayList may include ignored item in VML mode
  1571. && !list[i].ignore
  1572. && (hoverCheckResult = isHover(list[i], x, y))
  1573. ) {
  1574. !out.topTarget && (out.topTarget = list[i]);
  1575. if (hoverCheckResult !== SILENT) {
  1576. out.target = list[i];
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. return out;
  1582. }
  1583. };
  1584. // Common handlers
  1585. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1586. Handler.prototype[name] = function (event) {
  1587. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1588. var hovered = this.findHover(event.zrX, event.zrY);
  1589. var hoveredTarget = hovered.target;
  1590. if (name === 'mousedown') {
  1591. this._downEl = hoveredTarget;
  1592. this._downPoint = [event.zrX, event.zrY];
  1593. // In case click triggered before mouseup
  1594. this._upEl = hoveredTarget;
  1595. }
  1596. else if (name === 'mouseup') {
  1597. this._upEl = hoveredTarget;
  1598. }
  1599. else if (name === 'click') {
  1600. if (this._downEl !== this._upEl
  1601. // Original click event is triggered on the whole canvas element,
  1602. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1603. // which should be filtered, otherwise it will bring trouble to
  1604. // pan and zoom.
  1605. || !this._downPoint
  1606. // Arbitrary value
  1607. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1608. ) {
  1609. return;
  1610. }
  1611. this._downPoint = null;
  1612. }
  1613. this.dispatchToElement(hovered, name, event);
  1614. };
  1615. });
  1616. function isHover(displayable, x, y) {
  1617. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1618. var el = displayable;
  1619. var isSilent;
  1620. while (el) {
  1621. // If clipped by ancestor.
  1622. // FIXME: If clipPath has neither stroke nor fill,
  1623. // el.clipPath.contain(x, y) will always return false.
  1624. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1625. return false;
  1626. }
  1627. if (el.silent) {
  1628. isSilent = true;
  1629. }
  1630. el = el.parent;
  1631. }
  1632. return isSilent ? SILENT : true;
  1633. }
  1634. return false;
  1635. }
  1636. mixin(Handler, Eventful);
  1637. mixin(Handler, Draggable);
  1638. /**
  1639. * 3x2矩阵操作类
  1640. * @exports zrender/tool/matrix
  1641. */
  1642. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1643. ? Array
  1644. : Float32Array;
  1645. /**
  1646. * Create a identity matrix.
  1647. * @return {Float32Array|Array.<number>}
  1648. */
  1649. function create$1() {
  1650. var out = new ArrayCtor$1(6);
  1651. identity(out);
  1652. return out;
  1653. }
  1654. /**
  1655. * 设置矩阵为单位矩阵
  1656. * @param {Float32Array|Array.<number>} out
  1657. */
  1658. function identity(out) {
  1659. out[0] = 1;
  1660. out[1] = 0;
  1661. out[2] = 0;
  1662. out[3] = 1;
  1663. out[4] = 0;
  1664. out[5] = 0;
  1665. return out;
  1666. }
  1667. /**
  1668. * 复制矩阵
  1669. * @param {Float32Array|Array.<number>} out
  1670. * @param {Float32Array|Array.<number>} m
  1671. */
  1672. function copy$1(out, m) {
  1673. out[0] = m[0];
  1674. out[1] = m[1];
  1675. out[2] = m[2];
  1676. out[3] = m[3];
  1677. out[4] = m[4];
  1678. out[5] = m[5];
  1679. return out;
  1680. }
  1681. /**
  1682. * 矩阵相乘
  1683. * @param {Float32Array|Array.<number>} out
  1684. * @param {Float32Array|Array.<number>} m1
  1685. * @param {Float32Array|Array.<number>} m2
  1686. */
  1687. function mul$1(out, m1, m2) {
  1688. // Consider matrix.mul(m, m2, m);
  1689. // where out is the same as m2.
  1690. // So use temp variable to escape error.
  1691. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1692. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1693. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1694. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1695. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1696. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1697. out[0] = out0;
  1698. out[1] = out1;
  1699. out[2] = out2;
  1700. out[3] = out3;
  1701. out[4] = out4;
  1702. out[5] = out5;
  1703. return out;
  1704. }
  1705. /**
  1706. * 平移变换
  1707. * @param {Float32Array|Array.<number>} out
  1708. * @param {Float32Array|Array.<number>} a
  1709. * @param {Float32Array|Array.<number>} v
  1710. */
  1711. function translate(out, a, v) {
  1712. out[0] = a[0];
  1713. out[1] = a[1];
  1714. out[2] = a[2];
  1715. out[3] = a[3];
  1716. out[4] = a[4] + v[0];
  1717. out[5] = a[5] + v[1];
  1718. return out;
  1719. }
  1720. /**
  1721. * 旋转变换
  1722. * @param {Float32Array|Array.<number>} out
  1723. * @param {Float32Array|Array.<number>} a
  1724. * @param {number} rad
  1725. */
  1726. function rotate(out, a, rad) {
  1727. var aa = a[0];
  1728. var ac = a[2];
  1729. var atx = a[4];
  1730. var ab = a[1];
  1731. var ad = a[3];
  1732. var aty = a[5];
  1733. var st = Math.sin(rad);
  1734. var ct = Math.cos(rad);
  1735. out[0] = aa * ct + ab * st;
  1736. out[1] = -aa * st + ab * ct;
  1737. out[2] = ac * ct + ad * st;
  1738. out[3] = -ac * st + ct * ad;
  1739. out[4] = ct * atx + st * aty;
  1740. out[5] = ct * aty - st * atx;
  1741. return out;
  1742. }
  1743. /**
  1744. * 缩放变换
  1745. * @param {Float32Array|Array.<number>} out
  1746. * @param {Float32Array|Array.<number>} a
  1747. * @param {Float32Array|Array.<number>} v
  1748. */
  1749. function scale$1(out, a, v) {
  1750. var vx = v[0];
  1751. var vy = v[1];
  1752. out[0] = a[0] * vx;
  1753. out[1] = a[1] * vy;
  1754. out[2] = a[2] * vx;
  1755. out[3] = a[3] * vy;
  1756. out[4] = a[4] * vx;
  1757. out[5] = a[5] * vy;
  1758. return out;
  1759. }
  1760. /**
  1761. * 求逆矩阵
  1762. * @param {Float32Array|Array.<number>} out
  1763. * @param {Float32Array|Array.<number>} a
  1764. */
  1765. function invert(out, a) {
  1766. var aa = a[0];
  1767. var ac = a[2];
  1768. var atx = a[4];
  1769. var ab = a[1];
  1770. var ad = a[3];
  1771. var aty = a[5];
  1772. var det = aa * ad - ab * ac;
  1773. if (!det) {
  1774. return null;
  1775. }
  1776. det = 1.0 / det;
  1777. out[0] = ad * det;
  1778. out[1] = -ab * det;
  1779. out[2] = -ac * det;
  1780. out[3] = aa * det;
  1781. out[4] = (ac * aty - ad * atx) * det;
  1782. out[5] = (ab * atx - aa * aty) * det;
  1783. return out;
  1784. }
  1785. /**
  1786. * Clone a new matrix.
  1787. * @param {Float32Array|Array.<number>} a
  1788. */
  1789. function clone$2(a) {
  1790. var b = create$1();
  1791. copy$1(b, a);
  1792. return b;
  1793. }
  1794. var matrix = (Object.freeze || Object)({
  1795. create: create$1,
  1796. identity: identity,
  1797. copy: copy$1,
  1798. mul: mul$1,
  1799. translate: translate,
  1800. rotate: rotate,
  1801. scale: scale$1,
  1802. invert: invert,
  1803. clone: clone$2
  1804. });
  1805. /**
  1806. * 提供变换扩展
  1807. * @module zrender/mixin/Transformable
  1808. * @author pissang (https://www.github.com/pissang)
  1809. */
  1810. var mIdentity = identity;
  1811. var EPSILON = 5e-5;
  1812. function isNotAroundZero(val) {
  1813. return val > EPSILON || val < -EPSILON;
  1814. }
  1815. /**
  1816. * @alias module:zrender/mixin/Transformable
  1817. * @constructor
  1818. */
  1819. var Transformable = function (opts) {
  1820. opts = opts || {};
  1821. // If there are no given position, rotation, scale
  1822. if (!opts.position) {
  1823. /**
  1824. * 平移
  1825. * @type {Array.<number>}
  1826. * @default [0, 0]
  1827. */
  1828. this.position = [0, 0];
  1829. }
  1830. if (opts.rotation == null) {
  1831. /**
  1832. * 旋转
  1833. * @type {Array.<number>}
  1834. * @default 0
  1835. */
  1836. this.rotation = 0;
  1837. }
  1838. if (!opts.scale) {
  1839. /**
  1840. * 缩放
  1841. * @type {Array.<number>}
  1842. * @default [1, 1]
  1843. */
  1844. this.scale = [1, 1];
  1845. }
  1846. /**
  1847. * 旋转和缩放的原点
  1848. * @type {Array.<number>}
  1849. * @default null
  1850. */
  1851. this.origin = this.origin || null;
  1852. };
  1853. var transformableProto = Transformable.prototype;
  1854. transformableProto.transform = null;
  1855. /**
  1856. * 判断是否需要有坐标变换
  1857. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1858. */
  1859. transformableProto.needLocalTransform = function () {
  1860. return isNotAroundZero(this.rotation)
  1861. || isNotAroundZero(this.position[0])
  1862. || isNotAroundZero(this.position[1])
  1863. || isNotAroundZero(this.scale[0] - 1)
  1864. || isNotAroundZero(this.scale[1] - 1);
  1865. };
  1866. transformableProto.updateTransform = function () {
  1867. var parent = this.parent;
  1868. var parentHasTransform = parent && parent.transform;
  1869. var needLocalTransform = this.needLocalTransform();
  1870. var m = this.transform;
  1871. if (!(needLocalTransform || parentHasTransform)) {
  1872. m && mIdentity(m);
  1873. return;
  1874. }
  1875. m = m || create$1();
  1876. if (needLocalTransform) {
  1877. this.getLocalTransform(m);
  1878. }
  1879. else {
  1880. mIdentity(m);
  1881. }
  1882. // 应用父节点变换
  1883. if (parentHasTransform) {
  1884. if (needLocalTransform) {
  1885. mul$1(m, parent.transform, m);
  1886. }
  1887. else {
  1888. copy$1(m, parent.transform);
  1889. }
  1890. }
  1891. // 保存这个变换矩阵
  1892. this.transform = m;
  1893. this.invTransform = this.invTransform || create$1();
  1894. invert(this.invTransform, m);
  1895. };
  1896. transformableProto.getLocalTransform = function (m) {
  1897. return Transformable.getLocalTransform(this, m);
  1898. };
  1899. /**
  1900. * 将自己的transform应用到context上
  1901. * @param {CanvasRenderingContext2D} ctx
  1902. */
  1903. transformableProto.setTransform = function (ctx) {
  1904. var m = this.transform;
  1905. var dpr = ctx.dpr || 1;
  1906. if (m) {
  1907. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1908. }
  1909. else {
  1910. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1911. }
  1912. };
  1913. transformableProto.restoreTransform = function (ctx) {
  1914. var dpr = ctx.dpr || 1;
  1915. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1916. };
  1917. var tmpTransform = [];
  1918. /**
  1919. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1920. */
  1921. transformableProto.decomposeTransform = function () {
  1922. if (!this.transform) {
  1923. return;
  1924. }
  1925. var parent = this.parent;
  1926. var m = this.transform;
  1927. if (parent && parent.transform) {
  1928. // Get local transform and decompose them to position, scale, rotation
  1929. mul$1(tmpTransform, parent.invTransform, m);
  1930. m = tmpTransform;
  1931. }
  1932. var sx = m[0] * m[0] + m[1] * m[1];
  1933. var sy = m[2] * m[2] + m[3] * m[3];
  1934. var position = this.position;
  1935. var scale$$1 = this.scale;
  1936. if (isNotAroundZero(sx - 1)) {
  1937. sx = Math.sqrt(sx);
  1938. }
  1939. if (isNotAroundZero(sy - 1)) {
  1940. sy = Math.sqrt(sy);
  1941. }
  1942. if (m[0] < 0) {
  1943. sx = -sx;
  1944. }
  1945. if (m[3] < 0) {
  1946. sy = -sy;
  1947. }
  1948. position[0] = m[4];
  1949. position[1] = m[5];
  1950. scale$$1[0] = sx;
  1951. scale$$1[1] = sy;
  1952. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1953. };
  1954. /**
  1955. * Get global scale
  1956. * @return {Array.<number>}
  1957. */
  1958. transformableProto.getGlobalScale = function () {
  1959. var m = this.transform;
  1960. if (!m) {
  1961. return [1, 1];
  1962. }
  1963. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1964. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1965. if (m[0] < 0) {
  1966. sx = -sx;
  1967. }
  1968. if (m[3] < 0) {
  1969. sy = -sy;
  1970. }
  1971. return [sx, sy];
  1972. };
  1973. /**
  1974. * 变换坐标位置到 shape 的局部坐标空间
  1975. * @method
  1976. * @param {number} x
  1977. * @param {number} y
  1978. * @return {Array.<number>}
  1979. */
  1980. transformableProto.transformCoordToLocal = function (x, y) {
  1981. var v2 = [x, y];
  1982. var invTransform = this.invTransform;
  1983. if (invTransform) {
  1984. applyTransform(v2, v2, invTransform);
  1985. }
  1986. return v2;
  1987. };
  1988. /**
  1989. * 变换局部坐标位置到全局坐标空间
  1990. * @method
  1991. * @param {number} x
  1992. * @param {number} y
  1993. * @return {Array.<number>}
  1994. */
  1995. transformableProto.transformCoordToGlobal = function (x, y) {
  1996. var v2 = [x, y];
  1997. var transform = this.transform;
  1998. if (transform) {
  1999. applyTransform(v2, v2, transform);
  2000. }
  2001. return v2;
  2002. };
  2003. /**
  2004. * @static
  2005. * @param {Object} target
  2006. * @param {Array.<number>} target.origin
  2007. * @param {number} target.rotation
  2008. * @param {Array.<number>} target.position
  2009. * @param {Array.<number>} [m]
  2010. */
  2011. Transformable.getLocalTransform = function (target, m) {
  2012. m = m || [];
  2013. mIdentity(m);
  2014. var origin = target.origin;
  2015. var scale$$1 = target.scale || [1, 1];
  2016. var rotation = target.rotation || 0;
  2017. var position = target.position || [0, 0];
  2018. if (origin) {
  2019. // Translate to origin
  2020. m[4] -= origin[0];
  2021. m[5] -= origin[1];
  2022. }
  2023. scale$1(m, m, scale$$1);
  2024. if (rotation) {
  2025. rotate(m, m, rotation);
  2026. }
  2027. if (origin) {
  2028. // Translate back from origin
  2029. m[4] += origin[0];
  2030. m[5] += origin[1];
  2031. }
  2032. m[4] += position[0];
  2033. m[5] += position[1];
  2034. return m;
  2035. };
  2036. /**
  2037. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2038. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2039. * @exports zrender/animation/easing
  2040. */
  2041. var easing = {
  2042. /**
  2043. * @param {number} k
  2044. * @return {number}
  2045. */
  2046. linear: function (k) {
  2047. return k;
  2048. },
  2049. /**
  2050. * @param {number} k
  2051. * @return {number}
  2052. */
  2053. quadraticIn: function (k) {
  2054. return k * k;
  2055. },
  2056. /**
  2057. * @param {number} k
  2058. * @return {number}
  2059. */
  2060. quadraticOut: function (k) {
  2061. return k * (2 - k);
  2062. },
  2063. /**
  2064. * @param {number} k
  2065. * @return {number}
  2066. */
  2067. quadraticInOut: function (k) {
  2068. if ((k *= 2) < 1) {
  2069. return 0.5 * k * k;
  2070. }
  2071. return -0.5 * (--k * (k - 2) - 1);
  2072. },
  2073. // 三次方的缓动(t^3)
  2074. /**
  2075. * @param {number} k
  2076. * @return {number}
  2077. */
  2078. cubicIn: function (k) {
  2079. return k * k * k;
  2080. },
  2081. /**
  2082. * @param {number} k
  2083. * @return {number}
  2084. */
  2085. cubicOut: function (k) {
  2086. return --k * k * k + 1;
  2087. },
  2088. /**
  2089. * @param {number} k
  2090. * @return {number}
  2091. */
  2092. cubicInOut: function (k) {
  2093. if ((k *= 2) < 1) {
  2094. return 0.5 * k * k * k;
  2095. }
  2096. return 0.5 * ((k -= 2) * k * k + 2);
  2097. },
  2098. // 四次方的缓动(t^4)
  2099. /**
  2100. * @param {number} k
  2101. * @return {number}
  2102. */
  2103. quarticIn: function (k) {
  2104. return k * k * k * k;
  2105. },
  2106. /**
  2107. * @param {number} k
  2108. * @return {number}
  2109. */
  2110. quarticOut: function (k) {
  2111. return 1 - (--k * k * k * k);
  2112. },
  2113. /**
  2114. * @param {number} k
  2115. * @return {number}
  2116. */
  2117. quarticInOut: function (k) {
  2118. if ((k *= 2) < 1) {
  2119. return 0.5 * k * k * k * k;
  2120. }
  2121. return -0.5 * ((k -= 2) * k * k * k - 2);
  2122. },
  2123. // 五次方的缓动(t^5)
  2124. /**
  2125. * @param {number} k
  2126. * @return {number}
  2127. */
  2128. quinticIn: function (k) {
  2129. return k * k * k * k * k;
  2130. },
  2131. /**
  2132. * @param {number} k
  2133. * @return {number}
  2134. */
  2135. quinticOut: function (k) {
  2136. return --k * k * k * k * k + 1;
  2137. },
  2138. /**
  2139. * @param {number} k
  2140. * @return {number}
  2141. */
  2142. quinticInOut: function (k) {
  2143. if ((k *= 2) < 1) {
  2144. return 0.5 * k * k * k * k * k;
  2145. }
  2146. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2147. },
  2148. // 正弦曲线的缓动(sin(t))
  2149. /**
  2150. * @param {number} k
  2151. * @return {number}
  2152. */
  2153. sinusoidalIn: function (k) {
  2154. return 1 - Math.cos(k * Math.PI / 2);
  2155. },
  2156. /**
  2157. * @param {number} k
  2158. * @return {number}
  2159. */
  2160. sinusoidalOut: function (k) {
  2161. return Math.sin(k * Math.PI / 2);
  2162. },
  2163. /**
  2164. * @param {number} k
  2165. * @return {number}
  2166. */
  2167. sinusoidalInOut: function (k) {
  2168. return 0.5 * (1 - Math.cos(Math.PI * k));
  2169. },
  2170. // 指数曲线的缓动(2^t)
  2171. /**
  2172. * @param {number} k
  2173. * @return {number}
  2174. */
  2175. exponentialIn: function (k) {
  2176. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2177. },
  2178. /**
  2179. * @param {number} k
  2180. * @return {number}
  2181. */
  2182. exponentialOut: function (k) {
  2183. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2184. },
  2185. /**
  2186. * @param {number} k
  2187. * @return {number}
  2188. */
  2189. exponentialInOut: function (k) {
  2190. if (k === 0) {
  2191. return 0;
  2192. }
  2193. if (k === 1) {
  2194. return 1;
  2195. }
  2196. if ((k *= 2) < 1) {
  2197. return 0.5 * Math.pow(1024, k - 1);
  2198. }
  2199. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2200. },
  2201. // 圆形曲线的缓动(sqrt(1-t^2))
  2202. /**
  2203. * @param {number} k
  2204. * @return {number}
  2205. */
  2206. circularIn: function (k) {
  2207. return 1 - Math.sqrt(1 - k * k);
  2208. },
  2209. /**
  2210. * @param {number} k
  2211. * @return {number}
  2212. */
  2213. circularOut: function (k) {
  2214. return Math.sqrt(1 - (--k * k));
  2215. },
  2216. /**
  2217. * @param {number} k
  2218. * @return {number}
  2219. */
  2220. circularInOut: function (k) {
  2221. if ((k *= 2) < 1) {
  2222. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2223. }
  2224. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2225. },
  2226. // 创建类似于弹簧在停止前来回振荡的动画
  2227. /**
  2228. * @param {number} k
  2229. * @return {number}
  2230. */
  2231. elasticIn: function (k) {
  2232. var s;
  2233. var a = 0.1;
  2234. var p = 0.4;
  2235. if (k === 0) {
  2236. return 0;
  2237. }
  2238. if (k === 1) {
  2239. return 1;
  2240. }
  2241. if (!a || a < 1) {
  2242. a = 1; s = p / 4;
  2243. }
  2244. else {
  2245. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2246. }
  2247. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2248. Math.sin((k - s) * (2 * Math.PI) / p));
  2249. },
  2250. /**
  2251. * @param {number} k
  2252. * @return {number}
  2253. */
  2254. elasticOut: function (k) {
  2255. var s;
  2256. var a = 0.1;
  2257. var p = 0.4;
  2258. if (k === 0) {
  2259. return 0;
  2260. }
  2261. if (k === 1) {
  2262. return 1;
  2263. }
  2264. if (!a || a < 1) {
  2265. a = 1; s = p / 4;
  2266. }
  2267. else {
  2268. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2269. }
  2270. return (a * Math.pow(2, -10 * k) *
  2271. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2272. },
  2273. /**
  2274. * @param {number} k
  2275. * @return {number}
  2276. */
  2277. elasticInOut: function (k) {
  2278. var s;
  2279. var a = 0.1;
  2280. var p = 0.4;
  2281. if (k === 0) {
  2282. return 0;
  2283. }
  2284. if (k === 1) {
  2285. return 1;
  2286. }
  2287. if (!a || a < 1) {
  2288. a = 1; s = p / 4;
  2289. }
  2290. else {
  2291. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2292. }
  2293. if ((k *= 2) < 1) {
  2294. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2295. * Math.sin((k - s) * (2 * Math.PI) / p));
  2296. }
  2297. return a * Math.pow(2, -10 * (k -= 1))
  2298. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2299. },
  2300. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2301. /**
  2302. * @param {number} k
  2303. * @return {number}
  2304. */
  2305. backIn: function (k) {
  2306. var s = 1.70158;
  2307. return k * k * ((s + 1) * k - s);
  2308. },
  2309. /**
  2310. * @param {number} k
  2311. * @return {number}
  2312. */
  2313. backOut: function (k) {
  2314. var s = 1.70158;
  2315. return --k * k * ((s + 1) * k + s) + 1;
  2316. },
  2317. /**
  2318. * @param {number} k
  2319. * @return {number}
  2320. */
  2321. backInOut: function (k) {
  2322. var s = 1.70158 * 1.525;
  2323. if ((k *= 2) < 1) {
  2324. return 0.5 * (k * k * ((s + 1) * k - s));
  2325. }
  2326. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2327. },
  2328. // 创建弹跳效果
  2329. /**
  2330. * @param {number} k
  2331. * @return {number}
  2332. */
  2333. bounceIn: function (k) {
  2334. return 1 - easing.bounceOut(1 - k);
  2335. },
  2336. /**
  2337. * @param {number} k
  2338. * @return {number}
  2339. */
  2340. bounceOut: function (k) {
  2341. if (k < (1 / 2.75)) {
  2342. return 7.5625 * k * k;
  2343. }
  2344. else if (k < (2 / 2.75)) {
  2345. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2346. }
  2347. else if (k < (2.5 / 2.75)) {
  2348. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2349. }
  2350. else {
  2351. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2352. }
  2353. },
  2354. /**
  2355. * @param {number} k
  2356. * @return {number}
  2357. */
  2358. bounceInOut: function (k) {
  2359. if (k < 0.5) {
  2360. return easing.bounceIn(k * 2) * 0.5;
  2361. }
  2362. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2363. }
  2364. };
  2365. /**
  2366. * 动画主控制器
  2367. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2368. * @config life(1000) 动画时长
  2369. * @config delay(0) 动画延迟时间
  2370. * @config loop(true)
  2371. * @config gap(0) 循环的间隔时间
  2372. * @config onframe
  2373. * @config easing(optional)
  2374. * @config ondestroy(optional)
  2375. * @config onrestart(optional)
  2376. *
  2377. * TODO pause
  2378. */
  2379. function Clip(options) {
  2380. this._target = options.target;
  2381. // 生命周期
  2382. this._life = options.life || 1000;
  2383. // 延时
  2384. this._delay = options.delay || 0;
  2385. // 开始时间
  2386. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2387. this._initialized = false;
  2388. // 是否循环
  2389. this.loop = options.loop == null ? false : options.loop;
  2390. this.gap = options.gap || 0;
  2391. this.easing = options.easing || 'Linear';
  2392. this.onframe = options.onframe;
  2393. this.ondestroy = options.ondestroy;
  2394. this.onrestart = options.onrestart;
  2395. this._pausedTime = 0;
  2396. this._paused = false;
  2397. }
  2398. Clip.prototype = {
  2399. constructor: Clip,
  2400. step: function (globalTime, deltaTime) {
  2401. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2402. // PENDING
  2403. if (!this._initialized) {
  2404. this._startTime = globalTime + this._delay;
  2405. this._initialized = true;
  2406. }
  2407. if (this._paused) {
  2408. this._pausedTime += deltaTime;
  2409. return;
  2410. }
  2411. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2412. // 还没开始
  2413. if (percent < 0) {
  2414. return;
  2415. }
  2416. percent = Math.min(percent, 1);
  2417. var easing$$1 = this.easing;
  2418. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2419. var schedule = typeof easingFunc === 'function'
  2420. ? easingFunc(percent)
  2421. : percent;
  2422. this.fire('frame', schedule);
  2423. // 结束
  2424. if (percent == 1) {
  2425. if (this.loop) {
  2426. this.restart (globalTime);
  2427. // 重新开始周期
  2428. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2429. return 'restart';
  2430. }
  2431. // 动画完成将这个控制器标识为待删除
  2432. // 在Animation.update中进行批量删除
  2433. this._needsRemove = true;
  2434. return 'destroy';
  2435. }
  2436. return null;
  2437. },
  2438. restart: function (globalTime) {
  2439. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2440. this._startTime = globalTime - remainder + this.gap;
  2441. this._pausedTime = 0;
  2442. this._needsRemove = false;
  2443. },
  2444. fire: function (eventType, arg) {
  2445. eventType = 'on' + eventType;
  2446. if (this[eventType]) {
  2447. this[eventType](this._target, arg);
  2448. }
  2449. },
  2450. pause: function () {
  2451. this._paused = true;
  2452. },
  2453. resume: function () {
  2454. this._paused = false;
  2455. }
  2456. };
  2457. // Simple LRU cache use doubly linked list
  2458. // @module zrender/core/LRU
  2459. /**
  2460. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2461. * @constructor
  2462. */
  2463. var LinkedList = function () {
  2464. /**
  2465. * @type {module:zrender/core/LRU~Entry}
  2466. */
  2467. this.head = null;
  2468. /**
  2469. * @type {module:zrender/core/LRU~Entry}
  2470. */
  2471. this.tail = null;
  2472. this._len = 0;
  2473. };
  2474. var linkedListProto = LinkedList.prototype;
  2475. /**
  2476. * Insert a new value at the tail
  2477. * @param {} val
  2478. * @return {module:zrender/core/LRU~Entry}
  2479. */
  2480. linkedListProto.insert = function (val) {
  2481. var entry = new Entry(val);
  2482. this.insertEntry(entry);
  2483. return entry;
  2484. };
  2485. /**
  2486. * Insert an entry at the tail
  2487. * @param {module:zrender/core/LRU~Entry} entry
  2488. */
  2489. linkedListProto.insertEntry = function (entry) {
  2490. if (!this.head) {
  2491. this.head = this.tail = entry;
  2492. }
  2493. else {
  2494. this.tail.next = entry;
  2495. entry.prev = this.tail;
  2496. entry.next = null;
  2497. this.tail = entry;
  2498. }
  2499. this._len++;
  2500. };
  2501. /**
  2502. * Remove entry.
  2503. * @param {module:zrender/core/LRU~Entry} entry
  2504. */
  2505. linkedListProto.remove = function (entry) {
  2506. var prev = entry.prev;
  2507. var next = entry.next;
  2508. if (prev) {
  2509. prev.next = next;
  2510. }
  2511. else {
  2512. // Is head
  2513. this.head = next;
  2514. }
  2515. if (next) {
  2516. next.prev = prev;
  2517. }
  2518. else {
  2519. // Is tail
  2520. this.tail = prev;
  2521. }
  2522. entry.next = entry.prev = null;
  2523. this._len--;
  2524. };
  2525. /**
  2526. * @return {number}
  2527. */
  2528. linkedListProto.len = function () {
  2529. return this._len;
  2530. };
  2531. /**
  2532. * Clear list
  2533. */
  2534. linkedListProto.clear = function () {
  2535. this.head = this.tail = null;
  2536. this._len = 0;
  2537. };
  2538. /**
  2539. * @constructor
  2540. * @param {} val
  2541. */
  2542. var Entry = function (val) {
  2543. /**
  2544. * @type {}
  2545. */
  2546. this.value = val;
  2547. /**
  2548. * @type {module:zrender/core/LRU~Entry}
  2549. */
  2550. this.next;
  2551. /**
  2552. * @type {module:zrender/core/LRU~Entry}
  2553. */
  2554. this.prev;
  2555. };
  2556. /**
  2557. * LRU Cache
  2558. * @constructor
  2559. * @alias module:zrender/core/LRU
  2560. */
  2561. var LRU = function (maxSize) {
  2562. this._list = new LinkedList();
  2563. this._map = {};
  2564. this._maxSize = maxSize || 10;
  2565. this._lastRemovedEntry = null;
  2566. };
  2567. var LRUProto = LRU.prototype;
  2568. /**
  2569. * @param {string} key
  2570. * @param {} value
  2571. * @return {} Removed value
  2572. */
  2573. LRUProto.put = function (key, value) {
  2574. var list = this._list;
  2575. var map = this._map;
  2576. var removed = null;
  2577. if (map[key] == null) {
  2578. var len = list.len();
  2579. // Reuse last removed entry
  2580. var entry = this._lastRemovedEntry;
  2581. if (len >= this._maxSize && len > 0) {
  2582. // Remove the least recently used
  2583. var leastUsedEntry = list.head;
  2584. list.remove(leastUsedEntry);
  2585. delete map[leastUsedEntry.key];
  2586. removed = leastUsedEntry.value;
  2587. this._lastRemovedEntry = leastUsedEntry;
  2588. }
  2589. if (entry) {
  2590. entry.value = value;
  2591. }
  2592. else {
  2593. entry = new Entry(value);
  2594. }
  2595. entry.key = key;
  2596. list.insertEntry(entry);
  2597. map[key] = entry;
  2598. }
  2599. return removed;
  2600. };
  2601. /**
  2602. * @param {string} key
  2603. * @return {}
  2604. */
  2605. LRUProto.get = function (key) {
  2606. var entry = this._map[key];
  2607. var list = this._list;
  2608. if (entry != null) {
  2609. // Put the latest used entry in the tail
  2610. if (entry !== list.tail) {
  2611. list.remove(entry);
  2612. list.insertEntry(entry);
  2613. }
  2614. return entry.value;
  2615. }
  2616. };
  2617. /**
  2618. * Clear the cache
  2619. */
  2620. LRUProto.clear = function () {
  2621. this._list.clear();
  2622. this._map = {};
  2623. };
  2624. var kCSSColorTable = {
  2625. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2626. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2627. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2628. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2629. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2630. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2631. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2632. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2633. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2634. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2635. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2636. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2637. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2638. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2639. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2640. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2641. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2642. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2643. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2644. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2645. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2646. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2647. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2648. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2649. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2650. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2651. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2652. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2653. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2654. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2655. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2656. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2657. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2658. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2659. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2660. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2661. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2662. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2663. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2664. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2665. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2666. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2667. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2668. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2669. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2670. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2671. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2672. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2673. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2674. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2675. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2676. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2677. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2678. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2679. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2680. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2681. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2682. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2683. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2684. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2685. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2686. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2687. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2688. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2689. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2690. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2691. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2692. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2693. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2694. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2695. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2696. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2697. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2698. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2699. };
  2700. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2701. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2702. return i < 0 ? 0 : i > 255 ? 255 : i;
  2703. }
  2704. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2705. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2706. return i < 0 ? 0 : i > 360 ? 360 : i;
  2707. }
  2708. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2709. return f < 0 ? 0 : f > 1 ? 1 : f;
  2710. }
  2711. function parseCssInt(str) { // int or percentage.
  2712. if (str.length && str.charAt(str.length - 1) === '%') {
  2713. return clampCssByte(parseFloat(str) / 100 * 255);
  2714. }
  2715. return clampCssByte(parseInt(str, 10));
  2716. }
  2717. function parseCssFloat(str) { // float or percentage.
  2718. if (str.length && str.charAt(str.length - 1) === '%') {
  2719. return clampCssFloat(parseFloat(str) / 100);
  2720. }
  2721. return clampCssFloat(parseFloat(str));
  2722. }
  2723. function cssHueToRgb(m1, m2, h) {
  2724. if (h < 0) {
  2725. h += 1;
  2726. }
  2727. else if (h > 1) {
  2728. h -= 1;
  2729. }
  2730. if (h * 6 < 1) {
  2731. return m1 + (m2 - m1) * h * 6;
  2732. }
  2733. if (h * 2 < 1) {
  2734. return m2;
  2735. }
  2736. if (h * 3 < 2) {
  2737. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2738. }
  2739. return m1;
  2740. }
  2741. function lerpNumber(a, b, p) {
  2742. return a + (b - a) * p;
  2743. }
  2744. function setRgba(out, r, g, b, a) {
  2745. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2746. return out;
  2747. }
  2748. function copyRgba(out, a) {
  2749. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2750. return out;
  2751. }
  2752. var colorCache = new LRU(20);
  2753. var lastRemovedArr = null;
  2754. function putToCache(colorStr, rgbaArr) {
  2755. // Reuse removed array
  2756. if (lastRemovedArr) {
  2757. copyRgba(lastRemovedArr, rgbaArr);
  2758. }
  2759. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2760. }
  2761. /**
  2762. * @param {string} colorStr
  2763. * @param {Array.<number>} out
  2764. * @return {Array.<number>}
  2765. * @memberOf module:zrender/util/color
  2766. */
  2767. function parse(colorStr, rgbaArr) {
  2768. if (!colorStr) {
  2769. return;
  2770. }
  2771. rgbaArr = rgbaArr || [];
  2772. var cached = colorCache.get(colorStr);
  2773. if (cached) {
  2774. return copyRgba(rgbaArr, cached);
  2775. }
  2776. // colorStr may be not string
  2777. colorStr = colorStr + '';
  2778. // Remove all whitespace, not compliant, but should just be more accepting.
  2779. var str = colorStr.replace(/ /g, '').toLowerCase();
  2780. // Color keywords (and transparent) lookup.
  2781. if (str in kCSSColorTable) {
  2782. copyRgba(rgbaArr, kCSSColorTable[str]);
  2783. putToCache(colorStr, rgbaArr);
  2784. return rgbaArr;
  2785. }
  2786. // #abc and #abc123 syntax.
  2787. if (str.charAt(0) === '#') {
  2788. if (str.length === 4) {
  2789. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2790. if (!(iv >= 0 && iv <= 0xfff)) {
  2791. setRgba(rgbaArr, 0, 0, 0, 1);
  2792. return; // Covers NaN.
  2793. }
  2794. setRgba(rgbaArr,
  2795. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2796. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2797. (iv & 0xf) | ((iv & 0xf) << 4),
  2798. 1
  2799. );
  2800. putToCache(colorStr, rgbaArr);
  2801. return rgbaArr;
  2802. }
  2803. else if (str.length === 7) {
  2804. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2805. if (!(iv >= 0 && iv <= 0xffffff)) {
  2806. setRgba(rgbaArr, 0, 0, 0, 1);
  2807. return; // Covers NaN.
  2808. }
  2809. setRgba(rgbaArr,
  2810. (iv & 0xff0000) >> 16,
  2811. (iv & 0xff00) >> 8,
  2812. iv & 0xff,
  2813. 1
  2814. );
  2815. putToCache(colorStr, rgbaArr);
  2816. return rgbaArr;
  2817. }
  2818. return;
  2819. }
  2820. var op = str.indexOf('('), ep = str.indexOf(')');
  2821. if (op !== -1 && ep + 1 === str.length) {
  2822. var fname = str.substr(0, op);
  2823. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2824. var alpha = 1; // To allow case fallthrough.
  2825. switch (fname) {
  2826. case 'rgba':
  2827. if (params.length !== 4) {
  2828. setRgba(rgbaArr, 0, 0, 0, 1);
  2829. return;
  2830. }
  2831. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2832. // Fall through.
  2833. case 'rgb':
  2834. if (params.length !== 3) {
  2835. setRgba(rgbaArr, 0, 0, 0, 1);
  2836. return;
  2837. }
  2838. setRgba(rgbaArr,
  2839. parseCssInt(params[0]),
  2840. parseCssInt(params[1]),
  2841. parseCssInt(params[2]),
  2842. alpha
  2843. );
  2844. putToCache(colorStr, rgbaArr);
  2845. return rgbaArr;
  2846. case 'hsla':
  2847. if (params.length !== 4) {
  2848. setRgba(rgbaArr, 0, 0, 0, 1);
  2849. return;
  2850. }
  2851. params[3] = parseCssFloat(params[3]);
  2852. hsla2rgba(params, rgbaArr);
  2853. putToCache(colorStr, rgbaArr);
  2854. return rgbaArr;
  2855. case 'hsl':
  2856. if (params.length !== 3) {
  2857. setRgba(rgbaArr, 0, 0, 0, 1);
  2858. return;
  2859. }
  2860. hsla2rgba(params, rgbaArr);
  2861. putToCache(colorStr, rgbaArr);
  2862. return rgbaArr;
  2863. default:
  2864. return;
  2865. }
  2866. }
  2867. setRgba(rgbaArr, 0, 0, 0, 1);
  2868. return;
  2869. }
  2870. /**
  2871. * @param {Array.<number>} hsla
  2872. * @param {Array.<number>} rgba
  2873. * @return {Array.<number>} rgba
  2874. */
  2875. function hsla2rgba(hsla, rgba) {
  2876. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2877. // NOTE(deanm): According to the CSS spec s/l should only be
  2878. // percentages, but we don't bother and let float or percentage.
  2879. var s = parseCssFloat(hsla[1]);
  2880. var l = parseCssFloat(hsla[2]);
  2881. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2882. var m1 = l * 2 - m2;
  2883. rgba = rgba || [];
  2884. setRgba(rgba,
  2885. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2886. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2887. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2888. 1
  2889. );
  2890. if (hsla.length === 4) {
  2891. rgba[3] = hsla[3];
  2892. }
  2893. return rgba;
  2894. }
  2895. /**
  2896. * @param {Array.<number>} rgba
  2897. * @return {Array.<number>} hsla
  2898. */
  2899. function rgba2hsla(rgba) {
  2900. if (!rgba) {
  2901. return;
  2902. }
  2903. // RGB from 0 to 255
  2904. var R = rgba[0] / 255;
  2905. var G = rgba[1] / 255;
  2906. var B = rgba[2] / 255;
  2907. var vMin = Math.min(R, G, B); // Min. value of RGB
  2908. var vMax = Math.max(R, G, B); // Max. value of RGB
  2909. var delta = vMax - vMin; // Delta RGB value
  2910. var L = (vMax + vMin) / 2;
  2911. var H;
  2912. var S;
  2913. // HSL results from 0 to 1
  2914. if (delta === 0) {
  2915. H = 0;
  2916. S = 0;
  2917. }
  2918. else {
  2919. if (L < 0.5) {
  2920. S = delta / (vMax + vMin);
  2921. }
  2922. else {
  2923. S = delta / (2 - vMax - vMin);
  2924. }
  2925. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2926. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2927. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2928. if (R === vMax) {
  2929. H = deltaB - deltaG;
  2930. }
  2931. else if (G === vMax) {
  2932. H = (1 / 3) + deltaR - deltaB;
  2933. }
  2934. else if (B === vMax) {
  2935. H = (2 / 3) + deltaG - deltaR;
  2936. }
  2937. if (H < 0) {
  2938. H += 1;
  2939. }
  2940. if (H > 1) {
  2941. H -= 1;
  2942. }
  2943. }
  2944. var hsla = [H * 360, S, L];
  2945. if (rgba[3] != null) {
  2946. hsla.push(rgba[3]);
  2947. }
  2948. return hsla;
  2949. }
  2950. /**
  2951. * @param {string} color
  2952. * @param {number} level
  2953. * @return {string}
  2954. * @memberOf module:zrender/util/color
  2955. */
  2956. function lift(color, level) {
  2957. var colorArr = parse(color);
  2958. if (colorArr) {
  2959. for (var i = 0; i < 3; i++) {
  2960. if (level < 0) {
  2961. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2962. }
  2963. else {
  2964. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2965. }
  2966. }
  2967. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2968. }
  2969. }
  2970. /**
  2971. * @param {string} color
  2972. * @return {string}
  2973. * @memberOf module:zrender/util/color
  2974. */
  2975. function toHex(color) {
  2976. var colorArr = parse(color);
  2977. if (colorArr) {
  2978. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2979. }
  2980. }
  2981. /**
  2982. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  2983. * @param {number} normalizedValue A float between 0 and 1.
  2984. * @param {Array.<Array.<number>>} colors List of rgba color array
  2985. * @param {Array.<number>} [out] Mapped gba color array
  2986. * @return {Array.<number>} will be null/undefined if input illegal.
  2987. */
  2988. function fastLerp(normalizedValue, colors, out) {
  2989. if (!(colors && colors.length)
  2990. || !(normalizedValue >= 0 && normalizedValue <= 1)
  2991. ) {
  2992. return;
  2993. }
  2994. out = out || [];
  2995. var value = normalizedValue * (colors.length - 1);
  2996. var leftIndex = Math.floor(value);
  2997. var rightIndex = Math.ceil(value);
  2998. var leftColor = colors[leftIndex];
  2999. var rightColor = colors[rightIndex];
  3000. var dv = value - leftIndex;
  3001. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3002. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3003. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3004. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3005. return out;
  3006. }
  3007. /**
  3008. * @deprecated
  3009. */
  3010. var fastMapToColor = fastLerp;
  3011. /**
  3012. * @param {number} normalizedValue A float between 0 and 1.
  3013. * @param {Array.<string>} colors Color list.
  3014. * @param {boolean=} fullOutput Default false.
  3015. * @return {(string|Object)} Result color. If fullOutput,
  3016. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3017. * @memberOf module:zrender/util/color
  3018. */
  3019. function lerp$1(normalizedValue, colors, fullOutput) {
  3020. if (!(colors && colors.length)
  3021. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3022. ) {
  3023. return;
  3024. }
  3025. var value = normalizedValue * (colors.length - 1);
  3026. var leftIndex = Math.floor(value);
  3027. var rightIndex = Math.ceil(value);
  3028. var leftColor = parse(colors[leftIndex]);
  3029. var rightColor = parse(colors[rightIndex]);
  3030. var dv = value - leftIndex;
  3031. var color = stringify(
  3032. [
  3033. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3034. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3035. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3036. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3037. ],
  3038. 'rgba'
  3039. );
  3040. return fullOutput
  3041. ? {
  3042. color: color,
  3043. leftIndex: leftIndex,
  3044. rightIndex: rightIndex,
  3045. value: value
  3046. }
  3047. : color;
  3048. }
  3049. /**
  3050. * @deprecated
  3051. */
  3052. var mapToColor = lerp$1;
  3053. /**
  3054. * @param {string} color
  3055. * @param {number=} h 0 ~ 360, ignore when null.
  3056. * @param {number=} s 0 ~ 1, ignore when null.
  3057. * @param {number=} l 0 ~ 1, ignore when null.
  3058. * @return {string} Color string in rgba format.
  3059. * @memberOf module:zrender/util/color
  3060. */
  3061. function modifyHSL(color, h, s, l) {
  3062. color = parse(color);
  3063. if (color) {
  3064. color = rgba2hsla(color);
  3065. h != null && (color[0] = clampCssAngle(h));
  3066. s != null && (color[1] = parseCssFloat(s));
  3067. l != null && (color[2] = parseCssFloat(l));
  3068. return stringify(hsla2rgba(color), 'rgba');
  3069. }
  3070. }
  3071. /**
  3072. * @param {string} color
  3073. * @param {number=} alpha 0 ~ 1
  3074. * @return {string} Color string in rgba format.
  3075. * @memberOf module:zrender/util/color
  3076. */
  3077. function modifyAlpha(color, alpha) {
  3078. color = parse(color);
  3079. if (color && alpha != null) {
  3080. color[3] = clampCssFloat(alpha);
  3081. return stringify(color, 'rgba');
  3082. }
  3083. }
  3084. /**
  3085. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3086. * @param {string} type 'rgba', 'hsva', ...
  3087. * @return {string} Result color. (If input illegal, return undefined).
  3088. */
  3089. function stringify(arrColor, type) {
  3090. if (!arrColor || !arrColor.length) {
  3091. return;
  3092. }
  3093. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3094. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3095. colorStr += ',' + arrColor[3];
  3096. }
  3097. return type + '(' + colorStr + ')';
  3098. }
  3099. var color = (Object.freeze || Object)({
  3100. parse: parse,
  3101. lift: lift,
  3102. toHex: toHex,
  3103. fastLerp: fastLerp,
  3104. fastMapToColor: fastMapToColor,
  3105. lerp: lerp$1,
  3106. mapToColor: mapToColor,
  3107. modifyHSL: modifyHSL,
  3108. modifyAlpha: modifyAlpha,
  3109. stringify: stringify
  3110. });
  3111. /**
  3112. * @module echarts/animation/Animator
  3113. */
  3114. var arraySlice = Array.prototype.slice;
  3115. function defaultGetter(target, key) {
  3116. return target[key];
  3117. }
  3118. function defaultSetter(target, key, value) {
  3119. target[key] = value;
  3120. }
  3121. /**
  3122. * @param {number} p0
  3123. * @param {number} p1
  3124. * @param {number} percent
  3125. * @return {number}
  3126. */
  3127. function interpolateNumber(p0, p1, percent) {
  3128. return (p1 - p0) * percent + p0;
  3129. }
  3130. /**
  3131. * @param {string} p0
  3132. * @param {string} p1
  3133. * @param {number} percent
  3134. * @return {string}
  3135. */
  3136. function interpolateString(p0, p1, percent) {
  3137. return percent > 0.5 ? p1 : p0;
  3138. }
  3139. /**
  3140. * @param {Array} p0
  3141. * @param {Array} p1
  3142. * @param {number} percent
  3143. * @param {Array} out
  3144. * @param {number} arrDim
  3145. */
  3146. function interpolateArray(p0, p1, percent, out, arrDim) {
  3147. var len = p0.length;
  3148. if (arrDim == 1) {
  3149. for (var i = 0; i < len; i++) {
  3150. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3151. }
  3152. }
  3153. else {
  3154. var len2 = len && p0[0].length;
  3155. for (var i = 0; i < len; i++) {
  3156. for (var j = 0; j < len2; j++) {
  3157. out[i][j] = interpolateNumber(
  3158. p0[i][j], p1[i][j], percent
  3159. );
  3160. }
  3161. }
  3162. }
  3163. }
  3164. // arr0 is source array, arr1 is target array.
  3165. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3166. function fillArr(arr0, arr1, arrDim) {
  3167. var arr0Len = arr0.length;
  3168. var arr1Len = arr1.length;
  3169. if (arr0Len !== arr1Len) {
  3170. // FIXME Not work for TypedArray
  3171. var isPreviousLarger = arr0Len > arr1Len;
  3172. if (isPreviousLarger) {
  3173. // Cut the previous
  3174. arr0.length = arr1Len;
  3175. }
  3176. else {
  3177. // Fill the previous
  3178. for (var i = arr0Len; i < arr1Len; i++) {
  3179. arr0.push(
  3180. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3181. );
  3182. }
  3183. }
  3184. }
  3185. // Handling NaN value
  3186. var len2 = arr0[0] && arr0[0].length;
  3187. for (var i = 0; i < arr0.length; i++) {
  3188. if (arrDim === 1) {
  3189. if (isNaN(arr0[i])) {
  3190. arr0[i] = arr1[i];
  3191. }
  3192. }
  3193. else {
  3194. for (var j = 0; j < len2; j++) {
  3195. if (isNaN(arr0[i][j])) {
  3196. arr0[i][j] = arr1[i][j];
  3197. }
  3198. }
  3199. }
  3200. }
  3201. }
  3202. /**
  3203. * @param {Array} arr0
  3204. * @param {Array} arr1
  3205. * @param {number} arrDim
  3206. * @return {boolean}
  3207. */
  3208. function isArraySame(arr0, arr1, arrDim) {
  3209. if (arr0 === arr1) {
  3210. return true;
  3211. }
  3212. var len = arr0.length;
  3213. if (len !== arr1.length) {
  3214. return false;
  3215. }
  3216. if (arrDim === 1) {
  3217. for (var i = 0; i < len; i++) {
  3218. if (arr0[i] !== arr1[i]) {
  3219. return false;
  3220. }
  3221. }
  3222. }
  3223. else {
  3224. var len2 = arr0[0].length;
  3225. for (var i = 0; i < len; i++) {
  3226. for (var j = 0; j < len2; j++) {
  3227. if (arr0[i][j] !== arr1[i][j]) {
  3228. return false;
  3229. }
  3230. }
  3231. }
  3232. }
  3233. return true;
  3234. }
  3235. /**
  3236. * Catmull Rom interpolate array
  3237. * @param {Array} p0
  3238. * @param {Array} p1
  3239. * @param {Array} p2
  3240. * @param {Array} p3
  3241. * @param {number} t
  3242. * @param {number} t2
  3243. * @param {number} t3
  3244. * @param {Array} out
  3245. * @param {number} arrDim
  3246. */
  3247. function catmullRomInterpolateArray(
  3248. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3249. ) {
  3250. var len = p0.length;
  3251. if (arrDim == 1) {
  3252. for (var i = 0; i < len; i++) {
  3253. out[i] = catmullRomInterpolate(
  3254. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3255. );
  3256. }
  3257. }
  3258. else {
  3259. var len2 = p0[0].length;
  3260. for (var i = 0; i < len; i++) {
  3261. for (var j = 0; j < len2; j++) {
  3262. out[i][j] = catmullRomInterpolate(
  3263. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3264. t, t2, t3
  3265. );
  3266. }
  3267. }
  3268. }
  3269. }
  3270. /**
  3271. * Catmull Rom interpolate number
  3272. * @param {number} p0
  3273. * @param {number} p1
  3274. * @param {number} p2
  3275. * @param {number} p3
  3276. * @param {number} t
  3277. * @param {number} t2
  3278. * @param {number} t3
  3279. * @return {number}
  3280. */
  3281. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3282. var v0 = (p2 - p0) * 0.5;
  3283. var v1 = (p3 - p1) * 0.5;
  3284. return (2 * (p1 - p2) + v0 + v1) * t3
  3285. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3286. + v0 * t + p1;
  3287. }
  3288. function cloneValue(value) {
  3289. if (isArrayLike(value)) {
  3290. var len = value.length;
  3291. if (isArrayLike(value[0])) {
  3292. var ret = [];
  3293. for (var i = 0; i < len; i++) {
  3294. ret.push(arraySlice.call(value[i]));
  3295. }
  3296. return ret;
  3297. }
  3298. return arraySlice.call(value);
  3299. }
  3300. return value;
  3301. }
  3302. function rgba2String(rgba) {
  3303. rgba[0] = Math.floor(rgba[0]);
  3304. rgba[1] = Math.floor(rgba[1]);
  3305. rgba[2] = Math.floor(rgba[2]);
  3306. return 'rgba(' + rgba.join(',') + ')';
  3307. }
  3308. function getArrayDim(keyframes) {
  3309. var lastValue = keyframes[keyframes.length - 1].value;
  3310. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3311. }
  3312. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3313. var getter = animator._getter;
  3314. var setter = animator._setter;
  3315. var useSpline = easing === 'spline';
  3316. var trackLen = keyframes.length;
  3317. if (!trackLen) {
  3318. return;
  3319. }
  3320. // Guess data type
  3321. var firstVal = keyframes[0].value;
  3322. var isValueArray = isArrayLike(firstVal);
  3323. var isValueColor = false;
  3324. var isValueString = false;
  3325. // For vertices morphing
  3326. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3327. var trackMaxTime;
  3328. // Sort keyframe as ascending
  3329. keyframes.sort(function(a, b) {
  3330. return a.time - b.time;
  3331. });
  3332. trackMaxTime = keyframes[trackLen - 1].time;
  3333. // Percents of each keyframe
  3334. var kfPercents = [];
  3335. // Value of each keyframe
  3336. var kfValues = [];
  3337. var prevValue = keyframes[0].value;
  3338. var isAllValueEqual = true;
  3339. for (var i = 0; i < trackLen; i++) {
  3340. kfPercents.push(keyframes[i].time / trackMaxTime);
  3341. // Assume value is a color when it is a string
  3342. var value = keyframes[i].value;
  3343. // Check if value is equal, deep check if value is array
  3344. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3345. || (!isValueArray && value === prevValue))) {
  3346. isAllValueEqual = false;
  3347. }
  3348. prevValue = value;
  3349. // Try converting a string to a color array
  3350. if (typeof value == 'string') {
  3351. var colorArray = parse(value);
  3352. if (colorArray) {
  3353. value = colorArray;
  3354. isValueColor = true;
  3355. }
  3356. else {
  3357. isValueString = true;
  3358. }
  3359. }
  3360. kfValues.push(value);
  3361. }
  3362. if (!forceAnimate && isAllValueEqual) {
  3363. return;
  3364. }
  3365. var lastValue = kfValues[trackLen - 1];
  3366. // Polyfill array and NaN value
  3367. for (var i = 0; i < trackLen - 1; i++) {
  3368. if (isValueArray) {
  3369. fillArr(kfValues[i], lastValue, arrDim);
  3370. }
  3371. else {
  3372. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3373. kfValues[i] = lastValue;
  3374. }
  3375. }
  3376. }
  3377. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3378. // Cache the key of last frame to speed up when
  3379. // animation playback is sequency
  3380. var lastFrame = 0;
  3381. var lastFramePercent = 0;
  3382. var start;
  3383. var w;
  3384. var p0;
  3385. var p1;
  3386. var p2;
  3387. var p3;
  3388. if (isValueColor) {
  3389. var rgba = [0, 0, 0, 0];
  3390. }
  3391. var onframe = function (target, percent) {
  3392. // Find the range keyframes
  3393. // kf1-----kf2---------current--------kf3
  3394. // find kf2 and kf3 and do interpolation
  3395. var frame;
  3396. // In the easing function like elasticOut, percent may less than 0
  3397. if (percent < 0) {
  3398. frame = 0;
  3399. }
  3400. else if (percent < lastFramePercent) {
  3401. // Start from next key
  3402. // PENDING start from lastFrame ?
  3403. start = Math.min(lastFrame + 1, trackLen - 1);
  3404. for (frame = start; frame >= 0; frame--) {
  3405. if (kfPercents[frame] <= percent) {
  3406. break;
  3407. }
  3408. }
  3409. // PENDING really need to do this ?
  3410. frame = Math.min(frame, trackLen - 2);
  3411. }
  3412. else {
  3413. for (frame = lastFrame; frame < trackLen; frame++) {
  3414. if (kfPercents[frame] > percent) {
  3415. break;
  3416. }
  3417. }
  3418. frame = Math.min(frame - 1, trackLen - 2);
  3419. }
  3420. lastFrame = frame;
  3421. lastFramePercent = percent;
  3422. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3423. if (range === 0) {
  3424. return;
  3425. }
  3426. else {
  3427. w = (percent - kfPercents[frame]) / range;
  3428. }
  3429. if (useSpline) {
  3430. p1 = kfValues[frame];
  3431. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3432. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3433. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3434. if (isValueArray) {
  3435. catmullRomInterpolateArray(
  3436. p0, p1, p2, p3, w, w * w, w * w * w,
  3437. getter(target, propName),
  3438. arrDim
  3439. );
  3440. }
  3441. else {
  3442. var value;
  3443. if (isValueColor) {
  3444. value = catmullRomInterpolateArray(
  3445. p0, p1, p2, p3, w, w * w, w * w * w,
  3446. rgba, 1
  3447. );
  3448. value = rgba2String(rgba);
  3449. }
  3450. else if (isValueString) {
  3451. // String is step(0.5)
  3452. return interpolateString(p1, p2, w);
  3453. }
  3454. else {
  3455. value = catmullRomInterpolate(
  3456. p0, p1, p2, p3, w, w * w, w * w * w
  3457. );
  3458. }
  3459. setter(
  3460. target,
  3461. propName,
  3462. value
  3463. );
  3464. }
  3465. }
  3466. else {
  3467. if (isValueArray) {
  3468. interpolateArray(
  3469. kfValues[frame], kfValues[frame + 1], w,
  3470. getter(target, propName),
  3471. arrDim
  3472. );
  3473. }
  3474. else {
  3475. var value;
  3476. if (isValueColor) {
  3477. interpolateArray(
  3478. kfValues[frame], kfValues[frame + 1], w,
  3479. rgba, 1
  3480. );
  3481. value = rgba2String(rgba);
  3482. }
  3483. else if (isValueString) {
  3484. // String is step(0.5)
  3485. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3486. }
  3487. else {
  3488. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3489. }
  3490. setter(
  3491. target,
  3492. propName,
  3493. value
  3494. );
  3495. }
  3496. }
  3497. };
  3498. var clip = new Clip({
  3499. target: animator._target,
  3500. life: trackMaxTime,
  3501. loop: animator._loop,
  3502. delay: animator._delay,
  3503. onframe: onframe,
  3504. ondestroy: oneTrackDone
  3505. });
  3506. if (easing && easing !== 'spline') {
  3507. clip.easing = easing;
  3508. }
  3509. return clip;
  3510. }
  3511. /**
  3512. * @alias module:zrender/animation/Animator
  3513. * @constructor
  3514. * @param {Object} target
  3515. * @param {boolean} loop
  3516. * @param {Function} getter
  3517. * @param {Function} setter
  3518. */
  3519. var Animator = function(target, loop, getter, setter) {
  3520. this._tracks = {};
  3521. this._target = target;
  3522. this._loop = loop || false;
  3523. this._getter = getter || defaultGetter;
  3524. this._setter = setter || defaultSetter;
  3525. this._clipCount = 0;
  3526. this._delay = 0;
  3527. this._doneList = [];
  3528. this._onframeList = [];
  3529. this._clipList = [];
  3530. };
  3531. Animator.prototype = {
  3532. /**
  3533. * 设置动画关键帧
  3534. * @param {number} time 关键帧时间,单位是ms
  3535. * @param {Object} props 关键帧的属性值,key-value表示
  3536. * @return {module:zrender/animation/Animator}
  3537. */
  3538. when: function(time /* ms */, props) {
  3539. var tracks = this._tracks;
  3540. for (var propName in props) {
  3541. if (!props.hasOwnProperty(propName)) {
  3542. continue;
  3543. }
  3544. if (!tracks[propName]) {
  3545. tracks[propName] = [];
  3546. // Invalid value
  3547. var value = this._getter(this._target, propName);
  3548. if (value == null) {
  3549. // zrLog('Invalid property ' + propName);
  3550. continue;
  3551. }
  3552. // If time is 0
  3553. // Then props is given initialize value
  3554. // Else
  3555. // Initialize value from current prop value
  3556. if (time !== 0) {
  3557. tracks[propName].push({
  3558. time: 0,
  3559. value: cloneValue(value)
  3560. });
  3561. }
  3562. }
  3563. tracks[propName].push({
  3564. time: time,
  3565. value: props[propName]
  3566. });
  3567. }
  3568. return this;
  3569. },
  3570. /**
  3571. * 添加动画每一帧的回调函数
  3572. * @param {Function} callback
  3573. * @return {module:zrender/animation/Animator}
  3574. */
  3575. during: function (callback) {
  3576. this._onframeList.push(callback);
  3577. return this;
  3578. },
  3579. pause: function () {
  3580. for (var i = 0; i < this._clipList.length; i++) {
  3581. this._clipList[i].pause();
  3582. }
  3583. this._paused = true;
  3584. },
  3585. resume: function () {
  3586. for (var i = 0; i < this._clipList.length; i++) {
  3587. this._clipList[i].resume();
  3588. }
  3589. this._paused = false;
  3590. },
  3591. isPaused: function () {
  3592. return !!this._paused;
  3593. },
  3594. _doneCallback: function () {
  3595. // Clear all tracks
  3596. this._tracks = {};
  3597. // Clear all clips
  3598. this._clipList.length = 0;
  3599. var doneList = this._doneList;
  3600. var len = doneList.length;
  3601. for (var i = 0; i < len; i++) {
  3602. doneList[i].call(this);
  3603. }
  3604. },
  3605. /**
  3606. * 开始执行动画
  3607. * @param {string|Function} [easing]
  3608. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3609. * @param {boolean} forceAnimate
  3610. * @return {module:zrender/animation/Animator}
  3611. */
  3612. start: function (easing, forceAnimate) {
  3613. var self = this;
  3614. var clipCount = 0;
  3615. var oneTrackDone = function() {
  3616. clipCount--;
  3617. if (!clipCount) {
  3618. self._doneCallback();
  3619. }
  3620. };
  3621. var lastClip;
  3622. for (var propName in this._tracks) {
  3623. if (!this._tracks.hasOwnProperty(propName)) {
  3624. continue;
  3625. }
  3626. var clip = createTrackClip(
  3627. this, easing, oneTrackDone,
  3628. this._tracks[propName], propName, forceAnimate
  3629. );
  3630. if (clip) {
  3631. this._clipList.push(clip);
  3632. clipCount++;
  3633. // If start after added to animation
  3634. if (this.animation) {
  3635. this.animation.addClip(clip);
  3636. }
  3637. lastClip = clip;
  3638. }
  3639. }
  3640. // Add during callback on the last clip
  3641. if (lastClip) {
  3642. var oldOnFrame = lastClip.onframe;
  3643. lastClip.onframe = function (target, percent) {
  3644. oldOnFrame(target, percent);
  3645. for (var i = 0; i < self._onframeList.length; i++) {
  3646. self._onframeList[i](target, percent);
  3647. }
  3648. };
  3649. }
  3650. // This optimization will help the case that in the upper application
  3651. // the view may be refreshed frequently, where animation will be
  3652. // called repeatly but nothing changed.
  3653. if (!clipCount) {
  3654. this._doneCallback();
  3655. }
  3656. return this;
  3657. },
  3658. /**
  3659. * 停止动画
  3660. * @param {boolean} forwardToLast If move to last frame before stop
  3661. */
  3662. stop: function (forwardToLast) {
  3663. var clipList = this._clipList;
  3664. var animation = this.animation;
  3665. for (var i = 0; i < clipList.length; i++) {
  3666. var clip = clipList[i];
  3667. if (forwardToLast) {
  3668. // Move to last frame before stop
  3669. clip.onframe(this._target, 1);
  3670. }
  3671. animation && animation.removeClip(clip);
  3672. }
  3673. clipList.length = 0;
  3674. },
  3675. /**
  3676. * 设置动画延迟开始的时间
  3677. * @param {number} time 单位ms
  3678. * @return {module:zrender/animation/Animator}
  3679. */
  3680. delay: function (time) {
  3681. this._delay = time;
  3682. return this;
  3683. },
  3684. /**
  3685. * 添加动画结束的回调
  3686. * @param {Function} cb
  3687. * @return {module:zrender/animation/Animator}
  3688. */
  3689. done: function(cb) {
  3690. if (cb) {
  3691. this._doneList.push(cb);
  3692. }
  3693. return this;
  3694. },
  3695. /**
  3696. * @return {Array.<module:zrender/animation/Clip>}
  3697. */
  3698. getClips: function () {
  3699. return this._clipList;
  3700. }
  3701. };
  3702. var dpr = 1;
  3703. // If in browser environment
  3704. if (typeof window !== 'undefined') {
  3705. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3706. }
  3707. /**
  3708. * config默认配置项
  3709. * @exports zrender/config
  3710. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3711. */
  3712. /**
  3713. * debug日志选项:catchBrushException为true下有效
  3714. * 0 : 不生成debug数据,发布用
  3715. * 1 : 异常抛出,调试用
  3716. * 2 : 控制台输出,调试用
  3717. */
  3718. var debugMode = 0;
  3719. // retina 屏幕优化
  3720. var devicePixelRatio = dpr;
  3721. var log = function () {
  3722. };
  3723. if (debugMode === 1) {
  3724. log = function () {
  3725. for (var k in arguments) {
  3726. throw new Error(arguments[k]);
  3727. }
  3728. };
  3729. }
  3730. else if (debugMode > 1) {
  3731. log = function () {
  3732. for (var k in arguments) {
  3733. console.log(arguments[k]);
  3734. }
  3735. };
  3736. }
  3737. var zrLog = log;
  3738. /**
  3739. * @alias modue:zrender/mixin/Animatable
  3740. * @constructor
  3741. */
  3742. var Animatable = function () {
  3743. /**
  3744. * @type {Array.<module:zrender/animation/Animator>}
  3745. * @readOnly
  3746. */
  3747. this.animators = [];
  3748. };
  3749. Animatable.prototype = {
  3750. constructor: Animatable,
  3751. /**
  3752. * 动画
  3753. *
  3754. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3755. * @param {boolean} [loop] Whether to loop animation.
  3756. * @return {module:zrender/animation/Animator}
  3757. * @example:
  3758. * el.animate('style', false)
  3759. * .when(1000, {x: 10} )
  3760. * .done(function(){ // Animation done })
  3761. * .start()
  3762. */
  3763. animate: function (path, loop) {
  3764. var target;
  3765. var animatingShape = false;
  3766. var el = this;
  3767. var zr = this.__zr;
  3768. if (path) {
  3769. var pathSplitted = path.split('.');
  3770. var prop = el;
  3771. // If animating shape
  3772. animatingShape = pathSplitted[0] === 'shape';
  3773. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3774. if (!prop) {
  3775. continue;
  3776. }
  3777. prop = prop[pathSplitted[i]];
  3778. }
  3779. if (prop) {
  3780. target = prop;
  3781. }
  3782. }
  3783. else {
  3784. target = el;
  3785. }
  3786. if (!target) {
  3787. zrLog(
  3788. 'Property "'
  3789. + path
  3790. + '" is not existed in element '
  3791. + el.id
  3792. );
  3793. return;
  3794. }
  3795. var animators = el.animators;
  3796. var animator = new Animator(target, loop);
  3797. animator.during(function (target) {
  3798. el.dirty(animatingShape);
  3799. })
  3800. .done(function () {
  3801. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3802. animators.splice(indexOf(animators, animator), 1);
  3803. });
  3804. animators.push(animator);
  3805. // If animate after added to the zrender
  3806. if (zr) {
  3807. zr.animation.addAnimator(animator);
  3808. }
  3809. return animator;
  3810. },
  3811. /**
  3812. * 停止动画
  3813. * @param {boolean} forwardToLast If move to last frame before stop
  3814. */
  3815. stopAnimation: function (forwardToLast) {
  3816. var animators = this.animators;
  3817. var len = animators.length;
  3818. for (var i = 0; i < len; i++) {
  3819. animators[i].stop(forwardToLast);
  3820. }
  3821. animators.length = 0;
  3822. return this;
  3823. },
  3824. /**
  3825. * Caution: this method will stop previous animation.
  3826. * So do not use this method to one element twice before
  3827. * animation starts, unless you know what you are doing.
  3828. * @param {Object} target
  3829. * @param {number} [time=500] Time in ms
  3830. * @param {string} [easing='linear']
  3831. * @param {number} [delay=0]
  3832. * @param {Function} [callback]
  3833. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3834. * immediently when target values are the same as current values.
  3835. *
  3836. * @example
  3837. * // Animate position
  3838. * el.animateTo({
  3839. * position: [10, 10]
  3840. * }, function () { // done })
  3841. *
  3842. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3843. * el.animateTo({
  3844. * shape: {
  3845. * width: 500
  3846. * },
  3847. * style: {
  3848. * fill: 'red'
  3849. * }
  3850. * position: [10, 10]
  3851. * }, 100, 100, 'cubicOut', function () { // done })
  3852. */
  3853. // TODO Return animation key
  3854. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3855. // animateTo(target, time, easing, callback);
  3856. if (isString(delay)) {
  3857. callback = easing;
  3858. easing = delay;
  3859. delay = 0;
  3860. }
  3861. // animateTo(target, time, delay, callback);
  3862. else if (isFunction$1(easing)) {
  3863. callback = easing;
  3864. easing = 'linear';
  3865. delay = 0;
  3866. }
  3867. // animateTo(target, time, callback);
  3868. else if (isFunction$1(delay)) {
  3869. callback = delay;
  3870. delay = 0;
  3871. }
  3872. // animateTo(target, callback)
  3873. else if (isFunction$1(time)) {
  3874. callback = time;
  3875. time = 500;
  3876. }
  3877. // animateTo(target)
  3878. else if (!time) {
  3879. time = 500;
  3880. }
  3881. // Stop all previous animations
  3882. this.stopAnimation();
  3883. this._animateToShallow('', this, target, time, delay);
  3884. // Animators may be removed immediately after start
  3885. // if there is nothing to animate
  3886. var animators = this.animators.slice();
  3887. var count = animators.length;
  3888. function done() {
  3889. count--;
  3890. if (!count) {
  3891. callback && callback();
  3892. }
  3893. }
  3894. // No animators. This should be checked before animators[i].start(),
  3895. // because 'done' may be executed immediately if no need to animate.
  3896. if (!count) {
  3897. callback && callback();
  3898. }
  3899. // Start after all animators created
  3900. // Incase any animator is done immediately when all animation properties are not changed
  3901. for (var i = 0; i < animators.length; i++) {
  3902. animators[i]
  3903. .done(done)
  3904. .start(easing, forceAnimate);
  3905. }
  3906. },
  3907. /**
  3908. * @private
  3909. * @param {string} path=''
  3910. * @param {Object} source=this
  3911. * @param {Object} target
  3912. * @param {number} [time=500]
  3913. * @param {number} [delay=0]
  3914. *
  3915. * @example
  3916. * // Animate position
  3917. * el._animateToShallow({
  3918. * position: [10, 10]
  3919. * })
  3920. *
  3921. * // Animate shape, style and position in 100ms, delayed 100ms
  3922. * el._animateToShallow({
  3923. * shape: {
  3924. * width: 500
  3925. * },
  3926. * style: {
  3927. * fill: 'red'
  3928. * }
  3929. * position: [10, 10]
  3930. * }, 100, 100)
  3931. */
  3932. _animateToShallow: function (path, source, target, time, delay) {
  3933. var objShallow = {};
  3934. var propertyCount = 0;
  3935. for (var name in target) {
  3936. if (!target.hasOwnProperty(name)) {
  3937. continue;
  3938. }
  3939. if (source[name] != null) {
  3940. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3941. this._animateToShallow(
  3942. path ? path + '.' + name : name,
  3943. source[name],
  3944. target[name],
  3945. time,
  3946. delay
  3947. );
  3948. }
  3949. else {
  3950. objShallow[name] = target[name];
  3951. propertyCount++;
  3952. }
  3953. }
  3954. else if (target[name] != null) {
  3955. // Attr directly if not has property
  3956. // FIXME, if some property not needed for element ?
  3957. if (!path) {
  3958. this.attr(name, target[name]);
  3959. }
  3960. else { // Shape or style
  3961. var props = {};
  3962. props[path] = {};
  3963. props[path][name] = target[name];
  3964. this.attr(props);
  3965. }
  3966. }
  3967. }
  3968. if (propertyCount > 0) {
  3969. this.animate(path, false)
  3970. .when(time == null ? 500 : time, objShallow)
  3971. .delay(delay || 0);
  3972. }
  3973. return this;
  3974. }
  3975. };
  3976. /**
  3977. * @alias module:zrender/Element
  3978. * @constructor
  3979. * @extends {module:zrender/mixin/Animatable}
  3980. * @extends {module:zrender/mixin/Transformable}
  3981. * @extends {module:zrender/mixin/Eventful}
  3982. */
  3983. var Element = function (opts) { // jshint ignore:line
  3984. Transformable.call(this, opts);
  3985. Eventful.call(this, opts);
  3986. Animatable.call(this, opts);
  3987. /**
  3988. * 画布元素ID
  3989. * @type {string}
  3990. */
  3991. this.id = opts.id || guid();
  3992. };
  3993. Element.prototype = {
  3994. /**
  3995. * 元素类型
  3996. * Element type
  3997. * @type {string}
  3998. */
  3999. type: 'element',
  4000. /**
  4001. * 元素名字
  4002. * Element name
  4003. * @type {string}
  4004. */
  4005. name: '',
  4006. /**
  4007. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4008. * ZRender instance will be assigned when element is associated with zrender
  4009. * @name module:/zrender/Element#__zr
  4010. * @type {module:zrender/ZRender}
  4011. */
  4012. __zr: null,
  4013. /**
  4014. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4015. * If ignore drawing and events of the element object
  4016. * @name module:/zrender/Element#ignore
  4017. * @type {boolean}
  4018. * @default false
  4019. */
  4020. ignore: false,
  4021. /**
  4022. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4023. * 该路径会继承被裁减对象的变换
  4024. * @type {module:zrender/graphic/Path}
  4025. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4026. * @readOnly
  4027. */
  4028. clipPath: null,
  4029. /**
  4030. * 是否是 Group
  4031. * @type {boolean}
  4032. */
  4033. isGroup: false,
  4034. /**
  4035. * Drift element
  4036. * @param {number} dx dx on the global space
  4037. * @param {number} dy dy on the global space
  4038. */
  4039. drift: function (dx, dy) {
  4040. switch (this.draggable) {
  4041. case 'horizontal':
  4042. dy = 0;
  4043. break;
  4044. case 'vertical':
  4045. dx = 0;
  4046. break;
  4047. }
  4048. var m = this.transform;
  4049. if (!m) {
  4050. m = this.transform = [1, 0, 0, 1, 0, 0];
  4051. }
  4052. m[4] += dx;
  4053. m[5] += dy;
  4054. this.decomposeTransform();
  4055. this.dirty(false);
  4056. },
  4057. /**
  4058. * Hook before update
  4059. */
  4060. beforeUpdate: function () {},
  4061. /**
  4062. * Hook after update
  4063. */
  4064. afterUpdate: function () {},
  4065. /**
  4066. * Update each frame
  4067. */
  4068. update: function () {
  4069. this.updateTransform();
  4070. },
  4071. /**
  4072. * @param {Function} cb
  4073. * @param {} context
  4074. */
  4075. traverse: function (cb, context) {},
  4076. /**
  4077. * @protected
  4078. */
  4079. attrKV: function (key, value) {
  4080. if (key === 'position' || key === 'scale' || key === 'origin') {
  4081. // Copy the array
  4082. if (value) {
  4083. var target = this[key];
  4084. if (!target) {
  4085. target = this[key] = [];
  4086. }
  4087. target[0] = value[0];
  4088. target[1] = value[1];
  4089. }
  4090. }
  4091. else {
  4092. this[key] = value;
  4093. }
  4094. },
  4095. /**
  4096. * Hide the element
  4097. */
  4098. hide: function () {
  4099. this.ignore = true;
  4100. this.__zr && this.__zr.refresh();
  4101. },
  4102. /**
  4103. * Show the element
  4104. */
  4105. show: function () {
  4106. this.ignore = false;
  4107. this.__zr && this.__zr.refresh();
  4108. },
  4109. /**
  4110. * @param {string|Object} key
  4111. * @param {*} value
  4112. */
  4113. attr: function (key, value) {
  4114. if (typeof key === 'string') {
  4115. this.attrKV(key, value);
  4116. }
  4117. else if (isObject$1(key)) {
  4118. for (var name in key) {
  4119. if (key.hasOwnProperty(name)) {
  4120. this.attrKV(name, key[name]);
  4121. }
  4122. }
  4123. }
  4124. this.dirty(false);
  4125. return this;
  4126. },
  4127. /**
  4128. * @param {module:zrender/graphic/Path} clipPath
  4129. */
  4130. setClipPath: function (clipPath) {
  4131. var zr = this.__zr;
  4132. if (zr) {
  4133. clipPath.addSelfToZr(zr);
  4134. }
  4135. // Remove previous clip path
  4136. if (this.clipPath && this.clipPath !== clipPath) {
  4137. this.removeClipPath();
  4138. }
  4139. this.clipPath = clipPath;
  4140. clipPath.__zr = zr;
  4141. clipPath.__clipTarget = this;
  4142. this.dirty(false);
  4143. },
  4144. /**
  4145. */
  4146. removeClipPath: function () {
  4147. var clipPath = this.clipPath;
  4148. if (clipPath) {
  4149. if (clipPath.__zr) {
  4150. clipPath.removeSelfFromZr(clipPath.__zr);
  4151. }
  4152. clipPath.__zr = null;
  4153. clipPath.__clipTarget = null;
  4154. this.clipPath = null;
  4155. this.dirty(false);
  4156. }
  4157. },
  4158. /**
  4159. * Add self from zrender instance.
  4160. * Not recursively because it will be invoked when element added to storage.
  4161. * @param {module:zrender/ZRender} zr
  4162. */
  4163. addSelfToZr: function (zr) {
  4164. this.__zr = zr;
  4165. // 添加动画
  4166. var animators = this.animators;
  4167. if (animators) {
  4168. for (var i = 0; i < animators.length; i++) {
  4169. zr.animation.addAnimator(animators[i]);
  4170. }
  4171. }
  4172. if (this.clipPath) {
  4173. this.clipPath.addSelfToZr(zr);
  4174. }
  4175. },
  4176. /**
  4177. * Remove self from zrender instance.
  4178. * Not recursively because it will be invoked when element added to storage.
  4179. * @param {module:zrender/ZRender} zr
  4180. */
  4181. removeSelfFromZr: function (zr) {
  4182. this.__zr = null;
  4183. // 移除动画
  4184. var animators = this.animators;
  4185. if (animators) {
  4186. for (var i = 0; i < animators.length; i++) {
  4187. zr.animation.removeAnimator(animators[i]);
  4188. }
  4189. }
  4190. if (this.clipPath) {
  4191. this.clipPath.removeSelfFromZr(zr);
  4192. }
  4193. }
  4194. };
  4195. mixin(Element, Animatable);
  4196. mixin(Element, Transformable);
  4197. mixin(Element, Eventful);
  4198. /**
  4199. * @module echarts/core/BoundingRect
  4200. */
  4201. var v2ApplyTransform = applyTransform;
  4202. var mathMin = Math.min;
  4203. var mathMax = Math.max;
  4204. /**
  4205. * @alias module:echarts/core/BoundingRect
  4206. */
  4207. function BoundingRect(x, y, width, height) {
  4208. if (width < 0) {
  4209. x = x + width;
  4210. width = -width;
  4211. }
  4212. if (height < 0) {
  4213. y = y + height;
  4214. height = -height;
  4215. }
  4216. /**
  4217. * @type {number}
  4218. */
  4219. this.x = x;
  4220. /**
  4221. * @type {number}
  4222. */
  4223. this.y = y;
  4224. /**
  4225. * @type {number}
  4226. */
  4227. this.width = width;
  4228. /**
  4229. * @type {number}
  4230. */
  4231. this.height = height;
  4232. }
  4233. BoundingRect.prototype = {
  4234. constructor: BoundingRect,
  4235. /**
  4236. * @param {module:echarts/core/BoundingRect} other
  4237. */
  4238. union: function (other) {
  4239. var x = mathMin(other.x, this.x);
  4240. var y = mathMin(other.y, this.y);
  4241. this.width = mathMax(
  4242. other.x + other.width,
  4243. this.x + this.width
  4244. ) - x;
  4245. this.height = mathMax(
  4246. other.y + other.height,
  4247. this.y + this.height
  4248. ) - y;
  4249. this.x = x;
  4250. this.y = y;
  4251. },
  4252. /**
  4253. * @param {Array.<number>} m
  4254. * @methods
  4255. */
  4256. applyTransform: (function () {
  4257. var lt = [];
  4258. var rb = [];
  4259. var lb = [];
  4260. var rt = [];
  4261. return function (m) {
  4262. // In case usage like this
  4263. // el.getBoundingRect().applyTransform(el.transform)
  4264. // And element has no transform
  4265. if (!m) {
  4266. return;
  4267. }
  4268. lt[0] = lb[0] = this.x;
  4269. lt[1] = rt[1] = this.y;
  4270. rb[0] = rt[0] = this.x + this.width;
  4271. rb[1] = lb[1] = this.y + this.height;
  4272. v2ApplyTransform(lt, lt, m);
  4273. v2ApplyTransform(rb, rb, m);
  4274. v2ApplyTransform(lb, lb, m);
  4275. v2ApplyTransform(rt, rt, m);
  4276. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4277. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4278. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4279. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4280. this.width = maxX - this.x;
  4281. this.height = maxY - this.y;
  4282. };
  4283. })(),
  4284. /**
  4285. * Calculate matrix of transforming from self to target rect
  4286. * @param {module:zrender/core/BoundingRect} b
  4287. * @return {Array.<number>}
  4288. */
  4289. calculateTransform: function (b) {
  4290. var a = this;
  4291. var sx = b.width / a.width;
  4292. var sy = b.height / a.height;
  4293. var m = create$1();
  4294. // 矩阵右乘
  4295. translate(m, m, [-a.x, -a.y]);
  4296. scale$1(m, m, [sx, sy]);
  4297. translate(m, m, [b.x, b.y]);
  4298. return m;
  4299. },
  4300. /**
  4301. * @param {(module:echarts/core/BoundingRect|Object)} b
  4302. * @return {boolean}
  4303. */
  4304. intersect: function (b) {
  4305. if (!b) {
  4306. return false;
  4307. }
  4308. if (!(b instanceof BoundingRect)) {
  4309. // Normalize negative width/height.
  4310. b = BoundingRect.create(b);
  4311. }
  4312. var a = this;
  4313. var ax0 = a.x;
  4314. var ax1 = a.x + a.width;
  4315. var ay0 = a.y;
  4316. var ay1 = a.y + a.height;
  4317. var bx0 = b.x;
  4318. var bx1 = b.x + b.width;
  4319. var by0 = b.y;
  4320. var by1 = b.y + b.height;
  4321. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4322. },
  4323. contain: function (x, y) {
  4324. var rect = this;
  4325. return x >= rect.x
  4326. && x <= (rect.x + rect.width)
  4327. && y >= rect.y
  4328. && y <= (rect.y + rect.height);
  4329. },
  4330. /**
  4331. * @return {module:echarts/core/BoundingRect}
  4332. */
  4333. clone: function () {
  4334. return new BoundingRect(this.x, this.y, this.width, this.height);
  4335. },
  4336. /**
  4337. * Copy from another rect
  4338. */
  4339. copy: function (other) {
  4340. this.x = other.x;
  4341. this.y = other.y;
  4342. this.width = other.width;
  4343. this.height = other.height;
  4344. },
  4345. plain: function () {
  4346. return {
  4347. x: this.x,
  4348. y: this.y,
  4349. width: this.width,
  4350. height: this.height
  4351. };
  4352. }
  4353. };
  4354. /**
  4355. * @param {Object|module:zrender/core/BoundingRect} rect
  4356. * @param {number} rect.x
  4357. * @param {number} rect.y
  4358. * @param {number} rect.width
  4359. * @param {number} rect.height
  4360. * @return {module:zrender/core/BoundingRect}
  4361. */
  4362. BoundingRect.create = function (rect) {
  4363. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4364. };
  4365. /**
  4366. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4367. * @module zrender/graphic/Group
  4368. * @example
  4369. * var Group = require('zrender/container/Group');
  4370. * var Circle = require('zrender/graphic/shape/Circle');
  4371. * var g = new Group();
  4372. * g.position[0] = 100;
  4373. * g.position[1] = 100;
  4374. * g.add(new Circle({
  4375. * style: {
  4376. * x: 100,
  4377. * y: 100,
  4378. * r: 20,
  4379. * }
  4380. * }));
  4381. * zr.add(g);
  4382. */
  4383. /**
  4384. * @alias module:zrender/graphic/Group
  4385. * @constructor
  4386. * @extends module:zrender/mixin/Transformable
  4387. * @extends module:zrender/mixin/Eventful
  4388. */
  4389. var Group = function (opts) {
  4390. opts = opts || {};
  4391. Element.call(this, opts);
  4392. for (var key in opts) {
  4393. if (opts.hasOwnProperty(key)) {
  4394. this[key] = opts[key];
  4395. }
  4396. }
  4397. this._children = [];
  4398. this.__storage = null;
  4399. this.__dirty = true;
  4400. };
  4401. Group.prototype = {
  4402. constructor: Group,
  4403. isGroup: true,
  4404. /**
  4405. * @type {string}
  4406. */
  4407. type: 'group',
  4408. /**
  4409. * 所有子孙元素是否响应鼠标事件
  4410. * @name module:/zrender/container/Group#silent
  4411. * @type {boolean}
  4412. * @default false
  4413. */
  4414. silent: false,
  4415. /**
  4416. * @return {Array.<module:zrender/Element>}
  4417. */
  4418. children: function () {
  4419. return this._children.slice();
  4420. },
  4421. /**
  4422. * 获取指定 index 的儿子节点
  4423. * @param {number} idx
  4424. * @return {module:zrender/Element}
  4425. */
  4426. childAt: function (idx) {
  4427. return this._children[idx];
  4428. },
  4429. /**
  4430. * 获取指定名字的儿子节点
  4431. * @param {string} name
  4432. * @return {module:zrender/Element}
  4433. */
  4434. childOfName: function (name) {
  4435. var children = this._children;
  4436. for (var i = 0; i < children.length; i++) {
  4437. if (children[i].name === name) {
  4438. return children[i];
  4439. }
  4440. }
  4441. },
  4442. /**
  4443. * @return {number}
  4444. */
  4445. childCount: function () {
  4446. return this._children.length;
  4447. },
  4448. /**
  4449. * 添加子节点到最后
  4450. * @param {module:zrender/Element} child
  4451. */
  4452. add: function (child) {
  4453. if (child && child !== this && child.parent !== this) {
  4454. this._children.push(child);
  4455. this._doAdd(child);
  4456. }
  4457. return this;
  4458. },
  4459. /**
  4460. * 添加子节点在 nextSibling 之前
  4461. * @param {module:zrender/Element} child
  4462. * @param {module:zrender/Element} nextSibling
  4463. */
  4464. addBefore: function (child, nextSibling) {
  4465. if (child && child !== this && child.parent !== this
  4466. && nextSibling && nextSibling.parent === this) {
  4467. var children = this._children;
  4468. var idx = children.indexOf(nextSibling);
  4469. if (idx >= 0) {
  4470. children.splice(idx, 0, child);
  4471. this._doAdd(child);
  4472. }
  4473. }
  4474. return this;
  4475. },
  4476. _doAdd: function (child) {
  4477. if (child.parent) {
  4478. child.parent.remove(child);
  4479. }
  4480. child.parent = this;
  4481. var storage = this.__storage;
  4482. var zr = this.__zr;
  4483. if (storage && storage !== child.__storage) {
  4484. storage.addToStorage(child);
  4485. if (child instanceof Group) {
  4486. child.addChildrenToStorage(storage);
  4487. }
  4488. }
  4489. zr && zr.refresh();
  4490. },
  4491. /**
  4492. * 移除子节点
  4493. * @param {module:zrender/Element} child
  4494. */
  4495. remove: function (child) {
  4496. var zr = this.__zr;
  4497. var storage = this.__storage;
  4498. var children = this._children;
  4499. var idx = indexOf(children, child);
  4500. if (idx < 0) {
  4501. return this;
  4502. }
  4503. children.splice(idx, 1);
  4504. child.parent = null;
  4505. if (storage) {
  4506. storage.delFromStorage(child);
  4507. if (child instanceof Group) {
  4508. child.delChildrenFromStorage(storage);
  4509. }
  4510. }
  4511. zr && zr.refresh();
  4512. return this;
  4513. },
  4514. /**
  4515. * 移除所有子节点
  4516. */
  4517. removeAll: function () {
  4518. var children = this._children;
  4519. var storage = this.__storage;
  4520. var child;
  4521. var i;
  4522. for (i = 0; i < children.length; i++) {
  4523. child = children[i];
  4524. if (storage) {
  4525. storage.delFromStorage(child);
  4526. if (child instanceof Group) {
  4527. child.delChildrenFromStorage(storage);
  4528. }
  4529. }
  4530. child.parent = null;
  4531. }
  4532. children.length = 0;
  4533. return this;
  4534. },
  4535. /**
  4536. * 遍历所有子节点
  4537. * @param {Function} cb
  4538. * @param {} context
  4539. */
  4540. eachChild: function (cb, context) {
  4541. var children = this._children;
  4542. for (var i = 0; i < children.length; i++) {
  4543. var child = children[i];
  4544. cb.call(context, child, i);
  4545. }
  4546. return this;
  4547. },
  4548. /**
  4549. * 深度优先遍历所有子孙节点
  4550. * @param {Function} cb
  4551. * @param {} context
  4552. */
  4553. traverse: function (cb, context) {
  4554. for (var i = 0; i < this._children.length; i++) {
  4555. var child = this._children[i];
  4556. cb.call(context, child);
  4557. if (child.type === 'group') {
  4558. child.traverse(cb, context);
  4559. }
  4560. }
  4561. return this;
  4562. },
  4563. addChildrenToStorage: function (storage) {
  4564. for (var i = 0; i < this._children.length; i++) {
  4565. var child = this._children[i];
  4566. storage.addToStorage(child);
  4567. if (child instanceof Group) {
  4568. child.addChildrenToStorage(storage);
  4569. }
  4570. }
  4571. },
  4572. delChildrenFromStorage: function (storage) {
  4573. for (var i = 0; i < this._children.length; i++) {
  4574. var child = this._children[i];
  4575. storage.delFromStorage(child);
  4576. if (child instanceof Group) {
  4577. child.delChildrenFromStorage(storage);
  4578. }
  4579. }
  4580. },
  4581. dirty: function () {
  4582. this.__dirty = true;
  4583. this.__zr && this.__zr.refresh();
  4584. return this;
  4585. },
  4586. /**
  4587. * @return {module:zrender/core/BoundingRect}
  4588. */
  4589. getBoundingRect: function (includeChildren) {
  4590. // TODO Caching
  4591. var rect = null;
  4592. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4593. var children = includeChildren || this._children;
  4594. var tmpMat = [];
  4595. for (var i = 0; i < children.length; i++) {
  4596. var child = children[i];
  4597. if (child.ignore || child.invisible) {
  4598. continue;
  4599. }
  4600. var childRect = child.getBoundingRect();
  4601. var transform = child.getLocalTransform(tmpMat);
  4602. // TODO
  4603. // The boundingRect cacluated by transforming original
  4604. // rect may be bigger than the actual bundingRect when rotation
  4605. // is used. (Consider a circle rotated aginst its center, where
  4606. // the actual boundingRect should be the same as that not be
  4607. // rotated.) But we can not find better approach to calculate
  4608. // actual boundingRect yet, considering performance.
  4609. if (transform) {
  4610. tmpRect.copy(childRect);
  4611. tmpRect.applyTransform(transform);
  4612. rect = rect || tmpRect.clone();
  4613. rect.union(tmpRect);
  4614. }
  4615. else {
  4616. rect = rect || childRect.clone();
  4617. rect.union(childRect);
  4618. }
  4619. }
  4620. return rect || tmpRect;
  4621. }
  4622. };
  4623. inherits(Group, Element);
  4624. // https://github.com/mziccard/node-timsort
  4625. var DEFAULT_MIN_MERGE = 32;
  4626. var DEFAULT_MIN_GALLOPING = 7;
  4627. function minRunLength(n) {
  4628. var r = 0;
  4629. while (n >= DEFAULT_MIN_MERGE) {
  4630. r |= n & 1;
  4631. n >>= 1;
  4632. }
  4633. return n + r;
  4634. }
  4635. function makeAscendingRun(array, lo, hi, compare) {
  4636. var runHi = lo + 1;
  4637. if (runHi === hi) {
  4638. return 1;
  4639. }
  4640. if (compare(array[runHi++], array[lo]) < 0) {
  4641. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4642. runHi++;
  4643. }
  4644. reverseRun(array, lo, runHi);
  4645. }
  4646. else {
  4647. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4648. runHi++;
  4649. }
  4650. }
  4651. return runHi - lo;
  4652. }
  4653. function reverseRun(array, lo, hi) {
  4654. hi--;
  4655. while (lo < hi) {
  4656. var t = array[lo];
  4657. array[lo++] = array[hi];
  4658. array[hi--] = t;
  4659. }
  4660. }
  4661. function binaryInsertionSort(array, lo, hi, start, compare) {
  4662. if (start === lo) {
  4663. start++;
  4664. }
  4665. for (; start < hi; start++) {
  4666. var pivot = array[start];
  4667. var left = lo;
  4668. var right = start;
  4669. var mid;
  4670. while (left < right) {
  4671. mid = left + right >>> 1;
  4672. if (compare(pivot, array[mid]) < 0) {
  4673. right = mid;
  4674. }
  4675. else {
  4676. left = mid + 1;
  4677. }
  4678. }
  4679. var n = start - left;
  4680. switch (n) {
  4681. case 3:
  4682. array[left + 3] = array[left + 2];
  4683. case 2:
  4684. array[left + 2] = array[left + 1];
  4685. case 1:
  4686. array[left + 1] = array[left];
  4687. break;
  4688. default:
  4689. while (n > 0) {
  4690. array[left + n] = array[left + n - 1];
  4691. n--;
  4692. }
  4693. }
  4694. array[left] = pivot;
  4695. }
  4696. }
  4697. function gallopLeft(value, array, start, length, hint, compare) {
  4698. var lastOffset = 0;
  4699. var maxOffset = 0;
  4700. var offset = 1;
  4701. if (compare(value, array[start + hint]) > 0) {
  4702. maxOffset = length - hint;
  4703. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4704. lastOffset = offset;
  4705. offset = (offset << 1) + 1;
  4706. if (offset <= 0) {
  4707. offset = maxOffset;
  4708. }
  4709. }
  4710. if (offset > maxOffset) {
  4711. offset = maxOffset;
  4712. }
  4713. lastOffset += hint;
  4714. offset += hint;
  4715. }
  4716. else {
  4717. maxOffset = hint + 1;
  4718. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4719. lastOffset = offset;
  4720. offset = (offset << 1) + 1;
  4721. if (offset <= 0) {
  4722. offset = maxOffset;
  4723. }
  4724. }
  4725. if (offset > maxOffset) {
  4726. offset = maxOffset;
  4727. }
  4728. var tmp = lastOffset;
  4729. lastOffset = hint - offset;
  4730. offset = hint - tmp;
  4731. }
  4732. lastOffset++;
  4733. while (lastOffset < offset) {
  4734. var m = lastOffset + (offset - lastOffset >>> 1);
  4735. if (compare(value, array[start + m]) > 0) {
  4736. lastOffset = m + 1;
  4737. }
  4738. else {
  4739. offset = m;
  4740. }
  4741. }
  4742. return offset;
  4743. }
  4744. function gallopRight(value, array, start, length, hint, compare) {
  4745. var lastOffset = 0;
  4746. var maxOffset = 0;
  4747. var offset = 1;
  4748. if (compare(value, array[start + hint]) < 0) {
  4749. maxOffset = hint + 1;
  4750. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4751. lastOffset = offset;
  4752. offset = (offset << 1) + 1;
  4753. if (offset <= 0) {
  4754. offset = maxOffset;
  4755. }
  4756. }
  4757. if (offset > maxOffset) {
  4758. offset = maxOffset;
  4759. }
  4760. var tmp = lastOffset;
  4761. lastOffset = hint - offset;
  4762. offset = hint - tmp;
  4763. }
  4764. else {
  4765. maxOffset = length - hint;
  4766. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4767. lastOffset = offset;
  4768. offset = (offset << 1) + 1;
  4769. if (offset <= 0) {
  4770. offset = maxOffset;
  4771. }
  4772. }
  4773. if (offset > maxOffset) {
  4774. offset = maxOffset;
  4775. }
  4776. lastOffset += hint;
  4777. offset += hint;
  4778. }
  4779. lastOffset++;
  4780. while (lastOffset < offset) {
  4781. var m = lastOffset + (offset - lastOffset >>> 1);
  4782. if (compare(value, array[start + m]) < 0) {
  4783. offset = m;
  4784. }
  4785. else {
  4786. lastOffset = m + 1;
  4787. }
  4788. }
  4789. return offset;
  4790. }
  4791. function TimSort(array, compare) {
  4792. var minGallop = DEFAULT_MIN_GALLOPING;
  4793. var runStart;
  4794. var runLength;
  4795. var stackSize = 0;
  4796. var tmp = [];
  4797. runStart = [];
  4798. runLength = [];
  4799. function pushRun(_runStart, _runLength) {
  4800. runStart[stackSize] = _runStart;
  4801. runLength[stackSize] = _runLength;
  4802. stackSize += 1;
  4803. }
  4804. function mergeRuns() {
  4805. while (stackSize > 1) {
  4806. var n = stackSize - 2;
  4807. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4808. if (runLength[n - 1] < runLength[n + 1]) {
  4809. n--;
  4810. }
  4811. }
  4812. else if (runLength[n] > runLength[n + 1]) {
  4813. break;
  4814. }
  4815. mergeAt(n);
  4816. }
  4817. }
  4818. function forceMergeRuns() {
  4819. while (stackSize > 1) {
  4820. var n = stackSize - 2;
  4821. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4822. n--;
  4823. }
  4824. mergeAt(n);
  4825. }
  4826. }
  4827. function mergeAt(i) {
  4828. var start1 = runStart[i];
  4829. var length1 = runLength[i];
  4830. var start2 = runStart[i + 1];
  4831. var length2 = runLength[i + 1];
  4832. runLength[i] = length1 + length2;
  4833. if (i === stackSize - 3) {
  4834. runStart[i + 1] = runStart[i + 2];
  4835. runLength[i + 1] = runLength[i + 2];
  4836. }
  4837. stackSize--;
  4838. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4839. start1 += k;
  4840. length1 -= k;
  4841. if (length1 === 0) {
  4842. return;
  4843. }
  4844. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4845. if (length2 === 0) {
  4846. return;
  4847. }
  4848. if (length1 <= length2) {
  4849. mergeLow(start1, length1, start2, length2);
  4850. }
  4851. else {
  4852. mergeHigh(start1, length1, start2, length2);
  4853. }
  4854. }
  4855. function mergeLow(start1, length1, start2, length2) {
  4856. var i = 0;
  4857. for (i = 0; i < length1; i++) {
  4858. tmp[i] = array[start1 + i];
  4859. }
  4860. var cursor1 = 0;
  4861. var cursor2 = start2;
  4862. var dest = start1;
  4863. array[dest++] = array[cursor2++];
  4864. if (--length2 === 0) {
  4865. for (i = 0; i < length1; i++) {
  4866. array[dest + i] = tmp[cursor1 + i];
  4867. }
  4868. return;
  4869. }
  4870. if (length1 === 1) {
  4871. for (i = 0; i < length2; i++) {
  4872. array[dest + i] = array[cursor2 + i];
  4873. }
  4874. array[dest + length2] = tmp[cursor1];
  4875. return;
  4876. }
  4877. var _minGallop = minGallop;
  4878. var count1, count2, exit;
  4879. while (1) {
  4880. count1 = 0;
  4881. count2 = 0;
  4882. exit = false;
  4883. do {
  4884. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4885. array[dest++] = array[cursor2++];
  4886. count2++;
  4887. count1 = 0;
  4888. if (--length2 === 0) {
  4889. exit = true;
  4890. break;
  4891. }
  4892. }
  4893. else {
  4894. array[dest++] = tmp[cursor1++];
  4895. count1++;
  4896. count2 = 0;
  4897. if (--length1 === 1) {
  4898. exit = true;
  4899. break;
  4900. }
  4901. }
  4902. } while ((count1 | count2) < _minGallop);
  4903. if (exit) {
  4904. break;
  4905. }
  4906. do {
  4907. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4908. if (count1 !== 0) {
  4909. for (i = 0; i < count1; i++) {
  4910. array[dest + i] = tmp[cursor1 + i];
  4911. }
  4912. dest += count1;
  4913. cursor1 += count1;
  4914. length1 -= count1;
  4915. if (length1 <= 1) {
  4916. exit = true;
  4917. break;
  4918. }
  4919. }
  4920. array[dest++] = array[cursor2++];
  4921. if (--length2 === 0) {
  4922. exit = true;
  4923. break;
  4924. }
  4925. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4926. if (count2 !== 0) {
  4927. for (i = 0; i < count2; i++) {
  4928. array[dest + i] = array[cursor2 + i];
  4929. }
  4930. dest += count2;
  4931. cursor2 += count2;
  4932. length2 -= count2;
  4933. if (length2 === 0) {
  4934. exit = true;
  4935. break;
  4936. }
  4937. }
  4938. array[dest++] = tmp[cursor1++];
  4939. if (--length1 === 1) {
  4940. exit = true;
  4941. break;
  4942. }
  4943. _minGallop--;
  4944. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4945. if (exit) {
  4946. break;
  4947. }
  4948. if (_minGallop < 0) {
  4949. _minGallop = 0;
  4950. }
  4951. _minGallop += 2;
  4952. }
  4953. minGallop = _minGallop;
  4954. minGallop < 1 && (minGallop = 1);
  4955. if (length1 === 1) {
  4956. for (i = 0; i < length2; i++) {
  4957. array[dest + i] = array[cursor2 + i];
  4958. }
  4959. array[dest + length2] = tmp[cursor1];
  4960. }
  4961. else if (length1 === 0) {
  4962. throw new Error();
  4963. // throw new Error('mergeLow preconditions were not respected');
  4964. }
  4965. else {
  4966. for (i = 0; i < length1; i++) {
  4967. array[dest + i] = tmp[cursor1 + i];
  4968. }
  4969. }
  4970. }
  4971. function mergeHigh (start1, length1, start2, length2) {
  4972. var i = 0;
  4973. for (i = 0; i < length2; i++) {
  4974. tmp[i] = array[start2 + i];
  4975. }
  4976. var cursor1 = start1 + length1 - 1;
  4977. var cursor2 = length2 - 1;
  4978. var dest = start2 + length2 - 1;
  4979. var customCursor = 0;
  4980. var customDest = 0;
  4981. array[dest--] = array[cursor1--];
  4982. if (--length1 === 0) {
  4983. customCursor = dest - (length2 - 1);
  4984. for (i = 0; i < length2; i++) {
  4985. array[customCursor + i] = tmp[i];
  4986. }
  4987. return;
  4988. }
  4989. if (length2 === 1) {
  4990. dest -= length1;
  4991. cursor1 -= length1;
  4992. customDest = dest + 1;
  4993. customCursor = cursor1 + 1;
  4994. for (i = length1 - 1; i >= 0; i--) {
  4995. array[customDest + i] = array[customCursor + i];
  4996. }
  4997. array[dest] = tmp[cursor2];
  4998. return;
  4999. }
  5000. var _minGallop = minGallop;
  5001. while (true) {
  5002. var count1 = 0;
  5003. var count2 = 0;
  5004. var exit = false;
  5005. do {
  5006. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5007. array[dest--] = array[cursor1--];
  5008. count1++;
  5009. count2 = 0;
  5010. if (--length1 === 0) {
  5011. exit = true;
  5012. break;
  5013. }
  5014. }
  5015. else {
  5016. array[dest--] = tmp[cursor2--];
  5017. count2++;
  5018. count1 = 0;
  5019. if (--length2 === 1) {
  5020. exit = true;
  5021. break;
  5022. }
  5023. }
  5024. } while ((count1 | count2) < _minGallop);
  5025. if (exit) {
  5026. break;
  5027. }
  5028. do {
  5029. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5030. if (count1 !== 0) {
  5031. dest -= count1;
  5032. cursor1 -= count1;
  5033. length1 -= count1;
  5034. customDest = dest + 1;
  5035. customCursor = cursor1 + 1;
  5036. for (i = count1 - 1; i >= 0; i--) {
  5037. array[customDest + i] = array[customCursor + i];
  5038. }
  5039. if (length1 === 0) {
  5040. exit = true;
  5041. break;
  5042. }
  5043. }
  5044. array[dest--] = tmp[cursor2--];
  5045. if (--length2 === 1) {
  5046. exit = true;
  5047. break;
  5048. }
  5049. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5050. if (count2 !== 0) {
  5051. dest -= count2;
  5052. cursor2 -= count2;
  5053. length2 -= count2;
  5054. customDest = dest + 1;
  5055. customCursor = cursor2 + 1;
  5056. for (i = 0; i < count2; i++) {
  5057. array[customDest + i] = tmp[customCursor + i];
  5058. }
  5059. if (length2 <= 1) {
  5060. exit = true;
  5061. break;
  5062. }
  5063. }
  5064. array[dest--] = array[cursor1--];
  5065. if (--length1 === 0) {
  5066. exit = true;
  5067. break;
  5068. }
  5069. _minGallop--;
  5070. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5071. if (exit) {
  5072. break;
  5073. }
  5074. if (_minGallop < 0) {
  5075. _minGallop = 0;
  5076. }
  5077. _minGallop += 2;
  5078. }
  5079. minGallop = _minGallop;
  5080. if (minGallop < 1) {
  5081. minGallop = 1;
  5082. }
  5083. if (length2 === 1) {
  5084. dest -= length1;
  5085. cursor1 -= length1;
  5086. customDest = dest + 1;
  5087. customCursor = cursor1 + 1;
  5088. for (i = length1 - 1; i >= 0; i--) {
  5089. array[customDest + i] = array[customCursor + i];
  5090. }
  5091. array[dest] = tmp[cursor2];
  5092. }
  5093. else if (length2 === 0) {
  5094. throw new Error();
  5095. // throw new Error('mergeHigh preconditions were not respected');
  5096. }
  5097. else {
  5098. customCursor = dest - (length2 - 1);
  5099. for (i = 0; i < length2; i++) {
  5100. array[customCursor + i] = tmp[i];
  5101. }
  5102. }
  5103. }
  5104. this.mergeRuns = mergeRuns;
  5105. this.forceMergeRuns = forceMergeRuns;
  5106. this.pushRun = pushRun;
  5107. }
  5108. function sort(array, compare, lo, hi) {
  5109. if (!lo) {
  5110. lo = 0;
  5111. }
  5112. if (!hi) {
  5113. hi = array.length;
  5114. }
  5115. var remaining = hi - lo;
  5116. if (remaining < 2) {
  5117. return;
  5118. }
  5119. var runLength = 0;
  5120. if (remaining < DEFAULT_MIN_MERGE) {
  5121. runLength = makeAscendingRun(array, lo, hi, compare);
  5122. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5123. return;
  5124. }
  5125. var ts = new TimSort(array, compare);
  5126. var minRun = minRunLength(remaining);
  5127. do {
  5128. runLength = makeAscendingRun(array, lo, hi, compare);
  5129. if (runLength < minRun) {
  5130. var force = remaining;
  5131. if (force > minRun) {
  5132. force = minRun;
  5133. }
  5134. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5135. runLength = force;
  5136. }
  5137. ts.pushRun(lo, runLength);
  5138. ts.mergeRuns();
  5139. remaining -= runLength;
  5140. lo += runLength;
  5141. } while (remaining !== 0);
  5142. ts.forceMergeRuns();
  5143. }
  5144. // Use timsort because in most case elements are partially sorted
  5145. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5146. function shapeCompareFunc(a, b) {
  5147. if (a.zlevel === b.zlevel) {
  5148. if (a.z === b.z) {
  5149. // if (a.z2 === b.z2) {
  5150. // // FIXME Slow has renderidx compare
  5151. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5152. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5153. // return a.__renderidx - b.__renderidx;
  5154. // }
  5155. return a.z2 - b.z2;
  5156. }
  5157. return a.z - b.z;
  5158. }
  5159. return a.zlevel - b.zlevel;
  5160. }
  5161. /**
  5162. * 内容仓库 (M)
  5163. * @alias module:zrender/Storage
  5164. * @constructor
  5165. */
  5166. var Storage = function () { // jshint ignore:line
  5167. this._roots = [];
  5168. this._displayList = [];
  5169. this._displayListLen = 0;
  5170. };
  5171. Storage.prototype = {
  5172. constructor: Storage,
  5173. /**
  5174. * @param {Function} cb
  5175. *
  5176. */
  5177. traverse: function (cb, context) {
  5178. for (var i = 0; i < this._roots.length; i++) {
  5179. this._roots[i].traverse(cb, context);
  5180. }
  5181. },
  5182. /**
  5183. * 返回所有图形的绘制队列
  5184. * @param {boolean} [update=false] 是否在返回前更新该数组
  5185. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5186. *
  5187. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5188. * @return {Array.<module:zrender/graphic/Displayable>}
  5189. */
  5190. getDisplayList: function (update, includeIgnore) {
  5191. includeIgnore = includeIgnore || false;
  5192. if (update) {
  5193. this.updateDisplayList(includeIgnore);
  5194. }
  5195. return this._displayList;
  5196. },
  5197. /**
  5198. * 更新图形的绘制队列。
  5199. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5200. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5201. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5202. */
  5203. updateDisplayList: function (includeIgnore) {
  5204. this._displayListLen = 0;
  5205. var roots = this._roots;
  5206. var displayList = this._displayList;
  5207. for (var i = 0, len = roots.length; i < len; i++) {
  5208. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5209. }
  5210. displayList.length = this._displayListLen;
  5211. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5212. },
  5213. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5214. if (el.ignore && !includeIgnore) {
  5215. return;
  5216. }
  5217. el.beforeUpdate();
  5218. if (el.__dirty) {
  5219. el.update();
  5220. }
  5221. el.afterUpdate();
  5222. var userSetClipPath = el.clipPath;
  5223. if (userSetClipPath) {
  5224. // FIXME 效率影响
  5225. if (clipPaths) {
  5226. clipPaths = clipPaths.slice();
  5227. }
  5228. else {
  5229. clipPaths = [];
  5230. }
  5231. var currentClipPath = userSetClipPath;
  5232. var parentClipPath = el;
  5233. // Recursively add clip path
  5234. while (currentClipPath) {
  5235. // clipPath 的变换是基于使用这个 clipPath 的元素
  5236. currentClipPath.parent = parentClipPath;
  5237. currentClipPath.updateTransform();
  5238. clipPaths.push(currentClipPath);
  5239. parentClipPath = currentClipPath;
  5240. currentClipPath = currentClipPath.clipPath;
  5241. }
  5242. }
  5243. if (el.isGroup) {
  5244. var children = el._children;
  5245. for (var i = 0; i < children.length; i++) {
  5246. var child = children[i];
  5247. // Force to mark as dirty if group is dirty
  5248. // FIXME __dirtyPath ?
  5249. if (el.__dirty) {
  5250. child.__dirty = true;
  5251. }
  5252. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5253. }
  5254. // Mark group clean here
  5255. el.__dirty = false;
  5256. }
  5257. else {
  5258. el.__clipPaths = clipPaths;
  5259. this._displayList[this._displayListLen++] = el;
  5260. }
  5261. },
  5262. /**
  5263. * 添加图形(Shape)或者组(Group)到根节点
  5264. * @param {module:zrender/Element} el
  5265. */
  5266. addRoot: function (el) {
  5267. if (el.__storage === this) {
  5268. return;
  5269. }
  5270. if (el instanceof Group) {
  5271. el.addChildrenToStorage(this);
  5272. }
  5273. this.addToStorage(el);
  5274. this._roots.push(el);
  5275. },
  5276. /**
  5277. * 删除指定的图形(Shape)或者组(Group)
  5278. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5279. */
  5280. delRoot: function (el) {
  5281. if (el == null) {
  5282. // 不指定el清空
  5283. for (var i = 0; i < this._roots.length; i++) {
  5284. var root = this._roots[i];
  5285. if (root instanceof Group) {
  5286. root.delChildrenFromStorage(this);
  5287. }
  5288. }
  5289. this._roots = [];
  5290. this._displayList = [];
  5291. this._displayListLen = 0;
  5292. return;
  5293. }
  5294. if (el instanceof Array) {
  5295. for (var i = 0, l = el.length; i < l; i++) {
  5296. this.delRoot(el[i]);
  5297. }
  5298. return;
  5299. }
  5300. var idx = indexOf(this._roots, el);
  5301. if (idx >= 0) {
  5302. this.delFromStorage(el);
  5303. this._roots.splice(idx, 1);
  5304. if (el instanceof Group) {
  5305. el.delChildrenFromStorage(this);
  5306. }
  5307. }
  5308. },
  5309. addToStorage: function (el) {
  5310. if (el) {
  5311. el.__storage = this;
  5312. el.dirty(false);
  5313. }
  5314. return this;
  5315. },
  5316. delFromStorage: function (el) {
  5317. if (el) {
  5318. el.__storage = null;
  5319. }
  5320. return this;
  5321. },
  5322. /**
  5323. * 清空并且释放Storage
  5324. */
  5325. dispose: function () {
  5326. this._renderList =
  5327. this._roots = null;
  5328. },
  5329. displayableSortFunc: shapeCompareFunc
  5330. };
  5331. var SHADOW_PROPS = {
  5332. 'shadowBlur': 1,
  5333. 'shadowOffsetX': 1,
  5334. 'shadowOffsetY': 1,
  5335. 'textShadowBlur': 1,
  5336. 'textShadowOffsetX': 1,
  5337. 'textShadowOffsetY': 1,
  5338. 'textBoxShadowBlur': 1,
  5339. 'textBoxShadowOffsetX': 1,
  5340. 'textBoxShadowOffsetY': 1
  5341. };
  5342. var fixShadow = function (ctx, propName, value) {
  5343. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5344. return value *= ctx.dpr;
  5345. }
  5346. return value;
  5347. };
  5348. var STYLE_COMMON_PROPS = [
  5349. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5350. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5351. ];
  5352. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5353. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5354. var Style = function (opts, host) {
  5355. this.extendFrom(opts, false);
  5356. this.host = host;
  5357. };
  5358. function createLinearGradient(ctx, obj, rect) {
  5359. var x = obj.x == null ? 0 : obj.x;
  5360. var x2 = obj.x2 == null ? 1 : obj.x2;
  5361. var y = obj.y == null ? 0 : obj.y;
  5362. var y2 = obj.y2 == null ? 0 : obj.y2;
  5363. if (!obj.global) {
  5364. x = x * rect.width + rect.x;
  5365. x2 = x2 * rect.width + rect.x;
  5366. y = y * rect.height + rect.y;
  5367. y2 = y2 * rect.height + rect.y;
  5368. }
  5369. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5370. return canvasGradient;
  5371. }
  5372. function createRadialGradient(ctx, obj, rect) {
  5373. var width = rect.width;
  5374. var height = rect.height;
  5375. var min = Math.min(width, height);
  5376. var x = obj.x == null ? 0.5 : obj.x;
  5377. var y = obj.y == null ? 0.5 : obj.y;
  5378. var r = obj.r == null ? 0.5 : obj.r;
  5379. if (!obj.global) {
  5380. x = x * width + rect.x;
  5381. y = y * height + rect.y;
  5382. r = r * min;
  5383. }
  5384. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5385. return canvasGradient;
  5386. }
  5387. Style.prototype = {
  5388. constructor: Style,
  5389. /**
  5390. * @type {module:zrender/graphic/Displayable}
  5391. */
  5392. host: null,
  5393. /**
  5394. * @type {string}
  5395. */
  5396. fill: '#000',
  5397. /**
  5398. * @type {string}
  5399. */
  5400. stroke: null,
  5401. /**
  5402. * @type {number}
  5403. */
  5404. opacity: 1,
  5405. /**
  5406. * @type {Array.<number>}
  5407. */
  5408. lineDash: null,
  5409. /**
  5410. * @type {number}
  5411. */
  5412. lineDashOffset: 0,
  5413. /**
  5414. * @type {number}
  5415. */
  5416. shadowBlur: 0,
  5417. /**
  5418. * @type {number}
  5419. */
  5420. shadowOffsetX: 0,
  5421. /**
  5422. * @type {number}
  5423. */
  5424. shadowOffsetY: 0,
  5425. /**
  5426. * @type {number}
  5427. */
  5428. lineWidth: 1,
  5429. /**
  5430. * If stroke ignore scale
  5431. * @type {Boolean}
  5432. */
  5433. strokeNoScale: false,
  5434. // Bounding rect text configuration
  5435. // Not affected by element transform
  5436. /**
  5437. * @type {string}
  5438. */
  5439. text: null,
  5440. /**
  5441. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5442. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5443. * So do not visit it directly in upper application (like echarts),
  5444. * but use `contain/text#makeFont` instead.
  5445. * @type {string}
  5446. */
  5447. font: null,
  5448. /**
  5449. * The same as font. Use font please.
  5450. * @deprecated
  5451. * @type {string}
  5452. */
  5453. textFont: null,
  5454. /**
  5455. * It helps merging respectively, rather than parsing an entire font string.
  5456. * @type {string}
  5457. */
  5458. fontStyle: null,
  5459. /**
  5460. * It helps merging respectively, rather than parsing an entire font string.
  5461. * @type {string}
  5462. */
  5463. fontWeight: null,
  5464. /**
  5465. * It helps merging respectively, rather than parsing an entire font string.
  5466. * Should be 12 but not '12px'.
  5467. * @type {number}
  5468. */
  5469. fontSize: null,
  5470. /**
  5471. * It helps merging respectively, rather than parsing an entire font string.
  5472. * @type {string}
  5473. */
  5474. fontFamily: null,
  5475. /**
  5476. * Reserved for special functinality, like 'hr'.
  5477. * @type {string}
  5478. */
  5479. textTag: null,
  5480. /**
  5481. * @type {string}
  5482. */
  5483. textFill: '#000',
  5484. /**
  5485. * @type {string}
  5486. */
  5487. textStroke: null,
  5488. /**
  5489. * @type {number}
  5490. */
  5491. textWidth: null,
  5492. /**
  5493. * Only for textBackground.
  5494. * @type {number}
  5495. */
  5496. textHeight: null,
  5497. /**
  5498. * textStroke may be set as some color as a default
  5499. * value in upper applicaion, where the default value
  5500. * of textStrokeWidth should be 0 to make sure that
  5501. * user can choose to do not use text stroke.
  5502. * @type {number}
  5503. */
  5504. textStrokeWidth: 0,
  5505. /**
  5506. * @type {number}
  5507. */
  5508. textLineHeight: null,
  5509. /**
  5510. * 'inside', 'left', 'right', 'top', 'bottom'
  5511. * [x, y]
  5512. * Based on x, y of rect.
  5513. * @type {string|Array.<number>}
  5514. * @default 'inside'
  5515. */
  5516. textPosition: 'inside',
  5517. /**
  5518. * If not specified, use the boundingRect of a `displayable`.
  5519. * @type {Object}
  5520. */
  5521. textRect: null,
  5522. /**
  5523. * [x, y]
  5524. * @type {Array.<number>}
  5525. */
  5526. textOffset: null,
  5527. /**
  5528. * @type {string}
  5529. */
  5530. textAlign: null,
  5531. /**
  5532. * @type {string}
  5533. */
  5534. textVerticalAlign: null,
  5535. /**
  5536. * @type {number}
  5537. */
  5538. textDistance: 5,
  5539. /**
  5540. * @type {string}
  5541. */
  5542. textShadowColor: 'transparent',
  5543. /**
  5544. * @type {number}
  5545. */
  5546. textShadowBlur: 0,
  5547. /**
  5548. * @type {number}
  5549. */
  5550. textShadowOffsetX: 0,
  5551. /**
  5552. * @type {number}
  5553. */
  5554. textShadowOffsetY: 0,
  5555. /**
  5556. * @type {string}
  5557. */
  5558. textBoxShadowColor: 'transparent',
  5559. /**
  5560. * @type {number}
  5561. */
  5562. textBoxShadowBlur: 0,
  5563. /**
  5564. * @type {number}
  5565. */
  5566. textBoxShadowOffsetX: 0,
  5567. /**
  5568. * @type {number}
  5569. */
  5570. textBoxShadowOffsetY: 0,
  5571. /**
  5572. * Whether transform text.
  5573. * Only useful in Path and Image element
  5574. * @type {boolean}
  5575. */
  5576. transformText: false,
  5577. /**
  5578. * Text rotate around position of Path or Image
  5579. * Only useful in Path and Image element and transformText is false.
  5580. */
  5581. textRotation: 0,
  5582. /**
  5583. * Text origin of text rotation, like [10, 40].
  5584. * Based on x, y of rect.
  5585. * Useful in label rotation of circular symbol.
  5586. * By default, this origin is textPosition.
  5587. * Can be 'center'.
  5588. * @type {string|Array.<number>}
  5589. */
  5590. textOrigin: null,
  5591. /**
  5592. * @type {string}
  5593. */
  5594. textBackgroundColor: null,
  5595. /**
  5596. * @type {string}
  5597. */
  5598. textBorderColor: null,
  5599. /**
  5600. * @type {number}
  5601. */
  5602. textBorderWidth: 0,
  5603. /**
  5604. * @type {number}
  5605. */
  5606. textBorderRadius: 0,
  5607. /**
  5608. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5609. * @type {number|Array.<number>}
  5610. */
  5611. textPadding: null,
  5612. /**
  5613. * Text styles for rich text.
  5614. * @type {Object}
  5615. */
  5616. rich: null,
  5617. /**
  5618. * {outerWidth, outerHeight, ellipsis, placeholder}
  5619. * @type {Object}
  5620. */
  5621. truncate: null,
  5622. /**
  5623. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5624. * @type {string}
  5625. */
  5626. blend: null,
  5627. /**
  5628. * @param {CanvasRenderingContext2D} ctx
  5629. */
  5630. bind: function (ctx, el, prevEl) {
  5631. var style = this;
  5632. var prevStyle = prevEl && prevEl.style;
  5633. var firstDraw = !prevStyle;
  5634. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5635. var prop = STYLE_COMMON_PROPS[i];
  5636. var styleName = prop[0];
  5637. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5638. // FIXME Invalid property value will cause style leak from previous element.
  5639. ctx[styleName] =
  5640. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5641. }
  5642. }
  5643. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5644. ctx.fillStyle = style.fill;
  5645. }
  5646. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5647. ctx.strokeStyle = style.stroke;
  5648. }
  5649. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5650. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5651. }
  5652. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5653. ctx.globalCompositeOperation = style.blend || 'source-over';
  5654. }
  5655. if (this.hasStroke()) {
  5656. var lineWidth = style.lineWidth;
  5657. ctx.lineWidth = lineWidth / (
  5658. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5659. );
  5660. }
  5661. },
  5662. hasFill: function () {
  5663. var fill = this.fill;
  5664. return fill != null && fill !== 'none';
  5665. },
  5666. hasStroke: function () {
  5667. var stroke = this.stroke;
  5668. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5669. },
  5670. /**
  5671. * Extend from other style
  5672. * @param {zrender/graphic/Style} otherStyle
  5673. * @param {boolean} overwrite true: overwrirte any way.
  5674. * false: overwrite only when !target.hasOwnProperty
  5675. * others: overwrite when property is not null/undefined.
  5676. */
  5677. extendFrom: function (otherStyle, overwrite) {
  5678. if (otherStyle) {
  5679. for (var name in otherStyle) {
  5680. if (otherStyle.hasOwnProperty(name)
  5681. && (overwrite === true
  5682. || (
  5683. overwrite === false
  5684. ? !this.hasOwnProperty(name)
  5685. : otherStyle[name] != null
  5686. )
  5687. )
  5688. ) {
  5689. this[name] = otherStyle[name];
  5690. }
  5691. }
  5692. }
  5693. },
  5694. /**
  5695. * Batch setting style with a given object
  5696. * @param {Object|string} obj
  5697. * @param {*} [obj]
  5698. */
  5699. set: function (obj, value) {
  5700. if (typeof obj === 'string') {
  5701. this[obj] = value;
  5702. }
  5703. else {
  5704. this.extendFrom(obj, true);
  5705. }
  5706. },
  5707. /**
  5708. * Clone
  5709. * @return {zrender/graphic/Style} [description]
  5710. */
  5711. clone: function () {
  5712. var newStyle = new this.constructor();
  5713. newStyle.extendFrom(this, true);
  5714. return newStyle;
  5715. },
  5716. getGradient: function (ctx, obj, rect) {
  5717. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5718. var canvasGradient = method(ctx, obj, rect);
  5719. var colorStops = obj.colorStops;
  5720. for (var i = 0; i < colorStops.length; i++) {
  5721. canvasGradient.addColorStop(
  5722. colorStops[i].offset, colorStops[i].color
  5723. );
  5724. }
  5725. return canvasGradient;
  5726. }
  5727. };
  5728. var styleProto = Style.prototype;
  5729. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5730. var prop = STYLE_COMMON_PROPS[i];
  5731. if (!(prop[0] in styleProto)) {
  5732. styleProto[prop[0]] = prop[1];
  5733. }
  5734. }
  5735. // Provide for others
  5736. Style.getGradient = styleProto.getGradient;
  5737. var Pattern = function (image, repeat) {
  5738. // Should do nothing more in this constructor. Because gradient can be
  5739. // declard by `color: {image: ...}`, where this constructor will not be called.
  5740. this.image = image;
  5741. this.repeat = repeat;
  5742. // Can be cloned
  5743. this.type = 'pattern';
  5744. };
  5745. Pattern.prototype.getCanvasPattern = function (ctx) {
  5746. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5747. };
  5748. /**
  5749. * @module zrender/Layer
  5750. * @author pissang(https://www.github.com/pissang)
  5751. */
  5752. function returnFalse() {
  5753. return false;
  5754. }
  5755. /**
  5756. * 创建dom
  5757. *
  5758. * @inner
  5759. * @param {string} id dom id 待用
  5760. * @param {Painter} painter painter instance
  5761. * @param {number} number
  5762. */
  5763. function createDom(id, painter, dpr) {
  5764. var newDom = createCanvas();
  5765. var width = painter.getWidth();
  5766. var height = painter.getHeight();
  5767. var newDomStyle = newDom.style;
  5768. if (newDomStyle) { // In node or some other non-browser environment
  5769. newDomStyle.position = 'absolute';
  5770. newDomStyle.left = 0;
  5771. newDomStyle.top = 0;
  5772. newDomStyle.width = width + 'px';
  5773. newDomStyle.height = height + 'px';
  5774. newDom.setAttribute('data-zr-dom-id', id);
  5775. }
  5776. newDom.width = width * dpr;
  5777. newDom.height = height * dpr;
  5778. return newDom;
  5779. }
  5780. /**
  5781. * @alias module:zrender/Layer
  5782. * @constructor
  5783. * @extends module:zrender/mixin/Transformable
  5784. * @param {string} id
  5785. * @param {module:zrender/Painter} painter
  5786. * @param {number} [dpr]
  5787. */
  5788. var Layer = function(id, painter, dpr) {
  5789. var dom;
  5790. dpr = dpr || devicePixelRatio;
  5791. if (typeof id === 'string') {
  5792. dom = createDom(id, painter, dpr);
  5793. }
  5794. // Not using isDom because in node it will return false
  5795. else if (isObject$1(id)) {
  5796. dom = id;
  5797. id = dom.id;
  5798. }
  5799. this.id = id;
  5800. this.dom = dom;
  5801. var domStyle = dom.style;
  5802. if (domStyle) { // Not in node
  5803. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5804. domStyle['-webkit-user-select'] = 'none';
  5805. domStyle['user-select'] = 'none';
  5806. domStyle['-webkit-touch-callout'] = 'none';
  5807. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5808. domStyle['padding'] = 0;
  5809. domStyle['margin'] = 0;
  5810. domStyle['border-width'] = 0;
  5811. }
  5812. this.domBack = null;
  5813. this.ctxBack = null;
  5814. this.painter = painter;
  5815. this.config = null;
  5816. // Configs
  5817. /**
  5818. * 每次清空画布的颜色
  5819. * @type {string}
  5820. * @default 0
  5821. */
  5822. this.clearColor = 0;
  5823. /**
  5824. * 是否开启动态模糊
  5825. * @type {boolean}
  5826. * @default false
  5827. */
  5828. this.motionBlur = false;
  5829. /**
  5830. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5831. * @type {number}
  5832. * @default 0.7
  5833. */
  5834. this.lastFrameAlpha = 0.7;
  5835. /**
  5836. * Layer dpr
  5837. * @type {number}
  5838. */
  5839. this.dpr = dpr;
  5840. };
  5841. Layer.prototype = {
  5842. constructor: Layer,
  5843. __dirty: true,
  5844. __used: false,
  5845. __drawIndex: 0,
  5846. __startIndex: 0,
  5847. __endIndex: 0,
  5848. incremental: false,
  5849. getElementCount: function () {
  5850. return this.__endIndex - this.__startIndex;
  5851. },
  5852. initContext: function () {
  5853. this.ctx = this.dom.getContext('2d');
  5854. this.ctx.dpr = this.dpr;
  5855. },
  5856. createBackBuffer: function () {
  5857. var dpr = this.dpr;
  5858. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5859. this.ctxBack = this.domBack.getContext('2d');
  5860. if (dpr != 1) {
  5861. this.ctxBack.scale(dpr, dpr);
  5862. }
  5863. },
  5864. /**
  5865. * @param {number} width
  5866. * @param {number} height
  5867. */
  5868. resize: function (width, height) {
  5869. var dpr = this.dpr;
  5870. var dom = this.dom;
  5871. var domStyle = dom.style;
  5872. var domBack = this.domBack;
  5873. domStyle.width = width + 'px';
  5874. domStyle.height = height + 'px';
  5875. dom.width = width * dpr;
  5876. dom.height = height * dpr;
  5877. if (domBack) {
  5878. domBack.width = width * dpr;
  5879. domBack.height = height * dpr;
  5880. if (dpr != 1) {
  5881. this.ctxBack.scale(dpr, dpr);
  5882. }
  5883. }
  5884. },
  5885. /**
  5886. * 清空该层画布
  5887. * @param {boolean} clearAll Clear all with out motion blur
  5888. */
  5889. clear: function (clearAll) {
  5890. var dom = this.dom;
  5891. var ctx = this.ctx;
  5892. var width = dom.width;
  5893. var height = dom.height;
  5894. var clearColor = this.clearColor;
  5895. var haveMotionBLur = this.motionBlur && !clearAll;
  5896. var lastFrameAlpha = this.lastFrameAlpha;
  5897. var dpr = this.dpr;
  5898. if (haveMotionBLur) {
  5899. if (!this.domBack) {
  5900. this.createBackBuffer();
  5901. }
  5902. this.ctxBack.globalCompositeOperation = 'copy';
  5903. this.ctxBack.drawImage(
  5904. dom, 0, 0,
  5905. width / dpr,
  5906. height / dpr
  5907. );
  5908. }
  5909. ctx.clearRect(0, 0, width, height);
  5910. if (clearColor) {
  5911. var clearColorGradientOrPattern;
  5912. // Gradient
  5913. if (clearColor.colorStops) {
  5914. // Cache canvas gradient
  5915. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5916. x: 0,
  5917. y: 0,
  5918. width: width,
  5919. height: height
  5920. });
  5921. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5922. }
  5923. // Pattern
  5924. else if (clearColor.image) {
  5925. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5926. }
  5927. ctx.save();
  5928. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5929. ctx.fillRect(0, 0, width, height);
  5930. ctx.restore();
  5931. }
  5932. if (haveMotionBLur) {
  5933. var domBack = this.domBack;
  5934. ctx.save();
  5935. ctx.globalAlpha = lastFrameAlpha;
  5936. ctx.drawImage(domBack, 0, 0, width, height);
  5937. ctx.restore();
  5938. }
  5939. }
  5940. };
  5941. var requestAnimationFrame = (
  5942. typeof window !== 'undefined'
  5943. && (
  5944. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5945. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5946. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5947. || window.mozRequestAnimationFrame
  5948. || window.webkitRequestAnimationFrame
  5949. )
  5950. ) || function (func) {
  5951. setTimeout(func, 16);
  5952. };
  5953. var globalImageCache = new LRU(50);
  5954. /**
  5955. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5956. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5957. */
  5958. function findExistImage(newImageOrSrc) {
  5959. if (typeof newImageOrSrc === 'string') {
  5960. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5961. return cachedImgObj && cachedImgObj.image;
  5962. }
  5963. else {
  5964. return newImageOrSrc;
  5965. }
  5966. }
  5967. /**
  5968. * Caution: User should cache loaded images, but not just count on LRU.
  5969. * Consider if required images more than LRU size, will dead loop occur?
  5970. *
  5971. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5972. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  5973. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  5974. * @param {Function} [cb] params: (image, cbPayload)
  5975. * @param {Object} [cbPayload] Payload on cb calling.
  5976. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5977. */
  5978. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  5979. if (!newImageOrSrc) {
  5980. return image;
  5981. }
  5982. else if (typeof newImageOrSrc === 'string') {
  5983. // Image should not be loaded repeatly.
  5984. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  5985. return image;
  5986. }
  5987. // Only when there is no existent image or existent image src
  5988. // is different, this method is responsible for load.
  5989. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5990. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  5991. if (cachedImgObj) {
  5992. image = cachedImgObj.image;
  5993. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  5994. }
  5995. else {
  5996. !image && (image = new Image());
  5997. image.onload = imageOnLoad;
  5998. globalImageCache.put(
  5999. newImageOrSrc,
  6000. image.__cachedImgObj = {
  6001. image: image,
  6002. pending: [pendingWrap]
  6003. }
  6004. );
  6005. image.src = image.__zrImageSrc = newImageOrSrc;
  6006. }
  6007. return image;
  6008. }
  6009. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6010. else {
  6011. return newImageOrSrc;
  6012. }
  6013. }
  6014. function imageOnLoad() {
  6015. var cachedImgObj = this.__cachedImgObj;
  6016. this.onload = this.__cachedImgObj = null;
  6017. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6018. var pendingWrap = cachedImgObj.pending[i];
  6019. var cb = pendingWrap.cb;
  6020. cb && cb(this, pendingWrap.cbPayload);
  6021. pendingWrap.hostEl.dirty();
  6022. }
  6023. cachedImgObj.pending.length = 0;
  6024. }
  6025. function isImageReady(image) {
  6026. return image && image.width && image.height;
  6027. }
  6028. var textWidthCache = {};
  6029. var textWidthCacheCounter = 0;
  6030. var TEXT_CACHE_MAX = 5000;
  6031. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6032. var DEFAULT_FONT = '12px sans-serif';
  6033. // Avoid assign to an exported variable, for transforming to cjs.
  6034. var methods$1 = {};
  6035. function $override$1(name, fn) {
  6036. methods$1[name] = fn;
  6037. }
  6038. /**
  6039. * @public
  6040. * @param {string} text
  6041. * @param {string} font
  6042. * @return {number} width
  6043. */
  6044. function getWidth(text, font) {
  6045. font = font || DEFAULT_FONT;
  6046. var key = text + ':' + font;
  6047. if (textWidthCache[key]) {
  6048. return textWidthCache[key];
  6049. }
  6050. var textLines = (text + '').split('\n');
  6051. var width = 0;
  6052. for (var i = 0, l = textLines.length; i < l; i++) {
  6053. // textContain.measureText may be overrided in SVG or VML
  6054. width = Math.max(measureText(textLines[i], font).width, width);
  6055. }
  6056. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6057. textWidthCacheCounter = 0;
  6058. textWidthCache = {};
  6059. }
  6060. textWidthCacheCounter++;
  6061. textWidthCache[key] = width;
  6062. return width;
  6063. }
  6064. /**
  6065. * @public
  6066. * @param {string} text
  6067. * @param {string} font
  6068. * @param {string} [textAlign='left']
  6069. * @param {string} [textVerticalAlign='top']
  6070. * @param {Array.<number>} [textPadding]
  6071. * @param {Object} [rich]
  6072. * @param {Object} [truncate]
  6073. * @return {Object} {x, y, width, height, lineHeight}
  6074. */
  6075. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6076. return rich
  6077. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6078. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6079. }
  6080. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6081. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6082. var outerWidth = getWidth(text, font);
  6083. if (textPadding) {
  6084. outerWidth += textPadding[1] + textPadding[3];
  6085. }
  6086. var outerHeight = contentBlock.outerHeight;
  6087. var x = adjustTextX(0, outerWidth, textAlign);
  6088. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6089. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6090. rect.lineHeight = contentBlock.lineHeight;
  6091. return rect;
  6092. }
  6093. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6094. var contentBlock = parseRichText(text, {
  6095. rich: rich,
  6096. truncate: truncate,
  6097. font: font,
  6098. textAlign: textAlign,
  6099. textPadding: textPadding
  6100. });
  6101. var outerWidth = contentBlock.outerWidth;
  6102. var outerHeight = contentBlock.outerHeight;
  6103. var x = adjustTextX(0, outerWidth, textAlign);
  6104. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6105. return new BoundingRect(x, y, outerWidth, outerHeight);
  6106. }
  6107. /**
  6108. * @public
  6109. * @param {number} x
  6110. * @param {number} width
  6111. * @param {string} [textAlign='left']
  6112. * @return {number} Adjusted x.
  6113. */
  6114. function adjustTextX(x, width, textAlign) {
  6115. // FIXME Right to left language
  6116. if (textAlign === 'right') {
  6117. x -= width;
  6118. }
  6119. else if (textAlign === 'center') {
  6120. x -= width / 2;
  6121. }
  6122. return x;
  6123. }
  6124. /**
  6125. * @public
  6126. * @param {number} y
  6127. * @param {number} height
  6128. * @param {string} [textVerticalAlign='top']
  6129. * @return {number} Adjusted y.
  6130. */
  6131. function adjustTextY(y, height, textVerticalAlign) {
  6132. if (textVerticalAlign === 'middle') {
  6133. y -= height / 2;
  6134. }
  6135. else if (textVerticalAlign === 'bottom') {
  6136. y -= height;
  6137. }
  6138. return y;
  6139. }
  6140. /**
  6141. * @public
  6142. * @param {stirng} textPosition
  6143. * @param {Object} rect {x, y, width, height}
  6144. * @param {number} distance
  6145. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6146. */
  6147. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6148. var x = rect.x;
  6149. var y = rect.y;
  6150. var height = rect.height;
  6151. var width = rect.width;
  6152. var halfHeight = height / 2;
  6153. var textAlign = 'left';
  6154. var textVerticalAlign = 'top';
  6155. switch (textPosition) {
  6156. case 'left':
  6157. x -= distance;
  6158. y += halfHeight;
  6159. textAlign = 'right';
  6160. textVerticalAlign = 'middle';
  6161. break;
  6162. case 'right':
  6163. x += distance + width;
  6164. y += halfHeight;
  6165. textVerticalAlign = 'middle';
  6166. break;
  6167. case 'top':
  6168. x += width / 2;
  6169. y -= distance;
  6170. textAlign = 'center';
  6171. textVerticalAlign = 'bottom';
  6172. break;
  6173. case 'bottom':
  6174. x += width / 2;
  6175. y += height + distance;
  6176. textAlign = 'center';
  6177. break;
  6178. case 'inside':
  6179. x += width / 2;
  6180. y += halfHeight;
  6181. textAlign = 'center';
  6182. textVerticalAlign = 'middle';
  6183. break;
  6184. case 'insideLeft':
  6185. x += distance;
  6186. y += halfHeight;
  6187. textVerticalAlign = 'middle';
  6188. break;
  6189. case 'insideRight':
  6190. x += width - distance;
  6191. y += halfHeight;
  6192. textAlign = 'right';
  6193. textVerticalAlign = 'middle';
  6194. break;
  6195. case 'insideTop':
  6196. x += width / 2;
  6197. y += distance;
  6198. textAlign = 'center';
  6199. break;
  6200. case 'insideBottom':
  6201. x += width / 2;
  6202. y += height - distance;
  6203. textAlign = 'center';
  6204. textVerticalAlign = 'bottom';
  6205. break;
  6206. case 'insideTopLeft':
  6207. x += distance;
  6208. y += distance;
  6209. break;
  6210. case 'insideTopRight':
  6211. x += width - distance;
  6212. y += distance;
  6213. textAlign = 'right';
  6214. break;
  6215. case 'insideBottomLeft':
  6216. x += distance;
  6217. y += height - distance;
  6218. textVerticalAlign = 'bottom';
  6219. break;
  6220. case 'insideBottomRight':
  6221. x += width - distance;
  6222. y += height - distance;
  6223. textAlign = 'right';
  6224. textVerticalAlign = 'bottom';
  6225. break;
  6226. }
  6227. return {
  6228. x: x,
  6229. y: y,
  6230. textAlign: textAlign,
  6231. textVerticalAlign: textVerticalAlign
  6232. };
  6233. }
  6234. /**
  6235. * Show ellipsis if overflow.
  6236. *
  6237. * @public
  6238. * @param {string} text
  6239. * @param {string} containerWidth
  6240. * @param {string} font
  6241. * @param {number} [ellipsis='...']
  6242. * @param {Object} [options]
  6243. * @param {number} [options.maxIterations=3]
  6244. * @param {number} [options.minChar=0] If truncate result are less
  6245. * then minChar, ellipsis will not show, which is
  6246. * better for user hint in some cases.
  6247. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6248. * @return {string}
  6249. */
  6250. function truncateText(text, containerWidth, font, ellipsis, options) {
  6251. if (!containerWidth) {
  6252. return '';
  6253. }
  6254. var textLines = (text + '').split('\n');
  6255. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6256. // FIXME
  6257. // It is not appropriate that every line has '...' when truncate multiple lines.
  6258. for (var i = 0, len = textLines.length; i < len; i++) {
  6259. textLines[i] = truncateSingleLine(textLines[i], options);
  6260. }
  6261. return textLines.join('\n');
  6262. }
  6263. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6264. options = extend({}, options);
  6265. options.font = font;
  6266. var ellipsis = retrieve2(ellipsis, '...');
  6267. options.maxIterations = retrieve2(options.maxIterations, 2);
  6268. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6269. // FIXME
  6270. // Other languages?
  6271. options.cnCharWidth = getWidth('国', font);
  6272. // FIXME
  6273. // Consider proportional font?
  6274. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6275. options.placeholder = retrieve2(options.placeholder, '');
  6276. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6277. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6278. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6279. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6280. contentWidth -= ascCharWidth;
  6281. }
  6282. var ellipsisWidth = getWidth(ellipsis);
  6283. if (ellipsisWidth > contentWidth) {
  6284. ellipsis = '';
  6285. ellipsisWidth = 0;
  6286. }
  6287. contentWidth = containerWidth - ellipsisWidth;
  6288. options.ellipsis = ellipsis;
  6289. options.ellipsisWidth = ellipsisWidth;
  6290. options.contentWidth = contentWidth;
  6291. options.containerWidth = containerWidth;
  6292. return options;
  6293. }
  6294. function truncateSingleLine(textLine, options) {
  6295. var containerWidth = options.containerWidth;
  6296. var font = options.font;
  6297. var contentWidth = options.contentWidth;
  6298. if (!containerWidth) {
  6299. return '';
  6300. }
  6301. var lineWidth = getWidth(textLine, font);
  6302. if (lineWidth <= containerWidth) {
  6303. return textLine;
  6304. }
  6305. for (var j = 0;; j++) {
  6306. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6307. textLine += options.ellipsis;
  6308. break;
  6309. }
  6310. var subLength = j === 0
  6311. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6312. : lineWidth > 0
  6313. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6314. : 0;
  6315. textLine = textLine.substr(0, subLength);
  6316. lineWidth = getWidth(textLine, font);
  6317. }
  6318. if (textLine === '') {
  6319. textLine = options.placeholder;
  6320. }
  6321. return textLine;
  6322. }
  6323. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6324. var width = 0;
  6325. var i = 0;
  6326. for (var len = text.length; i < len && width < contentWidth; i++) {
  6327. var charCode = text.charCodeAt(i);
  6328. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6329. }
  6330. return i;
  6331. }
  6332. /**
  6333. * @public
  6334. * @param {string} font
  6335. * @return {number} line height
  6336. */
  6337. function getLineHeight(font) {
  6338. // FIXME A rough approach.
  6339. return getWidth('国', font);
  6340. }
  6341. /**
  6342. * @public
  6343. * @param {string} text
  6344. * @param {string} font
  6345. * @return {Object} width
  6346. */
  6347. function measureText(text, font) {
  6348. return methods$1.measureText(text, font);
  6349. }
  6350. // Avoid assign to an exported variable, for transforming to cjs.
  6351. methods$1.measureText = function (text, font) {
  6352. var ctx = getContext();
  6353. ctx.font = font || DEFAULT_FONT;
  6354. return ctx.measureText(text);
  6355. };
  6356. /**
  6357. * @public
  6358. * @param {string} text
  6359. * @param {string} font
  6360. * @param {Object} [truncate]
  6361. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6362. * Notice: for performance, do not calculate outerWidth util needed.
  6363. */
  6364. function parsePlainText(text, font, padding, truncate) {
  6365. text != null && (text += '');
  6366. var lineHeight = getLineHeight(font);
  6367. var lines = text ? text.split('\n') : [];
  6368. var height = lines.length * lineHeight;
  6369. var outerHeight = height;
  6370. if (padding) {
  6371. outerHeight += padding[0] + padding[2];
  6372. }
  6373. if (text && truncate) {
  6374. var truncOuterHeight = truncate.outerHeight;
  6375. var truncOuterWidth = truncate.outerWidth;
  6376. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6377. text = '';
  6378. lines = [];
  6379. }
  6380. else if (truncOuterWidth != null) {
  6381. var options = prepareTruncateOptions(
  6382. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6383. font,
  6384. truncate.ellipsis,
  6385. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6386. );
  6387. // FIXME
  6388. // It is not appropriate that every line has '...' when truncate multiple lines.
  6389. for (var i = 0, len = lines.length; i < len; i++) {
  6390. lines[i] = truncateSingleLine(lines[i], options);
  6391. }
  6392. }
  6393. }
  6394. return {
  6395. lines: lines,
  6396. height: height,
  6397. outerHeight: outerHeight,
  6398. lineHeight: lineHeight
  6399. };
  6400. }
  6401. /**
  6402. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6403. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6404. *
  6405. * @public
  6406. * @param {string} text
  6407. * @param {Object} style
  6408. * @return {Object} block
  6409. * {
  6410. * width,
  6411. * height,
  6412. * lines: [{
  6413. * lineHeight,
  6414. * width,
  6415. * tokens: [[{
  6416. * styleName,
  6417. * text,
  6418. * width, // include textPadding
  6419. * height, // include textPadding
  6420. * textWidth, // pure text width
  6421. * textHeight, // pure text height
  6422. * lineHeihgt,
  6423. * font,
  6424. * textAlign,
  6425. * textVerticalAlign
  6426. * }], [...], ...]
  6427. * }, ...]
  6428. * }
  6429. * If styleName is undefined, it is plain text.
  6430. */
  6431. function parseRichText(text, style) {
  6432. var contentBlock = {lines: [], width: 0, height: 0};
  6433. text != null && (text += '');
  6434. if (!text) {
  6435. return contentBlock;
  6436. }
  6437. var lastIndex = STYLE_REG.lastIndex = 0;
  6438. var result;
  6439. while ((result = STYLE_REG.exec(text)) != null) {
  6440. var matchedIndex = result.index;
  6441. if (matchedIndex > lastIndex) {
  6442. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6443. }
  6444. pushTokens(contentBlock, result[2], result[1]);
  6445. lastIndex = STYLE_REG.lastIndex;
  6446. }
  6447. if (lastIndex < text.length) {
  6448. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6449. }
  6450. var lines = contentBlock.lines;
  6451. var contentHeight = 0;
  6452. var contentWidth = 0;
  6453. // For `textWidth: 100%`
  6454. var pendingList = [];
  6455. var stlPadding = style.textPadding;
  6456. var truncate = style.truncate;
  6457. var truncateWidth = truncate && truncate.outerWidth;
  6458. var truncateHeight = truncate && truncate.outerHeight;
  6459. if (stlPadding) {
  6460. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6461. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6462. }
  6463. // Calculate layout info of tokens.
  6464. for (var i = 0; i < lines.length; i++) {
  6465. var line = lines[i];
  6466. var lineHeight = 0;
  6467. var lineWidth = 0;
  6468. for (var j = 0; j < line.tokens.length; j++) {
  6469. var token = line.tokens[j];
  6470. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6471. // textPadding should not inherit from style.
  6472. var textPadding = token.textPadding = tokenStyle.textPadding;
  6473. // textFont has been asigned to font by `normalizeStyle`.
  6474. var font = token.font = tokenStyle.font || style.font;
  6475. // textHeight can be used when textVerticalAlign is specified in token.
  6476. var tokenHeight = token.textHeight = retrieve2(
  6477. // textHeight should not be inherited, consider it can be specified
  6478. // as box height of the block.
  6479. tokenStyle.textHeight, getLineHeight(font)
  6480. );
  6481. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6482. token.height = tokenHeight;
  6483. token.lineHeight = retrieve3(
  6484. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6485. );
  6486. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6487. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6488. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6489. return {lines: [], width: 0, height: 0};
  6490. }
  6491. token.textWidth = getWidth(token.text, font);
  6492. var tokenWidth = tokenStyle.textWidth;
  6493. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6494. // Percent width, can be `100%`, can be used in drawing separate
  6495. // line when box width is needed to be auto.
  6496. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6497. token.percentWidth = tokenWidth;
  6498. pendingList.push(token);
  6499. tokenWidth = 0;
  6500. // Do not truncate in this case, because there is no user case
  6501. // and it is too complicated.
  6502. }
  6503. else {
  6504. if (tokenWidthNotSpecified) {
  6505. tokenWidth = token.textWidth;
  6506. // FIXME: If image is not loaded and textWidth is not specified, calling
  6507. // `getBoundingRect()` will not get correct result.
  6508. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6509. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6510. // Use cases:
  6511. // (1) If image is not loaded, it will be loaded at render phase and call
  6512. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6513. // image, and then the right size will be calculated here at the next tick.
  6514. // See `graphic/helper/text.js`.
  6515. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6516. // use `imageHelper.findExistImage` to find cached image.
  6517. // `imageHelper.findExistImage` will always be called here before
  6518. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6519. // which ensures that image will not be rendered before correct size calcualted.
  6520. if (bgImg) {
  6521. bgImg = findExistImage(bgImg);
  6522. if (isImageReady(bgImg)) {
  6523. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6524. }
  6525. }
  6526. }
  6527. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6528. tokenWidth += paddingW;
  6529. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6530. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6531. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6532. token.text = '';
  6533. token.textWidth = tokenWidth = 0;
  6534. }
  6535. else {
  6536. token.text = truncateText(
  6537. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6538. {minChar: truncate.minChar}
  6539. );
  6540. token.textWidth = getWidth(token.text, font);
  6541. tokenWidth = token.textWidth + paddingW;
  6542. }
  6543. }
  6544. }
  6545. lineWidth += (token.width = tokenWidth);
  6546. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6547. }
  6548. line.width = lineWidth;
  6549. line.lineHeight = lineHeight;
  6550. contentHeight += lineHeight;
  6551. contentWidth = Math.max(contentWidth, lineWidth);
  6552. }
  6553. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6554. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6555. if (stlPadding) {
  6556. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6557. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6558. }
  6559. for (var i = 0; i < pendingList.length; i++) {
  6560. var token = pendingList[i];
  6561. var percentWidth = token.percentWidth;
  6562. // Should not base on outerWidth, because token can not be placed out of padding.
  6563. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6564. }
  6565. return contentBlock;
  6566. }
  6567. function pushTokens(block, str, styleName) {
  6568. var isEmptyStr = str === '';
  6569. var strs = str.split('\n');
  6570. var lines = block.lines;
  6571. for (var i = 0; i < strs.length; i++) {
  6572. var text = strs[i];
  6573. var token = {
  6574. styleName: styleName,
  6575. text: text,
  6576. isLineHolder: !text && !isEmptyStr
  6577. };
  6578. // The first token should be appended to the last line.
  6579. if (!i) {
  6580. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6581. // Consider cases:
  6582. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6583. // (which is a placeholder) should be replaced by new token.
  6584. // (2) A image backage, where token likes {a|}.
  6585. // (3) A redundant '' will affect textAlign in line.
  6586. // (4) tokens with the same tplName should not be merged, because
  6587. // they should be displayed in different box (with border and padding).
  6588. var tokensLen = tokens.length;
  6589. (tokensLen === 1 && tokens[0].isLineHolder)
  6590. ? (tokens[0] = token)
  6591. // Consider text is '', only insert when it is the "lineHolder" or
  6592. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6593. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6594. }
  6595. // Other tokens always start a new line.
  6596. else {
  6597. // If there is '', insert it as a placeholder.
  6598. lines.push({tokens: [token]});
  6599. }
  6600. }
  6601. }
  6602. function makeFont(style) {
  6603. // FIXME in node-canvas fontWeight is before fontStyle
  6604. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6605. var font = (style.fontSize || style.fontFamily) && [
  6606. style.fontStyle,
  6607. style.fontWeight,
  6608. (style.fontSize || 12) + 'px',
  6609. // If font properties are defined, `fontFamily` should not be ignored.
  6610. style.fontFamily || 'sans-serif'
  6611. ].join(' ');
  6612. return font && trim(font) || style.textFont || style.font;
  6613. }
  6614. function buildPath(ctx, shape) {
  6615. var x = shape.x;
  6616. var y = shape.y;
  6617. var width = shape.width;
  6618. var height = shape.height;
  6619. var r = shape.r;
  6620. var r1;
  6621. var r2;
  6622. var r3;
  6623. var r4;
  6624. // Convert width and height to positive for better borderRadius
  6625. if (width < 0) {
  6626. x = x + width;
  6627. width = -width;
  6628. }
  6629. if (height < 0) {
  6630. y = y + height;
  6631. height = -height;
  6632. }
  6633. if (typeof r === 'number') {
  6634. r1 = r2 = r3 = r4 = r;
  6635. }
  6636. else if (r instanceof Array) {
  6637. if (r.length === 1) {
  6638. r1 = r2 = r3 = r4 = r[0];
  6639. }
  6640. else if (r.length === 2) {
  6641. r1 = r3 = r[0];
  6642. r2 = r4 = r[1];
  6643. }
  6644. else if (r.length === 3) {
  6645. r1 = r[0];
  6646. r2 = r4 = r[1];
  6647. r3 = r[2];
  6648. }
  6649. else {
  6650. r1 = r[0];
  6651. r2 = r[1];
  6652. r3 = r[2];
  6653. r4 = r[3];
  6654. }
  6655. }
  6656. else {
  6657. r1 = r2 = r3 = r4 = 0;
  6658. }
  6659. var total;
  6660. if (r1 + r2 > width) {
  6661. total = r1 + r2;
  6662. r1 *= width / total;
  6663. r2 *= width / total;
  6664. }
  6665. if (r3 + r4 > width) {
  6666. total = r3 + r4;
  6667. r3 *= width / total;
  6668. r4 *= width / total;
  6669. }
  6670. if (r2 + r3 > height) {
  6671. total = r2 + r3;
  6672. r2 *= height / total;
  6673. r3 *= height / total;
  6674. }
  6675. if (r1 + r4 > height) {
  6676. total = r1 + r4;
  6677. r1 *= height / total;
  6678. r4 *= height / total;
  6679. }
  6680. ctx.moveTo(x + r1, y);
  6681. ctx.lineTo(x + width - r2, y);
  6682. r2 !== 0 && ctx.quadraticCurveTo(
  6683. x + width, y, x + width, y + r2
  6684. );
  6685. ctx.lineTo(x + width, y + height - r3);
  6686. r3 !== 0 && ctx.quadraticCurveTo(
  6687. x + width, y + height, x + width - r3, y + height
  6688. );
  6689. ctx.lineTo(x + r4, y + height);
  6690. r4 !== 0 && ctx.quadraticCurveTo(
  6691. x, y + height, x, y + height - r4
  6692. );
  6693. ctx.lineTo(x, y + r1);
  6694. r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y);
  6695. }
  6696. // TODO: Have not support 'start', 'end' yet.
  6697. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6698. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6699. /**
  6700. * @param {module:zrender/graphic/Style} style
  6701. * @return {module:zrender/graphic/Style} The input style.
  6702. */
  6703. function normalizeTextStyle(style) {
  6704. normalizeStyle(style);
  6705. each$1(style.rich, normalizeStyle);
  6706. return style;
  6707. }
  6708. function normalizeStyle(style) {
  6709. if (style) {
  6710. style.font = makeFont(style);
  6711. var textAlign = style.textAlign;
  6712. textAlign === 'middle' && (textAlign = 'center');
  6713. style.textAlign = (
  6714. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6715. ) ? textAlign : 'left';
  6716. // Compatible with textBaseline.
  6717. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6718. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6719. style.textVerticalAlign = (
  6720. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6721. ) ? textVerticalAlign : 'top';
  6722. var textPadding = style.textPadding;
  6723. if (textPadding) {
  6724. style.textPadding = normalizeCssArray(style.textPadding);
  6725. }
  6726. }
  6727. }
  6728. /**
  6729. * @param {CanvasRenderingContext2D} ctx
  6730. * @param {string} text
  6731. * @param {module:zrender/graphic/Style} style
  6732. * @param {Object|boolean} [rect] {x, y, width, height}
  6733. * If set false, rect text is not used.
  6734. */
  6735. function renderText(hostEl, ctx, text, style, rect) {
  6736. style.rich
  6737. ? renderRichText(hostEl, ctx, text, style, rect)
  6738. : renderPlainText(hostEl, ctx, text, style, rect);
  6739. }
  6740. function renderPlainText(hostEl, ctx, text, style, rect) {
  6741. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6742. var textPadding = style.textPadding;
  6743. var contentBlock = hostEl.__textCotentBlock;
  6744. if (!contentBlock || hostEl.__dirty) {
  6745. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6746. text, font, textPadding, style.truncate
  6747. );
  6748. }
  6749. var outerHeight = contentBlock.outerHeight;
  6750. var textLines = contentBlock.lines;
  6751. var lineHeight = contentBlock.lineHeight;
  6752. var boxPos = getBoxPosition(outerHeight, style, rect);
  6753. var baseX = boxPos.baseX;
  6754. var baseY = boxPos.baseY;
  6755. var textAlign = boxPos.textAlign;
  6756. var textVerticalAlign = boxPos.textVerticalAlign;
  6757. // Origin of textRotation should be the base point of text drawing.
  6758. applyTextRotation(ctx, style, rect, baseX, baseY);
  6759. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6760. var textX = baseX;
  6761. var textY = boxY;
  6762. var needDrawBg = needDrawBackground(style);
  6763. if (needDrawBg || textPadding) {
  6764. // Consider performance, do not call getTextWidth util necessary.
  6765. var textWidth = getWidth(text, font);
  6766. var outerWidth = textWidth;
  6767. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6768. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6769. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6770. if (textPadding) {
  6771. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6772. textY += textPadding[0];
  6773. }
  6774. }
  6775. setCtx(ctx, 'textAlign', textAlign || 'left');
  6776. // Force baseline to be "middle". Otherwise, if using "top", the
  6777. // text will offset downward a little bit in font "Microsoft YaHei".
  6778. setCtx(ctx, 'textBaseline', 'middle');
  6779. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6780. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6781. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6782. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6783. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6784. // `textBaseline` is set as 'middle'.
  6785. textY += lineHeight / 2;
  6786. var textStrokeWidth = style.textStrokeWidth;
  6787. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6788. var textFill = getFill(style.textFill);
  6789. if (textStroke) {
  6790. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6791. setCtx(ctx, 'strokeStyle', textStroke);
  6792. }
  6793. if (textFill) {
  6794. setCtx(ctx, 'fillStyle', textFill);
  6795. }
  6796. for (var i = 0; i < textLines.length; i++) {
  6797. // Fill after stroke so the outline will not cover the main part.
  6798. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6799. textFill && ctx.fillText(textLines[i], textX, textY);
  6800. textY += lineHeight;
  6801. }
  6802. }
  6803. function renderRichText(hostEl, ctx, text, style, rect) {
  6804. var contentBlock = hostEl.__textCotentBlock;
  6805. if (!contentBlock || hostEl.__dirty) {
  6806. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6807. }
  6808. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6809. }
  6810. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6811. var contentWidth = contentBlock.width;
  6812. var outerWidth = contentBlock.outerWidth;
  6813. var outerHeight = contentBlock.outerHeight;
  6814. var textPadding = style.textPadding;
  6815. var boxPos = getBoxPosition(outerHeight, style, rect);
  6816. var baseX = boxPos.baseX;
  6817. var baseY = boxPos.baseY;
  6818. var textAlign = boxPos.textAlign;
  6819. var textVerticalAlign = boxPos.textVerticalAlign;
  6820. // Origin of textRotation should be the base point of text drawing.
  6821. applyTextRotation(ctx, style, rect, baseX, baseY);
  6822. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6823. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6824. var xLeft = boxX;
  6825. var lineTop = boxY;
  6826. if (textPadding) {
  6827. xLeft += textPadding[3];
  6828. lineTop += textPadding[0];
  6829. }
  6830. var xRight = xLeft + contentWidth;
  6831. needDrawBackground(style) && drawBackground(
  6832. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6833. );
  6834. for (var i = 0; i < contentBlock.lines.length; i++) {
  6835. var line = contentBlock.lines[i];
  6836. var tokens = line.tokens;
  6837. var tokenCount = tokens.length;
  6838. var lineHeight = line.lineHeight;
  6839. var usedWidth = line.width;
  6840. var leftIndex = 0;
  6841. var lineXLeft = xLeft;
  6842. var lineXRight = xRight;
  6843. var rightIndex = tokenCount - 1;
  6844. var token;
  6845. while (
  6846. leftIndex < tokenCount
  6847. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6848. ) {
  6849. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6850. usedWidth -= token.width;
  6851. lineXLeft += token.width;
  6852. leftIndex++;
  6853. }
  6854. while (
  6855. rightIndex >= 0
  6856. && (token = tokens[rightIndex], token.textAlign === 'right')
  6857. ) {
  6858. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6859. usedWidth -= token.width;
  6860. lineXRight -= token.width;
  6861. rightIndex--;
  6862. }
  6863. // The other tokens are placed as textAlign 'center' if there is enough space.
  6864. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6865. while (leftIndex <= rightIndex) {
  6866. token = tokens[leftIndex];
  6867. // Consider width specified by user, use 'center' rather than 'left'.
  6868. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6869. lineXLeft += token.width;
  6870. leftIndex++;
  6871. }
  6872. lineTop += lineHeight;
  6873. }
  6874. }
  6875. function applyTextRotation(ctx, style, rect, x, y) {
  6876. // textRotation only apply in RectText.
  6877. if (rect && style.textRotation) {
  6878. var origin = style.textOrigin;
  6879. if (origin === 'center') {
  6880. x = rect.width / 2 + rect.x;
  6881. y = rect.height / 2 + rect.y;
  6882. }
  6883. else if (origin) {
  6884. x = origin[0] + rect.x;
  6885. y = origin[1] + rect.y;
  6886. }
  6887. ctx.translate(x, y);
  6888. // Positive: anticlockwise
  6889. ctx.rotate(-style.textRotation);
  6890. ctx.translate(-x, -y);
  6891. }
  6892. }
  6893. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6894. var tokenStyle = style.rich[token.styleName] || {};
  6895. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6896. // the bias of "Microsoft YaHei".
  6897. var textVerticalAlign = token.textVerticalAlign;
  6898. var y = lineTop + lineHeight / 2;
  6899. if (textVerticalAlign === 'top') {
  6900. y = lineTop + token.height / 2;
  6901. }
  6902. else if (textVerticalAlign === 'bottom') {
  6903. y = lineTop + lineHeight - token.height / 2;
  6904. }
  6905. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6906. hostEl,
  6907. ctx,
  6908. tokenStyle,
  6909. textAlign === 'right'
  6910. ? x - token.width
  6911. : textAlign === 'center'
  6912. ? x - token.width / 2
  6913. : x,
  6914. y - token.height / 2,
  6915. token.width,
  6916. token.height
  6917. );
  6918. var textPadding = token.textPadding;
  6919. if (textPadding) {
  6920. x = getTextXForPadding(x, textAlign, textPadding);
  6921. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6922. }
  6923. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6924. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6925. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6926. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6927. setCtx(ctx, 'textAlign', textAlign);
  6928. // Force baseline to be "middle". Otherwise, if using "top", the
  6929. // text will offset downward a little bit in font "Microsoft YaHei".
  6930. setCtx(ctx, 'textBaseline', 'middle');
  6931. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6932. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6933. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6934. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6935. // Fill after stroke so the outline will not cover the main part.
  6936. if (textStroke) {
  6937. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6938. setCtx(ctx, 'strokeStyle', textStroke);
  6939. ctx.strokeText(token.text, x, y);
  6940. }
  6941. if (textFill) {
  6942. setCtx(ctx, 'fillStyle', textFill);
  6943. ctx.fillText(token.text, x, y);
  6944. }
  6945. }
  6946. function needDrawBackground(style) {
  6947. return style.textBackgroundColor
  6948. || (style.textBorderWidth && style.textBorderColor);
  6949. }
  6950. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6951. // shape: {x, y, width, height}
  6952. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6953. var textBackgroundColor = style.textBackgroundColor;
  6954. var textBorderWidth = style.textBorderWidth;
  6955. var textBorderColor = style.textBorderColor;
  6956. var isPlainBg = isString(textBackgroundColor);
  6957. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6958. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6959. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6960. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6961. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6962. ctx.beginPath();
  6963. var textBorderRadius = style.textBorderRadius;
  6964. if (!textBorderRadius) {
  6965. ctx.rect(x, y, width, height);
  6966. }
  6967. else {
  6968. buildPath(ctx, {
  6969. x: x, y: y, width: width, height: height, r: textBorderRadius
  6970. });
  6971. }
  6972. ctx.closePath();
  6973. }
  6974. if (isPlainBg) {
  6975. setCtx(ctx, 'fillStyle', textBackgroundColor);
  6976. ctx.fill();
  6977. }
  6978. else if (isObject$1(textBackgroundColor)) {
  6979. var image = textBackgroundColor.image;
  6980. image = createOrUpdateImage(
  6981. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  6982. );
  6983. if (image && isImageReady(image)) {
  6984. ctx.drawImage(image, x, y, width, height);
  6985. }
  6986. }
  6987. if (textBorderWidth && textBorderColor) {
  6988. setCtx(ctx, 'lineWidth', textBorderWidth);
  6989. setCtx(ctx, 'strokeStyle', textBorderColor);
  6990. ctx.stroke();
  6991. }
  6992. }
  6993. function onBgImageLoaded(image, textBackgroundColor) {
  6994. // Replace image, so that `contain/text.js#parseRichText`
  6995. // will get correct result in next tick.
  6996. textBackgroundColor.image = image;
  6997. }
  6998. function getBoxPosition(blockHeiht, style, rect) {
  6999. var baseX = style.x || 0;
  7000. var baseY = style.y || 0;
  7001. var textAlign = style.textAlign;
  7002. var textVerticalAlign = style.textVerticalAlign;
  7003. // Text position represented by coord
  7004. if (rect) {
  7005. var textPosition = style.textPosition;
  7006. if (textPosition instanceof Array) {
  7007. // Percent
  7008. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7009. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7010. }
  7011. else {
  7012. var res = adjustTextPositionOnRect(
  7013. textPosition, rect, style.textDistance
  7014. );
  7015. baseX = res.x;
  7016. baseY = res.y;
  7017. // Default align and baseline when has textPosition
  7018. textAlign = textAlign || res.textAlign;
  7019. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7020. }
  7021. // textOffset is only support in RectText, otherwise
  7022. // we have to adjust boundingRect for textOffset.
  7023. var textOffset = style.textOffset;
  7024. if (textOffset) {
  7025. baseX += textOffset[0];
  7026. baseY += textOffset[1];
  7027. }
  7028. }
  7029. return {
  7030. baseX: baseX,
  7031. baseY: baseY,
  7032. textAlign: textAlign,
  7033. textVerticalAlign: textVerticalAlign
  7034. };
  7035. }
  7036. function setCtx(ctx, prop, value) {
  7037. ctx[prop] = fixShadow(ctx, prop, value);
  7038. return ctx[prop];
  7039. }
  7040. /**
  7041. * @param {string} [stroke] If specified, do not check style.textStroke.
  7042. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7043. * @param {number} style
  7044. */
  7045. function getStroke(stroke, lineWidth) {
  7046. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7047. ? null
  7048. // TODO pattern and gradient?
  7049. : (stroke.image || stroke.colorStops)
  7050. ? '#000'
  7051. : stroke;
  7052. }
  7053. function getFill(fill) {
  7054. return (fill == null || fill === 'none')
  7055. ? null
  7056. // TODO pattern and gradient?
  7057. : (fill.image || fill.colorStops)
  7058. ? '#000'
  7059. : fill;
  7060. }
  7061. function parsePercent(value, maxValue) {
  7062. if (typeof value === 'string') {
  7063. if (value.lastIndexOf('%') >= 0) {
  7064. return parseFloat(value) / 100 * maxValue;
  7065. }
  7066. return parseFloat(value);
  7067. }
  7068. return value;
  7069. }
  7070. function getTextXForPadding(x, textAlign, textPadding) {
  7071. return textAlign === 'right'
  7072. ? (x - textPadding[1])
  7073. : textAlign === 'center'
  7074. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7075. : (x + textPadding[3]);
  7076. }
  7077. /**
  7078. * @param {string} text
  7079. * @param {module:zrender/Style} style
  7080. * @return {boolean}
  7081. */
  7082. function needDrawText(text, style) {
  7083. return text != null
  7084. && (text
  7085. || style.textBackgroundColor
  7086. || (style.textBorderWidth && style.textBorderColor)
  7087. || style.textPadding
  7088. );
  7089. }
  7090. /**
  7091. * Mixin for drawing text in a element bounding rect
  7092. * @module zrender/mixin/RectText
  7093. */
  7094. var tmpRect$1 = new BoundingRect();
  7095. var RectText = function () {};
  7096. RectText.prototype = {
  7097. constructor: RectText,
  7098. /**
  7099. * Draw text in a rect with specified position.
  7100. * @param {CanvasRenderingContext2D} ctx
  7101. * @param {Object} rect Displayable rect
  7102. */
  7103. drawRectText: function (ctx, rect) {
  7104. var style = this.style;
  7105. rect = style.textRect || rect;
  7106. // Optimize, avoid normalize every time.
  7107. this.__dirty && normalizeTextStyle(style, true);
  7108. var text = style.text;
  7109. // Convert to string
  7110. text != null && (text += '');
  7111. if (!needDrawText(text, style)) {
  7112. return;
  7113. }
  7114. // FIXME
  7115. ctx.save();
  7116. // Transform rect to view space
  7117. var transform = this.transform;
  7118. if (!style.transformText) {
  7119. if (transform) {
  7120. tmpRect$1.copy(rect);
  7121. tmpRect$1.applyTransform(transform);
  7122. rect = tmpRect$1;
  7123. }
  7124. }
  7125. else {
  7126. this.setTransform(ctx);
  7127. }
  7128. // transformText and textRotation can not be used at the same time.
  7129. renderText(this, ctx, text, style, rect);
  7130. ctx.restore();
  7131. }
  7132. };
  7133. /**
  7134. * 可绘制的图形基类
  7135. * Base class of all displayable graphic objects
  7136. * @module zrender/graphic/Displayable
  7137. */
  7138. /**
  7139. * @alias module:zrender/graphic/Displayable
  7140. * @extends module:zrender/Element
  7141. * @extends module:zrender/graphic/mixin/RectText
  7142. */
  7143. function Displayable(opts) {
  7144. opts = opts || {};
  7145. Element.call(this, opts);
  7146. // Extend properties
  7147. for (var name in opts) {
  7148. if (
  7149. opts.hasOwnProperty(name) &&
  7150. name !== 'style'
  7151. ) {
  7152. this[name] = opts[name];
  7153. }
  7154. }
  7155. /**
  7156. * @type {module:zrender/graphic/Style}
  7157. */
  7158. this.style = new Style(opts.style, this);
  7159. this._rect = null;
  7160. // Shapes for cascade clipping.
  7161. this.__clipPaths = [];
  7162. // FIXME Stateful must be mixined after style is setted
  7163. // Stateful.call(this, opts);
  7164. }
  7165. Displayable.prototype = {
  7166. constructor: Displayable,
  7167. type: 'displayable',
  7168. /**
  7169. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7170. * Dirty flag. From which painter will determine if this displayable object needs brush
  7171. * @name module:zrender/graphic/Displayable#__dirty
  7172. * @type {boolean}
  7173. */
  7174. __dirty: true,
  7175. /**
  7176. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7177. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7178. * @name module:/zrender/graphic/Displayable#invisible
  7179. * @type {boolean}
  7180. * @default false
  7181. */
  7182. invisible: false,
  7183. /**
  7184. * @name module:/zrender/graphic/Displayable#z
  7185. * @type {number}
  7186. * @default 0
  7187. */
  7188. z: 0,
  7189. /**
  7190. * @name module:/zrender/graphic/Displayable#z
  7191. * @type {number}
  7192. * @default 0
  7193. */
  7194. z2: 0,
  7195. /**
  7196. * z层level,决定绘画在哪层canvas中
  7197. * @name module:/zrender/graphic/Displayable#zlevel
  7198. * @type {number}
  7199. * @default 0
  7200. */
  7201. zlevel: 0,
  7202. /**
  7203. * 是否可拖拽
  7204. * @name module:/zrender/graphic/Displayable#draggable
  7205. * @type {boolean}
  7206. * @default false
  7207. */
  7208. draggable: false,
  7209. /**
  7210. * 是否正在拖拽
  7211. * @name module:/zrender/graphic/Displayable#draggable
  7212. * @type {boolean}
  7213. * @default false
  7214. */
  7215. dragging: false,
  7216. /**
  7217. * 是否相应鼠标事件
  7218. * @name module:/zrender/graphic/Displayable#silent
  7219. * @type {boolean}
  7220. * @default false
  7221. */
  7222. silent: false,
  7223. /**
  7224. * If enable culling
  7225. * @type {boolean}
  7226. * @default false
  7227. */
  7228. culling: false,
  7229. /**
  7230. * Mouse cursor when hovered
  7231. * @name module:/zrender/graphic/Displayable#cursor
  7232. * @type {string}
  7233. */
  7234. cursor: 'pointer',
  7235. /**
  7236. * If hover area is bounding rect
  7237. * @name module:/zrender/graphic/Displayable#rectHover
  7238. * @type {string}
  7239. */
  7240. rectHover: false,
  7241. /**
  7242. * Render the element progressively when the value >= 0,
  7243. * usefull for large data.
  7244. * @type {boolean}
  7245. */
  7246. progressive: false,
  7247. /**
  7248. * @type {boolean}
  7249. */
  7250. incremental: false,
  7251. // inplace is used with incremental
  7252. inplace: false,
  7253. beforeBrush: function (ctx) {},
  7254. afterBrush: function (ctx) {},
  7255. /**
  7256. * 图形绘制方法
  7257. * @param {CanvasRenderingContext2D} ctx
  7258. */
  7259. // Interface
  7260. brush: function (ctx, prevEl) {},
  7261. /**
  7262. * 获取最小包围盒
  7263. * @return {module:zrender/core/BoundingRect}
  7264. */
  7265. // Interface
  7266. getBoundingRect: function () {},
  7267. /**
  7268. * 判断坐标 x, y 是否在图形上
  7269. * If displayable element contain coord x, y
  7270. * @param {number} x
  7271. * @param {number} y
  7272. * @return {boolean}
  7273. */
  7274. contain: function (x, y) {
  7275. return this.rectContain(x, y);
  7276. },
  7277. /**
  7278. * @param {Function} cb
  7279. * @param {} context
  7280. */
  7281. traverse: function (cb, context) {
  7282. cb.call(context, this);
  7283. },
  7284. /**
  7285. * 判断坐标 x, y 是否在图形的包围盒上
  7286. * If bounding rect of element contain coord x, y
  7287. * @param {number} x
  7288. * @param {number} y
  7289. * @return {boolean}
  7290. */
  7291. rectContain: function (x, y) {
  7292. var coord = this.transformCoordToLocal(x, y);
  7293. var rect = this.getBoundingRect();
  7294. return rect.contain(coord[0], coord[1]);
  7295. },
  7296. /**
  7297. * 标记图形元素为脏,并且在下一帧重绘
  7298. * Mark displayable element dirty and refresh next frame
  7299. */
  7300. dirty: function () {
  7301. this.__dirty = true;
  7302. this._rect = null;
  7303. this.__zr && this.__zr.refresh();
  7304. },
  7305. /**
  7306. * 图形是否会触发事件
  7307. * If displayable object binded any event
  7308. * @return {boolean}
  7309. */
  7310. // TODO, 通过 bind 绑定的事件
  7311. // isSilent: function () {
  7312. // return !(
  7313. // this.hoverable || this.draggable
  7314. // || this.onmousemove || this.onmouseover || this.onmouseout
  7315. // || this.onmousedown || this.onmouseup || this.onclick
  7316. // || this.ondragenter || this.ondragover || this.ondragleave
  7317. // || this.ondrop
  7318. // );
  7319. // },
  7320. /**
  7321. * Alias for animate('style')
  7322. * @param {boolean} loop
  7323. */
  7324. animateStyle: function (loop) {
  7325. return this.animate('style', loop);
  7326. },
  7327. attrKV: function (key, value) {
  7328. if (key !== 'style') {
  7329. Element.prototype.attrKV.call(this, key, value);
  7330. }
  7331. else {
  7332. this.style.set(value);
  7333. }
  7334. },
  7335. /**
  7336. * @param {Object|string} key
  7337. * @param {*} value
  7338. */
  7339. setStyle: function (key, value) {
  7340. this.style.set(key, value);
  7341. this.dirty(false);
  7342. return this;
  7343. },
  7344. /**
  7345. * Use given style object
  7346. * @param {Object} obj
  7347. */
  7348. useStyle: function (obj) {
  7349. this.style = new Style(obj, this);
  7350. this.dirty(false);
  7351. return this;
  7352. }
  7353. };
  7354. inherits(Displayable, Element);
  7355. mixin(Displayable, RectText);
  7356. /**
  7357. * @alias zrender/graphic/Image
  7358. * @extends module:zrender/graphic/Displayable
  7359. * @constructor
  7360. * @param {Object} opts
  7361. */
  7362. function ZImage(opts) {
  7363. Displayable.call(this, opts);
  7364. }
  7365. ZImage.prototype = {
  7366. constructor: ZImage,
  7367. type: 'image',
  7368. brush: function (ctx, prevEl) {
  7369. var style = this.style;
  7370. var src = style.image;
  7371. // Must bind each time
  7372. style.bind(ctx, this, prevEl);
  7373. var image = this._image = createOrUpdateImage(
  7374. src,
  7375. this._image,
  7376. this,
  7377. this.onload
  7378. );
  7379. if (!image || !isImageReady(image)) {
  7380. return;
  7381. }
  7382. // 图片已经加载完成
  7383. // if (image.nodeName.toUpperCase() == 'IMG') {
  7384. // if (!image.complete) {
  7385. // return;
  7386. // }
  7387. // }
  7388. // Else is canvas
  7389. var x = style.x || 0;
  7390. var y = style.y || 0;
  7391. var width = style.width;
  7392. var height = style.height;
  7393. var aspect = image.width / image.height;
  7394. if (width == null && height != null) {
  7395. // Keep image/height ratio
  7396. width = height * aspect;
  7397. }
  7398. else if (height == null && width != null) {
  7399. height = width / aspect;
  7400. }
  7401. else if (width == null && height == null) {
  7402. width = image.width;
  7403. height = image.height;
  7404. }
  7405. // 设置transform
  7406. this.setTransform(ctx);
  7407. if (style.sWidth && style.sHeight) {
  7408. var sx = style.sx || 0;
  7409. var sy = style.sy || 0;
  7410. ctx.drawImage(
  7411. image,
  7412. sx, sy, style.sWidth, style.sHeight,
  7413. x, y, width, height
  7414. );
  7415. }
  7416. else if (style.sx && style.sy) {
  7417. var sx = style.sx;
  7418. var sy = style.sy;
  7419. var sWidth = width - sx;
  7420. var sHeight = height - sy;
  7421. ctx.drawImage(
  7422. image,
  7423. sx, sy, sWidth, sHeight,
  7424. x, y, width, height
  7425. );
  7426. }
  7427. else {
  7428. ctx.drawImage(image, x, y, width, height);
  7429. }
  7430. // Draw rect text
  7431. if (style.text != null) {
  7432. // Only restore transform when needs draw text.
  7433. this.restoreTransform(ctx);
  7434. this.drawRectText(ctx, this.getBoundingRect());
  7435. }
  7436. },
  7437. getBoundingRect: function () {
  7438. var style = this.style;
  7439. if (! this._rect) {
  7440. this._rect = new BoundingRect(
  7441. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7442. );
  7443. }
  7444. return this._rect;
  7445. }
  7446. };
  7447. inherits(ZImage, Displayable);
  7448. var HOVER_LAYER_ZLEVEL = 1e5;
  7449. var CANVAS_ZLEVEL = 314159;
  7450. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7451. var INCREMENTAL_INC = 0.001;
  7452. function parseInt10(val) {
  7453. return parseInt(val, 10);
  7454. }
  7455. function isLayerValid(layer) {
  7456. if (!layer) {
  7457. return false;
  7458. }
  7459. if (layer.__builtin__) {
  7460. return true;
  7461. }
  7462. if (typeof(layer.resize) !== 'function'
  7463. || typeof(layer.refresh) !== 'function'
  7464. ) {
  7465. return false;
  7466. }
  7467. return true;
  7468. }
  7469. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7470. var viewRect = new BoundingRect(0, 0, 0, 0);
  7471. function isDisplayableCulled(el, width, height) {
  7472. tmpRect.copy(el.getBoundingRect());
  7473. if (el.transform) {
  7474. tmpRect.applyTransform(el.transform);
  7475. }
  7476. viewRect.width = width;
  7477. viewRect.height = height;
  7478. return !tmpRect.intersect(viewRect);
  7479. }
  7480. function isClipPathChanged(clipPaths, prevClipPaths) {
  7481. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7482. return false;
  7483. }
  7484. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7485. return true;
  7486. }
  7487. for (var i = 0; i < clipPaths.length; i++) {
  7488. if (clipPaths[i] !== prevClipPaths[i]) {
  7489. return true;
  7490. }
  7491. }
  7492. }
  7493. function doClip(clipPaths, ctx) {
  7494. for (var i = 0; i < clipPaths.length; i++) {
  7495. var clipPath = clipPaths[i];
  7496. clipPath.setTransform(ctx);
  7497. ctx.beginPath();
  7498. clipPath.buildPath(ctx, clipPath.shape);
  7499. ctx.clip();
  7500. // Transform back
  7501. clipPath.restoreTransform(ctx);
  7502. }
  7503. }
  7504. function createRoot(width, height) {
  7505. var domRoot = document.createElement('div');
  7506. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7507. domRoot.style.cssText = [
  7508. 'position:relative',
  7509. 'overflow:hidden',
  7510. 'width:' + width + 'px',
  7511. 'height:' + height + 'px',
  7512. 'padding:0',
  7513. 'margin:0',
  7514. 'border-width:0'
  7515. ].join(';') + ';';
  7516. return domRoot;
  7517. }
  7518. /**
  7519. * @alias module:zrender/Painter
  7520. * @constructor
  7521. * @param {HTMLElement} root 绘图容器
  7522. * @param {module:zrender/Storage} storage
  7523. * @param {Object} opts
  7524. */
  7525. var Painter = function (root, storage, opts) {
  7526. this.type = 'canvas';
  7527. // In node environment using node-canvas
  7528. var singleCanvas = !root.nodeName // In node ?
  7529. || root.nodeName.toUpperCase() === 'CANVAS';
  7530. this._opts = opts = extend({}, opts || {});
  7531. /**
  7532. * @type {number}
  7533. */
  7534. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7535. /**
  7536. * @type {boolean}
  7537. * @private
  7538. */
  7539. this._singleCanvas = singleCanvas;
  7540. /**
  7541. * 绘图容器
  7542. * @type {HTMLElement}
  7543. */
  7544. this.root = root;
  7545. var rootStyle = root.style;
  7546. if (rootStyle) {
  7547. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7548. rootStyle['-webkit-user-select'] =
  7549. rootStyle['user-select'] =
  7550. rootStyle['-webkit-touch-callout'] = 'none';
  7551. root.innerHTML = '';
  7552. }
  7553. /**
  7554. * @type {module:zrender/Storage}
  7555. */
  7556. this.storage = storage;
  7557. /**
  7558. * @type {Array.<number>}
  7559. * @private
  7560. */
  7561. var zlevelList = this._zlevelList = [];
  7562. /**
  7563. * @type {Object.<string, module:zrender/Layer>}
  7564. * @private
  7565. */
  7566. var layers = this._layers = {};
  7567. /**
  7568. * @type {Object.<string, Object>}
  7569. * @private
  7570. */
  7571. this._layerConfig = {};
  7572. /**
  7573. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7574. */
  7575. this._needsManuallyCompositing = false;
  7576. if (!singleCanvas) {
  7577. this._width = this._getSize(0);
  7578. this._height = this._getSize(1);
  7579. var domRoot = this._domRoot = createRoot(
  7580. this._width, this._height
  7581. );
  7582. root.appendChild(domRoot);
  7583. }
  7584. else {
  7585. if (opts.width != null) {
  7586. root.width = opts.width;
  7587. }
  7588. if (opts.height != null) {
  7589. root.height = opts.height;
  7590. }
  7591. // Use canvas width and height directly
  7592. var width = root.width;
  7593. var height = root.height;
  7594. this._width = width;
  7595. this._height = height;
  7596. // Create layer if only one given canvas
  7597. // Device pixel ratio is fixed to 1 because given canvas has its specified width and height
  7598. var mainLayer = new Layer(root, this, 1);
  7599. mainLayer.__builtin__ = true;
  7600. mainLayer.initContext();
  7601. // FIXME Use canvas width and height
  7602. // mainLayer.resize(width, height);
  7603. layers[CANVAS_ZLEVEL] = mainLayer;
  7604. // Not use common zlevel.
  7605. zlevelList.push(CANVAS_ZLEVEL);
  7606. this._domRoot = root;
  7607. }
  7608. /**
  7609. * @type {module:zrender/Layer}
  7610. * @private
  7611. */
  7612. this._hoverlayer = null;
  7613. this._hoverElements = [];
  7614. };
  7615. Painter.prototype = {
  7616. constructor: Painter,
  7617. getType: function () {
  7618. return 'canvas';
  7619. },
  7620. /**
  7621. * If painter use a single canvas
  7622. * @return {boolean}
  7623. */
  7624. isSingleCanvas: function () {
  7625. return this._singleCanvas;
  7626. },
  7627. /**
  7628. * @return {HTMLDivElement}
  7629. */
  7630. getViewportRoot: function () {
  7631. return this._domRoot;
  7632. },
  7633. getViewportRootOffset: function () {
  7634. var viewportRoot = this.getViewportRoot();
  7635. if (viewportRoot) {
  7636. return {
  7637. offsetLeft: viewportRoot.offsetLeft || 0,
  7638. offsetTop: viewportRoot.offsetTop || 0
  7639. };
  7640. }
  7641. },
  7642. /**
  7643. * 刷新
  7644. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7645. */
  7646. refresh: function (paintAll) {
  7647. var list = this.storage.getDisplayList(true);
  7648. var zlevelList = this._zlevelList;
  7649. this._redrawId = Math.random();
  7650. this._paintList(list, paintAll, this._redrawId);
  7651. // Paint custum layers
  7652. for (var i = 0; i < zlevelList.length; i++) {
  7653. var z = zlevelList[i];
  7654. var layer = this._layers[z];
  7655. if (!layer.__builtin__ && layer.refresh) {
  7656. layer.refresh();
  7657. }
  7658. }
  7659. this.refreshHover();
  7660. return this;
  7661. },
  7662. addHover: function (el, hoverStyle) {
  7663. if (el.__hoverMir) {
  7664. return;
  7665. }
  7666. var elMirror = new el.constructor({
  7667. style: el.style,
  7668. shape: el.shape
  7669. });
  7670. elMirror.__from = el;
  7671. el.__hoverMir = elMirror;
  7672. elMirror.setStyle(hoverStyle);
  7673. this._hoverElements.push(elMirror);
  7674. },
  7675. removeHover: function (el) {
  7676. var elMirror = el.__hoverMir;
  7677. var hoverElements = this._hoverElements;
  7678. var idx = indexOf(hoverElements, elMirror);
  7679. if (idx >= 0) {
  7680. hoverElements.splice(idx, 1);
  7681. }
  7682. el.__hoverMir = null;
  7683. },
  7684. clearHover: function (el) {
  7685. var hoverElements = this._hoverElements;
  7686. for (var i = 0; i < hoverElements.length; i++) {
  7687. var from = hoverElements[i].__from;
  7688. if (from) {
  7689. from.__hoverMir = null;
  7690. }
  7691. }
  7692. hoverElements.length = 0;
  7693. },
  7694. refreshHover: function () {
  7695. var hoverElements = this._hoverElements;
  7696. var len = hoverElements.length;
  7697. var hoverLayer = this._hoverlayer;
  7698. hoverLayer && hoverLayer.clear();
  7699. if (!len) {
  7700. return;
  7701. }
  7702. sort(hoverElements, this.storage.displayableSortFunc);
  7703. // Use a extream large zlevel
  7704. // FIXME?
  7705. if (!hoverLayer) {
  7706. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7707. }
  7708. var scope = {};
  7709. hoverLayer.ctx.save();
  7710. for (var i = 0; i < len;) {
  7711. var el = hoverElements[i];
  7712. var originalEl = el.__from;
  7713. // Original el is removed
  7714. // PENDING
  7715. if (!(originalEl && originalEl.__zr)) {
  7716. hoverElements.splice(i, 1);
  7717. originalEl.__hoverMir = null;
  7718. len--;
  7719. continue;
  7720. }
  7721. i++;
  7722. // Use transform
  7723. // FIXME style and shape ?
  7724. if (!originalEl.invisible) {
  7725. el.transform = originalEl.transform;
  7726. el.invTransform = originalEl.invTransform;
  7727. el.__clipPaths = originalEl.__clipPaths;
  7728. // el.
  7729. this._doPaintEl(el, hoverLayer, true, scope);
  7730. }
  7731. }
  7732. hoverLayer.ctx.restore();
  7733. },
  7734. getHoverLayer: function () {
  7735. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7736. },
  7737. _paintList: function (list, paintAll, redrawId) {
  7738. if (this._redrawId !== redrawId) {
  7739. return;
  7740. }
  7741. paintAll = paintAll || false;
  7742. this._updateLayerStatus(list);
  7743. var finished = this._doPaintList(list, paintAll);
  7744. if (this._needsManuallyCompositing) {
  7745. this._compositeManually();
  7746. }
  7747. if (!finished) {
  7748. var self = this;
  7749. requestAnimationFrame(function () {
  7750. self._paintList(list, paintAll, redrawId);
  7751. });
  7752. }
  7753. },
  7754. _compositeManually: function () {
  7755. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7756. var width = this._domRoot.width;
  7757. var height = this._domRoot.height;
  7758. ctx.clearRect(0, 0, width, height);
  7759. // PENDING, If only builtin layer?
  7760. this.eachBuiltinLayer(function (layer) {
  7761. if (layer.virtual) {
  7762. ctx.drawImage(layer.dom, 0, 0, width, height);
  7763. }
  7764. });
  7765. },
  7766. _doPaintList: function (list, paintAll) {
  7767. var layerList = [];
  7768. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7769. var zlevel = this._zlevelList[zi];
  7770. var layer = this._layers[zlevel];
  7771. if (layer.__builtin__
  7772. && layer !== this._hoverlayer
  7773. && (layer.__dirty || paintAll)
  7774. ) {
  7775. layerList.push(layer);
  7776. }
  7777. }
  7778. var finished = true;
  7779. for (var k = 0; k < layerList.length; k++) {
  7780. var layer = layerList[k];
  7781. var ctx = layer.ctx;
  7782. var scope = {};
  7783. ctx.save();
  7784. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7785. var useTimer = !paintAll && layer.incremental && Date.now;
  7786. var startTime = useTimer && Date.now();
  7787. // All elements in this layer are cleared.
  7788. if (layer.__startIndex === layer.__endIndex) {
  7789. layer.clear();
  7790. }
  7791. else if (start === layer.__startIndex) {
  7792. var firstEl = list[start];
  7793. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7794. layer.clear();
  7795. }
  7796. }
  7797. if (start === -1) {
  7798. console.error('For some unknown reason. drawIndex is -1');
  7799. start = layer.__startIndex;
  7800. }
  7801. for (var i = start; i < layer.__endIndex; i++) {
  7802. var el = list[i];
  7803. this._doPaintEl(el, layer, paintAll, scope);
  7804. el.__dirty = false;
  7805. if (useTimer) {
  7806. // Date.now can be executed in 13,025,305 ops/second.
  7807. var dTime = Date.now() - startTime;
  7808. // Give 15 millisecond to draw.
  7809. // The rest elements will be drawn in the next frame.
  7810. if (dTime > 15) {
  7811. break;
  7812. }
  7813. }
  7814. }
  7815. layer.__drawIndex = i;
  7816. if (layer.__drawIndex < layer.__endIndex) {
  7817. finished = false;
  7818. }
  7819. if (scope.prevElClipPaths) {
  7820. // Needs restore the state. If last drawn element is in the clipping area.
  7821. ctx.restore();
  7822. }
  7823. ctx.restore();
  7824. }
  7825. if (env$1.wxa) {
  7826. // Flush for weixin application
  7827. each$1(this._layers, function (layer) {
  7828. if (layer && layer.ctx && layer.ctx.draw) {
  7829. layer.ctx.draw();
  7830. }
  7831. });
  7832. }
  7833. return finished;
  7834. },
  7835. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7836. var ctx = currentLayer.ctx;
  7837. var m = el.transform;
  7838. if (
  7839. (currentLayer.__dirty || forcePaint)
  7840. // Ignore invisible element
  7841. && !el.invisible
  7842. // Ignore transparent element
  7843. && el.style.opacity !== 0
  7844. // Ignore scale 0 element, in some environment like node-canvas
  7845. // Draw a scale 0 element can cause all following draw wrong
  7846. // And setTransform with scale 0 will cause set back transform failed.
  7847. && !(m && !m[0] && !m[3])
  7848. // Ignore culled element
  7849. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7850. ) {
  7851. var clipPaths = el.__clipPaths;
  7852. // Optimize when clipping on group with several elements
  7853. if (!scope.prevElClipPaths
  7854. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7855. ) {
  7856. // If has previous clipping state, restore from it
  7857. if (scope.prevElClipPaths) {
  7858. currentLayer.ctx.restore();
  7859. scope.prevElClipPaths = null;
  7860. // Reset prevEl since context has been restored
  7861. scope.prevEl = null;
  7862. }
  7863. // New clipping state
  7864. if (clipPaths) {
  7865. ctx.save();
  7866. doClip(clipPaths, ctx);
  7867. scope.prevElClipPaths = clipPaths;
  7868. }
  7869. }
  7870. el.beforeBrush && el.beforeBrush(ctx);
  7871. el.brush(ctx, scope.prevEl || null);
  7872. scope.prevEl = el;
  7873. el.afterBrush && el.afterBrush(ctx);
  7874. }
  7875. },
  7876. /**
  7877. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7878. * @param {number} zlevel
  7879. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7880. * @return {module:zrender/Layer}
  7881. */
  7882. getLayer: function (zlevel, virtual) {
  7883. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7884. zlevel = CANVAS_ZLEVEL;
  7885. }
  7886. var layer = this._layers[zlevel];
  7887. if (!layer) {
  7888. // Create a new layer
  7889. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7890. layer.zlevel = zlevel;
  7891. layer.__builtin__ = true;
  7892. if (this._layerConfig[zlevel]) {
  7893. merge(layer, this._layerConfig[zlevel], true);
  7894. }
  7895. if (virtual) {
  7896. layer.virtual = virtual;
  7897. }
  7898. this.insertLayer(zlevel, layer);
  7899. // Context is created after dom inserted to document
  7900. // Or excanvas will get 0px clientWidth and clientHeight
  7901. layer.initContext();
  7902. }
  7903. return layer;
  7904. },
  7905. insertLayer: function (zlevel, layer) {
  7906. var layersMap = this._layers;
  7907. var zlevelList = this._zlevelList;
  7908. var len = zlevelList.length;
  7909. var prevLayer = null;
  7910. var i = -1;
  7911. var domRoot = this._domRoot;
  7912. if (layersMap[zlevel]) {
  7913. zrLog('ZLevel ' + zlevel + ' has been used already');
  7914. return;
  7915. }
  7916. // Check if is a valid layer
  7917. if (!isLayerValid(layer)) {
  7918. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7919. return;
  7920. }
  7921. if (len > 0 && zlevel > zlevelList[0]) {
  7922. for (i = 0; i < len - 1; i++) {
  7923. if (
  7924. zlevelList[i] < zlevel
  7925. && zlevelList[i + 1] > zlevel
  7926. ) {
  7927. break;
  7928. }
  7929. }
  7930. prevLayer = layersMap[zlevelList[i]];
  7931. }
  7932. zlevelList.splice(i + 1, 0, zlevel);
  7933. layersMap[zlevel] = layer;
  7934. // Vitual layer will not directly show on the screen.
  7935. // (It can be a WebGL layer and assigned to a ZImage element)
  7936. // But it still under management of zrender.
  7937. if (!layer.virtual) {
  7938. if (prevLayer) {
  7939. var prevDom = prevLayer.dom;
  7940. if (prevDom.nextSibling) {
  7941. domRoot.insertBefore(
  7942. layer.dom,
  7943. prevDom.nextSibling
  7944. );
  7945. }
  7946. else {
  7947. domRoot.appendChild(layer.dom);
  7948. }
  7949. }
  7950. else {
  7951. if (domRoot.firstChild) {
  7952. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7953. }
  7954. else {
  7955. domRoot.appendChild(layer.dom);
  7956. }
  7957. }
  7958. }
  7959. },
  7960. // Iterate each layer
  7961. eachLayer: function (cb, context) {
  7962. var zlevelList = this._zlevelList;
  7963. var z;
  7964. var i;
  7965. for (i = 0; i < zlevelList.length; i++) {
  7966. z = zlevelList[i];
  7967. cb.call(context, this._layers[z], z);
  7968. }
  7969. },
  7970. // Iterate each buildin layer
  7971. eachBuiltinLayer: function (cb, context) {
  7972. var zlevelList = this._zlevelList;
  7973. var layer;
  7974. var z;
  7975. var i;
  7976. for (i = 0; i < zlevelList.length; i++) {
  7977. z = zlevelList[i];
  7978. layer = this._layers[z];
  7979. if (layer.__builtin__) {
  7980. cb.call(context, layer, z);
  7981. }
  7982. }
  7983. },
  7984. // Iterate each other layer except buildin layer
  7985. eachOtherLayer: function (cb, context) {
  7986. var zlevelList = this._zlevelList;
  7987. var layer;
  7988. var z;
  7989. var i;
  7990. for (i = 0; i < zlevelList.length; i++) {
  7991. z = zlevelList[i];
  7992. layer = this._layers[z];
  7993. if (!layer.__builtin__) {
  7994. cb.call(context, layer, z);
  7995. }
  7996. }
  7997. },
  7998. /**
  7999. * 获取所有已创建的层
  8000. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8001. */
  8002. getLayers: function () {
  8003. return this._layers;
  8004. },
  8005. _updateLayerStatus: function (list) {
  8006. this.eachBuiltinLayer(function (layer, z) {
  8007. layer.__dirty = layer.__used = false;
  8008. });
  8009. function updatePrevLayer(idx) {
  8010. if (prevLayer) {
  8011. if (prevLayer.__endIndex !== idx) {
  8012. prevLayer.__dirty = true;
  8013. }
  8014. prevLayer.__endIndex = idx;
  8015. }
  8016. }
  8017. if (this._singleCanvas) {
  8018. for (var i = 1; i < list.length; i++) {
  8019. var el = list[i];
  8020. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8021. this._needsManuallyCompositing = true;
  8022. break;
  8023. }
  8024. }
  8025. }
  8026. var prevLayer = null;
  8027. var incrementalLayerCount = 0;
  8028. for (var i = 0; i < list.length; i++) {
  8029. var el = list[i];
  8030. var zlevel = el.zlevel;
  8031. var layer;
  8032. // PENDING If change one incremental element style ?
  8033. // TODO Where there are non-incremental elements between incremental elements.
  8034. if (el.incremental) {
  8035. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8036. layer.incremental = true;
  8037. incrementalLayerCount = 1;
  8038. }
  8039. else {
  8040. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8041. }
  8042. if (!layer.__builtin__) {
  8043. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8044. }
  8045. if (layer !== prevLayer) {
  8046. layer.__used = true;
  8047. if (layer.__startIndex !== i) {
  8048. layer.__dirty = true;
  8049. }
  8050. layer.__startIndex = i;
  8051. if (!layer.incremental) {
  8052. layer.__drawIndex = i;
  8053. }
  8054. else {
  8055. // Mark layer draw index needs to update.
  8056. layer.__drawIndex = -1;
  8057. }
  8058. updatePrevLayer(i);
  8059. prevLayer = layer;
  8060. }
  8061. if (el.__dirty) {
  8062. layer.__dirty = true;
  8063. if (layer.incremental && layer.__drawIndex < 0) {
  8064. // Start draw from the first dirty element.
  8065. layer.__drawIndex = i;
  8066. }
  8067. }
  8068. }
  8069. updatePrevLayer(i);
  8070. this.eachBuiltinLayer(function (layer, z) {
  8071. // Used in last frame but not in this frame. Needs clear
  8072. if (!layer.__used && layer.getElementCount() > 0) {
  8073. layer.__dirty = true;
  8074. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8075. }
  8076. // For incremental layer. In case start index changed and no elements are dirty.
  8077. if (layer.__dirty && layer.__drawIndex < 0) {
  8078. layer.__drawIndex = layer.__startIndex;
  8079. }
  8080. });
  8081. },
  8082. /**
  8083. * 清除hover层外所有内容
  8084. */
  8085. clear: function () {
  8086. this.eachBuiltinLayer(this._clearLayer);
  8087. return this;
  8088. },
  8089. _clearLayer: function (layer) {
  8090. layer.clear();
  8091. },
  8092. /**
  8093. * 修改指定zlevel的绘制参数
  8094. *
  8095. * @param {string} zlevel
  8096. * @param {Object} config 配置对象
  8097. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8098. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8099. * @param {number} [config.lastFrameAlpha=0.7]
  8100. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8101. */
  8102. configLayer: function (zlevel, config) {
  8103. if (config) {
  8104. var layerConfig = this._layerConfig;
  8105. if (!layerConfig[zlevel]) {
  8106. layerConfig[zlevel] = config;
  8107. }
  8108. else {
  8109. merge(layerConfig[zlevel], config, true);
  8110. }
  8111. for (var i = 0; i < this._zlevelList.length; i++) {
  8112. var _zlevel = this._zlevelList[i];
  8113. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8114. var layer = this._layers[_zlevel];
  8115. merge(layer, layerConfig[zlevel], true);
  8116. }
  8117. }
  8118. }
  8119. },
  8120. /**
  8121. * 删除指定层
  8122. * @param {number} zlevel 层所在的zlevel
  8123. */
  8124. delLayer: function (zlevel) {
  8125. var layers = this._layers;
  8126. var zlevelList = this._zlevelList;
  8127. var layer = layers[zlevel];
  8128. if (!layer) {
  8129. return;
  8130. }
  8131. layer.dom.parentNode.removeChild(layer.dom);
  8132. delete layers[zlevel];
  8133. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8134. },
  8135. /**
  8136. * 区域大小变化后重绘
  8137. */
  8138. resize: function (width, height) {
  8139. if (!this._domRoot.style) { // Maybe in node or worker
  8140. if (width == null || height == null) {
  8141. return;
  8142. }
  8143. this._width = width;
  8144. this._height = height;
  8145. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8146. }
  8147. else {
  8148. var domRoot = this._domRoot;
  8149. // FIXME Why ?
  8150. domRoot.style.display = 'none';
  8151. // Save input w/h
  8152. var opts = this._opts;
  8153. width != null && (opts.width = width);
  8154. height != null && (opts.height = height);
  8155. width = this._getSize(0);
  8156. height = this._getSize(1);
  8157. domRoot.style.display = '';
  8158. // 优化没有实际改变的resize
  8159. if (this._width != width || height != this._height) {
  8160. domRoot.style.width = width + 'px';
  8161. domRoot.style.height = height + 'px';
  8162. for (var id in this._layers) {
  8163. if (this._layers.hasOwnProperty(id)) {
  8164. this._layers[id].resize(width, height);
  8165. }
  8166. }
  8167. each$1(this._progressiveLayers, function (layer) {
  8168. layer.resize(width, height);
  8169. });
  8170. this.refresh(true);
  8171. }
  8172. this._width = width;
  8173. this._height = height;
  8174. }
  8175. return this;
  8176. },
  8177. /**
  8178. * 清除单独的一个层
  8179. * @param {number} zlevel
  8180. */
  8181. clearLayer: function (zlevel) {
  8182. var layer = this._layers[zlevel];
  8183. if (layer) {
  8184. layer.clear();
  8185. }
  8186. },
  8187. /**
  8188. * 释放
  8189. */
  8190. dispose: function () {
  8191. this.root.innerHTML = '';
  8192. this.root =
  8193. this.storage =
  8194. this._domRoot =
  8195. this._layers = null;
  8196. },
  8197. /**
  8198. * Get canvas which has all thing rendered
  8199. * @param {Object} opts
  8200. * @param {string} [opts.backgroundColor]
  8201. * @param {number} [opts.pixelRatio]
  8202. */
  8203. getRenderedCanvas: function (opts) {
  8204. opts = opts || {};
  8205. if (this._singleCanvas && !this._compositeManually) {
  8206. return this._layers[CANVAS_ZLEVEL].dom;
  8207. }
  8208. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8209. imageLayer.initContext();
  8210. imageLayer.clearColor = opts.backgroundColor;
  8211. imageLayer.clear();
  8212. if (opts.pixelRatio <= this.dpr) {
  8213. this.refresh();
  8214. var width = imageLayer.dom.width;
  8215. var height = imageLayer.dom.height;
  8216. var ctx = imageLayer.ctx;
  8217. this.eachLayer(function (layer) {
  8218. if (layer.__builtin__) {
  8219. ctx.drawImage(layer.dom, 0, 0, width, height);
  8220. }
  8221. else if (layer.renderToCanvas) {
  8222. imageLayer.ctx.save();
  8223. layer.renderToCanvas(imageLayer.ctx);
  8224. imageLayer.ctx.restore();
  8225. }
  8226. });
  8227. }
  8228. else {
  8229. // PENDING, echarts-gl and incremental rendering.
  8230. var scope = {};
  8231. var displayList = this.storage.getDisplayList(true);
  8232. for (var i = 0; i < displayList.length; i++) {
  8233. var el = displayList[i];
  8234. this._doPaintEl(el, imageLayer, true, scope);
  8235. }
  8236. }
  8237. return imageLayer.dom;
  8238. },
  8239. /**
  8240. * 获取绘图区域宽度
  8241. */
  8242. getWidth: function () {
  8243. return this._width;
  8244. },
  8245. /**
  8246. * 获取绘图区域高度
  8247. */
  8248. getHeight: function () {
  8249. return this._height;
  8250. },
  8251. _getSize: function (whIdx) {
  8252. var opts = this._opts;
  8253. var wh = ['width', 'height'][whIdx];
  8254. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8255. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8256. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8257. if (opts[wh] != null && opts[wh] !== 'auto') {
  8258. return parseFloat(opts[wh]);
  8259. }
  8260. var root = this.root;
  8261. // IE8 does not support getComputedStyle, but it use VML.
  8262. var stl = document.defaultView.getComputedStyle(root);
  8263. return (
  8264. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8265. - (parseInt10(stl[plt]) || 0)
  8266. - (parseInt10(stl[prb]) || 0)
  8267. ) | 0;
  8268. },
  8269. pathToImage: function (path, dpr) {
  8270. dpr = dpr || this.dpr;
  8271. var canvas = document.createElement('canvas');
  8272. var ctx = canvas.getContext('2d');
  8273. var rect = path.getBoundingRect();
  8274. var style = path.style;
  8275. var shadowBlurSize = style.shadowBlur * dpr;
  8276. var shadowOffsetX = style.shadowOffsetX * dpr;
  8277. var shadowOffsetY = style.shadowOffsetY * dpr;
  8278. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8279. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8280. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8281. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8282. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8283. var width = rect.width + leftMargin + rightMargin;
  8284. var height = rect.height + topMargin + bottomMargin;
  8285. canvas.width = width * dpr;
  8286. canvas.height = height * dpr;
  8287. ctx.scale(dpr, dpr);
  8288. ctx.clearRect(0, 0, width, height);
  8289. ctx.dpr = dpr;
  8290. var pathTransform = {
  8291. position: path.position,
  8292. rotation: path.rotation,
  8293. scale: path.scale
  8294. };
  8295. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8296. path.rotation = 0;
  8297. path.scale = [1, 1];
  8298. path.updateTransform();
  8299. if (path) {
  8300. path.brush(ctx);
  8301. }
  8302. var ImageShape = ZImage;
  8303. var imgShape = new ImageShape({
  8304. style: {
  8305. x: 0,
  8306. y: 0,
  8307. image: canvas
  8308. }
  8309. });
  8310. if (pathTransform.position != null) {
  8311. imgShape.position = path.position = pathTransform.position;
  8312. }
  8313. if (pathTransform.rotation != null) {
  8314. imgShape.rotation = path.rotation = pathTransform.rotation;
  8315. }
  8316. if (pathTransform.scale != null) {
  8317. imgShape.scale = path.scale = pathTransform.scale;
  8318. }
  8319. return imgShape;
  8320. }
  8321. };
  8322. /**
  8323. * 事件辅助类
  8324. * @module zrender/core/event
  8325. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8326. */
  8327. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8328. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8329. function getBoundingClientRect(el) {
  8330. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8331. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8332. }
  8333. // `calculate` is optional, default false
  8334. function clientToLocal(el, e, out, calculate) {
  8335. out = out || {};
  8336. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8337. // to the padding edge of the target element. The only browser using this convention
  8338. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8339. // not support the properties.
  8340. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8341. // In zr painter.dom, padding edge equals to border edge.
  8342. // FIXME
  8343. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8344. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8345. // is too complex. So css-transfrom dont support in this case temporarily.
  8346. if (calculate || !env$1.canvasSupported) {
  8347. defaultGetZrXY(el, e, out);
  8348. }
  8349. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8350. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8351. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8352. // zoom-factor, overflow / opacity layers, transforms ...)
  8353. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8354. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8355. // BTW3, In ff, offsetX/offsetY is always 0.
  8356. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8357. out.zrX = e.layerX;
  8358. out.zrY = e.layerY;
  8359. }
  8360. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8361. else if (e.offsetX != null) {
  8362. out.zrX = e.offsetX;
  8363. out.zrY = e.offsetY;
  8364. }
  8365. // For some other device, e.g., IOS safari.
  8366. else {
  8367. defaultGetZrXY(el, e, out);
  8368. }
  8369. return out;
  8370. }
  8371. function defaultGetZrXY(el, e, out) {
  8372. // This well-known method below does not support css transform.
  8373. var box = getBoundingClientRect(el);
  8374. out.zrX = e.clientX - box.left;
  8375. out.zrY = e.clientY - box.top;
  8376. }
  8377. /**
  8378. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8379. * `calculate` is optional, default false.
  8380. */
  8381. function normalizeEvent(el, e, calculate) {
  8382. e = e || window.event;
  8383. if (e.zrX != null) {
  8384. return e;
  8385. }
  8386. var eventType = e.type;
  8387. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8388. if (!isTouch) {
  8389. clientToLocal(el, e, e, calculate);
  8390. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8391. }
  8392. else {
  8393. var touch = eventType != 'touchend'
  8394. ? e.targetTouches[0]
  8395. : e.changedTouches[0];
  8396. touch && clientToLocal(el, touch, e, calculate);
  8397. }
  8398. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8399. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8400. // If e.which has been defined, if may be readonly,
  8401. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8402. var button = e.button;
  8403. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8404. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8405. }
  8406. return e;
  8407. }
  8408. function addEventListener(el, name, handler) {
  8409. if (isDomLevel2) {
  8410. el.addEventListener(name, handler);
  8411. }
  8412. else {
  8413. el.attachEvent('on' + name, handler);
  8414. }
  8415. }
  8416. function removeEventListener(el, name, handler) {
  8417. if (isDomLevel2) {
  8418. el.removeEventListener(name, handler);
  8419. }
  8420. else {
  8421. el.detachEvent('on' + name, handler);
  8422. }
  8423. }
  8424. /**
  8425. * preventDefault and stopPropagation.
  8426. * Notice: do not do that in zrender. Upper application
  8427. * do that if necessary.
  8428. *
  8429. * @memberOf module:zrender/core/event
  8430. * @method
  8431. * @param {Event} e : event对象
  8432. */
  8433. var stop = isDomLevel2
  8434. ? function (e) {
  8435. e.preventDefault();
  8436. e.stopPropagation();
  8437. e.cancelBubble = true;
  8438. }
  8439. : function (e) {
  8440. e.returnValue = false;
  8441. e.cancelBubble = true;
  8442. };
  8443. function notLeftMouse(e) {
  8444. // If e.which is undefined, considered as left mouse event.
  8445. return e.which > 1;
  8446. }
  8447. /**
  8448. * 动画主类, 调度和管理所有动画控制器
  8449. *
  8450. * @module zrender/animation/Animation
  8451. * @author pissang(https://github.com/pissang)
  8452. */
  8453. // TODO Additive animation
  8454. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8455. // https://developer.apple.com/videos/wwdc2014/#236
  8456. /**
  8457. * @typedef {Object} IZRenderStage
  8458. * @property {Function} update
  8459. */
  8460. /**
  8461. * @alias module:zrender/animation/Animation
  8462. * @constructor
  8463. * @param {Object} [options]
  8464. * @param {Function} [options.onframe]
  8465. * @param {IZRenderStage} [options.stage]
  8466. * @example
  8467. * var animation = new Animation();
  8468. * var obj = {
  8469. * x: 100,
  8470. * y: 100
  8471. * };
  8472. * animation.animate(node.position)
  8473. * .when(1000, {
  8474. * x: 500,
  8475. * y: 500
  8476. * })
  8477. * .when(2000, {
  8478. * x: 100,
  8479. * y: 100
  8480. * })
  8481. * .start('spline');
  8482. */
  8483. var Animation = function (options) {
  8484. options = options || {};
  8485. this.stage = options.stage || {};
  8486. this.onframe = options.onframe || function() {};
  8487. // private properties
  8488. this._clips = [];
  8489. this._running = false;
  8490. this._time;
  8491. this._pausedTime;
  8492. this._pauseStart;
  8493. this._paused = false;
  8494. Eventful.call(this);
  8495. };
  8496. Animation.prototype = {
  8497. constructor: Animation,
  8498. /**
  8499. * 添加 clip
  8500. * @param {module:zrender/animation/Clip} clip
  8501. */
  8502. addClip: function (clip) {
  8503. this._clips.push(clip);
  8504. },
  8505. /**
  8506. * 添加 animator
  8507. * @param {module:zrender/animation/Animator} animator
  8508. */
  8509. addAnimator: function (animator) {
  8510. animator.animation = this;
  8511. var clips = animator.getClips();
  8512. for (var i = 0; i < clips.length; i++) {
  8513. this.addClip(clips[i]);
  8514. }
  8515. },
  8516. /**
  8517. * 删除动画片段
  8518. * @param {module:zrender/animation/Clip} clip
  8519. */
  8520. removeClip: function(clip) {
  8521. var idx = indexOf(this._clips, clip);
  8522. if (idx >= 0) {
  8523. this._clips.splice(idx, 1);
  8524. }
  8525. },
  8526. /**
  8527. * 删除动画片段
  8528. * @param {module:zrender/animation/Animator} animator
  8529. */
  8530. removeAnimator: function (animator) {
  8531. var clips = animator.getClips();
  8532. for (var i = 0; i < clips.length; i++) {
  8533. this.removeClip(clips[i]);
  8534. }
  8535. animator.animation = null;
  8536. },
  8537. _update: function() {
  8538. var time = new Date().getTime() - this._pausedTime;
  8539. var delta = time - this._time;
  8540. var clips = this._clips;
  8541. var len = clips.length;
  8542. var deferredEvents = [];
  8543. var deferredClips = [];
  8544. for (var i = 0; i < len; i++) {
  8545. var clip = clips[i];
  8546. var e = clip.step(time, delta);
  8547. // Throw out the events need to be called after
  8548. // stage.update, like destroy
  8549. if (e) {
  8550. deferredEvents.push(e);
  8551. deferredClips.push(clip);
  8552. }
  8553. }
  8554. // Remove the finished clip
  8555. for (var i = 0; i < len;) {
  8556. if (clips[i]._needsRemove) {
  8557. clips[i] = clips[len - 1];
  8558. clips.pop();
  8559. len--;
  8560. }
  8561. else {
  8562. i++;
  8563. }
  8564. }
  8565. len = deferredEvents.length;
  8566. for (var i = 0; i < len; i++) {
  8567. deferredClips[i].fire(deferredEvents[i]);
  8568. }
  8569. this._time = time;
  8570. this.onframe(delta);
  8571. // Frame should before stage update. Upper application
  8572. // depends on the sequence (e.g., echarts-stream)
  8573. this.trigger('frame', delta);
  8574. if (this.stage.update) {
  8575. this.stage.update();
  8576. }
  8577. },
  8578. _startLoop: function () {
  8579. var self = this;
  8580. this._running = true;
  8581. function step() {
  8582. if (self._running) {
  8583. requestAnimationFrame(step);
  8584. !self._paused && self._update();
  8585. }
  8586. }
  8587. requestAnimationFrame(step);
  8588. },
  8589. /**
  8590. * 开始运行动画
  8591. */
  8592. start: function () {
  8593. this._time = new Date().getTime();
  8594. this._pausedTime = 0;
  8595. this._startLoop();
  8596. },
  8597. /**
  8598. * 停止运行动画
  8599. */
  8600. stop: function () {
  8601. this._running = false;
  8602. },
  8603. /**
  8604. * Pause
  8605. */
  8606. pause: function () {
  8607. if (!this._paused) {
  8608. this._pauseStart = new Date().getTime();
  8609. this._paused = true;
  8610. }
  8611. },
  8612. /**
  8613. * Resume
  8614. */
  8615. resume: function () {
  8616. if (this._paused) {
  8617. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8618. this._paused = false;
  8619. }
  8620. },
  8621. /**
  8622. * 清除所有动画片段
  8623. */
  8624. clear: function () {
  8625. this._clips = [];
  8626. },
  8627. /**
  8628. * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画
  8629. * @param {Object} target
  8630. * @param {Object} options
  8631. * @param {boolean} [options.loop=false] 是否循环播放动画
  8632. * @param {Function} [options.getter=null]
  8633. * 如果指定getter函数,会通过getter函数取属性值
  8634. * @param {Function} [options.setter=null]
  8635. * 如果指定setter函数,会通过setter函数设置属性值
  8636. * @return {module:zrender/animation/Animation~Animator}
  8637. */
  8638. // TODO Gap
  8639. animate: function (target, options) {
  8640. options = options || {};
  8641. var animator = new Animator(
  8642. target,
  8643. options.loop,
  8644. options.getter,
  8645. options.setter
  8646. );
  8647. this.addAnimator(animator);
  8648. return animator;
  8649. }
  8650. };
  8651. mixin(Animation, Eventful);
  8652. /**
  8653. * Only implements needed gestures for mobile.
  8654. */
  8655. var GestureMgr = function () {
  8656. /**
  8657. * @private
  8658. * @type {Array.<Object>}
  8659. */
  8660. this._track = [];
  8661. };
  8662. GestureMgr.prototype = {
  8663. constructor: GestureMgr,
  8664. recognize: function (event, target, root) {
  8665. this._doTrack(event, target, root);
  8666. return this._recognize(event);
  8667. },
  8668. clear: function () {
  8669. this._track.length = 0;
  8670. return this;
  8671. },
  8672. _doTrack: function (event, target, root) {
  8673. var touches = event.touches;
  8674. if (!touches) {
  8675. return;
  8676. }
  8677. var trackItem = {
  8678. points: [],
  8679. touches: [],
  8680. target: target,
  8681. event: event
  8682. };
  8683. for (var i = 0, len = touches.length; i < len; i++) {
  8684. var touch = touches[i];
  8685. var pos = clientToLocal(root, touch, {});
  8686. trackItem.points.push([pos.zrX, pos.zrY]);
  8687. trackItem.touches.push(touch);
  8688. }
  8689. this._track.push(trackItem);
  8690. },
  8691. _recognize: function (event) {
  8692. for (var eventName in recognizers) {
  8693. if (recognizers.hasOwnProperty(eventName)) {
  8694. var gestureInfo = recognizers[eventName](this._track, event);
  8695. if (gestureInfo) {
  8696. return gestureInfo;
  8697. }
  8698. }
  8699. }
  8700. }
  8701. };
  8702. function dist$1(pointPair) {
  8703. var dx = pointPair[1][0] - pointPair[0][0];
  8704. var dy = pointPair[1][1] - pointPair[0][1];
  8705. return Math.sqrt(dx * dx + dy * dy);
  8706. }
  8707. function center(pointPair) {
  8708. return [
  8709. (pointPair[0][0] + pointPair[1][0]) / 2,
  8710. (pointPair[0][1] + pointPair[1][1]) / 2
  8711. ];
  8712. }
  8713. var recognizers = {
  8714. pinch: function (track, event) {
  8715. var trackLen = track.length;
  8716. if (!trackLen) {
  8717. return;
  8718. }
  8719. var pinchEnd = (track[trackLen - 1] || {}).points;
  8720. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8721. if (pinchPre
  8722. && pinchPre.length > 1
  8723. && pinchEnd
  8724. && pinchEnd.length > 1
  8725. ) {
  8726. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8727. !isFinite(pinchScale) && (pinchScale = 1);
  8728. event.pinchScale = pinchScale;
  8729. var pinchCenter = center(pinchEnd);
  8730. event.pinchX = pinchCenter[0];
  8731. event.pinchY = pinchCenter[1];
  8732. return {
  8733. type: 'pinch',
  8734. target: track[0].target,
  8735. event: event
  8736. };
  8737. }
  8738. }
  8739. // Only pinch currently.
  8740. };
  8741. var TOUCH_CLICK_DELAY = 300;
  8742. var mouseHandlerNames = [
  8743. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8744. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8745. ];
  8746. var touchHandlerNames = [
  8747. 'touchstart', 'touchend', 'touchmove'
  8748. ];
  8749. var pointerEventNames = {
  8750. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8751. };
  8752. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8753. var nm = name.replace('mouse', 'pointer');
  8754. return pointerEventNames[nm] ? nm : name;
  8755. });
  8756. function eventNameFix(name) {
  8757. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8758. }
  8759. function processGesture(proxy, event, stage) {
  8760. var gestureMgr = proxy._gestureMgr;
  8761. stage === 'start' && gestureMgr.clear();
  8762. var gestureInfo = gestureMgr.recognize(
  8763. event,
  8764. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8765. proxy.dom
  8766. );
  8767. stage === 'end' && gestureMgr.clear();
  8768. // Do not do any preventDefault here. Upper application do that if necessary.
  8769. if (gestureInfo) {
  8770. var type = gestureInfo.type;
  8771. event.gestureEvent = type;
  8772. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8773. }
  8774. }
  8775. // function onMSGestureChange(proxy, event) {
  8776. // if (event.translationX || event.translationY) {
  8777. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8778. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8779. // }
  8780. // if (event.scale !== 1) {
  8781. // event.pinchX = event.offsetX;
  8782. // event.pinchY = event.offsetY;
  8783. // event.pinchScale = event.scale;
  8784. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8785. // }
  8786. // }
  8787. /**
  8788. * Prevent mouse event from being dispatched after Touch Events action
  8789. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8790. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8791. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8792. * Result: Blocking Mouse Events for 700ms.
  8793. */
  8794. function setTouchTimer(instance) {
  8795. instance._touching = true;
  8796. clearTimeout(instance._touchTimer);
  8797. instance._touchTimer = setTimeout(function () {
  8798. instance._touching = false;
  8799. }, 700);
  8800. }
  8801. var domHandlers = {
  8802. /**
  8803. * Mouse move handler
  8804. * @inner
  8805. * @param {Event} event
  8806. */
  8807. mousemove: function (event) {
  8808. event = normalizeEvent(this.dom, event);
  8809. this.trigger('mousemove', event);
  8810. },
  8811. /**
  8812. * Mouse out handler
  8813. * @inner
  8814. * @param {Event} event
  8815. */
  8816. mouseout: function (event) {
  8817. event = normalizeEvent(this.dom, event);
  8818. var element = event.toElement || event.relatedTarget;
  8819. if (element != this.dom) {
  8820. while (element && element.nodeType != 9) {
  8821. // 忽略包含在root中的dom引起的mouseOut
  8822. if (element === this.dom) {
  8823. return;
  8824. }
  8825. element = element.parentNode;
  8826. }
  8827. }
  8828. this.trigger('mouseout', event);
  8829. },
  8830. /**
  8831. * Touch开始响应函数
  8832. * @inner
  8833. * @param {Event} event
  8834. */
  8835. touchstart: function (event) {
  8836. // Default mouse behaviour should not be disabled here.
  8837. // For example, page may needs to be slided.
  8838. event = normalizeEvent(this.dom, event);
  8839. // Mark touch, which is useful in distinguish touch and
  8840. // mouse event in upper applicatoin.
  8841. event.zrByTouch = true;
  8842. this._lastTouchMoment = new Date();
  8843. processGesture(this, event, 'start');
  8844. // In touch device, trigger `mousemove`(`mouseover`) should
  8845. // be triggered, and must before `mousedown` triggered.
  8846. domHandlers.mousemove.call(this, event);
  8847. domHandlers.mousedown.call(this, event);
  8848. setTouchTimer(this);
  8849. },
  8850. /**
  8851. * Touch移动响应函数
  8852. * @inner
  8853. * @param {Event} event
  8854. */
  8855. touchmove: function (event) {
  8856. event = normalizeEvent(this.dom, event);
  8857. // Mark touch, which is useful in distinguish touch and
  8858. // mouse event in upper applicatoin.
  8859. event.zrByTouch = true;
  8860. processGesture(this, event, 'change');
  8861. // Mouse move should always be triggered no matter whether
  8862. // there is gestrue event, because mouse move and pinch may
  8863. // be used at the same time.
  8864. domHandlers.mousemove.call(this, event);
  8865. setTouchTimer(this);
  8866. },
  8867. /**
  8868. * Touch结束响应函数
  8869. * @inner
  8870. * @param {Event} event
  8871. */
  8872. touchend: function (event) {
  8873. event = normalizeEvent(this.dom, event);
  8874. // Mark touch, which is useful in distinguish touch and
  8875. // mouse event in upper applicatoin.
  8876. event.zrByTouch = true;
  8877. processGesture(this, event, 'end');
  8878. domHandlers.mouseup.call(this, event);
  8879. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8880. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8881. // we can conveniently implement "hover style" in both PC and touch device just
  8882. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8883. // to remove "hover style" on an element, without any additional code for
  8884. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8885. // style" will remain for user view)
  8886. // click event should always be triggered no matter whether
  8887. // there is gestrue event. System click can not be prevented.
  8888. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8889. domHandlers.click.call(this, event);
  8890. }
  8891. setTouchTimer(this);
  8892. },
  8893. pointerdown: function (event) {
  8894. domHandlers.mousedown.call(this, event);
  8895. // if (useMSGuesture(this, event)) {
  8896. // this._msGesture.addPointer(event.pointerId);
  8897. // }
  8898. },
  8899. pointermove: function (event) {
  8900. // FIXME
  8901. // pointermove is so sensitive that it always triggered when
  8902. // tap(click) on touch screen, which affect some judgement in
  8903. // upper application. So, we dont support mousemove on MS touch
  8904. // device yet.
  8905. if (!isPointerFromTouch(event)) {
  8906. domHandlers.mousemove.call(this, event);
  8907. }
  8908. },
  8909. pointerup: function (event) {
  8910. domHandlers.mouseup.call(this, event);
  8911. },
  8912. pointerout: function (event) {
  8913. // pointerout will be triggered when tap on touch screen
  8914. // (IE11+/Edge on MS Surface) after click event triggered,
  8915. // which is inconsistent with the mousout behavior we defined
  8916. // in touchend. So we unify them.
  8917. // (check domHandlers.touchend for detailed explanation)
  8918. if (!isPointerFromTouch(event)) {
  8919. domHandlers.mouseout.call(this, event);
  8920. }
  8921. }
  8922. };
  8923. function isPointerFromTouch(event) {
  8924. var pointerType = event.pointerType;
  8925. return pointerType === 'pen' || pointerType === 'touch';
  8926. }
  8927. // function useMSGuesture(handlerProxy, event) {
  8928. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8929. // }
  8930. // Common handlers
  8931. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8932. domHandlers[name] = function (event) {
  8933. event = normalizeEvent(this.dom, event);
  8934. this.trigger(name, event);
  8935. };
  8936. });
  8937. /**
  8938. * 为控制类实例初始化dom 事件处理函数
  8939. *
  8940. * @inner
  8941. * @param {module:zrender/Handler} instance 控制类实例
  8942. */
  8943. function initDomHandler(instance) {
  8944. each$1(touchHandlerNames, function (name) {
  8945. instance._handlers[name] = bind(domHandlers[name], instance);
  8946. });
  8947. each$1(pointerHandlerNames, function (name) {
  8948. instance._handlers[name] = bind(domHandlers[name], instance);
  8949. });
  8950. each$1(mouseHandlerNames, function (name) {
  8951. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  8952. });
  8953. function makeMouseHandler(fn, instance) {
  8954. return function () {
  8955. if (instance._touching) {
  8956. return;
  8957. }
  8958. return fn.apply(instance, arguments);
  8959. };
  8960. }
  8961. }
  8962. function HandlerDomProxy(dom) {
  8963. Eventful.call(this);
  8964. this.dom = dom;
  8965. /**
  8966. * @private
  8967. * @type {boolean}
  8968. */
  8969. this._touching = false;
  8970. /**
  8971. * @private
  8972. * @type {number}
  8973. */
  8974. this._touchTimer;
  8975. /**
  8976. * @private
  8977. * @type {module:zrender/core/GestureMgr}
  8978. */
  8979. this._gestureMgr = new GestureMgr();
  8980. this._handlers = {};
  8981. initDomHandler(this);
  8982. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  8983. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  8984. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  8985. // at the same time.
  8986. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  8987. // screen, which do not occurs in pointer event.
  8988. // So we use pointer event to both detect touch gesture and mouse behavior.
  8989. mountHandlers(pointerHandlerNames, this);
  8990. // FIXME
  8991. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  8992. // which does not prevent defuault behavior occasionally (which may cause view port
  8993. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  8994. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  8995. // touch screen. And we only support click behavior on MS touch screen now.
  8996. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  8997. // We dont support touch on IE on win7.
  8998. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  8999. // if (typeof MSGesture === 'function') {
  9000. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9001. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9002. // }
  9003. }
  9004. else {
  9005. if (env$1.touchEventsSupported) {
  9006. mountHandlers(touchHandlerNames, this);
  9007. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9008. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9009. }
  9010. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9011. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9012. // mouse event can not be handle in those devices.
  9013. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9014. // mouseevent after touch event triggered, see `setTouchTimer`.
  9015. mountHandlers(mouseHandlerNames, this);
  9016. }
  9017. function mountHandlers(handlerNames, instance) {
  9018. each$1(handlerNames, function (name) {
  9019. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9020. }, instance);
  9021. }
  9022. }
  9023. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9024. handlerDomProxyProto.dispose = function () {
  9025. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9026. for (var i = 0; i < handlerNames.length; i++) {
  9027. var name = handlerNames[i];
  9028. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9029. }
  9030. };
  9031. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9032. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9033. };
  9034. mixin(HandlerDomProxy, Eventful);
  9035. /*!
  9036. * ZRender, a high performance 2d drawing library.
  9037. *
  9038. * Copyright (c) 2013, Baidu Inc.
  9039. * All rights reserved.
  9040. *
  9041. * LICENSE
  9042. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9043. */
  9044. var useVML = !env$1.canvasSupported;
  9045. var painterCtors = {
  9046. canvas: Painter
  9047. };
  9048. var instances$1 = {}; // ZRender实例map索引
  9049. /**
  9050. * @type {string}
  9051. */
  9052. var version$1 = '4.0.1';
  9053. /**
  9054. * Initializing a zrender instance
  9055. * @param {HTMLElement} dom
  9056. * @param {Object} opts
  9057. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9058. * @param {number} [opts.devicePixelRatio]
  9059. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9060. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9061. * @return {module:zrender/ZRender}
  9062. */
  9063. function init$1(dom, opts) {
  9064. var zr = new ZRender(guid(), dom, opts);
  9065. instances$1[zr.id] = zr;
  9066. return zr;
  9067. }
  9068. /**
  9069. * Dispose zrender instance
  9070. * @param {module:zrender/ZRender} zr
  9071. */
  9072. function dispose$1(zr) {
  9073. if (zr) {
  9074. zr.dispose();
  9075. }
  9076. else {
  9077. for (var key in instances$1) {
  9078. if (instances$1.hasOwnProperty(key)) {
  9079. instances$1[key].dispose();
  9080. }
  9081. }
  9082. instances$1 = {};
  9083. }
  9084. return this;
  9085. }
  9086. /**
  9087. * Get zrender instance by id
  9088. * @param {string} id zrender instance id
  9089. * @return {module:zrender/ZRender}
  9090. */
  9091. function getInstance(id) {
  9092. return instances$1[id];
  9093. }
  9094. function registerPainter(name, Ctor) {
  9095. painterCtors[name] = Ctor;
  9096. }
  9097. function delInstance(id) {
  9098. delete instances$1[id];
  9099. }
  9100. /**
  9101. * @module zrender/ZRender
  9102. */
  9103. /**
  9104. * @constructor
  9105. * @alias module:zrender/ZRender
  9106. * @param {string} id
  9107. * @param {HTMLElement} dom
  9108. * @param {Object} opts
  9109. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9110. * @param {number} [opts.devicePixelRatio]
  9111. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9112. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9113. */
  9114. var ZRender = function (id, dom, opts) {
  9115. opts = opts || {};
  9116. /**
  9117. * @type {HTMLDomElement}
  9118. */
  9119. this.dom = dom;
  9120. /**
  9121. * @type {string}
  9122. */
  9123. this.id = id;
  9124. var self = this;
  9125. var storage = new Storage();
  9126. var rendererType = opts.renderer;
  9127. // TODO WebGL
  9128. if (useVML) {
  9129. if (!painterCtors.vml) {
  9130. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9131. }
  9132. rendererType = 'vml';
  9133. }
  9134. else if (!rendererType || !painterCtors[rendererType]) {
  9135. rendererType = 'canvas';
  9136. }
  9137. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9138. this.storage = storage;
  9139. this.painter = painter;
  9140. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9141. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9142. /**
  9143. * @type {module:zrender/animation/Animation}
  9144. */
  9145. this.animation = new Animation({
  9146. stage: {
  9147. update: bind(this.flush, this)
  9148. }
  9149. });
  9150. this.animation.start();
  9151. /**
  9152. * @type {boolean}
  9153. * @private
  9154. */
  9155. this._needsRefresh;
  9156. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9157. // FIXME 有点ugly
  9158. var oldDelFromStorage = storage.delFromStorage;
  9159. var oldAddToStorage = storage.addToStorage;
  9160. storage.delFromStorage = function (el) {
  9161. oldDelFromStorage.call(storage, el);
  9162. el && el.removeSelfFromZr(self);
  9163. };
  9164. storage.addToStorage = function (el) {
  9165. oldAddToStorage.call(storage, el);
  9166. el.addSelfToZr(self);
  9167. };
  9168. };
  9169. ZRender.prototype = {
  9170. constructor: ZRender,
  9171. /**
  9172. * 获取实例唯一标识
  9173. * @return {string}
  9174. */
  9175. getId: function () {
  9176. return this.id;
  9177. },
  9178. /**
  9179. * 添加元素
  9180. * @param {module:zrender/Element} el
  9181. */
  9182. add: function (el) {
  9183. this.storage.addRoot(el);
  9184. this._needsRefresh = true;
  9185. },
  9186. /**
  9187. * 删除元素
  9188. * @param {module:zrender/Element} el
  9189. */
  9190. remove: function (el) {
  9191. this.storage.delRoot(el);
  9192. this._needsRefresh = true;
  9193. },
  9194. /**
  9195. * Change configuration of layer
  9196. * @param {string} zLevel
  9197. * @param {Object} config
  9198. * @param {string} [config.clearColor=0] Clear color
  9199. * @param {string} [config.motionBlur=false] If enable motion blur
  9200. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9201. */
  9202. configLayer: function (zLevel, config) {
  9203. this.painter.configLayer(zLevel, config);
  9204. this._needsRefresh = true;
  9205. },
  9206. /**
  9207. * Repaint the canvas immediately
  9208. */
  9209. refreshImmediately: function () {
  9210. // var start = new Date();
  9211. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9212. // Or it will cause zrender refreshes again and again.
  9213. this._needsRefresh = false;
  9214. this.painter.refresh();
  9215. /**
  9216. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9217. */
  9218. this._needsRefresh = false;
  9219. // var end = new Date();
  9220. // var log = document.getElementById('log');
  9221. // if (log) {
  9222. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9223. // }
  9224. },
  9225. /**
  9226. * Mark and repaint the canvas in the next frame of browser
  9227. */
  9228. refresh: function() {
  9229. this._needsRefresh = true;
  9230. },
  9231. /**
  9232. * Perform all refresh
  9233. */
  9234. flush: function () {
  9235. if (this._needsRefresh) {
  9236. this.refreshImmediately();
  9237. }
  9238. if (this._needsRefreshHover) {
  9239. this.refreshHoverImmediately();
  9240. }
  9241. },
  9242. /**
  9243. * Add element to hover layer
  9244. * @param {module:zrender/Element} el
  9245. * @param {Object} style
  9246. */
  9247. addHover: function (el, style) {
  9248. if (this.painter.addHover) {
  9249. this.painter.addHover(el, style);
  9250. this.refreshHover();
  9251. }
  9252. },
  9253. /**
  9254. * Add element from hover layer
  9255. * @param {module:zrender/Element} el
  9256. */
  9257. removeHover: function (el) {
  9258. if (this.painter.removeHover) {
  9259. this.painter.removeHover(el);
  9260. this.refreshHover();
  9261. }
  9262. },
  9263. /**
  9264. * Clear all hover elements in hover layer
  9265. * @param {module:zrender/Element} el
  9266. */
  9267. clearHover: function () {
  9268. if (this.painter.clearHover) {
  9269. this.painter.clearHover();
  9270. this.refreshHover();
  9271. }
  9272. },
  9273. /**
  9274. * Refresh hover in next frame
  9275. */
  9276. refreshHover: function () {
  9277. this._needsRefreshHover = true;
  9278. },
  9279. /**
  9280. * Refresh hover immediately
  9281. */
  9282. refreshHoverImmediately: function () {
  9283. this._needsRefreshHover = false;
  9284. this.painter.refreshHover && this.painter.refreshHover();
  9285. },
  9286. /**
  9287. * Resize the canvas.
  9288. * Should be invoked when container size is changed
  9289. * @param {Object} [opts]
  9290. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9291. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9292. */
  9293. resize: function(opts) {
  9294. opts = opts || {};
  9295. this.painter.resize(opts.width, opts.height);
  9296. this.handler.resize();
  9297. },
  9298. /**
  9299. * Stop and clear all animation immediately
  9300. */
  9301. clearAnimation: function () {
  9302. this.animation.clear();
  9303. },
  9304. /**
  9305. * Get container width
  9306. */
  9307. getWidth: function() {
  9308. return this.painter.getWidth();
  9309. },
  9310. /**
  9311. * Get container height
  9312. */
  9313. getHeight: function() {
  9314. return this.painter.getHeight();
  9315. },
  9316. /**
  9317. * Export the canvas as Base64 URL
  9318. * @param {string} type
  9319. * @param {string} [backgroundColor='#fff']
  9320. * @return {string} Base64 URL
  9321. */
  9322. // toDataURL: function(type, backgroundColor) {
  9323. // return this.painter.getRenderedCanvas({
  9324. // backgroundColor: backgroundColor
  9325. // }).toDataURL(type);
  9326. // },
  9327. /**
  9328. * Converting a path to image.
  9329. * It has much better performance of drawing image rather than drawing a vector path.
  9330. * @param {module:zrender/graphic/Path} e
  9331. * @param {number} width
  9332. * @param {number} height
  9333. */
  9334. pathToImage: function(e, dpr) {
  9335. return this.painter.pathToImage(e, dpr);
  9336. },
  9337. /**
  9338. * Set default cursor
  9339. * @param {string} [cursorStyle='default'] 例如 crosshair
  9340. */
  9341. setCursorStyle: function (cursorStyle) {
  9342. this.handler.setCursorStyle(cursorStyle);
  9343. },
  9344. /**
  9345. * Find hovered element
  9346. * @param {number} x
  9347. * @param {number} y
  9348. * @return {Object} {target, topTarget}
  9349. */
  9350. findHover: function (x, y) {
  9351. return this.handler.findHover(x, y);
  9352. },
  9353. /**
  9354. * Bind event
  9355. *
  9356. * @param {string} eventName Event name
  9357. * @param {Function} eventHandler Handler function
  9358. * @param {Object} [context] Context object
  9359. */
  9360. on: function(eventName, eventHandler, context) {
  9361. this.handler.on(eventName, eventHandler, context);
  9362. },
  9363. /**
  9364. * Unbind event
  9365. * @param {string} eventName Event name
  9366. * @param {Function} [eventHandler] Handler function
  9367. */
  9368. off: function(eventName, eventHandler) {
  9369. this.handler.off(eventName, eventHandler);
  9370. },
  9371. /**
  9372. * Trigger event manually
  9373. *
  9374. * @param {string} eventName Event name
  9375. * @param {event=} event Event object
  9376. */
  9377. trigger: function (eventName, event) {
  9378. this.handler.trigger(eventName, event);
  9379. },
  9380. /**
  9381. * Clear all objects and the canvas.
  9382. */
  9383. clear: function () {
  9384. this.storage.delRoot();
  9385. this.painter.clear();
  9386. },
  9387. /**
  9388. * Dispose self.
  9389. */
  9390. dispose: function () {
  9391. this.animation.stop();
  9392. this.clear();
  9393. this.storage.dispose();
  9394. this.painter.dispose();
  9395. this.handler.dispose();
  9396. this.animation =
  9397. this.storage =
  9398. this.painter =
  9399. this.handler = null;
  9400. delInstance(this.id);
  9401. }
  9402. };
  9403. var zrender = (Object.freeze || Object)({
  9404. version: version$1,
  9405. init: init$1,
  9406. dispose: dispose$1,
  9407. getInstance: getInstance,
  9408. registerPainter: registerPainter
  9409. });
  9410. var each$2 = each$1;
  9411. var isObject$2 = isObject$1;
  9412. var isArray$1 = isArray;
  9413. /**
  9414. * name may be displayed on screen, so use '-'.
  9415. * But we should make sure it is not duplicated
  9416. * with user specified name, so use '\0';
  9417. */
  9418. var DEFAULT_COMPONENT_NAME = '\0-';
  9419. /**
  9420. * If value is not array, then translate it to array.
  9421. * @param {*} value
  9422. * @return {Array} [value] or value
  9423. */
  9424. function normalizeToArray(value) {
  9425. return value instanceof Array
  9426. ? value
  9427. : value == null
  9428. ? []
  9429. : [value];
  9430. }
  9431. /**
  9432. * Sync default option between normal and emphasis like `position` and `show`
  9433. * In case some one will write code like
  9434. * label: {
  9435. * show: false,
  9436. * position: 'outside',
  9437. * fontSize: 18
  9438. * },
  9439. * emphasis: {
  9440. * label: { show: true }
  9441. * }
  9442. * @param {Object} opt
  9443. * @param {string} key
  9444. * @param {Array.<string>} subOpts
  9445. */
  9446. function defaultEmphasis(opt, key, subOpts) {
  9447. if (opt) {
  9448. opt[key] = opt[key] || {};
  9449. opt.emphasis = opt.emphasis || {};
  9450. opt.emphasis[key] = opt.emphasis[key] || {};
  9451. // Default emphasis option from normal
  9452. for (var i = 0, len = subOpts.length; i < len; i++) {
  9453. var subOptName = subOpts[i];
  9454. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9455. && opt[key].hasOwnProperty(subOptName)
  9456. ) {
  9457. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9458. }
  9459. }
  9460. }
  9461. }
  9462. var TEXT_STYLE_OPTIONS = [
  9463. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9464. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9465. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9466. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9467. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9468. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9469. ];
  9470. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9471. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9472. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9473. // // FIXME: deprecated, check and remove it.
  9474. // 'textStyle'
  9475. // ]);
  9476. /**
  9477. * The method do not ensure performance.
  9478. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9479. * This helper method retieves value from data.
  9480. * @param {string|number|Date|Array|Object} dataItem
  9481. * @return {number|string|Date|Array.<number|string|Date>}
  9482. */
  9483. function getDataItemValue(dataItem) {
  9484. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9485. ? dataItem.value : dataItem;
  9486. }
  9487. /**
  9488. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9489. * This helper method determine if dataItem has extra option besides value
  9490. * @param {string|number|Date|Array|Object} dataItem
  9491. */
  9492. function isDataItemOption(dataItem) {
  9493. return isObject$2(dataItem)
  9494. && !(dataItem instanceof Array);
  9495. // // markLine data can be array
  9496. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9497. }
  9498. /**
  9499. * Mapping to exists for merge.
  9500. *
  9501. * @public
  9502. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9503. * @param {Object|Array.<Object>} newCptOptions
  9504. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9505. * index of which is the same as exists.
  9506. */
  9507. function mappingToExists(exists, newCptOptions) {
  9508. // Mapping by the order by original option (but not order of
  9509. // new option) in merge mode. Because we should ensure
  9510. // some specified index (like xAxisIndex) is consistent with
  9511. // original option, which is easy to understand, espatially in
  9512. // media query. And in most case, merge option is used to
  9513. // update partial option but not be expected to change order.
  9514. newCptOptions = (newCptOptions || []).slice();
  9515. var result = map(exists || [], function (obj, index) {
  9516. return {exist: obj};
  9517. });
  9518. // Mapping by id or name if specified.
  9519. each$2(newCptOptions, function (cptOption, index) {
  9520. if (!isObject$2(cptOption)) {
  9521. return;
  9522. }
  9523. // id has highest priority.
  9524. for (var i = 0; i < result.length; i++) {
  9525. if (!result[i].option // Consider name: two map to one.
  9526. && cptOption.id != null
  9527. && result[i].exist.id === cptOption.id + ''
  9528. ) {
  9529. result[i].option = cptOption;
  9530. newCptOptions[index] = null;
  9531. return;
  9532. }
  9533. }
  9534. for (var i = 0; i < result.length; i++) {
  9535. var exist = result[i].exist;
  9536. if (!result[i].option // Consider name: two map to one.
  9537. // Can not match when both ids exist but different.
  9538. && (exist.id == null || cptOption.id == null)
  9539. && cptOption.name != null
  9540. && !isIdInner(cptOption)
  9541. && !isIdInner(exist)
  9542. && exist.name === cptOption.name + ''
  9543. ) {
  9544. result[i].option = cptOption;
  9545. newCptOptions[index] = null;
  9546. return;
  9547. }
  9548. }
  9549. });
  9550. // Otherwise mapping by index.
  9551. each$2(newCptOptions, function (cptOption, index) {
  9552. if (!isObject$2(cptOption)) {
  9553. return;
  9554. }
  9555. var i = 0;
  9556. for (; i < result.length; i++) {
  9557. var exist = result[i].exist;
  9558. if (!result[i].option
  9559. // Existing model that already has id should be able to
  9560. // mapped to (because after mapping performed model may
  9561. // be assigned with a id, whish should not affect next
  9562. // mapping), except those has inner id.
  9563. && !isIdInner(exist)
  9564. // Caution:
  9565. // Do not overwrite id. But name can be overwritten,
  9566. // because axis use name as 'show label text'.
  9567. // 'exist' always has id and name and we dont
  9568. // need to check it.
  9569. && cptOption.id == null
  9570. ) {
  9571. result[i].option = cptOption;
  9572. break;
  9573. }
  9574. }
  9575. if (i >= result.length) {
  9576. result.push({option: cptOption});
  9577. }
  9578. });
  9579. return result;
  9580. }
  9581. /**
  9582. * Make id and name for mapping result (result of mappingToExists)
  9583. * into `keyInfo` field.
  9584. *
  9585. * @public
  9586. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9587. * which order is the same as exists.
  9588. * @return {Array.<Object>} The input.
  9589. */
  9590. function makeIdAndName(mapResult) {
  9591. // We use this id to hash component models and view instances
  9592. // in echarts. id can be specified by user, or auto generated.
  9593. // The id generation rule ensures new view instance are able
  9594. // to mapped to old instance when setOption are called in
  9595. // no-merge mode. So we generate model id by name and plus
  9596. // type in view id.
  9597. // name can be duplicated among components, which is convenient
  9598. // to specify multi components (like series) by one name.
  9599. // Ensure that each id is distinct.
  9600. var idMap = createHashMap();
  9601. each$2(mapResult, function (item, index) {
  9602. var existCpt = item.exist;
  9603. existCpt && idMap.set(existCpt.id, item);
  9604. });
  9605. each$2(mapResult, function (item, index) {
  9606. var opt = item.option;
  9607. assert$1(
  9608. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9609. 'id duplicates: ' + (opt && opt.id)
  9610. );
  9611. opt && opt.id != null && idMap.set(opt.id, item);
  9612. !item.keyInfo && (item.keyInfo = {});
  9613. });
  9614. // Make name and id.
  9615. each$2(mapResult, function (item, index) {
  9616. var existCpt = item.exist;
  9617. var opt = item.option;
  9618. var keyInfo = item.keyInfo;
  9619. if (!isObject$2(opt)) {
  9620. return;
  9621. }
  9622. // name can be overwitten. Consider case: axis.name = '20km'.
  9623. // But id generated by name will not be changed, which affect
  9624. // only in that case: setOption with 'not merge mode' and view
  9625. // instance will be recreated, which can be accepted.
  9626. keyInfo.name = opt.name != null
  9627. ? opt.name + ''
  9628. : existCpt
  9629. ? existCpt.name
  9630. : DEFAULT_COMPONENT_NAME;
  9631. if (existCpt) {
  9632. keyInfo.id = existCpt.id;
  9633. }
  9634. else if (opt.id != null) {
  9635. keyInfo.id = opt.id + '';
  9636. }
  9637. else {
  9638. // Consider this situatoin:
  9639. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9640. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9641. // Series with the same name between optionA and optionB
  9642. // should be mapped.
  9643. var idNum = 0;
  9644. do {
  9645. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9646. }
  9647. while (idMap.get(keyInfo.id));
  9648. }
  9649. idMap.set(keyInfo.id, item);
  9650. });
  9651. }
  9652. /**
  9653. * @public
  9654. * @param {Object} cptOption
  9655. * @return {boolean}
  9656. */
  9657. function isIdInner(cptOption) {
  9658. return isObject$2(cptOption)
  9659. && cptOption.id
  9660. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9661. }
  9662. /**
  9663. * A helper for removing duplicate items between batchA and batchB,
  9664. * and in themselves, and categorize by series.
  9665. *
  9666. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9667. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9668. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9669. */
  9670. function compressBatches(batchA, batchB) {
  9671. var mapA = {};
  9672. var mapB = {};
  9673. makeMap(batchA || [], mapA);
  9674. makeMap(batchB || [], mapB, mapA);
  9675. return [mapToArray(mapA), mapToArray(mapB)];
  9676. function makeMap(sourceBatch, map$$1, otherMap) {
  9677. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9678. var seriesId = sourceBatch[i].seriesId;
  9679. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9680. var otherDataIndices = otherMap && otherMap[seriesId];
  9681. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9682. var dataIndex = dataIndices[j];
  9683. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9684. otherDataIndices[dataIndex] = null;
  9685. }
  9686. else {
  9687. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9688. }
  9689. }
  9690. }
  9691. }
  9692. function mapToArray(map$$1, isData) {
  9693. var result = [];
  9694. for (var i in map$$1) {
  9695. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9696. if (isData) {
  9697. result.push(+i);
  9698. }
  9699. else {
  9700. var dataIndices = mapToArray(map$$1[i], true);
  9701. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9702. }
  9703. }
  9704. }
  9705. return result;
  9706. }
  9707. }
  9708. /**
  9709. * @param {module:echarts/data/List} data
  9710. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9711. * each of which can be Array or primary type.
  9712. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9713. */
  9714. function queryDataIndex(data, payload) {
  9715. if (payload.dataIndexInside != null) {
  9716. return payload.dataIndexInside;
  9717. }
  9718. else if (payload.dataIndex != null) {
  9719. return isArray(payload.dataIndex)
  9720. ? map(payload.dataIndex, function (value) {
  9721. return data.indexOfRawIndex(value);
  9722. })
  9723. : data.indexOfRawIndex(payload.dataIndex);
  9724. }
  9725. else if (payload.name != null) {
  9726. return isArray(payload.name)
  9727. ? map(payload.name, function (value) {
  9728. return data.indexOfName(value);
  9729. })
  9730. : data.indexOfName(payload.name);
  9731. }
  9732. }
  9733. /**
  9734. * Enable property storage to any host object.
  9735. * Notice: Serialization is not supported.
  9736. *
  9737. * For example:
  9738. * var inner = zrUitl.makeInner();
  9739. *
  9740. * function some1(hostObj) {
  9741. * inner(hostObj).someProperty = 1212;
  9742. * ...
  9743. * }
  9744. * function some2() {
  9745. * var fields = inner(this);
  9746. * fields.someProperty1 = 1212;
  9747. * fields.someProperty2 = 'xx';
  9748. * ...
  9749. * }
  9750. *
  9751. * @return {Function}
  9752. */
  9753. function makeInner() {
  9754. // Consider different scope by es module import.
  9755. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9756. return function (hostObj) {
  9757. return hostObj[key] || (hostObj[key] = {});
  9758. };
  9759. }
  9760. var innerUniqueIndex = 0;
  9761. /**
  9762. * @param {module:echarts/model/Global} ecModel
  9763. * @param {string|Object} finder
  9764. * If string, e.g., 'geo', means {geoIndex: 0}.
  9765. * If Object, could contain some of these properties below:
  9766. * {
  9767. * seriesIndex, seriesId, seriesName,
  9768. * geoIndex, geoId, geoName,
  9769. * bmapIndex, bmapId, bmapName,
  9770. * xAxisIndex, xAxisId, xAxisName,
  9771. * yAxisIndex, yAxisId, yAxisName,
  9772. * gridIndex, gridId, gridName,
  9773. * ... (can be extended)
  9774. * }
  9775. * Each properties can be number|string|Array.<number>|Array.<string>
  9776. * For example, a finder could be
  9777. * {
  9778. * seriesIndex: 3,
  9779. * geoId: ['aa', 'cc'],
  9780. * gridName: ['xx', 'rr']
  9781. * }
  9782. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9783. * If nothing or null/undefined specified, return nothing.
  9784. * @param {Object} [opt]
  9785. * @param {string} [opt.defaultMainType]
  9786. * @param {Array.<string>} [opt.includeMainTypes]
  9787. * @return {Object} result like:
  9788. * {
  9789. * seriesModels: [seriesModel1, seriesModel2],
  9790. * seriesModel: seriesModel1, // The first model
  9791. * geoModels: [geoModel1, geoModel2],
  9792. * geoModel: geoModel1, // The first model
  9793. * ...
  9794. * }
  9795. */
  9796. function parseFinder(ecModel, finder, opt) {
  9797. if (isString(finder)) {
  9798. var obj = {};
  9799. obj[finder + 'Index'] = 0;
  9800. finder = obj;
  9801. }
  9802. var defaultMainType = opt && opt.defaultMainType;
  9803. if (defaultMainType
  9804. && !has(finder, defaultMainType + 'Index')
  9805. && !has(finder, defaultMainType + 'Id')
  9806. && !has(finder, defaultMainType + 'Name')
  9807. ) {
  9808. finder[defaultMainType + 'Index'] = 0;
  9809. }
  9810. var result = {};
  9811. each$2(finder, function (value, key) {
  9812. var value = finder[key];
  9813. // Exclude 'dataIndex' and other illgal keys.
  9814. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9815. result[key] = value;
  9816. return;
  9817. }
  9818. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9819. var mainType = parsedKey[1];
  9820. var queryType = (parsedKey[2] || '').toLowerCase();
  9821. if (!mainType
  9822. || !queryType
  9823. || value == null
  9824. || (queryType === 'index' && value === 'none')
  9825. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9826. ) {
  9827. return;
  9828. }
  9829. var queryParam = {mainType: mainType};
  9830. if (queryType !== 'index' || value !== 'all') {
  9831. queryParam[queryType] = value;
  9832. }
  9833. var models = ecModel.queryComponents(queryParam);
  9834. result[mainType + 'Models'] = models;
  9835. result[mainType + 'Model'] = models[0];
  9836. });
  9837. return result;
  9838. }
  9839. function has(obj, prop) {
  9840. return obj && obj.hasOwnProperty(prop);
  9841. }
  9842. function setAttribute(dom, key, value) {
  9843. dom.setAttribute
  9844. ? dom.setAttribute(key, value)
  9845. : (dom[key] = value);
  9846. }
  9847. function getAttribute(dom, key) {
  9848. return dom.getAttribute
  9849. ? dom.getAttribute(key)
  9850. : dom[key];
  9851. }
  9852. var TYPE_DELIMITER = '.';
  9853. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9854. /**
  9855. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9856. * @public
  9857. */
  9858. function parseClassType$1(componentType) {
  9859. var ret = {main: '', sub: ''};
  9860. if (componentType) {
  9861. componentType = componentType.split(TYPE_DELIMITER);
  9862. ret.main = componentType[0] || '';
  9863. ret.sub = componentType[1] || '';
  9864. }
  9865. return ret;
  9866. }
  9867. /**
  9868. * @public
  9869. */
  9870. function checkClassType(componentType) {
  9871. assert$1(
  9872. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9873. 'componentType "' + componentType + '" illegal'
  9874. );
  9875. }
  9876. /**
  9877. * @public
  9878. */
  9879. function enableClassExtend(RootClass, mandatoryMethods) {
  9880. RootClass.$constructor = RootClass;
  9881. RootClass.extend = function (proto) {
  9882. if (__DEV__) {
  9883. each$1(mandatoryMethods, function (method) {
  9884. if (!proto[method]) {
  9885. console.warn(
  9886. 'Method `' + method + '` should be implemented'
  9887. + (proto.type ? ' in ' + proto.type : '') + '.'
  9888. );
  9889. }
  9890. });
  9891. }
  9892. var superClass = this;
  9893. var ExtendedClass = function () {
  9894. if (!proto.$constructor) {
  9895. superClass.apply(this, arguments);
  9896. }
  9897. else {
  9898. proto.$constructor.apply(this, arguments);
  9899. }
  9900. };
  9901. extend(ExtendedClass.prototype, proto);
  9902. ExtendedClass.extend = this.extend;
  9903. ExtendedClass.superCall = superCall;
  9904. ExtendedClass.superApply = superApply;
  9905. inherits(ExtendedClass, this);
  9906. ExtendedClass.superClass = superClass;
  9907. return ExtendedClass;
  9908. };
  9909. }
  9910. var classBase = 0;
  9911. /**
  9912. * Can not use instanceof, consider different scope by
  9913. * cross domain or es module import in ec extensions.
  9914. * Mount a method "isInstance()" to Clz.
  9915. */
  9916. function enableClassCheck(Clz) {
  9917. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  9918. Clz.prototype[classAttr] = true;
  9919. if (__DEV__) {
  9920. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  9921. }
  9922. Clz.isInstance = function (obj) {
  9923. return !!(obj && obj[classAttr]);
  9924. };
  9925. }
  9926. // superCall should have class info, which can not be fetch from 'this'.
  9927. // Consider this case:
  9928. // class A has method f,
  9929. // class B inherits class A, overrides method f, f call superApply('f'),
  9930. // class C inherits class B, do not overrides method f,
  9931. // then when method of class C is called, dead loop occured.
  9932. function superCall(context, methodName) {
  9933. var args = slice(arguments, 2);
  9934. return this.superClass.prototype[methodName].apply(context, args);
  9935. }
  9936. function superApply(context, methodName, args) {
  9937. return this.superClass.prototype[methodName].apply(context, args);
  9938. }
  9939. /**
  9940. * @param {Object} entity
  9941. * @param {Object} options
  9942. * @param {boolean} [options.registerWhenExtend]
  9943. * @public
  9944. */
  9945. function enableClassManagement(entity, options) {
  9946. options = options || {};
  9947. /**
  9948. * Component model classes
  9949. * key: componentType,
  9950. * value:
  9951. * componentClass, when componentType is 'xxx'
  9952. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  9953. * @type {Object}
  9954. */
  9955. var storage = {};
  9956. entity.registerClass = function (Clazz, componentType) {
  9957. if (componentType) {
  9958. checkClassType(componentType);
  9959. componentType = parseClassType$1(componentType);
  9960. if (!componentType.sub) {
  9961. if (__DEV__) {
  9962. if (storage[componentType.main]) {
  9963. console.warn(componentType.main + ' exists.');
  9964. }
  9965. }
  9966. storage[componentType.main] = Clazz;
  9967. }
  9968. else if (componentType.sub !== IS_CONTAINER) {
  9969. var container = makeContainer(componentType);
  9970. container[componentType.sub] = Clazz;
  9971. }
  9972. }
  9973. return Clazz;
  9974. };
  9975. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  9976. var Clazz = storage[componentMainType];
  9977. if (Clazz && Clazz[IS_CONTAINER]) {
  9978. Clazz = subType ? Clazz[subType] : null;
  9979. }
  9980. if (throwWhenNotFound && !Clazz) {
  9981. throw new Error(
  9982. !subType
  9983. ? componentMainType + '.' + 'type should be specified.'
  9984. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  9985. );
  9986. }
  9987. return Clazz;
  9988. };
  9989. entity.getClassesByMainType = function (componentType) {
  9990. componentType = parseClassType$1(componentType);
  9991. var result = [];
  9992. var obj = storage[componentType.main];
  9993. if (obj && obj[IS_CONTAINER]) {
  9994. each$1(obj, function (o, type) {
  9995. type !== IS_CONTAINER && result.push(o);
  9996. });
  9997. }
  9998. else {
  9999. result.push(obj);
  10000. }
  10001. return result;
  10002. };
  10003. entity.hasClass = function (componentType) {
  10004. // Just consider componentType.main.
  10005. componentType = parseClassType$1(componentType);
  10006. return !!storage[componentType.main];
  10007. };
  10008. /**
  10009. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10010. */
  10011. entity.getAllClassMainTypes = function () {
  10012. var types = [];
  10013. each$1(storage, function (obj, type) {
  10014. types.push(type);
  10015. });
  10016. return types;
  10017. };
  10018. /**
  10019. * If a main type is container and has sub types
  10020. * @param {string} mainType
  10021. * @return {boolean}
  10022. */
  10023. entity.hasSubTypes = function (componentType) {
  10024. componentType = parseClassType$1(componentType);
  10025. var obj = storage[componentType.main];
  10026. return obj && obj[IS_CONTAINER];
  10027. };
  10028. entity.parseClassType = parseClassType$1;
  10029. function makeContainer(componentType) {
  10030. var container = storage[componentType.main];
  10031. if (!container || !container[IS_CONTAINER]) {
  10032. container = storage[componentType.main] = {};
  10033. container[IS_CONTAINER] = true;
  10034. }
  10035. return container;
  10036. }
  10037. if (options.registerWhenExtend) {
  10038. var originalExtend = entity.extend;
  10039. if (originalExtend) {
  10040. entity.extend = function (proto) {
  10041. var ExtendedClass = originalExtend.call(this, proto);
  10042. return entity.registerClass(ExtendedClass, proto.type);
  10043. };
  10044. }
  10045. }
  10046. return entity;
  10047. }
  10048. /**
  10049. * @param {string|Array.<string>} properties
  10050. */
  10051. // TODO Parse shadow style
  10052. // TODO Only shallow path support
  10053. var makeStyleMapper = function (properties) {
  10054. // Normalize
  10055. for (var i = 0; i < properties.length; i++) {
  10056. if (!properties[i][1]) {
  10057. properties[i][1] = properties[i][0];
  10058. }
  10059. }
  10060. return function (model, excludes, includes) {
  10061. var style = {};
  10062. for (var i = 0; i < properties.length; i++) {
  10063. var propName = properties[i][1];
  10064. if ((excludes && indexOf(excludes, propName) >= 0)
  10065. || (includes && indexOf(includes, propName) < 0)
  10066. ) {
  10067. continue;
  10068. }
  10069. var val = model.getShallow(propName);
  10070. if (val != null) {
  10071. style[properties[i][0]] = val;
  10072. }
  10073. }
  10074. return style;
  10075. };
  10076. };
  10077. var getLineStyle = makeStyleMapper(
  10078. [
  10079. ['lineWidth', 'width'],
  10080. ['stroke', 'color'],
  10081. ['opacity'],
  10082. ['shadowBlur'],
  10083. ['shadowOffsetX'],
  10084. ['shadowOffsetY'],
  10085. ['shadowColor']
  10086. ]
  10087. );
  10088. var lineStyleMixin = {
  10089. getLineStyle: function (excludes) {
  10090. var style = getLineStyle(this, excludes);
  10091. var lineDash = this.getLineDash(style.lineWidth);
  10092. lineDash && (style.lineDash = lineDash);
  10093. return style;
  10094. },
  10095. getLineDash: function (lineWidth) {
  10096. if (lineWidth == null) {
  10097. lineWidth = 1;
  10098. }
  10099. var lineType = this.get('type');
  10100. var dotSize = Math.max(lineWidth, 2);
  10101. var dashSize = lineWidth * 4;
  10102. return (lineType === 'solid' || lineType == null) ? null
  10103. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10104. }
  10105. };
  10106. var getAreaStyle = makeStyleMapper(
  10107. [
  10108. ['fill', 'color'],
  10109. ['shadowBlur'],
  10110. ['shadowOffsetX'],
  10111. ['shadowOffsetY'],
  10112. ['opacity'],
  10113. ['shadowColor']
  10114. ]
  10115. );
  10116. var areaStyleMixin = {
  10117. getAreaStyle: function (excludes, includes) {
  10118. return getAreaStyle(this, excludes, includes);
  10119. }
  10120. };
  10121. /**
  10122. * 曲线辅助模块
  10123. * @module zrender/core/curve
  10124. * @author pissang(https://www.github.com/pissang)
  10125. */
  10126. var mathPow = Math.pow;
  10127. var mathSqrt$2 = Math.sqrt;
  10128. var EPSILON$1 = 1e-8;
  10129. var EPSILON_NUMERIC = 1e-4;
  10130. var THREE_SQRT = mathSqrt$2(3);
  10131. var ONE_THIRD = 1 / 3;
  10132. // 临时变量
  10133. var _v0 = create();
  10134. var _v1 = create();
  10135. var _v2 = create();
  10136. function isAroundZero(val) {
  10137. return val > -EPSILON$1 && val < EPSILON$1;
  10138. }
  10139. function isNotAroundZero$1(val) {
  10140. return val > EPSILON$1 || val < -EPSILON$1;
  10141. }
  10142. /**
  10143. * 计算三次贝塞尔值
  10144. * @memberOf module:zrender/core/curve
  10145. * @param {number} p0
  10146. * @param {number} p1
  10147. * @param {number} p2
  10148. * @param {number} p3
  10149. * @param {number} t
  10150. * @return {number}
  10151. */
  10152. function cubicAt(p0, p1, p2, p3, t) {
  10153. var onet = 1 - t;
  10154. return onet * onet * (onet * p0 + 3 * t * p1)
  10155. + t * t * (t * p3 + 3 * onet * p2);
  10156. }
  10157. /**
  10158. * 计算三次贝塞尔导数值
  10159. * @memberOf module:zrender/core/curve
  10160. * @param {number} p0
  10161. * @param {number} p1
  10162. * @param {number} p2
  10163. * @param {number} p3
  10164. * @param {number} t
  10165. * @return {number}
  10166. */
  10167. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10168. var onet = 1 - t;
  10169. return 3 * (
  10170. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10171. + (p3 - p2) * t * t
  10172. );
  10173. }
  10174. /**
  10175. * 计算三次贝塞尔方程根,使用盛金公式
  10176. * @memberOf module:zrender/core/curve
  10177. * @param {number} p0
  10178. * @param {number} p1
  10179. * @param {number} p2
  10180. * @param {number} p3
  10181. * @param {number} val
  10182. * @param {Array.<number>} roots
  10183. * @return {number} 有效根数目
  10184. */
  10185. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10186. // Evaluate roots of cubic functions
  10187. var a = p3 + 3 * (p1 - p2) - p0;
  10188. var b = 3 * (p2 - p1 * 2 + p0);
  10189. var c = 3 * (p1 - p0);
  10190. var d = p0 - val;
  10191. var A = b * b - 3 * a * c;
  10192. var B = b * c - 9 * a * d;
  10193. var C = c * c - 3 * b * d;
  10194. var n = 0;
  10195. if (isAroundZero(A) && isAroundZero(B)) {
  10196. if (isAroundZero(b)) {
  10197. roots[0] = 0;
  10198. }
  10199. else {
  10200. var t1 = -c / b; //t1, t2, t3, b is not zero
  10201. if (t1 >= 0 && t1 <= 1) {
  10202. roots[n++] = t1;
  10203. }
  10204. }
  10205. }
  10206. else {
  10207. var disc = B * B - 4 * A * C;
  10208. if (isAroundZero(disc)) {
  10209. var K = B / A;
  10210. var t1 = -b / a + K; // t1, a is not zero
  10211. var t2 = -K / 2; // t2, t3
  10212. if (t1 >= 0 && t1 <= 1) {
  10213. roots[n++] = t1;
  10214. }
  10215. if (t2 >= 0 && t2 <= 1) {
  10216. roots[n++] = t2;
  10217. }
  10218. }
  10219. else if (disc > 0) {
  10220. var discSqrt = mathSqrt$2(disc);
  10221. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10222. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10223. if (Y1 < 0) {
  10224. Y1 = -mathPow(-Y1, ONE_THIRD);
  10225. }
  10226. else {
  10227. Y1 = mathPow(Y1, ONE_THIRD);
  10228. }
  10229. if (Y2 < 0) {
  10230. Y2 = -mathPow(-Y2, ONE_THIRD);
  10231. }
  10232. else {
  10233. Y2 = mathPow(Y2, ONE_THIRD);
  10234. }
  10235. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10236. if (t1 >= 0 && t1 <= 1) {
  10237. roots[n++] = t1;
  10238. }
  10239. }
  10240. else {
  10241. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10242. var theta = Math.acos(T) / 3;
  10243. var ASqrt = mathSqrt$2(A);
  10244. var tmp = Math.cos(theta);
  10245. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10246. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10247. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10248. if (t1 >= 0 && t1 <= 1) {
  10249. roots[n++] = t1;
  10250. }
  10251. if (t2 >= 0 && t2 <= 1) {
  10252. roots[n++] = t2;
  10253. }
  10254. if (t3 >= 0 && t3 <= 1) {
  10255. roots[n++] = t3;
  10256. }
  10257. }
  10258. }
  10259. return n;
  10260. }
  10261. /**
  10262. * 计算三次贝塞尔方程极限值的位置
  10263. * @memberOf module:zrender/core/curve
  10264. * @param {number} p0
  10265. * @param {number} p1
  10266. * @param {number} p2
  10267. * @param {number} p3
  10268. * @param {Array.<number>} extrema
  10269. * @return {number} 有效数目
  10270. */
  10271. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10272. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10273. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10274. var c = 3 * p1 - 3 * p0;
  10275. var n = 0;
  10276. if (isAroundZero(a)) {
  10277. if (isNotAroundZero$1(b)) {
  10278. var t1 = -c / b;
  10279. if (t1 >= 0 && t1 <=1) {
  10280. extrema[n++] = t1;
  10281. }
  10282. }
  10283. }
  10284. else {
  10285. var disc = b * b - 4 * a * c;
  10286. if (isAroundZero(disc)) {
  10287. extrema[0] = -b / (2 * a);
  10288. }
  10289. else if (disc > 0) {
  10290. var discSqrt = mathSqrt$2(disc);
  10291. var t1 = (-b + discSqrt) / (2 * a);
  10292. var t2 = (-b - discSqrt) / (2 * a);
  10293. if (t1 >= 0 && t1 <= 1) {
  10294. extrema[n++] = t1;
  10295. }
  10296. if (t2 >= 0 && t2 <= 1) {
  10297. extrema[n++] = t2;
  10298. }
  10299. }
  10300. }
  10301. return n;
  10302. }
  10303. /**
  10304. * 细分三次贝塞尔曲线
  10305. * @memberOf module:zrender/core/curve
  10306. * @param {number} p0
  10307. * @param {number} p1
  10308. * @param {number} p2
  10309. * @param {number} p3
  10310. * @param {number} t
  10311. * @param {Array.<number>} out
  10312. */
  10313. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10314. var p01 = (p1 - p0) * t + p0;
  10315. var p12 = (p2 - p1) * t + p1;
  10316. var p23 = (p3 - p2) * t + p2;
  10317. var p012 = (p12 - p01) * t + p01;
  10318. var p123 = (p23 - p12) * t + p12;
  10319. var p0123 = (p123 - p012) * t + p012;
  10320. // Seg0
  10321. out[0] = p0;
  10322. out[1] = p01;
  10323. out[2] = p012;
  10324. out[3] = p0123;
  10325. // Seg1
  10326. out[4] = p0123;
  10327. out[5] = p123;
  10328. out[6] = p23;
  10329. out[7] = p3;
  10330. }
  10331. /**
  10332. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10333. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10334. * @param {number} x0
  10335. * @param {number} y0
  10336. * @param {number} x1
  10337. * @param {number} y1
  10338. * @param {number} x2
  10339. * @param {number} y2
  10340. * @param {number} x3
  10341. * @param {number} y3
  10342. * @param {number} x
  10343. * @param {number} y
  10344. * @param {Array.<number>} [out] 投射点
  10345. * @return {number}
  10346. */
  10347. function cubicProjectPoint(
  10348. x0, y0, x1, y1, x2, y2, x3, y3,
  10349. x, y, out
  10350. ) {
  10351. // http://pomax.github.io/bezierinfo/#projections
  10352. var t;
  10353. var interval = 0.005;
  10354. var d = Infinity;
  10355. var prev;
  10356. var next;
  10357. var d1;
  10358. var d2;
  10359. _v0[0] = x;
  10360. _v0[1] = y;
  10361. // 先粗略估计一下可能的最小距离的 t 值
  10362. // PENDING
  10363. for (var _t = 0; _t < 1; _t += 0.05) {
  10364. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10365. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10366. d1 = distSquare(_v0, _v1);
  10367. if (d1 < d) {
  10368. t = _t;
  10369. d = d1;
  10370. }
  10371. }
  10372. d = Infinity;
  10373. // At most 32 iteration
  10374. for (var i = 0; i < 32; i++) {
  10375. if (interval < EPSILON_NUMERIC) {
  10376. break;
  10377. }
  10378. prev = t - interval;
  10379. next = t + interval;
  10380. // t - interval
  10381. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10382. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10383. d1 = distSquare(_v1, _v0);
  10384. if (prev >= 0 && d1 < d) {
  10385. t = prev;
  10386. d = d1;
  10387. }
  10388. else {
  10389. // t + interval
  10390. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10391. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10392. d2 = distSquare(_v2, _v0);
  10393. if (next <= 1 && d2 < d) {
  10394. t = next;
  10395. d = d2;
  10396. }
  10397. else {
  10398. interval *= 0.5;
  10399. }
  10400. }
  10401. }
  10402. // t
  10403. if (out) {
  10404. out[0] = cubicAt(x0, x1, x2, x3, t);
  10405. out[1] = cubicAt(y0, y1, y2, y3, t);
  10406. }
  10407. // console.log(interval, i);
  10408. return mathSqrt$2(d);
  10409. }
  10410. /**
  10411. * 计算二次方贝塞尔值
  10412. * @param {number} p0
  10413. * @param {number} p1
  10414. * @param {number} p2
  10415. * @param {number} t
  10416. * @return {number}
  10417. */
  10418. function quadraticAt(p0, p1, p2, t) {
  10419. var onet = 1 - t;
  10420. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10421. }
  10422. /**
  10423. * 计算二次方贝塞尔导数值
  10424. * @param {number} p0
  10425. * @param {number} p1
  10426. * @param {number} p2
  10427. * @param {number} t
  10428. * @return {number}
  10429. */
  10430. function quadraticDerivativeAt(p0, p1, p2, t) {
  10431. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10432. }
  10433. /**
  10434. * 计算二次方贝塞尔方程根
  10435. * @param {number} p0
  10436. * @param {number} p1
  10437. * @param {number} p2
  10438. * @param {number} t
  10439. * @param {Array.<number>} roots
  10440. * @return {number} 有效根数目
  10441. */
  10442. function quadraticRootAt(p0, p1, p2, val, roots) {
  10443. var a = p0 - 2 * p1 + p2;
  10444. var b = 2 * (p1 - p0);
  10445. var c = p0 - val;
  10446. var n = 0;
  10447. if (isAroundZero(a)) {
  10448. if (isNotAroundZero$1(b)) {
  10449. var t1 = -c / b;
  10450. if (t1 >= 0 && t1 <= 1) {
  10451. roots[n++] = t1;
  10452. }
  10453. }
  10454. }
  10455. else {
  10456. var disc = b * b - 4 * a * c;
  10457. if (isAroundZero(disc)) {
  10458. var t1 = -b / (2 * a);
  10459. if (t1 >= 0 && t1 <= 1) {
  10460. roots[n++] = t1;
  10461. }
  10462. }
  10463. else if (disc > 0) {
  10464. var discSqrt = mathSqrt$2(disc);
  10465. var t1 = (-b + discSqrt) / (2 * a);
  10466. var t2 = (-b - discSqrt) / (2 * a);
  10467. if (t1 >= 0 && t1 <= 1) {
  10468. roots[n++] = t1;
  10469. }
  10470. if (t2 >= 0 && t2 <= 1) {
  10471. roots[n++] = t2;
  10472. }
  10473. }
  10474. }
  10475. return n;
  10476. }
  10477. /**
  10478. * 计算二次贝塞尔方程极限值
  10479. * @memberOf module:zrender/core/curve
  10480. * @param {number} p0
  10481. * @param {number} p1
  10482. * @param {number} p2
  10483. * @return {number}
  10484. */
  10485. function quadraticExtremum(p0, p1, p2) {
  10486. var divider = p0 + p2 - 2 * p1;
  10487. if (divider === 0) {
  10488. // p1 is center of p0 and p2
  10489. return 0.5;
  10490. }
  10491. else {
  10492. return (p0 - p1) / divider;
  10493. }
  10494. }
  10495. /**
  10496. * 细分二次贝塞尔曲线
  10497. * @memberOf module:zrender/core/curve
  10498. * @param {number} p0
  10499. * @param {number} p1
  10500. * @param {number} p2
  10501. * @param {number} t
  10502. * @param {Array.<number>} out
  10503. */
  10504. function quadraticSubdivide(p0, p1, p2, t, out) {
  10505. var p01 = (p1 - p0) * t + p0;
  10506. var p12 = (p2 - p1) * t + p1;
  10507. var p012 = (p12 - p01) * t + p01;
  10508. // Seg0
  10509. out[0] = p0;
  10510. out[1] = p01;
  10511. out[2] = p012;
  10512. // Seg1
  10513. out[3] = p012;
  10514. out[4] = p12;
  10515. out[5] = p2;
  10516. }
  10517. /**
  10518. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10519. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10520. * @param {number} x0
  10521. * @param {number} y0
  10522. * @param {number} x1
  10523. * @param {number} y1
  10524. * @param {number} x2
  10525. * @param {number} y2
  10526. * @param {number} x
  10527. * @param {number} y
  10528. * @param {Array.<number>} out 投射点
  10529. * @return {number}
  10530. */
  10531. function quadraticProjectPoint(
  10532. x0, y0, x1, y1, x2, y2,
  10533. x, y, out
  10534. ) {
  10535. // http://pomax.github.io/bezierinfo/#projections
  10536. var t;
  10537. var interval = 0.005;
  10538. var d = Infinity;
  10539. _v0[0] = x;
  10540. _v0[1] = y;
  10541. // 先粗略估计一下可能的最小距离的 t 值
  10542. // PENDING
  10543. for (var _t = 0; _t < 1; _t += 0.05) {
  10544. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10545. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10546. var d1 = distSquare(_v0, _v1);
  10547. if (d1 < d) {
  10548. t = _t;
  10549. d = d1;
  10550. }
  10551. }
  10552. d = Infinity;
  10553. // At most 32 iteration
  10554. for (var i = 0; i < 32; i++) {
  10555. if (interval < EPSILON_NUMERIC) {
  10556. break;
  10557. }
  10558. var prev = t - interval;
  10559. var next = t + interval;
  10560. // t - interval
  10561. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10562. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10563. var d1 = distSquare(_v1, _v0);
  10564. if (prev >= 0 && d1 < d) {
  10565. t = prev;
  10566. d = d1;
  10567. }
  10568. else {
  10569. // t + interval
  10570. _v2[0] = quadraticAt(x0, x1, x2, next);
  10571. _v2[1] = quadraticAt(y0, y1, y2, next);
  10572. var d2 = distSquare(_v2, _v0);
  10573. if (next <= 1 && d2 < d) {
  10574. t = next;
  10575. d = d2;
  10576. }
  10577. else {
  10578. interval *= 0.5;
  10579. }
  10580. }
  10581. }
  10582. // t
  10583. if (out) {
  10584. out[0] = quadraticAt(x0, x1, x2, t);
  10585. out[1] = quadraticAt(y0, y1, y2, t);
  10586. }
  10587. // console.log(interval, i);
  10588. return mathSqrt$2(d);
  10589. }
  10590. /**
  10591. * @author Yi Shen(https://github.com/pissang)
  10592. */
  10593. var mathMin$3 = Math.min;
  10594. var mathMax$3 = Math.max;
  10595. var mathSin$2 = Math.sin;
  10596. var mathCos$2 = Math.cos;
  10597. var PI2 = Math.PI * 2;
  10598. var start = create();
  10599. var end = create();
  10600. var extremity = create();
  10601. /**
  10602. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10603. * @module zrender/core/bbox
  10604. * @param {Array<Object>} points 顶点数组
  10605. * @param {number} min
  10606. * @param {number} max
  10607. */
  10608. function fromPoints(points, min$$1, max$$1) {
  10609. if (points.length === 0) {
  10610. return;
  10611. }
  10612. var p = points[0];
  10613. var left = p[0];
  10614. var right = p[0];
  10615. var top = p[1];
  10616. var bottom = p[1];
  10617. var i;
  10618. for (i = 1; i < points.length; i++) {
  10619. p = points[i];
  10620. left = mathMin$3(left, p[0]);
  10621. right = mathMax$3(right, p[0]);
  10622. top = mathMin$3(top, p[1]);
  10623. bottom = mathMax$3(bottom, p[1]);
  10624. }
  10625. min$$1[0] = left;
  10626. min$$1[1] = top;
  10627. max$$1[0] = right;
  10628. max$$1[1] = bottom;
  10629. }
  10630. /**
  10631. * @memberOf module:zrender/core/bbox
  10632. * @param {number} x0
  10633. * @param {number} y0
  10634. * @param {number} x1
  10635. * @param {number} y1
  10636. * @param {Array.<number>} min
  10637. * @param {Array.<number>} max
  10638. */
  10639. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10640. min$$1[0] = mathMin$3(x0, x1);
  10641. min$$1[1] = mathMin$3(y0, y1);
  10642. max$$1[0] = mathMax$3(x0, x1);
  10643. max$$1[1] = mathMax$3(y0, y1);
  10644. }
  10645. var xDim = [];
  10646. var yDim = [];
  10647. /**
  10648. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10649. * @memberOf module:zrender/core/bbox
  10650. * @param {number} x0
  10651. * @param {number} y0
  10652. * @param {number} x1
  10653. * @param {number} y1
  10654. * @param {number} x2
  10655. * @param {number} y2
  10656. * @param {number} x3
  10657. * @param {number} y3
  10658. * @param {Array.<number>} min
  10659. * @param {Array.<number>} max
  10660. */
  10661. function fromCubic(
  10662. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10663. ) {
  10664. var cubicExtrema$$1 = cubicExtrema;
  10665. var cubicAt$$1 = cubicAt;
  10666. var i;
  10667. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10668. min$$1[0] = Infinity;
  10669. min$$1[1] = Infinity;
  10670. max$$1[0] = -Infinity;
  10671. max$$1[1] = -Infinity;
  10672. for (i = 0; i < n; i++) {
  10673. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10674. min$$1[0] = mathMin$3(x, min$$1[0]);
  10675. max$$1[0] = mathMax$3(x, max$$1[0]);
  10676. }
  10677. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10678. for (i = 0; i < n; i++) {
  10679. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10680. min$$1[1] = mathMin$3(y, min$$1[1]);
  10681. max$$1[1] = mathMax$3(y, max$$1[1]);
  10682. }
  10683. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10684. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10685. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10686. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10687. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10688. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10689. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10690. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10691. }
  10692. /**
  10693. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10694. * @memberOf module:zrender/core/bbox
  10695. * @param {number} x0
  10696. * @param {number} y0
  10697. * @param {number} x1
  10698. * @param {number} y1
  10699. * @param {number} x2
  10700. * @param {number} y2
  10701. * @param {Array.<number>} min
  10702. * @param {Array.<number>} max
  10703. */
  10704. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10705. var quadraticExtremum$$1 = quadraticExtremum;
  10706. var quadraticAt$$1 = quadraticAt;
  10707. // Find extremities, where derivative in x dim or y dim is zero
  10708. var tx =
  10709. mathMax$3(
  10710. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10711. );
  10712. var ty =
  10713. mathMax$3(
  10714. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10715. );
  10716. var x = quadraticAt$$1(x0, x1, x2, tx);
  10717. var y = quadraticAt$$1(y0, y1, y2, ty);
  10718. min$$1[0] = mathMin$3(x0, x2, x);
  10719. min$$1[1] = mathMin$3(y0, y2, y);
  10720. max$$1[0] = mathMax$3(x0, x2, x);
  10721. max$$1[1] = mathMax$3(y0, y2, y);
  10722. }
  10723. /**
  10724. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10725. * @method
  10726. * @memberOf module:zrender/core/bbox
  10727. * @param {number} x
  10728. * @param {number} y
  10729. * @param {number} rx
  10730. * @param {number} ry
  10731. * @param {number} startAngle
  10732. * @param {number} endAngle
  10733. * @param {number} anticlockwise
  10734. * @param {Array.<number>} min
  10735. * @param {Array.<number>} max
  10736. */
  10737. function fromArc(
  10738. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10739. ) {
  10740. var vec2Min = min;
  10741. var vec2Max = max;
  10742. var diff = Math.abs(startAngle - endAngle);
  10743. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10744. // Is a circle
  10745. min$$1[0] = x - rx;
  10746. min$$1[1] = y - ry;
  10747. max$$1[0] = x + rx;
  10748. max$$1[1] = y + ry;
  10749. return;
  10750. }
  10751. start[0] = mathCos$2(startAngle) * rx + x;
  10752. start[1] = mathSin$2(startAngle) * ry + y;
  10753. end[0] = mathCos$2(endAngle) * rx + x;
  10754. end[1] = mathSin$2(endAngle) * ry + y;
  10755. vec2Min(min$$1, start, end);
  10756. vec2Max(max$$1, start, end);
  10757. // Thresh to [0, Math.PI * 2]
  10758. startAngle = startAngle % (PI2);
  10759. if (startAngle < 0) {
  10760. startAngle = startAngle + PI2;
  10761. }
  10762. endAngle = endAngle % (PI2);
  10763. if (endAngle < 0) {
  10764. endAngle = endAngle + PI2;
  10765. }
  10766. if (startAngle > endAngle && !anticlockwise) {
  10767. endAngle += PI2;
  10768. }
  10769. else if (startAngle < endAngle && anticlockwise) {
  10770. startAngle += PI2;
  10771. }
  10772. if (anticlockwise) {
  10773. var tmp = endAngle;
  10774. endAngle = startAngle;
  10775. startAngle = tmp;
  10776. }
  10777. // var number = 0;
  10778. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10779. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10780. if (angle > startAngle) {
  10781. extremity[0] = mathCos$2(angle) * rx + x;
  10782. extremity[1] = mathSin$2(angle) * ry + y;
  10783. vec2Min(min$$1, extremity, min$$1);
  10784. vec2Max(max$$1, extremity, max$$1);
  10785. }
  10786. }
  10787. }
  10788. /**
  10789. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10790. * 可以用于 isInsidePath 判断以及获取boundingRect
  10791. *
  10792. * @module zrender/core/PathProxy
  10793. * @author Yi Shen (http://www.github.com/pissang)
  10794. */
  10795. // TODO getTotalLength, getPointAtLength
  10796. var CMD = {
  10797. M: 1,
  10798. L: 2,
  10799. C: 3,
  10800. Q: 4,
  10801. A: 5,
  10802. Z: 6,
  10803. // Rect
  10804. R: 7
  10805. };
  10806. // var CMD_MEM_SIZE = {
  10807. // M: 3,
  10808. // L: 3,
  10809. // C: 7,
  10810. // Q: 5,
  10811. // A: 9,
  10812. // R: 5,
  10813. // Z: 1
  10814. // };
  10815. var min$1 = [];
  10816. var max$1 = [];
  10817. var min2 = [];
  10818. var max2 = [];
  10819. var mathMin$2 = Math.min;
  10820. var mathMax$2 = Math.max;
  10821. var mathCos$1 = Math.cos;
  10822. var mathSin$1 = Math.sin;
  10823. var mathSqrt$1 = Math.sqrt;
  10824. var mathAbs = Math.abs;
  10825. var hasTypedArray = typeof Float32Array != 'undefined';
  10826. /**
  10827. * @alias module:zrender/core/PathProxy
  10828. * @constructor
  10829. */
  10830. var PathProxy = function (notSaveData) {
  10831. this._saveData = !(notSaveData || false);
  10832. if (this._saveData) {
  10833. /**
  10834. * Path data. Stored as flat array
  10835. * @type {Array.<Object>}
  10836. */
  10837. this.data = [];
  10838. }
  10839. this._ctx = null;
  10840. };
  10841. /**
  10842. * 快速计算Path包围盒(并不是最小包围盒)
  10843. * @return {Object}
  10844. */
  10845. PathProxy.prototype = {
  10846. constructor: PathProxy,
  10847. _xi: 0,
  10848. _yi: 0,
  10849. _x0: 0,
  10850. _y0: 0,
  10851. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10852. _ux: 0,
  10853. _uy: 0,
  10854. _len: 0,
  10855. _lineDash: null,
  10856. _dashOffset: 0,
  10857. _dashIdx: 0,
  10858. _dashSum: 0,
  10859. /**
  10860. * @readOnly
  10861. */
  10862. setScale: function (sx, sy) {
  10863. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10864. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10865. },
  10866. getContext: function () {
  10867. return this._ctx;
  10868. },
  10869. /**
  10870. * @param {CanvasRenderingContext2D} ctx
  10871. * @return {module:zrender/core/PathProxy}
  10872. */
  10873. beginPath: function (ctx) {
  10874. this._ctx = ctx;
  10875. ctx && ctx.beginPath();
  10876. ctx && (this.dpr = ctx.dpr);
  10877. // Reset
  10878. if (this._saveData) {
  10879. this._len = 0;
  10880. }
  10881. if (this._lineDash) {
  10882. this._lineDash = null;
  10883. this._dashOffset = 0;
  10884. }
  10885. return this;
  10886. },
  10887. /**
  10888. * @param {number} x
  10889. * @param {number} y
  10890. * @return {module:zrender/core/PathProxy}
  10891. */
  10892. moveTo: function (x, y) {
  10893. this.addData(CMD.M, x, y);
  10894. this._ctx && this._ctx.moveTo(x, y);
  10895. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10896. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10897. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10898. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10899. this._x0 = x;
  10900. this._y0 = y;
  10901. this._xi = x;
  10902. this._yi = y;
  10903. return this;
  10904. },
  10905. /**
  10906. * @param {number} x
  10907. * @param {number} y
  10908. * @return {module:zrender/core/PathProxy}
  10909. */
  10910. lineTo: function (x, y) {
  10911. var exceedUnit = mathAbs(x - this._xi) > this._ux
  10912. || mathAbs(y - this._yi) > this._uy
  10913. // Force draw the first segment
  10914. || this._len < 5;
  10915. this.addData(CMD.L, x, y);
  10916. if (this._ctx && exceedUnit) {
  10917. this._needsDash() ? this._dashedLineTo(x, y)
  10918. : this._ctx.lineTo(x, y);
  10919. }
  10920. if (exceedUnit) {
  10921. this._xi = x;
  10922. this._yi = y;
  10923. }
  10924. return this;
  10925. },
  10926. /**
  10927. * @param {number} x1
  10928. * @param {number} y1
  10929. * @param {number} x2
  10930. * @param {number} y2
  10931. * @param {number} x3
  10932. * @param {number} y3
  10933. * @return {module:zrender/core/PathProxy}
  10934. */
  10935. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  10936. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  10937. if (this._ctx) {
  10938. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  10939. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10940. }
  10941. this._xi = x3;
  10942. this._yi = y3;
  10943. return this;
  10944. },
  10945. /**
  10946. * @param {number} x1
  10947. * @param {number} y1
  10948. * @param {number} x2
  10949. * @param {number} y2
  10950. * @return {module:zrender/core/PathProxy}
  10951. */
  10952. quadraticCurveTo: function (x1, y1, x2, y2) {
  10953. this.addData(CMD.Q, x1, y1, x2, y2);
  10954. if (this._ctx) {
  10955. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  10956. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  10957. }
  10958. this._xi = x2;
  10959. this._yi = y2;
  10960. return this;
  10961. },
  10962. /**
  10963. * @param {number} cx
  10964. * @param {number} cy
  10965. * @param {number} r
  10966. * @param {number} startAngle
  10967. * @param {number} endAngle
  10968. * @param {boolean} anticlockwise
  10969. * @return {module:zrender/core/PathProxy}
  10970. */
  10971. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  10972. this.addData(
  10973. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  10974. );
  10975. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10976. this._xi = mathCos$1(endAngle) * r + cx;
  10977. this._yi = mathSin$1(endAngle) * r + cx;
  10978. return this;
  10979. },
  10980. // TODO
  10981. arcTo: function (x1, y1, x2, y2, radius) {
  10982. if (this._ctx) {
  10983. this._ctx.arcTo(x1, y1, x2, y2, radius);
  10984. }
  10985. return this;
  10986. },
  10987. // TODO
  10988. rect: function (x, y, w, h) {
  10989. this._ctx && this._ctx.rect(x, y, w, h);
  10990. this.addData(CMD.R, x, y, w, h);
  10991. return this;
  10992. },
  10993. /**
  10994. * @return {module:zrender/core/PathProxy}
  10995. */
  10996. closePath: function () {
  10997. this.addData(CMD.Z);
  10998. var ctx = this._ctx;
  10999. var x0 = this._x0;
  11000. var y0 = this._y0;
  11001. if (ctx) {
  11002. this._needsDash() && this._dashedLineTo(x0, y0);
  11003. ctx.closePath();
  11004. }
  11005. this._xi = x0;
  11006. this._yi = y0;
  11007. return this;
  11008. },
  11009. /**
  11010. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11011. * stroke 同样
  11012. * @param {CanvasRenderingContext2D} ctx
  11013. * @return {module:zrender/core/PathProxy}
  11014. */
  11015. fill: function (ctx) {
  11016. ctx && ctx.fill();
  11017. this.toStatic();
  11018. },
  11019. /**
  11020. * @param {CanvasRenderingContext2D} ctx
  11021. * @return {module:zrender/core/PathProxy}
  11022. */
  11023. stroke: function (ctx) {
  11024. ctx && ctx.stroke();
  11025. this.toStatic();
  11026. },
  11027. /**
  11028. * 必须在其它绘制命令前调用
  11029. * Must be invoked before all other path drawing methods
  11030. * @return {module:zrender/core/PathProxy}
  11031. */
  11032. setLineDash: function (lineDash) {
  11033. if (lineDash instanceof Array) {
  11034. this._lineDash = lineDash;
  11035. this._dashIdx = 0;
  11036. var lineDashSum = 0;
  11037. for (var i = 0; i < lineDash.length; i++) {
  11038. lineDashSum += lineDash[i];
  11039. }
  11040. this._dashSum = lineDashSum;
  11041. }
  11042. return this;
  11043. },
  11044. /**
  11045. * 必须在其它绘制命令前调用
  11046. * Must be invoked before all other path drawing methods
  11047. * @return {module:zrender/core/PathProxy}
  11048. */
  11049. setLineDashOffset: function (offset) {
  11050. this._dashOffset = offset;
  11051. return this;
  11052. },
  11053. /**
  11054. *
  11055. * @return {boolean}
  11056. */
  11057. len: function () {
  11058. return this._len;
  11059. },
  11060. /**
  11061. * 直接设置 Path 数据
  11062. */
  11063. setData: function (data) {
  11064. var len$$1 = data.length;
  11065. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11066. this.data = new Float32Array(len$$1);
  11067. }
  11068. for (var i = 0; i < len$$1; i++) {
  11069. this.data[i] = data[i];
  11070. }
  11071. this._len = len$$1;
  11072. },
  11073. /**
  11074. * 添加子路径
  11075. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11076. */
  11077. appendPath: function (path) {
  11078. if (!(path instanceof Array)) {
  11079. path = [path];
  11080. }
  11081. var len$$1 = path.length;
  11082. var appendSize = 0;
  11083. var offset = this._len;
  11084. for (var i = 0; i < len$$1; i++) {
  11085. appendSize += path[i].len();
  11086. }
  11087. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11088. this.data = new Float32Array(offset + appendSize);
  11089. }
  11090. for (var i = 0; i < len$$1; i++) {
  11091. var appendPathData = path[i].data;
  11092. for (var k = 0; k < appendPathData.length; k++) {
  11093. this.data[offset++] = appendPathData[k];
  11094. }
  11095. }
  11096. this._len = offset;
  11097. },
  11098. /**
  11099. * 填充 Path 数据。
  11100. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11101. */
  11102. addData: function (cmd) {
  11103. if (!this._saveData) {
  11104. return;
  11105. }
  11106. var data = this.data;
  11107. if (this._len + arguments.length > data.length) {
  11108. // 因为之前的数组已经转换成静态的 Float32Array
  11109. // 所以不够用时需要扩展一个新的动态数组
  11110. this._expandData();
  11111. data = this.data;
  11112. }
  11113. for (var i = 0; i < arguments.length; i++) {
  11114. data[this._len++] = arguments[i];
  11115. }
  11116. this._prevCmd = cmd;
  11117. },
  11118. _expandData: function () {
  11119. // Only if data is Float32Array
  11120. if (!(this.data instanceof Array)) {
  11121. var newData = [];
  11122. for (var i = 0; i < this._len; i++) {
  11123. newData[i] = this.data[i];
  11124. }
  11125. this.data = newData;
  11126. }
  11127. },
  11128. /**
  11129. * If needs js implemented dashed line
  11130. * @return {boolean}
  11131. * @private
  11132. */
  11133. _needsDash: function () {
  11134. return this._lineDash;
  11135. },
  11136. _dashedLineTo: function (x1, y1) {
  11137. var dashSum = this._dashSum;
  11138. var offset = this._dashOffset;
  11139. var lineDash = this._lineDash;
  11140. var ctx = this._ctx;
  11141. var x0 = this._xi;
  11142. var y0 = this._yi;
  11143. var dx = x1 - x0;
  11144. var dy = y1 - y0;
  11145. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11146. var x = x0;
  11147. var y = y0;
  11148. var dash;
  11149. var nDash = lineDash.length;
  11150. var idx;
  11151. dx /= dist$$1;
  11152. dy /= dist$$1;
  11153. if (offset < 0) {
  11154. // Convert to positive offset
  11155. offset = dashSum + offset;
  11156. }
  11157. offset %= dashSum;
  11158. x -= offset * dx;
  11159. y -= offset * dy;
  11160. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11161. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11162. idx = this._dashIdx;
  11163. dash = lineDash[idx];
  11164. x += dx * dash;
  11165. y += dy * dash;
  11166. this._dashIdx = (idx + 1) % nDash;
  11167. // Skip positive offset
  11168. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11169. continue;
  11170. }
  11171. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11172. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11173. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11174. );
  11175. }
  11176. // Offset for next lineTo
  11177. dx = x - x1;
  11178. dy = y - y1;
  11179. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11180. },
  11181. // Not accurate dashed line to
  11182. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11183. var dashSum = this._dashSum;
  11184. var offset = this._dashOffset;
  11185. var lineDash = this._lineDash;
  11186. var ctx = this._ctx;
  11187. var x0 = this._xi;
  11188. var y0 = this._yi;
  11189. var t;
  11190. var dx;
  11191. var dy;
  11192. var cubicAt$$1 = cubicAt;
  11193. var bezierLen = 0;
  11194. var idx = this._dashIdx;
  11195. var nDash = lineDash.length;
  11196. var x;
  11197. var y;
  11198. var tmpLen = 0;
  11199. if (offset < 0) {
  11200. // Convert to positive offset
  11201. offset = dashSum + offset;
  11202. }
  11203. offset %= dashSum;
  11204. // Bezier approx length
  11205. for (t = 0; t < 1; t += 0.1) {
  11206. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11207. - cubicAt$$1(x0, x1, x2, x3, t);
  11208. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11209. - cubicAt$$1(y0, y1, y2, y3, t);
  11210. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11211. }
  11212. // Find idx after add offset
  11213. for (; idx < nDash; idx++) {
  11214. tmpLen += lineDash[idx];
  11215. if (tmpLen > offset) {
  11216. break;
  11217. }
  11218. }
  11219. t = (tmpLen - offset) / bezierLen;
  11220. while (t <= 1) {
  11221. x = cubicAt$$1(x0, x1, x2, x3, t);
  11222. y = cubicAt$$1(y0, y1, y2, y3, t);
  11223. // Use line to approximate dashed bezier
  11224. // Bad result if dash is long
  11225. idx % 2 ? ctx.moveTo(x, y)
  11226. : ctx.lineTo(x, y);
  11227. t += lineDash[idx] / bezierLen;
  11228. idx = (idx + 1) % nDash;
  11229. }
  11230. // Finish the last segment and calculate the new offset
  11231. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11232. dx = x3 - x;
  11233. dy = y3 - y;
  11234. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11235. },
  11236. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11237. // Convert quadratic to cubic using degree elevation
  11238. var x3 = x2;
  11239. var y3 = y2;
  11240. x2 = (x2 + 2 * x1) / 3;
  11241. y2 = (y2 + 2 * y1) / 3;
  11242. x1 = (this._xi + 2 * x1) / 3;
  11243. y1 = (this._yi + 2 * y1) / 3;
  11244. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11245. },
  11246. /**
  11247. * 转成静态的 Float32Array 减少堆内存占用
  11248. * Convert dynamic array to static Float32Array
  11249. */
  11250. toStatic: function () {
  11251. var data = this.data;
  11252. if (data instanceof Array) {
  11253. data.length = this._len;
  11254. if (hasTypedArray) {
  11255. this.data = new Float32Array(data);
  11256. }
  11257. }
  11258. },
  11259. /**
  11260. * @return {module:zrender/core/BoundingRect}
  11261. */
  11262. getBoundingRect: function () {
  11263. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11264. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11265. var data = this.data;
  11266. var xi = 0;
  11267. var yi = 0;
  11268. var x0 = 0;
  11269. var y0 = 0;
  11270. for (var i = 0; i < data.length;) {
  11271. var cmd = data[i++];
  11272. if (i == 1) {
  11273. // 如果第一个命令是 L, C, Q
  11274. // 则 previous point 同绘制命令的第一个 point
  11275. //
  11276. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11277. xi = data[i];
  11278. yi = data[i + 1];
  11279. x0 = xi;
  11280. y0 = yi;
  11281. }
  11282. switch (cmd) {
  11283. case CMD.M:
  11284. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11285. // 在 closePath 的时候使用
  11286. x0 = data[i++];
  11287. y0 = data[i++];
  11288. xi = x0;
  11289. yi = y0;
  11290. min2[0] = x0;
  11291. min2[1] = y0;
  11292. max2[0] = x0;
  11293. max2[1] = y0;
  11294. break;
  11295. case CMD.L:
  11296. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11297. xi = data[i++];
  11298. yi = data[i++];
  11299. break;
  11300. case CMD.C:
  11301. fromCubic(
  11302. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11303. min2, max2
  11304. );
  11305. xi = data[i++];
  11306. yi = data[i++];
  11307. break;
  11308. case CMD.Q:
  11309. fromQuadratic(
  11310. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11311. min2, max2
  11312. );
  11313. xi = data[i++];
  11314. yi = data[i++];
  11315. break;
  11316. case CMD.A:
  11317. // TODO Arc 判断的开销比较大
  11318. var cx = data[i++];
  11319. var cy = data[i++];
  11320. var rx = data[i++];
  11321. var ry = data[i++];
  11322. var startAngle = data[i++];
  11323. var endAngle = data[i++] + startAngle;
  11324. // TODO Arc 旋转
  11325. var psi = data[i++];
  11326. var anticlockwise = 1 - data[i++];
  11327. if (i == 1) {
  11328. // 直接使用 arc 命令
  11329. // 第一个命令起点还未定义
  11330. x0 = mathCos$1(startAngle) * rx + cx;
  11331. y0 = mathSin$1(startAngle) * ry + cy;
  11332. }
  11333. fromArc(
  11334. cx, cy, rx, ry, startAngle, endAngle,
  11335. anticlockwise, min2, max2
  11336. );
  11337. xi = mathCos$1(endAngle) * rx + cx;
  11338. yi = mathSin$1(endAngle) * ry + cy;
  11339. break;
  11340. case CMD.R:
  11341. x0 = xi = data[i++];
  11342. y0 = yi = data[i++];
  11343. var width = data[i++];
  11344. var height = data[i++];
  11345. // Use fromLine
  11346. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11347. break;
  11348. case CMD.Z:
  11349. xi = x0;
  11350. yi = y0;
  11351. break;
  11352. }
  11353. // Union
  11354. min(min$1, min$1, min2);
  11355. max(max$1, max$1, max2);
  11356. }
  11357. // No data
  11358. if (i === 0) {
  11359. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11360. }
  11361. return new BoundingRect(
  11362. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11363. );
  11364. },
  11365. /**
  11366. * Rebuild path from current data
  11367. * Rebuild path will not consider javascript implemented line dash.
  11368. * @param {CanvasRenderingContext2D} ctx
  11369. */
  11370. rebuildPath: function (ctx) {
  11371. var d = this.data;
  11372. var x0, y0;
  11373. var xi, yi;
  11374. var x, y;
  11375. var ux = this._ux;
  11376. var uy = this._uy;
  11377. var len$$1 = this._len;
  11378. for (var i = 0; i < len$$1;) {
  11379. var cmd = d[i++];
  11380. if (i == 1) {
  11381. // 如果第一个命令是 L, C, Q
  11382. // 则 previous point 同绘制命令的第一个 point
  11383. //
  11384. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11385. xi = d[i];
  11386. yi = d[i + 1];
  11387. x0 = xi;
  11388. y0 = yi;
  11389. }
  11390. switch (cmd) {
  11391. case CMD.M:
  11392. x0 = xi = d[i++];
  11393. y0 = yi = d[i++];
  11394. ctx.moveTo(xi, yi);
  11395. break;
  11396. case CMD.L:
  11397. x = d[i++];
  11398. y = d[i++];
  11399. // Not draw too small seg between
  11400. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11401. ctx.lineTo(x, y);
  11402. xi = x;
  11403. yi = y;
  11404. }
  11405. break;
  11406. case CMD.C:
  11407. ctx.bezierCurveTo(
  11408. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11409. );
  11410. xi = d[i - 2];
  11411. yi = d[i - 1];
  11412. break;
  11413. case CMD.Q:
  11414. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11415. xi = d[i - 2];
  11416. yi = d[i - 1];
  11417. break;
  11418. case CMD.A:
  11419. var cx = d[i++];
  11420. var cy = d[i++];
  11421. var rx = d[i++];
  11422. var ry = d[i++];
  11423. var theta = d[i++];
  11424. var dTheta = d[i++];
  11425. var psi = d[i++];
  11426. var fs = d[i++];
  11427. var r = (rx > ry) ? rx : ry;
  11428. var scaleX = (rx > ry) ? 1 : rx / ry;
  11429. var scaleY = (rx > ry) ? ry / rx : 1;
  11430. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11431. var endAngle = theta + dTheta;
  11432. if (isEllipse) {
  11433. ctx.translate(cx, cy);
  11434. ctx.rotate(psi);
  11435. ctx.scale(scaleX, scaleY);
  11436. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11437. ctx.scale(1 / scaleX, 1 / scaleY);
  11438. ctx.rotate(-psi);
  11439. ctx.translate(-cx, -cy);
  11440. }
  11441. else {
  11442. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11443. }
  11444. if (i == 1) {
  11445. // 直接使用 arc 命令
  11446. // 第一个命令起点还未定义
  11447. x0 = mathCos$1(theta) * rx + cx;
  11448. y0 = mathSin$1(theta) * ry + cy;
  11449. }
  11450. xi = mathCos$1(endAngle) * rx + cx;
  11451. yi = mathSin$1(endAngle) * ry + cy;
  11452. break;
  11453. case CMD.R:
  11454. x0 = xi = d[i];
  11455. y0 = yi = d[i + 1];
  11456. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11457. break;
  11458. case CMD.Z:
  11459. ctx.closePath();
  11460. xi = x0;
  11461. yi = y0;
  11462. }
  11463. }
  11464. }
  11465. };
  11466. PathProxy.CMD = CMD;
  11467. /**
  11468. * 线段包含判断
  11469. * @param {number} x0
  11470. * @param {number} y0
  11471. * @param {number} x1
  11472. * @param {number} y1
  11473. * @param {number} lineWidth
  11474. * @param {number} x
  11475. * @param {number} y
  11476. * @return {boolean}
  11477. */
  11478. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11479. if (lineWidth === 0) {
  11480. return false;
  11481. }
  11482. var _l = lineWidth;
  11483. var _a = 0;
  11484. var _b = x0;
  11485. // Quick reject
  11486. if (
  11487. (y > y0 + _l && y > y1 + _l)
  11488. || (y < y0 - _l && y < y1 - _l)
  11489. || (x > x0 + _l && x > x1 + _l)
  11490. || (x < x0 - _l && x < x1 - _l)
  11491. ) {
  11492. return false;
  11493. }
  11494. if (x0 !== x1) {
  11495. _a = (y0 - y1) / (x0 - x1);
  11496. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11497. }
  11498. else {
  11499. return Math.abs(x - x0) <= _l / 2;
  11500. }
  11501. var tmp = _a * x - y + _b;
  11502. var _s = tmp * tmp / (_a * _a + 1);
  11503. return _s <= _l / 2 * _l / 2;
  11504. }
  11505. /**
  11506. * 三次贝塞尔曲线描边包含判断
  11507. * @param {number} x0
  11508. * @param {number} y0
  11509. * @param {number} x1
  11510. * @param {number} y1
  11511. * @param {number} x2
  11512. * @param {number} y2
  11513. * @param {number} x3
  11514. * @param {number} y3
  11515. * @param {number} lineWidth
  11516. * @param {number} x
  11517. * @param {number} y
  11518. * @return {boolean}
  11519. */
  11520. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11521. if (lineWidth === 0) {
  11522. return false;
  11523. }
  11524. var _l = lineWidth;
  11525. // Quick reject
  11526. if (
  11527. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11528. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11529. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11530. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11531. ) {
  11532. return false;
  11533. }
  11534. var d = cubicProjectPoint(
  11535. x0, y0, x1, y1, x2, y2, x3, y3,
  11536. x, y, null
  11537. );
  11538. return d <= _l / 2;
  11539. }
  11540. /**
  11541. * 二次贝塞尔曲线描边包含判断
  11542. * @param {number} x0
  11543. * @param {number} y0
  11544. * @param {number} x1
  11545. * @param {number} y1
  11546. * @param {number} x2
  11547. * @param {number} y2
  11548. * @param {number} lineWidth
  11549. * @param {number} x
  11550. * @param {number} y
  11551. * @return {boolean}
  11552. */
  11553. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11554. if (lineWidth === 0) {
  11555. return false;
  11556. }
  11557. var _l = lineWidth;
  11558. // Quick reject
  11559. if (
  11560. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11561. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11562. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11563. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11564. ) {
  11565. return false;
  11566. }
  11567. var d = quadraticProjectPoint(
  11568. x0, y0, x1, y1, x2, y2,
  11569. x, y, null
  11570. );
  11571. return d <= _l / 2;
  11572. }
  11573. var PI2$3 = Math.PI * 2;
  11574. function normalizeRadian(angle) {
  11575. angle %= PI2$3;
  11576. if (angle < 0) {
  11577. angle += PI2$3;
  11578. }
  11579. return angle;
  11580. }
  11581. var PI2$2 = Math.PI * 2;
  11582. /**
  11583. * 圆弧描边包含判断
  11584. * @param {number} cx
  11585. * @param {number} cy
  11586. * @param {number} r
  11587. * @param {number} startAngle
  11588. * @param {number} endAngle
  11589. * @param {boolean} anticlockwise
  11590. * @param {number} lineWidth
  11591. * @param {number} x
  11592. * @param {number} y
  11593. * @return {Boolean}
  11594. */
  11595. function containStroke$4(
  11596. cx, cy, r, startAngle, endAngle, anticlockwise,
  11597. lineWidth, x, y
  11598. ) {
  11599. if (lineWidth === 0) {
  11600. return false;
  11601. }
  11602. var _l = lineWidth;
  11603. x -= cx;
  11604. y -= cy;
  11605. var d = Math.sqrt(x * x + y * y);
  11606. if ((d - _l > r) || (d + _l < r)) {
  11607. return false;
  11608. }
  11609. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11610. // Is a circle
  11611. return true;
  11612. }
  11613. if (anticlockwise) {
  11614. var tmp = startAngle;
  11615. startAngle = normalizeRadian(endAngle);
  11616. endAngle = normalizeRadian(tmp);
  11617. } else {
  11618. startAngle = normalizeRadian(startAngle);
  11619. endAngle = normalizeRadian(endAngle);
  11620. }
  11621. if (startAngle > endAngle) {
  11622. endAngle += PI2$2;
  11623. }
  11624. var angle = Math.atan2(y, x);
  11625. if (angle < 0) {
  11626. angle += PI2$2;
  11627. }
  11628. return (angle >= startAngle && angle <= endAngle)
  11629. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11630. }
  11631. function windingLine(x0, y0, x1, y1, x, y) {
  11632. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11633. return 0;
  11634. }
  11635. // Ignore horizontal line
  11636. if (y1 === y0) {
  11637. return 0;
  11638. }
  11639. var dir = y1 < y0 ? 1 : -1;
  11640. var t = (y - y0) / (y1 - y0);
  11641. // Avoid winding error when intersection point is the connect point of two line of polygon
  11642. if (t === 1 || t === 0) {
  11643. dir = y1 < y0 ? 0.5 : -0.5;
  11644. }
  11645. var x_ = t * (x1 - x0) + x0;
  11646. return x_ > x ? dir : 0;
  11647. }
  11648. var CMD$1 = PathProxy.CMD;
  11649. var PI2$1 = Math.PI * 2;
  11650. var EPSILON$2 = 1e-4;
  11651. function isAroundEqual(a, b) {
  11652. return Math.abs(a - b) < EPSILON$2;
  11653. }
  11654. // 临时数组
  11655. var roots = [-1, -1, -1];
  11656. var extrema = [-1, -1];
  11657. function swapExtrema() {
  11658. var tmp = extrema[0];
  11659. extrema[0] = extrema[1];
  11660. extrema[1] = tmp;
  11661. }
  11662. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11663. // Quick reject
  11664. if (
  11665. (y > y0 && y > y1 && y > y2 && y > y3)
  11666. || (y < y0 && y < y1 && y < y2 && y < y3)
  11667. ) {
  11668. return 0;
  11669. }
  11670. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11671. if (nRoots === 0) {
  11672. return 0;
  11673. }
  11674. else {
  11675. var w = 0;
  11676. var nExtrema = -1;
  11677. var y0_, y1_;
  11678. for (var i = 0; i < nRoots; i++) {
  11679. var t = roots[i];
  11680. // Avoid winding error when intersection point is the connect point of two line of polygon
  11681. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11682. var x_ = cubicAt(x0, x1, x2, x3, t);
  11683. if (x_ < x) { // Quick reject
  11684. continue;
  11685. }
  11686. if (nExtrema < 0) {
  11687. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11688. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11689. swapExtrema();
  11690. }
  11691. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11692. if (nExtrema > 1) {
  11693. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11694. }
  11695. }
  11696. if (nExtrema == 2) {
  11697. // 分成三段单调函数
  11698. if (t < extrema[0]) {
  11699. w += y0_ < y0 ? unit : -unit;
  11700. }
  11701. else if (t < extrema[1]) {
  11702. w += y1_ < y0_ ? unit : -unit;
  11703. }
  11704. else {
  11705. w += y3 < y1_ ? unit : -unit;
  11706. }
  11707. }
  11708. else {
  11709. // 分成两段单调函数
  11710. if (t < extrema[0]) {
  11711. w += y0_ < y0 ? unit : -unit;
  11712. }
  11713. else {
  11714. w += y3 < y0_ ? unit : -unit;
  11715. }
  11716. }
  11717. }
  11718. return w;
  11719. }
  11720. }
  11721. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11722. // Quick reject
  11723. if (
  11724. (y > y0 && y > y1 && y > y2)
  11725. || (y < y0 && y < y1 && y < y2)
  11726. ) {
  11727. return 0;
  11728. }
  11729. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11730. if (nRoots === 0) {
  11731. return 0;
  11732. }
  11733. else {
  11734. var t = quadraticExtremum(y0, y1, y2);
  11735. if (t >= 0 && t <= 1) {
  11736. var w = 0;
  11737. var y_ = quadraticAt(y0, y1, y2, t);
  11738. for (var i = 0; i < nRoots; i++) {
  11739. // Remove one endpoint.
  11740. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11741. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11742. if (x_ < x) { // Quick reject
  11743. continue;
  11744. }
  11745. if (roots[i] < t) {
  11746. w += y_ < y0 ? unit : -unit;
  11747. }
  11748. else {
  11749. w += y2 < y_ ? unit : -unit;
  11750. }
  11751. }
  11752. return w;
  11753. }
  11754. else {
  11755. // Remove one endpoint.
  11756. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11757. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11758. if (x_ < x) { // Quick reject
  11759. return 0;
  11760. }
  11761. return y2 < y0 ? unit : -unit;
  11762. }
  11763. }
  11764. }
  11765. // TODO
  11766. // Arc 旋转
  11767. function windingArc(
  11768. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11769. ) {
  11770. y -= cy;
  11771. if (y > r || y < -r) {
  11772. return 0;
  11773. }
  11774. var tmp = Math.sqrt(r * r - y * y);
  11775. roots[0] = -tmp;
  11776. roots[1] = tmp;
  11777. var diff = Math.abs(startAngle - endAngle);
  11778. if (diff < 1e-4) {
  11779. return 0;
  11780. }
  11781. if (diff % PI2$1 < 1e-4) {
  11782. // Is a circle
  11783. startAngle = 0;
  11784. endAngle = PI2$1;
  11785. var dir = anticlockwise ? 1 : -1;
  11786. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11787. return dir;
  11788. } else {
  11789. return 0;
  11790. }
  11791. }
  11792. if (anticlockwise) {
  11793. var tmp = startAngle;
  11794. startAngle = normalizeRadian(endAngle);
  11795. endAngle = normalizeRadian(tmp);
  11796. }
  11797. else {
  11798. startAngle = normalizeRadian(startAngle);
  11799. endAngle = normalizeRadian(endAngle);
  11800. }
  11801. if (startAngle > endAngle) {
  11802. endAngle += PI2$1;
  11803. }
  11804. var w = 0;
  11805. for (var i = 0; i < 2; i++) {
  11806. var x_ = roots[i];
  11807. if (x_ + cx > x) {
  11808. var angle = Math.atan2(y, x_);
  11809. var dir = anticlockwise ? 1 : -1;
  11810. if (angle < 0) {
  11811. angle = PI2$1 + angle;
  11812. }
  11813. if (
  11814. (angle >= startAngle && angle <= endAngle)
  11815. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11816. ) {
  11817. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11818. dir = -dir;
  11819. }
  11820. w += dir;
  11821. }
  11822. }
  11823. }
  11824. return w;
  11825. }
  11826. function containPath(data, lineWidth, isStroke, x, y) {
  11827. var w = 0;
  11828. var xi = 0;
  11829. var yi = 0;
  11830. var x0 = 0;
  11831. var y0 = 0;
  11832. for (var i = 0; i < data.length;) {
  11833. var cmd = data[i++];
  11834. // Begin a new subpath
  11835. if (cmd === CMD$1.M && i > 1) {
  11836. // Close previous subpath
  11837. if (!isStroke) {
  11838. w += windingLine(xi, yi, x0, y0, x, y);
  11839. }
  11840. // 如果被任何一个 subpath 包含
  11841. // if (w !== 0) {
  11842. // return true;
  11843. // }
  11844. }
  11845. if (i == 1) {
  11846. // 如果第一个命令是 L, C, Q
  11847. // 则 previous point 同绘制命令的第一个 point
  11848. //
  11849. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11850. xi = data[i];
  11851. yi = data[i + 1];
  11852. x0 = xi;
  11853. y0 = yi;
  11854. }
  11855. switch (cmd) {
  11856. case CMD$1.M:
  11857. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11858. // 在 closePath 的时候使用
  11859. x0 = data[i++];
  11860. y0 = data[i++];
  11861. xi = x0;
  11862. yi = y0;
  11863. break;
  11864. case CMD$1.L:
  11865. if (isStroke) {
  11866. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11867. return true;
  11868. }
  11869. }
  11870. else {
  11871. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11872. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11873. }
  11874. xi = data[i++];
  11875. yi = data[i++];
  11876. break;
  11877. case CMD$1.C:
  11878. if (isStroke) {
  11879. if (containStroke$2(xi, yi,
  11880. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11881. lineWidth, x, y
  11882. )) {
  11883. return true;
  11884. }
  11885. }
  11886. else {
  11887. w += windingCubic(
  11888. xi, yi,
  11889. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11890. x, y
  11891. ) || 0;
  11892. }
  11893. xi = data[i++];
  11894. yi = data[i++];
  11895. break;
  11896. case CMD$1.Q:
  11897. if (isStroke) {
  11898. if (containStroke$3(xi, yi,
  11899. data[i++], data[i++], data[i], data[i + 1],
  11900. lineWidth, x, y
  11901. )) {
  11902. return true;
  11903. }
  11904. }
  11905. else {
  11906. w += windingQuadratic(
  11907. xi, yi,
  11908. data[i++], data[i++], data[i], data[i + 1],
  11909. x, y
  11910. ) || 0;
  11911. }
  11912. xi = data[i++];
  11913. yi = data[i++];
  11914. break;
  11915. case CMD$1.A:
  11916. // TODO Arc 判断的开销比较大
  11917. var cx = data[i++];
  11918. var cy = data[i++];
  11919. var rx = data[i++];
  11920. var ry = data[i++];
  11921. var theta = data[i++];
  11922. var dTheta = data[i++];
  11923. // TODO Arc 旋转
  11924. var psi = data[i++];
  11925. var anticlockwise = 1 - data[i++];
  11926. var x1 = Math.cos(theta) * rx + cx;
  11927. var y1 = Math.sin(theta) * ry + cy;
  11928. // 不是直接使用 arc 命令
  11929. if (i > 1) {
  11930. w += windingLine(xi, yi, x1, y1, x, y);
  11931. }
  11932. else {
  11933. // 第一个命令起点还未定义
  11934. x0 = x1;
  11935. y0 = y1;
  11936. }
  11937. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  11938. var _x = (x - cx) * ry / rx + cx;
  11939. if (isStroke) {
  11940. if (containStroke$4(
  11941. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11942. lineWidth, _x, y
  11943. )) {
  11944. return true;
  11945. }
  11946. }
  11947. else {
  11948. w += windingArc(
  11949. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11950. _x, y
  11951. );
  11952. }
  11953. xi = Math.cos(theta + dTheta) * rx + cx;
  11954. yi = Math.sin(theta + dTheta) * ry + cy;
  11955. break;
  11956. case CMD$1.R:
  11957. x0 = xi = data[i++];
  11958. y0 = yi = data[i++];
  11959. var width = data[i++];
  11960. var height = data[i++];
  11961. var x1 = x0 + width;
  11962. var y1 = y0 + height;
  11963. if (isStroke) {
  11964. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  11965. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  11966. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  11967. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  11968. ) {
  11969. return true;
  11970. }
  11971. }
  11972. else {
  11973. // FIXME Clockwise ?
  11974. w += windingLine(x1, y0, x1, y1, x, y);
  11975. w += windingLine(x0, y1, x0, y0, x, y);
  11976. }
  11977. break;
  11978. case CMD$1.Z:
  11979. if (isStroke) {
  11980. if (containStroke$1(
  11981. xi, yi, x0, y0, lineWidth, x, y
  11982. )) {
  11983. return true;
  11984. }
  11985. }
  11986. else {
  11987. // Close a subpath
  11988. w += windingLine(xi, yi, x0, y0, x, y);
  11989. // 如果被任何一个 subpath 包含
  11990. // FIXME subpaths may overlap
  11991. // if (w !== 0) {
  11992. // return true;
  11993. // }
  11994. }
  11995. xi = x0;
  11996. yi = y0;
  11997. break;
  11998. }
  11999. }
  12000. if (!isStroke && !isAroundEqual(yi, y0)) {
  12001. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12002. }
  12003. return w !== 0;
  12004. }
  12005. function contain(pathData, x, y) {
  12006. return containPath(pathData, 0, false, x, y);
  12007. }
  12008. function containStroke(pathData, lineWidth, x, y) {
  12009. return containPath(pathData, lineWidth, true, x, y);
  12010. }
  12011. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12012. var abs = Math.abs;
  12013. var pathProxyForDraw = new PathProxy(true);
  12014. /**
  12015. * @alias module:zrender/graphic/Path
  12016. * @extends module:zrender/graphic/Displayable
  12017. * @constructor
  12018. * @param {Object} opts
  12019. */
  12020. function Path(opts) {
  12021. Displayable.call(this, opts);
  12022. /**
  12023. * @type {module:zrender/core/PathProxy}
  12024. * @readOnly
  12025. */
  12026. this.path = null;
  12027. }
  12028. Path.prototype = {
  12029. constructor: Path,
  12030. type: 'path',
  12031. __dirtyPath: true,
  12032. strokeContainThreshold: 5,
  12033. brush: function (ctx, prevEl) {
  12034. var style = this.style;
  12035. var path = this.path || pathProxyForDraw;
  12036. var hasStroke = style.hasStroke();
  12037. var hasFill = style.hasFill();
  12038. var fill = style.fill;
  12039. var stroke = style.stroke;
  12040. var hasFillGradient = hasFill && !!(fill.colorStops);
  12041. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12042. var hasFillPattern = hasFill && !!(fill.image);
  12043. var hasStrokePattern = hasStroke && !!(stroke.image);
  12044. style.bind(ctx, this, prevEl);
  12045. this.setTransform(ctx);
  12046. if (this.__dirty) {
  12047. var rect;
  12048. // Update gradient because bounding rect may changed
  12049. if (hasFillGradient) {
  12050. rect = rect || this.getBoundingRect();
  12051. this._fillGradient = style.getGradient(ctx, fill, rect);
  12052. }
  12053. if (hasStrokeGradient) {
  12054. rect = rect || this.getBoundingRect();
  12055. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12056. }
  12057. }
  12058. // Use the gradient or pattern
  12059. if (hasFillGradient) {
  12060. // PENDING If may have affect the state
  12061. ctx.fillStyle = this._fillGradient;
  12062. }
  12063. else if (hasFillPattern) {
  12064. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12065. }
  12066. if (hasStrokeGradient) {
  12067. ctx.strokeStyle = this._strokeGradient;
  12068. }
  12069. else if (hasStrokePattern) {
  12070. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12071. }
  12072. var lineDash = style.lineDash;
  12073. var lineDashOffset = style.lineDashOffset;
  12074. var ctxLineDash = !!ctx.setLineDash;
  12075. // Update path sx, sy
  12076. var scale = this.getGlobalScale();
  12077. path.setScale(scale[0], scale[1]);
  12078. // Proxy context
  12079. // Rebuild path in following 2 cases
  12080. // 1. Path is dirty
  12081. // 2. Path needs javascript implemented lineDash stroking.
  12082. // In this case, lineDash information will not be saved in PathProxy
  12083. if (this.__dirtyPath
  12084. || (lineDash && !ctxLineDash && hasStroke)
  12085. ) {
  12086. path.beginPath(ctx);
  12087. // Setting line dash before build path
  12088. if (lineDash && !ctxLineDash) {
  12089. path.setLineDash(lineDash);
  12090. path.setLineDashOffset(lineDashOffset);
  12091. }
  12092. this.buildPath(path, this.shape, false);
  12093. // Clear path dirty flag
  12094. if (this.path) {
  12095. this.__dirtyPath = false;
  12096. }
  12097. }
  12098. else {
  12099. // Replay path building
  12100. ctx.beginPath();
  12101. this.path.rebuildPath(ctx);
  12102. }
  12103. hasFill && path.fill(ctx);
  12104. if (lineDash && ctxLineDash) {
  12105. ctx.setLineDash(lineDash);
  12106. ctx.lineDashOffset = lineDashOffset;
  12107. }
  12108. hasStroke && path.stroke(ctx);
  12109. if (lineDash && ctxLineDash) {
  12110. // PENDING
  12111. // Remove lineDash
  12112. ctx.setLineDash([]);
  12113. }
  12114. // Draw rect text
  12115. if (style.text != null) {
  12116. // Only restore transform when needs draw text.
  12117. this.restoreTransform(ctx);
  12118. this.drawRectText(ctx, this.getBoundingRect());
  12119. }
  12120. },
  12121. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12122. // Like in circle
  12123. buildPath: function (ctx, shapeCfg, inBundle) {},
  12124. createPathProxy: function () {
  12125. this.path = new PathProxy();
  12126. },
  12127. getBoundingRect: function () {
  12128. var rect = this._rect;
  12129. var style = this.style;
  12130. var needsUpdateRect = !rect;
  12131. if (needsUpdateRect) {
  12132. var path = this.path;
  12133. if (!path) {
  12134. // Create path on demand.
  12135. path = this.path = new PathProxy();
  12136. }
  12137. if (this.__dirtyPath) {
  12138. path.beginPath();
  12139. this.buildPath(path, this.shape, false);
  12140. }
  12141. rect = path.getBoundingRect();
  12142. }
  12143. this._rect = rect;
  12144. if (style.hasStroke()) {
  12145. // Needs update rect with stroke lineWidth when
  12146. // 1. Element changes scale or lineWidth
  12147. // 2. Shape is changed
  12148. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12149. if (this.__dirty || needsUpdateRect) {
  12150. rectWithStroke.copy(rect);
  12151. // FIXME Must after updateTransform
  12152. var w = style.lineWidth;
  12153. // PENDING, Min line width is needed when line is horizontal or vertical
  12154. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12155. // Only add extra hover lineWidth when there are no fill
  12156. if (!style.hasFill()) {
  12157. w = Math.max(w, this.strokeContainThreshold || 4);
  12158. }
  12159. // Consider line width
  12160. // Line scale can't be 0;
  12161. if (lineScale > 1e-10) {
  12162. rectWithStroke.width += w / lineScale;
  12163. rectWithStroke.height += w / lineScale;
  12164. rectWithStroke.x -= w / lineScale / 2;
  12165. rectWithStroke.y -= w / lineScale / 2;
  12166. }
  12167. }
  12168. // Return rect with stroke
  12169. return rectWithStroke;
  12170. }
  12171. return rect;
  12172. },
  12173. contain: function (x, y) {
  12174. var localPos = this.transformCoordToLocal(x, y);
  12175. var rect = this.getBoundingRect();
  12176. var style = this.style;
  12177. x = localPos[0];
  12178. y = localPos[1];
  12179. if (rect.contain(x, y)) {
  12180. var pathData = this.path.data;
  12181. if (style.hasStroke()) {
  12182. var lineWidth = style.lineWidth;
  12183. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12184. // Line scale can't be 0;
  12185. if (lineScale > 1e-10) {
  12186. // Only add extra hover lineWidth when there are no fill
  12187. if (!style.hasFill()) {
  12188. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12189. }
  12190. if (containStroke(
  12191. pathData, lineWidth / lineScale, x, y
  12192. )) {
  12193. return true;
  12194. }
  12195. }
  12196. }
  12197. if (style.hasFill()) {
  12198. return contain(pathData, x, y);
  12199. }
  12200. }
  12201. return false;
  12202. },
  12203. /**
  12204. * @param {boolean} dirtyPath
  12205. */
  12206. dirty: function (dirtyPath) {
  12207. if (dirtyPath == null) {
  12208. dirtyPath = true;
  12209. }
  12210. // Only mark dirty, not mark clean
  12211. if (dirtyPath) {
  12212. this.__dirtyPath = dirtyPath;
  12213. this._rect = null;
  12214. }
  12215. this.__dirty = true;
  12216. this.__zr && this.__zr.refresh();
  12217. // Used as a clipping path
  12218. if (this.__clipTarget) {
  12219. this.__clipTarget.dirty();
  12220. }
  12221. },
  12222. /**
  12223. * Alias for animate('shape')
  12224. * @param {boolean} loop
  12225. */
  12226. animateShape: function (loop) {
  12227. return this.animate('shape', loop);
  12228. },
  12229. // Overwrite attrKV
  12230. attrKV: function (key, value) {
  12231. // FIXME
  12232. if (key === 'shape') {
  12233. this.setShape(value);
  12234. this.__dirtyPath = true;
  12235. this._rect = null;
  12236. }
  12237. else {
  12238. Displayable.prototype.attrKV.call(this, key, value);
  12239. }
  12240. },
  12241. /**
  12242. * @param {Object|string} key
  12243. * @param {*} value
  12244. */
  12245. setShape: function (key, value) {
  12246. var shape = this.shape;
  12247. // Path from string may not have shape
  12248. if (shape) {
  12249. if (isObject$1(key)) {
  12250. for (var name in key) {
  12251. if (key.hasOwnProperty(name)) {
  12252. shape[name] = key[name];
  12253. }
  12254. }
  12255. }
  12256. else {
  12257. shape[key] = value;
  12258. }
  12259. this.dirty(true);
  12260. }
  12261. return this;
  12262. },
  12263. getLineScale: function () {
  12264. var m = this.transform;
  12265. // Get the line scale.
  12266. // Determinant of `m` means how much the area is enlarged by the
  12267. // transformation. So its square root can be used as a scale factor
  12268. // for width.
  12269. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12270. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12271. : 1;
  12272. }
  12273. };
  12274. /**
  12275. * 扩展一个 Path element, 比如星形,圆等。
  12276. * Extend a path element
  12277. * @param {Object} props
  12278. * @param {string} props.type Path type
  12279. * @param {Function} props.init Initialize
  12280. * @param {Function} props.buildPath Overwrite buildPath method
  12281. * @param {Object} [props.style] Extended default style config
  12282. * @param {Object} [props.shape] Extended default shape config
  12283. */
  12284. Path.extend = function (defaults$$1) {
  12285. var Sub = function (opts) {
  12286. Path.call(this, opts);
  12287. if (defaults$$1.style) {
  12288. // Extend default style
  12289. this.style.extendFrom(defaults$$1.style, false);
  12290. }
  12291. // Extend default shape
  12292. var defaultShape = defaults$$1.shape;
  12293. if (defaultShape) {
  12294. this.shape = this.shape || {};
  12295. var thisShape = this.shape;
  12296. for (var name in defaultShape) {
  12297. if (
  12298. ! thisShape.hasOwnProperty(name)
  12299. && defaultShape.hasOwnProperty(name)
  12300. ) {
  12301. thisShape[name] = defaultShape[name];
  12302. }
  12303. }
  12304. }
  12305. defaults$$1.init && defaults$$1.init.call(this, opts);
  12306. };
  12307. inherits(Sub, Path);
  12308. // FIXME 不能 extend position, rotation 等引用对象
  12309. for (var name in defaults$$1) {
  12310. // Extending prototype values and methods
  12311. if (name !== 'style' && name !== 'shape') {
  12312. Sub.prototype[name] = defaults$$1[name];
  12313. }
  12314. }
  12315. return Sub;
  12316. };
  12317. inherits(Path, Displayable);
  12318. var CMD$2 = PathProxy.CMD;
  12319. var points = [[], [], []];
  12320. var mathSqrt$3 = Math.sqrt;
  12321. var mathAtan2 = Math.atan2;
  12322. var transformPath = function (path, m) {
  12323. var data = path.data;
  12324. var cmd;
  12325. var nPoint;
  12326. var i;
  12327. var j;
  12328. var k;
  12329. var p;
  12330. var M = CMD$2.M;
  12331. var C = CMD$2.C;
  12332. var L = CMD$2.L;
  12333. var R = CMD$2.R;
  12334. var A = CMD$2.A;
  12335. var Q = CMD$2.Q;
  12336. for (i = 0, j = 0; i < data.length;) {
  12337. cmd = data[i++];
  12338. j = i;
  12339. nPoint = 0;
  12340. switch (cmd) {
  12341. case M:
  12342. nPoint = 1;
  12343. break;
  12344. case L:
  12345. nPoint = 1;
  12346. break;
  12347. case C:
  12348. nPoint = 3;
  12349. break;
  12350. case Q:
  12351. nPoint = 2;
  12352. break;
  12353. case A:
  12354. var x = m[4];
  12355. var y = m[5];
  12356. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12357. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12358. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12359. // cx
  12360. data[i] *= sx;
  12361. data[i++] += x;
  12362. // cy
  12363. data[i] *= sy;
  12364. data[i++] += y;
  12365. // Scale rx and ry
  12366. // FIXME Assume psi is 0 here
  12367. data[i++] *= sx;
  12368. data[i++] *= sy;
  12369. // Start angle
  12370. data[i++] += angle;
  12371. // end angle
  12372. data[i++] += angle;
  12373. // FIXME psi
  12374. i += 2;
  12375. j = i;
  12376. break;
  12377. case R:
  12378. // x0, y0
  12379. p[0] = data[i++];
  12380. p[1] = data[i++];
  12381. applyTransform(p, p, m);
  12382. data[j++] = p[0];
  12383. data[j++] = p[1];
  12384. // x1, y1
  12385. p[0] += data[i++];
  12386. p[1] += data[i++];
  12387. applyTransform(p, p, m);
  12388. data[j++] = p[0];
  12389. data[j++] = p[1];
  12390. }
  12391. for (k = 0; k < nPoint; k++) {
  12392. var p = points[k];
  12393. p[0] = data[i++];
  12394. p[1] = data[i++];
  12395. applyTransform(p, p, m);
  12396. // Write back
  12397. data[j++] = p[0];
  12398. data[j++] = p[1];
  12399. }
  12400. }
  12401. };
  12402. // command chars
  12403. var cc = [
  12404. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12405. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12406. ];
  12407. var mathSqrt = Math.sqrt;
  12408. var mathSin = Math.sin;
  12409. var mathCos = Math.cos;
  12410. var PI = Math.PI;
  12411. var vMag = function(v) {
  12412. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12413. };
  12414. var vRatio = function(u, v) {
  12415. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12416. };
  12417. var vAngle = function(u, v) {
  12418. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12419. * Math.acos(vRatio(u, v));
  12420. };
  12421. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12422. var psi = psiDeg * (PI / 180.0);
  12423. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12424. + mathSin(psi) * (y1 - y2) / 2.0;
  12425. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12426. + mathCos(psi) * (y1 - y2) / 2.0;
  12427. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12428. if (lambda > 1) {
  12429. rx *= mathSqrt(lambda);
  12430. ry *= mathSqrt(lambda);
  12431. }
  12432. var f = (fa === fs ? -1 : 1)
  12433. * mathSqrt((((rx * rx) * (ry * ry))
  12434. - ((rx * rx) * (yp * yp))
  12435. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12436. + (ry * ry) * (xp * xp))
  12437. ) || 0;
  12438. var cxp = f * rx * yp / ry;
  12439. var cyp = f * -ry * xp / rx;
  12440. var cx = (x1 + x2) / 2.0
  12441. + mathCos(psi) * cxp
  12442. - mathSin(psi) * cyp;
  12443. var cy = (y1 + y2) / 2.0
  12444. + mathSin(psi) * cxp
  12445. + mathCos(psi) * cyp;
  12446. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12447. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12448. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12449. var dTheta = vAngle(u, v);
  12450. if (vRatio(u, v) <= -1) {
  12451. dTheta = PI;
  12452. }
  12453. if (vRatio(u, v) >= 1) {
  12454. dTheta = 0;
  12455. }
  12456. if (fs === 0 && dTheta > 0) {
  12457. dTheta = dTheta - 2 * PI;
  12458. }
  12459. if (fs === 1 && dTheta < 0) {
  12460. dTheta = dTheta + 2 * PI;
  12461. }
  12462. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12463. }
  12464. function createPathProxyFromString(data) {
  12465. if (!data) {
  12466. return [];
  12467. }
  12468. // command string
  12469. var cs = data.replace(/-/g, ' -')
  12470. .replace(/ /g, ' ')
  12471. .replace(/ /g, ',')
  12472. .replace(/,,/g, ',');
  12473. var n;
  12474. // create pipes so that we can split the data
  12475. for (n = 0; n < cc.length; n++) {
  12476. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12477. }
  12478. // create array
  12479. var arr = cs.split('|');
  12480. // init context point
  12481. var cpx = 0;
  12482. var cpy = 0;
  12483. var path = new PathProxy();
  12484. var CMD = PathProxy.CMD;
  12485. var prevCmd;
  12486. for (n = 1; n < arr.length; n++) {
  12487. var str = arr[n];
  12488. var c = str.charAt(0);
  12489. var off = 0;
  12490. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12491. var cmd;
  12492. if (p.length > 0 && p[0] === '') {
  12493. p.shift();
  12494. }
  12495. for (var i = 0; i < p.length; i++) {
  12496. p[i] = parseFloat(p[i]);
  12497. }
  12498. while (off < p.length && !isNaN(p[off])) {
  12499. if (isNaN(p[0])) {
  12500. break;
  12501. }
  12502. var ctlPtx;
  12503. var ctlPty;
  12504. var rx;
  12505. var ry;
  12506. var psi;
  12507. var fa;
  12508. var fs;
  12509. var x1 = cpx;
  12510. var y1 = cpy;
  12511. // convert l, H, h, V, and v to L
  12512. switch (c) {
  12513. case 'l':
  12514. cpx += p[off++];
  12515. cpy += p[off++];
  12516. cmd = CMD.L;
  12517. path.addData(cmd, cpx, cpy);
  12518. break;
  12519. case 'L':
  12520. cpx = p[off++];
  12521. cpy = p[off++];
  12522. cmd = CMD.L;
  12523. path.addData(cmd, cpx, cpy);
  12524. break;
  12525. case 'm':
  12526. cpx += p[off++];
  12527. cpy += p[off++];
  12528. cmd = CMD.M;
  12529. path.addData(cmd, cpx, cpy);
  12530. c = 'l';
  12531. break;
  12532. case 'M':
  12533. cpx = p[off++];
  12534. cpy = p[off++];
  12535. cmd = CMD.M;
  12536. path.addData(cmd, cpx, cpy);
  12537. c = 'L';
  12538. break;
  12539. case 'h':
  12540. cpx += p[off++];
  12541. cmd = CMD.L;
  12542. path.addData(cmd, cpx, cpy);
  12543. break;
  12544. case 'H':
  12545. cpx = p[off++];
  12546. cmd = CMD.L;
  12547. path.addData(cmd, cpx, cpy);
  12548. break;
  12549. case 'v':
  12550. cpy += p[off++];
  12551. cmd = CMD.L;
  12552. path.addData(cmd, cpx, cpy);
  12553. break;
  12554. case 'V':
  12555. cpy = p[off++];
  12556. cmd = CMD.L;
  12557. path.addData(cmd, cpx, cpy);
  12558. break;
  12559. case 'C':
  12560. cmd = CMD.C;
  12561. path.addData(
  12562. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12563. );
  12564. cpx = p[off - 2];
  12565. cpy = p[off - 1];
  12566. break;
  12567. case 'c':
  12568. cmd = CMD.C;
  12569. path.addData(
  12570. cmd,
  12571. p[off++] + cpx, p[off++] + cpy,
  12572. p[off++] + cpx, p[off++] + cpy,
  12573. p[off++] + cpx, p[off++] + cpy
  12574. );
  12575. cpx += p[off - 2];
  12576. cpy += p[off - 1];
  12577. break;
  12578. case 'S':
  12579. ctlPtx = cpx;
  12580. ctlPty = cpy;
  12581. var len = path.len();
  12582. var pathData = path.data;
  12583. if (prevCmd === CMD.C) {
  12584. ctlPtx += cpx - pathData[len - 4];
  12585. ctlPty += cpy - pathData[len - 3];
  12586. }
  12587. cmd = CMD.C;
  12588. x1 = p[off++];
  12589. y1 = p[off++];
  12590. cpx = p[off++];
  12591. cpy = p[off++];
  12592. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12593. break;
  12594. case 's':
  12595. ctlPtx = cpx;
  12596. ctlPty = cpy;
  12597. var len = path.len();
  12598. var pathData = path.data;
  12599. if (prevCmd === CMD.C) {
  12600. ctlPtx += cpx - pathData[len - 4];
  12601. ctlPty += cpy - pathData[len - 3];
  12602. }
  12603. cmd = CMD.C;
  12604. x1 = cpx + p[off++];
  12605. y1 = cpy + p[off++];
  12606. cpx += p[off++];
  12607. cpy += p[off++];
  12608. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12609. break;
  12610. case 'Q':
  12611. x1 = p[off++];
  12612. y1 = p[off++];
  12613. cpx = p[off++];
  12614. cpy = p[off++];
  12615. cmd = CMD.Q;
  12616. path.addData(cmd, x1, y1, cpx, cpy);
  12617. break;
  12618. case 'q':
  12619. x1 = p[off++] + cpx;
  12620. y1 = p[off++] + cpy;
  12621. cpx += p[off++];
  12622. cpy += p[off++];
  12623. cmd = CMD.Q;
  12624. path.addData(cmd, x1, y1, cpx, cpy);
  12625. break;
  12626. case 'T':
  12627. ctlPtx = cpx;
  12628. ctlPty = cpy;
  12629. var len = path.len();
  12630. var pathData = path.data;
  12631. if (prevCmd === CMD.Q) {
  12632. ctlPtx += cpx - pathData[len - 4];
  12633. ctlPty += cpy - pathData[len - 3];
  12634. }
  12635. cpx = p[off++];
  12636. cpy = p[off++];
  12637. cmd = CMD.Q;
  12638. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12639. break;
  12640. case 't':
  12641. ctlPtx = cpx;
  12642. ctlPty = cpy;
  12643. var len = path.len();
  12644. var pathData = path.data;
  12645. if (prevCmd === CMD.Q) {
  12646. ctlPtx += cpx - pathData[len - 4];
  12647. ctlPty += cpy - pathData[len - 3];
  12648. }
  12649. cpx += p[off++];
  12650. cpy += p[off++];
  12651. cmd = CMD.Q;
  12652. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12653. break;
  12654. case 'A':
  12655. rx = p[off++];
  12656. ry = p[off++];
  12657. psi = p[off++];
  12658. fa = p[off++];
  12659. fs = p[off++];
  12660. x1 = cpx, y1 = cpy;
  12661. cpx = p[off++];
  12662. cpy = p[off++];
  12663. cmd = CMD.A;
  12664. processArc(
  12665. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12666. );
  12667. break;
  12668. case 'a':
  12669. rx = p[off++];
  12670. ry = p[off++];
  12671. psi = p[off++];
  12672. fa = p[off++];
  12673. fs = p[off++];
  12674. x1 = cpx, y1 = cpy;
  12675. cpx += p[off++];
  12676. cpy += p[off++];
  12677. cmd = CMD.A;
  12678. processArc(
  12679. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12680. );
  12681. break;
  12682. }
  12683. }
  12684. if (c === 'z' || c === 'Z') {
  12685. cmd = CMD.Z;
  12686. path.addData(cmd);
  12687. }
  12688. prevCmd = cmd;
  12689. }
  12690. path.toStatic();
  12691. return path;
  12692. }
  12693. // TODO Optimize double memory cost problem
  12694. function createPathOptions(str, opts) {
  12695. var pathProxy = createPathProxyFromString(str);
  12696. opts = opts || {};
  12697. opts.buildPath = function (path) {
  12698. if (path.setData) {
  12699. path.setData(pathProxy.data);
  12700. // Svg and vml renderer don't have context
  12701. var ctx = path.getContext();
  12702. if (ctx) {
  12703. path.rebuildPath(ctx);
  12704. }
  12705. }
  12706. else {
  12707. var ctx = path;
  12708. pathProxy.rebuildPath(ctx);
  12709. }
  12710. };
  12711. opts.applyTransform = function (m) {
  12712. transformPath(pathProxy, m);
  12713. this.dirty(true);
  12714. };
  12715. return opts;
  12716. }
  12717. /**
  12718. * Create a Path object from path string data
  12719. * http://www.w3.org/TR/SVG/paths.html#PathData
  12720. * @param {Object} opts Other options
  12721. */
  12722. function createFromString(str, opts) {
  12723. return new Path(createPathOptions(str, opts));
  12724. }
  12725. /**
  12726. * Create a Path class from path string data
  12727. * @param {string} str
  12728. * @param {Object} opts Other options
  12729. */
  12730. function extendFromString(str, opts) {
  12731. return Path.extend(createPathOptions(str, opts));
  12732. }
  12733. /**
  12734. * Merge multiple paths
  12735. */
  12736. // TODO Apply transform
  12737. // TODO stroke dash
  12738. // TODO Optimize double memory cost problem
  12739. function mergePath$1(pathEls, opts) {
  12740. var pathList = [];
  12741. var len = pathEls.length;
  12742. for (var i = 0; i < len; i++) {
  12743. var pathEl = pathEls[i];
  12744. if (!pathEl.path) {
  12745. pathEl.createPathProxy();
  12746. }
  12747. if (pathEl.__dirtyPath) {
  12748. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12749. }
  12750. pathList.push(pathEl.path);
  12751. }
  12752. var pathBundle = new Path(opts);
  12753. // Need path proxy.
  12754. pathBundle.createPathProxy();
  12755. pathBundle.buildPath = function (path) {
  12756. path.appendPath(pathList);
  12757. // Svg and vml renderer don't have context
  12758. var ctx = path.getContext();
  12759. if (ctx) {
  12760. path.rebuildPath(ctx);
  12761. }
  12762. };
  12763. return pathBundle;
  12764. }
  12765. /**
  12766. * @alias zrender/graphic/Text
  12767. * @extends module:zrender/graphic/Displayable
  12768. * @constructor
  12769. * @param {Object} opts
  12770. */
  12771. var Text = function (opts) { // jshint ignore:line
  12772. Displayable.call(this, opts);
  12773. };
  12774. Text.prototype = {
  12775. constructor: Text,
  12776. type: 'text',
  12777. brush: function (ctx, prevEl) {
  12778. var style = this.style;
  12779. // Optimize, avoid normalize every time.
  12780. this.__dirty && normalizeTextStyle(style, true);
  12781. // Use props with prefix 'text'.
  12782. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12783. style.shadowOffsetX = style.shadowOffsetY = null;
  12784. var text = style.text;
  12785. // Convert to string
  12786. text != null && (text += '');
  12787. // Always bind style
  12788. style.bind(ctx, this, prevEl);
  12789. if (!needDrawText(text, style)) {
  12790. return;
  12791. }
  12792. this.setTransform(ctx);
  12793. renderText(this, ctx, text, style);
  12794. this.restoreTransform(ctx);
  12795. },
  12796. getBoundingRect: function () {
  12797. var style = this.style;
  12798. // Optimize, avoid normalize every time.
  12799. this.__dirty && normalizeTextStyle(style, true);
  12800. if (!this._rect) {
  12801. var text = style.text;
  12802. text != null ? (text += '') : (text = '');
  12803. var rect = getBoundingRect(
  12804. style.text + '',
  12805. style.font,
  12806. style.textAlign,
  12807. style.textVerticalAlign,
  12808. style.textPadding,
  12809. style.rich
  12810. );
  12811. rect.x += style.x || 0;
  12812. rect.y += style.y || 0;
  12813. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12814. var w = style.textStrokeWidth;
  12815. rect.x -= w / 2;
  12816. rect.y -= w / 2;
  12817. rect.width += w;
  12818. rect.height += w;
  12819. }
  12820. this._rect = rect;
  12821. }
  12822. return this._rect;
  12823. }
  12824. };
  12825. inherits(Text, Displayable);
  12826. /**
  12827. * 圆形
  12828. * @module zrender/shape/Circle
  12829. */
  12830. var Circle = Path.extend({
  12831. type: 'circle',
  12832. shape: {
  12833. cx: 0,
  12834. cy: 0,
  12835. r: 0
  12836. },
  12837. buildPath : function (ctx, shape, inBundle) {
  12838. // Better stroking in ShapeBundle
  12839. // Always do it may have performence issue ( fill may be 2x more cost)
  12840. if (inBundle) {
  12841. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12842. }
  12843. // else {
  12844. // if (ctx.allocate && !ctx.data.length) {
  12845. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12846. // }
  12847. // }
  12848. // Better stroking in ShapeBundle
  12849. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12850. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12851. }
  12852. });
  12853. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12854. // where exception "unexpected call to method or property access"
  12855. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12856. // whose area size is zero is drawn and ctx.clip() is called and
  12857. // shadowBlur is set. See #4572, #3112, #5777.
  12858. // (e.g.,
  12859. // ctx.moveTo(10, 10);
  12860. // ctx.lineTo(20, 10);
  12861. // ctx.closePath();
  12862. // ctx.clip();
  12863. // ctx.shadowBlur = 10;
  12864. // ...
  12865. // ctx.fill();
  12866. // )
  12867. var shadowTemp = [
  12868. ['shadowBlur', 0],
  12869. ['shadowColor', '#000'],
  12870. ['shadowOffsetX', 0],
  12871. ['shadowOffsetY', 0]
  12872. ];
  12873. var fixClipWithShadow = function (orignalBrush) {
  12874. // version string can be: '11.0'
  12875. return (env$1.browser.ie && env$1.browser.version >= 11)
  12876. ? function () {
  12877. var clipPaths = this.__clipPaths;
  12878. var style = this.style;
  12879. var modified;
  12880. if (clipPaths) {
  12881. for (var i = 0; i < clipPaths.length; i++) {
  12882. var clipPath = clipPaths[i];
  12883. var shape = clipPath && clipPath.shape;
  12884. var type = clipPath && clipPath.type;
  12885. if (shape && (
  12886. (type === 'sector' && shape.startAngle === shape.endAngle)
  12887. || (type === 'rect' && (!shape.width || !shape.height))
  12888. )) {
  12889. for (var j = 0; j < shadowTemp.length; j++) {
  12890. // It is save to put shadowTemp static, because shadowTemp
  12891. // will be all modified each item brush called.
  12892. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12893. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12894. }
  12895. modified = true;
  12896. break;
  12897. }
  12898. }
  12899. }
  12900. orignalBrush.apply(this, arguments);
  12901. if (modified) {
  12902. for (var j = 0; j < shadowTemp.length; j++) {
  12903. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12904. }
  12905. }
  12906. }
  12907. : orignalBrush;
  12908. };
  12909. /**
  12910. * 扇形
  12911. * @module zrender/graphic/shape/Sector
  12912. */
  12913. var Sector = Path.extend({
  12914. type: 'sector',
  12915. shape: {
  12916. cx: 0,
  12917. cy: 0,
  12918. r0: 0,
  12919. r: 0,
  12920. startAngle: 0,
  12921. endAngle: Math.PI * 2,
  12922. clockwise: true
  12923. },
  12924. brush: fixClipWithShadow(Path.prototype.brush),
  12925. buildPath: function (ctx, shape) {
  12926. var x = shape.cx;
  12927. var y = shape.cy;
  12928. var r0 = Math.max(shape.r0 || 0, 0);
  12929. var r = Math.max(shape.r, 0);
  12930. var startAngle = shape.startAngle;
  12931. var endAngle = shape.endAngle;
  12932. var clockwise = shape.clockwise;
  12933. var unitX = Math.cos(startAngle);
  12934. var unitY = Math.sin(startAngle);
  12935. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  12936. ctx.lineTo(unitX * r + x, unitY * r + y);
  12937. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  12938. ctx.lineTo(
  12939. Math.cos(endAngle) * r0 + x,
  12940. Math.sin(endAngle) * r0 + y
  12941. );
  12942. if (r0 !== 0) {
  12943. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  12944. }
  12945. ctx.closePath();
  12946. }
  12947. });
  12948. /**
  12949. * 圆环
  12950. * @module zrender/graphic/shape/Ring
  12951. */
  12952. var Ring = Path.extend({
  12953. type: 'ring',
  12954. shape: {
  12955. cx: 0,
  12956. cy: 0,
  12957. r: 0,
  12958. r0: 0
  12959. },
  12960. buildPath: function (ctx, shape) {
  12961. var x = shape.cx;
  12962. var y = shape.cy;
  12963. var PI2 = Math.PI * 2;
  12964. ctx.moveTo(x + shape.r, y);
  12965. ctx.arc(x, y, shape.r, 0, PI2, false);
  12966. ctx.moveTo(x + shape.r0, y);
  12967. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12968. }
  12969. });
  12970. /**
  12971. * Catmull-Rom spline 插值折线
  12972. * @module zrender/shape/util/smoothSpline
  12973. * @author pissang (https://www.github.com/pissang)
  12974. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  12975. * errorrik (errorrik@gmail.com)
  12976. */
  12977. /**
  12978. * @inner
  12979. */
  12980. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12981. var v0 = (p2 - p0) * 0.5;
  12982. var v1 = (p3 - p1) * 0.5;
  12983. return (2 * (p1 - p2) + v0 + v1) * t3
  12984. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12985. + v0 * t + p1;
  12986. }
  12987. /**
  12988. * @alias module:zrender/shape/util/smoothSpline
  12989. * @param {Array} points 线段顶点数组
  12990. * @param {boolean} isLoop
  12991. * @return {Array}
  12992. */
  12993. var smoothSpline = function (points, isLoop) {
  12994. var len$$1 = points.length;
  12995. var ret = [];
  12996. var distance$$1 = 0;
  12997. for (var i = 1; i < len$$1; i++) {
  12998. distance$$1 += distance(points[i - 1], points[i]);
  12999. }
  13000. var segs = distance$$1 / 2;
  13001. segs = segs < len$$1 ? len$$1 : segs;
  13002. for (var i = 0; i < segs; i++) {
  13003. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13004. var idx = Math.floor(pos);
  13005. var w = pos - idx;
  13006. var p0;
  13007. var p1 = points[idx % len$$1];
  13008. var p2;
  13009. var p3;
  13010. if (!isLoop) {
  13011. p0 = points[idx === 0 ? idx : idx - 1];
  13012. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13013. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13014. }
  13015. else {
  13016. p0 = points[(idx - 1 + len$$1) % len$$1];
  13017. p2 = points[(idx + 1) % len$$1];
  13018. p3 = points[(idx + 2) % len$$1];
  13019. }
  13020. var w2 = w * w;
  13021. var w3 = w * w2;
  13022. ret.push([
  13023. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13024. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13025. ]);
  13026. }
  13027. return ret;
  13028. };
  13029. /**
  13030. * 贝塞尔平滑曲线
  13031. * @module zrender/shape/util/smoothBezier
  13032. * @author pissang (https://www.github.com/pissang)
  13033. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13034. * errorrik (errorrik@gmail.com)
  13035. */
  13036. /**
  13037. * 贝塞尔平滑曲线
  13038. * @alias module:zrender/shape/util/smoothBezier
  13039. * @param {Array} points 线段顶点数组
  13040. * @param {number} smooth 平滑等级, 0-1
  13041. * @param {boolean} isLoop
  13042. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13043. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13044. * 整个折线的包围盒做一个并集用来约束控制点。
  13045. * @param {Array} 计算出来的控制点数组
  13046. */
  13047. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13048. var cps = [];
  13049. var v = [];
  13050. var v1 = [];
  13051. var v2 = [];
  13052. var prevPoint;
  13053. var nextPoint;
  13054. var min$$1, max$$1;
  13055. if (constraint) {
  13056. min$$1 = [Infinity, Infinity];
  13057. max$$1 = [-Infinity, -Infinity];
  13058. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13059. min(min$$1, min$$1, points[i]);
  13060. max(max$$1, max$$1, points[i]);
  13061. }
  13062. // 与指定的包围盒做并集
  13063. min(min$$1, min$$1, constraint[0]);
  13064. max(max$$1, max$$1, constraint[1]);
  13065. }
  13066. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13067. var point = points[i];
  13068. if (isLoop) {
  13069. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13070. nextPoint = points[(i + 1) % len$$1];
  13071. }
  13072. else {
  13073. if (i === 0 || i === len$$1 - 1) {
  13074. cps.push(clone$1(points[i]));
  13075. continue;
  13076. }
  13077. else {
  13078. prevPoint = points[i - 1];
  13079. nextPoint = points[i + 1];
  13080. }
  13081. }
  13082. sub(v, nextPoint, prevPoint);
  13083. // use degree to scale the handle length
  13084. scale(v, v, smooth);
  13085. var d0 = distance(point, prevPoint);
  13086. var d1 = distance(point, nextPoint);
  13087. var sum = d0 + d1;
  13088. if (sum !== 0) {
  13089. d0 /= sum;
  13090. d1 /= sum;
  13091. }
  13092. scale(v1, v, -d0);
  13093. scale(v2, v, d1);
  13094. var cp0 = add([], point, v1);
  13095. var cp1 = add([], point, v2);
  13096. if (constraint) {
  13097. max(cp0, cp0, min$$1);
  13098. min(cp0, cp0, max$$1);
  13099. max(cp1, cp1, min$$1);
  13100. min(cp1, cp1, max$$1);
  13101. }
  13102. cps.push(cp0);
  13103. cps.push(cp1);
  13104. }
  13105. if (isLoop) {
  13106. cps.push(cps.shift());
  13107. }
  13108. return cps;
  13109. };
  13110. function buildPath$1(ctx, shape, closePath) {
  13111. var points = shape.points;
  13112. var smooth = shape.smooth;
  13113. if (points && points.length >= 2) {
  13114. if (smooth && smooth !== 'spline') {
  13115. var controlPoints = smoothBezier(
  13116. points, smooth, closePath, shape.smoothConstraint
  13117. );
  13118. ctx.moveTo(points[0][0], points[0][1]);
  13119. var len = points.length;
  13120. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13121. var cp1 = controlPoints[i * 2];
  13122. var cp2 = controlPoints[i * 2 + 1];
  13123. var p = points[(i + 1) % len];
  13124. ctx.bezierCurveTo(
  13125. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13126. );
  13127. }
  13128. }
  13129. else {
  13130. if (smooth === 'spline') {
  13131. points = smoothSpline(points, closePath);
  13132. }
  13133. ctx.moveTo(points[0][0], points[0][1]);
  13134. for (var i = 1, l = points.length; i < l; i++) {
  13135. ctx.lineTo(points[i][0], points[i][1]);
  13136. }
  13137. }
  13138. closePath && ctx.closePath();
  13139. }
  13140. }
  13141. /**
  13142. * 多边形
  13143. * @module zrender/shape/Polygon
  13144. */
  13145. var Polygon = Path.extend({
  13146. type: 'polygon',
  13147. shape: {
  13148. points: null,
  13149. smooth: false,
  13150. smoothConstraint: null
  13151. },
  13152. buildPath: function (ctx, shape) {
  13153. buildPath$1(ctx, shape, true);
  13154. }
  13155. });
  13156. /**
  13157. * @module zrender/graphic/shape/Polyline
  13158. */
  13159. var Polyline = Path.extend({
  13160. type: 'polyline',
  13161. shape: {
  13162. points: null,
  13163. smooth: false,
  13164. smoothConstraint: null
  13165. },
  13166. style: {
  13167. stroke: '#000',
  13168. fill: null
  13169. },
  13170. buildPath: function (ctx, shape) {
  13171. buildPath$1(ctx, shape, false);
  13172. }
  13173. });
  13174. /**
  13175. * 矩形
  13176. * @module zrender/graphic/shape/Rect
  13177. */
  13178. var Rect = Path.extend({
  13179. type: 'rect',
  13180. shape: {
  13181. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13182. // r缩写为1 相当于 [1, 1, 1, 1]
  13183. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13184. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13185. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13186. r: 0,
  13187. x: 0,
  13188. y: 0,
  13189. width: 0,
  13190. height: 0
  13191. },
  13192. buildPath: function (ctx, shape) {
  13193. var x = shape.x;
  13194. var y = shape.y;
  13195. var width = shape.width;
  13196. var height = shape.height;
  13197. if (!shape.r) {
  13198. ctx.rect(x, y, width, height);
  13199. }
  13200. else {
  13201. buildPath(ctx, shape);
  13202. }
  13203. ctx.closePath();
  13204. return;
  13205. }
  13206. });
  13207. /**
  13208. * 直线
  13209. * @module zrender/graphic/shape/Line
  13210. */
  13211. var Line = Path.extend({
  13212. type: 'line',
  13213. shape: {
  13214. // Start point
  13215. x1: 0,
  13216. y1: 0,
  13217. // End point
  13218. x2: 0,
  13219. y2: 0,
  13220. percent: 1
  13221. },
  13222. style: {
  13223. stroke: '#000',
  13224. fill: null
  13225. },
  13226. buildPath: function (ctx, shape) {
  13227. var x1 = shape.x1;
  13228. var y1 = shape.y1;
  13229. var x2 = shape.x2;
  13230. var y2 = shape.y2;
  13231. var percent = shape.percent;
  13232. if (percent === 0) {
  13233. return;
  13234. }
  13235. ctx.moveTo(x1, y1);
  13236. if (percent < 1) {
  13237. x2 = x1 * (1 - percent) + x2 * percent;
  13238. y2 = y1 * (1 - percent) + y2 * percent;
  13239. }
  13240. ctx.lineTo(x2, y2);
  13241. },
  13242. /**
  13243. * Get point at percent
  13244. * @param {number} percent
  13245. * @return {Array.<number>}
  13246. */
  13247. pointAt: function (p) {
  13248. var shape = this.shape;
  13249. return [
  13250. shape.x1 * (1 - p) + shape.x2 * p,
  13251. shape.y1 * (1 - p) + shape.y2 * p
  13252. ];
  13253. }
  13254. });
  13255. /**
  13256. * 贝塞尔曲线
  13257. * @module zrender/shape/BezierCurve
  13258. */
  13259. var out = [];
  13260. function someVectorAt(shape, t, isTangent) {
  13261. var cpx2 = shape.cpx2;
  13262. var cpy2 = shape.cpy2;
  13263. if (cpx2 === null || cpy2 === null) {
  13264. return [
  13265. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13266. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13267. ];
  13268. }
  13269. else {
  13270. return [
  13271. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13272. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13273. ];
  13274. }
  13275. }
  13276. var BezierCurve = Path.extend({
  13277. type: 'bezier-curve',
  13278. shape: {
  13279. x1: 0,
  13280. y1: 0,
  13281. x2: 0,
  13282. y2: 0,
  13283. cpx1: 0,
  13284. cpy1: 0,
  13285. // cpx2: 0,
  13286. // cpy2: 0
  13287. // Curve show percent, for animating
  13288. percent: 1
  13289. },
  13290. style: {
  13291. stroke: '#000',
  13292. fill: null
  13293. },
  13294. buildPath: function (ctx, shape) {
  13295. var x1 = shape.x1;
  13296. var y1 = shape.y1;
  13297. var x2 = shape.x2;
  13298. var y2 = shape.y2;
  13299. var cpx1 = shape.cpx1;
  13300. var cpy1 = shape.cpy1;
  13301. var cpx2 = shape.cpx2;
  13302. var cpy2 = shape.cpy2;
  13303. var percent = shape.percent;
  13304. if (percent === 0) {
  13305. return;
  13306. }
  13307. ctx.moveTo(x1, y1);
  13308. if (cpx2 == null || cpy2 == null) {
  13309. if (percent < 1) {
  13310. quadraticSubdivide(
  13311. x1, cpx1, x2, percent, out
  13312. );
  13313. cpx1 = out[1];
  13314. x2 = out[2];
  13315. quadraticSubdivide(
  13316. y1, cpy1, y2, percent, out
  13317. );
  13318. cpy1 = out[1];
  13319. y2 = out[2];
  13320. }
  13321. ctx.quadraticCurveTo(
  13322. cpx1, cpy1,
  13323. x2, y2
  13324. );
  13325. }
  13326. else {
  13327. if (percent < 1) {
  13328. cubicSubdivide(
  13329. x1, cpx1, cpx2, x2, percent, out
  13330. );
  13331. cpx1 = out[1];
  13332. cpx2 = out[2];
  13333. x2 = out[3];
  13334. cubicSubdivide(
  13335. y1, cpy1, cpy2, y2, percent, out
  13336. );
  13337. cpy1 = out[1];
  13338. cpy2 = out[2];
  13339. y2 = out[3];
  13340. }
  13341. ctx.bezierCurveTo(
  13342. cpx1, cpy1,
  13343. cpx2, cpy2,
  13344. x2, y2
  13345. );
  13346. }
  13347. },
  13348. /**
  13349. * Get point at percent
  13350. * @param {number} t
  13351. * @return {Array.<number>}
  13352. */
  13353. pointAt: function (t) {
  13354. return someVectorAt(this.shape, t, false);
  13355. },
  13356. /**
  13357. * Get tangent at percent
  13358. * @param {number} t
  13359. * @return {Array.<number>}
  13360. */
  13361. tangentAt: function (t) {
  13362. var p = someVectorAt(this.shape, t, true);
  13363. return normalize(p, p);
  13364. }
  13365. });
  13366. /**
  13367. * 圆弧
  13368. * @module zrender/graphic/shape/Arc
  13369. */
  13370. var Arc = Path.extend({
  13371. type: 'arc',
  13372. shape: {
  13373. cx: 0,
  13374. cy: 0,
  13375. r: 0,
  13376. startAngle: 0,
  13377. endAngle: Math.PI * 2,
  13378. clockwise: true
  13379. },
  13380. style: {
  13381. stroke: '#000',
  13382. fill: null
  13383. },
  13384. buildPath: function (ctx, shape) {
  13385. var x = shape.cx;
  13386. var y = shape.cy;
  13387. var r = Math.max(shape.r, 0);
  13388. var startAngle = shape.startAngle;
  13389. var endAngle = shape.endAngle;
  13390. var clockwise = shape.clockwise;
  13391. var unitX = Math.cos(startAngle);
  13392. var unitY = Math.sin(startAngle);
  13393. ctx.moveTo(unitX * r + x, unitY * r + y);
  13394. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13395. }
  13396. });
  13397. // CompoundPath to improve performance
  13398. var CompoundPath = Path.extend({
  13399. type: 'compound',
  13400. shape: {
  13401. paths: null
  13402. },
  13403. _updatePathDirty: function () {
  13404. var dirtyPath = this.__dirtyPath;
  13405. var paths = this.shape.paths;
  13406. for (var i = 0; i < paths.length; i++) {
  13407. // Mark as dirty if any subpath is dirty
  13408. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13409. }
  13410. this.__dirtyPath = dirtyPath;
  13411. this.__dirty = this.__dirty || dirtyPath;
  13412. },
  13413. beforeBrush: function () {
  13414. this._updatePathDirty();
  13415. var paths = this.shape.paths || [];
  13416. var scale = this.getGlobalScale();
  13417. // Update path scale
  13418. for (var i = 0; i < paths.length; i++) {
  13419. if (!paths[i].path) {
  13420. paths[i].createPathProxy();
  13421. }
  13422. paths[i].path.setScale(scale[0], scale[1]);
  13423. }
  13424. },
  13425. buildPath: function (ctx, shape) {
  13426. var paths = shape.paths || [];
  13427. for (var i = 0; i < paths.length; i++) {
  13428. paths[i].buildPath(ctx, paths[i].shape, true);
  13429. }
  13430. },
  13431. afterBrush: function () {
  13432. var paths = this.shape.paths || [];
  13433. for (var i = 0; i < paths.length; i++) {
  13434. paths[i].__dirtyPath = false;
  13435. }
  13436. },
  13437. getBoundingRect: function () {
  13438. this._updatePathDirty();
  13439. return Path.prototype.getBoundingRect.call(this);
  13440. }
  13441. });
  13442. /**
  13443. * @param {Array.<Object>} colorStops
  13444. */
  13445. var Gradient = function (colorStops) {
  13446. this.colorStops = colorStops || [];
  13447. };
  13448. Gradient.prototype = {
  13449. constructor: Gradient,
  13450. addColorStop: function (offset, color) {
  13451. this.colorStops.push({
  13452. offset: offset,
  13453. color: color
  13454. });
  13455. }
  13456. };
  13457. /**
  13458. * x, y, x2, y2 are all percent from 0 to 1
  13459. * @param {number} [x=0]
  13460. * @param {number} [y=0]
  13461. * @param {number} [x2=1]
  13462. * @param {number} [y2=0]
  13463. * @param {Array.<Object>} colorStops
  13464. * @param {boolean} [globalCoord=false]
  13465. */
  13466. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13467. // Should do nothing more in this constructor. Because gradient can be
  13468. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13469. // this constructor will not be called.
  13470. this.x = x == null ? 0 : x;
  13471. this.y = y == null ? 0 : y;
  13472. this.x2 = x2 == null ? 1 : x2;
  13473. this.y2 = y2 == null ? 0 : y2;
  13474. // Can be cloned
  13475. this.type = 'linear';
  13476. // If use global coord
  13477. this.global = globalCoord || false;
  13478. Gradient.call(this, colorStops);
  13479. };
  13480. LinearGradient.prototype = {
  13481. constructor: LinearGradient
  13482. };
  13483. inherits(LinearGradient, Gradient);
  13484. /**
  13485. * x, y, r are all percent from 0 to 1
  13486. * @param {number} [x=0.5]
  13487. * @param {number} [y=0.5]
  13488. * @param {number} [r=0.5]
  13489. * @param {Array.<Object>} [colorStops]
  13490. * @param {boolean} [globalCoord=false]
  13491. */
  13492. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13493. // Should do nothing more in this constructor. Because gradient can be
  13494. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13495. // this constructor will not be called.
  13496. this.x = x == null ? 0.5 : x;
  13497. this.y = y == null ? 0.5 : y;
  13498. this.r = r == null ? 0.5 : r;
  13499. // Can be cloned
  13500. this.type = 'radial';
  13501. // If use global coord
  13502. this.global = globalCoord || false;
  13503. Gradient.call(this, colorStops);
  13504. };
  13505. RadialGradient.prototype = {
  13506. constructor: RadialGradient
  13507. };
  13508. inherits(RadialGradient, Gradient);
  13509. /**
  13510. * Displayable for incremental rendering. It will be rendered in a separate layer
  13511. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13512. * addDisplayables will render the added displayables incremetally.
  13513. *
  13514. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13515. */
  13516. // TODO Style override ?
  13517. function IncrementalDisplayble(opts) {
  13518. Displayable.call(this, opts);
  13519. this._displayables = [];
  13520. this._temporaryDisplayables = [];
  13521. this._cursor = 0;
  13522. this.notClear = true;
  13523. }
  13524. IncrementalDisplayble.prototype.incremental = true;
  13525. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13526. this._displayables = [];
  13527. this._temporaryDisplayables = [];
  13528. this._cursor = 0;
  13529. this.dirty();
  13530. this.notClear = false;
  13531. };
  13532. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13533. if (notPersistent) {
  13534. this._temporaryDisplayables.push(displayable);
  13535. }
  13536. else {
  13537. this._displayables.push(displayable);
  13538. }
  13539. this.dirty();
  13540. };
  13541. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13542. notPersistent = notPersistent || false;
  13543. for (var i = 0; i < displayables.length; i++) {
  13544. this.addDisplayable(displayables[i], notPersistent);
  13545. }
  13546. };
  13547. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13548. for (var i = this._cursor; i < this._displayables.length; i++) {
  13549. cb && cb(this._displayables[i]);
  13550. }
  13551. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13552. cb && cb(this._temporaryDisplayables[i]);
  13553. }
  13554. };
  13555. IncrementalDisplayble.prototype.update = function () {
  13556. this.updateTransform();
  13557. for (var i = this._cursor; i < this._displayables.length; i++) {
  13558. var displayable = this._displayables[i];
  13559. // PENDING
  13560. displayable.parent = this;
  13561. displayable.update();
  13562. displayable.parent = null;
  13563. }
  13564. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13565. var displayable = this._temporaryDisplayables[i];
  13566. // PENDING
  13567. displayable.parent = this;
  13568. displayable.update();
  13569. displayable.parent = null;
  13570. }
  13571. };
  13572. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13573. // Render persistant displayables.
  13574. for (var i = this._cursor; i < this._displayables.length; i++) {
  13575. var displayable = this._temporaryDisplayables[i];
  13576. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13577. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13578. displayable.afterBrush && displayable.afterBrush(ctx);
  13579. }
  13580. this._cursor = i;
  13581. // Render temporary displayables.
  13582. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13583. var displayable = this._temporaryDisplayables[i];
  13584. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13585. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13586. displayable.afterBrush && displayable.afterBrush(ctx);
  13587. }
  13588. this._temporaryDisplayables = [];
  13589. this.notClear = true;
  13590. };
  13591. var m = [];
  13592. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13593. if (!this._rect) {
  13594. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13595. for (var i = 0; i < this._displayables.length; i++) {
  13596. var displayable = this._displayables[i];
  13597. var childRect = displayable.getBoundingRect().clone();
  13598. if (displayable.needLocalTransform()) {
  13599. childRect.applyTransform(displayable.getLocalTransform(m));
  13600. }
  13601. rect.union(childRect);
  13602. }
  13603. this._rect = rect;
  13604. }
  13605. return this._rect;
  13606. };
  13607. IncrementalDisplayble.prototype.contain = function (x, y) {
  13608. var localPos = this.transformCoordToLocal(x, y);
  13609. var rect = this.getBoundingRect();
  13610. if (rect.contain(localPos[0], localPos[1])) {
  13611. for (var i = 0; i < this._displayables.length; i++) {
  13612. var displayable = this._displayables[i];
  13613. if (displayable.contain(x, y)) {
  13614. return true;
  13615. }
  13616. }
  13617. }
  13618. return false;
  13619. };
  13620. inherits(IncrementalDisplayble, Displayable);
  13621. var round = Math.round;
  13622. var mathMax$1 = Math.max;
  13623. var mathMin$1 = Math.min;
  13624. var EMPTY_OBJ = {};
  13625. /**
  13626. * Extend shape with parameters
  13627. */
  13628. function extendShape(opts) {
  13629. return Path.extend(opts);
  13630. }
  13631. /**
  13632. * Extend path
  13633. */
  13634. function extendPath(pathData, opts) {
  13635. return extendFromString(pathData, opts);
  13636. }
  13637. /**
  13638. * Create a path element from path data string
  13639. * @param {string} pathData
  13640. * @param {Object} opts
  13641. * @param {module:zrender/core/BoundingRect} rect
  13642. * @param {string} [layout=cover] 'center' or 'cover'
  13643. */
  13644. function makePath(pathData, opts, rect, layout) {
  13645. var path = createFromString(pathData, opts);
  13646. var boundingRect = path.getBoundingRect();
  13647. if (rect) {
  13648. if (layout === 'center') {
  13649. rect = centerGraphic(rect, boundingRect);
  13650. }
  13651. resizePath(path, rect);
  13652. }
  13653. return path;
  13654. }
  13655. /**
  13656. * Create a image element from image url
  13657. * @param {string} imageUrl image url
  13658. * @param {Object} opts options
  13659. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13660. * @param {string} [layout=cover] 'center' or 'cover'
  13661. */
  13662. function makeImage(imageUrl, rect, layout) {
  13663. var path = new ZImage({
  13664. style: {
  13665. image: imageUrl,
  13666. x: rect.x,
  13667. y: rect.y,
  13668. width: rect.width,
  13669. height: rect.height
  13670. },
  13671. onload: function (img) {
  13672. if (layout === 'center') {
  13673. var boundingRect = {
  13674. width: img.width,
  13675. height: img.height
  13676. };
  13677. path.setStyle(centerGraphic(rect, boundingRect));
  13678. }
  13679. }
  13680. });
  13681. return path;
  13682. }
  13683. /**
  13684. * Get position of centered element in bounding box.
  13685. *
  13686. * @param {Object} rect element local bounding box
  13687. * @param {Object} boundingRect constraint bounding box
  13688. * @return {Object} element position containing x, y, width, and height
  13689. */
  13690. function centerGraphic(rect, boundingRect) {
  13691. // Set rect to center, keep width / height ratio.
  13692. var aspect = boundingRect.width / boundingRect.height;
  13693. var width = rect.height * aspect;
  13694. var height;
  13695. if (width <= rect.width) {
  13696. height = rect.height;
  13697. }
  13698. else {
  13699. width = rect.width;
  13700. height = width / aspect;
  13701. }
  13702. var cx = rect.x + rect.width / 2;
  13703. var cy = rect.y + rect.height / 2;
  13704. return {
  13705. x: cx - width / 2,
  13706. y: cy - height / 2,
  13707. width: width,
  13708. height: height
  13709. };
  13710. }
  13711. var mergePath = mergePath$1;
  13712. /**
  13713. * Resize a path to fit the rect
  13714. * @param {module:zrender/graphic/Path} path
  13715. * @param {Object} rect
  13716. */
  13717. function resizePath(path, rect) {
  13718. if (!path.applyTransform) {
  13719. return;
  13720. }
  13721. var pathRect = path.getBoundingRect();
  13722. var m = pathRect.calculateTransform(rect);
  13723. path.applyTransform(m);
  13724. }
  13725. /**
  13726. * Sub pixel optimize line for canvas
  13727. *
  13728. * @param {Object} param
  13729. * @param {Object} [param.shape]
  13730. * @param {number} [param.shape.x1]
  13731. * @param {number} [param.shape.y1]
  13732. * @param {number} [param.shape.x2]
  13733. * @param {number} [param.shape.y2]
  13734. * @param {Object} [param.style]
  13735. * @param {number} [param.style.lineWidth]
  13736. * @return {Object} Modified param
  13737. */
  13738. function subPixelOptimizeLine(param) {
  13739. var shape = param.shape;
  13740. var lineWidth = param.style.lineWidth;
  13741. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13742. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13743. }
  13744. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13745. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13746. }
  13747. return param;
  13748. }
  13749. /**
  13750. * Sub pixel optimize rect for canvas
  13751. *
  13752. * @param {Object} param
  13753. * @param {Object} [param.shape]
  13754. * @param {number} [param.shape.x]
  13755. * @param {number} [param.shape.y]
  13756. * @param {number} [param.shape.width]
  13757. * @param {number} [param.shape.height]
  13758. * @param {Object} [param.style]
  13759. * @param {number} [param.style.lineWidth]
  13760. * @return {Object} Modified param
  13761. */
  13762. function subPixelOptimizeRect(param) {
  13763. var shape = param.shape;
  13764. var lineWidth = param.style.lineWidth;
  13765. var originX = shape.x;
  13766. var originY = shape.y;
  13767. var originWidth = shape.width;
  13768. var originHeight = shape.height;
  13769. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13770. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13771. shape.width = Math.max(
  13772. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13773. originWidth === 0 ? 0 : 1
  13774. );
  13775. shape.height = Math.max(
  13776. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13777. originHeight === 0 ? 0 : 1
  13778. );
  13779. return param;
  13780. }
  13781. /**
  13782. * Sub pixel optimize for canvas
  13783. *
  13784. * @param {number} position Coordinate, such as x, y
  13785. * @param {number} lineWidth Should be nonnegative integer.
  13786. * @param {boolean=} positiveOrNegative Default false (negative).
  13787. * @return {number} Optimized position.
  13788. */
  13789. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13790. // Assure that (position + lineWidth / 2) is near integer edge,
  13791. // otherwise line will be fuzzy in canvas.
  13792. var doubledPosition = round(position * 2);
  13793. return (doubledPosition + round(lineWidth)) % 2 === 0
  13794. ? doubledPosition / 2
  13795. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13796. }
  13797. function hasFillOrStroke(fillOrStroke) {
  13798. return fillOrStroke != null && fillOrStroke != 'none';
  13799. }
  13800. function liftColor(color) {
  13801. return typeof color === 'string' ? lift(color, -0.1) : color;
  13802. }
  13803. /**
  13804. * @private
  13805. */
  13806. function cacheElementStl(el) {
  13807. if (el.__hoverStlDirty) {
  13808. var stroke = el.style.stroke;
  13809. var fill = el.style.fill;
  13810. // Create hoverStyle on mouseover
  13811. var hoverStyle = el.__hoverStl;
  13812. hoverStyle.fill = hoverStyle.fill
  13813. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13814. hoverStyle.stroke = hoverStyle.stroke
  13815. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13816. var normalStyle = {};
  13817. for (var name in hoverStyle) {
  13818. // See comment in `doSingleEnterHover`.
  13819. if (hoverStyle[name] != null) {
  13820. normalStyle[name] = el.style[name];
  13821. }
  13822. }
  13823. el.__normalStl = normalStyle;
  13824. el.__hoverStlDirty = false;
  13825. }
  13826. }
  13827. /**
  13828. * @private
  13829. */
  13830. function doSingleEnterHover(el) {
  13831. if (el.__isHover) {
  13832. return;
  13833. }
  13834. cacheElementStl(el);
  13835. if (el.useHoverLayer) {
  13836. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13837. }
  13838. else {
  13839. var style = el.style;
  13840. var insideRollbackOpt = style.insideRollbackOpt;
  13841. // Consider case: only `position: 'top'` is set on emphasis, then text
  13842. // color should be returned to `autoColor`, rather than remain '#fff'.
  13843. // So we should rollback then apply again after style merging.
  13844. insideRollbackOpt && rollbackInsideStyle(style);
  13845. // styles can be:
  13846. // {
  13847. // label: {
  13848. // show: false,
  13849. // position: 'outside',
  13850. // fontSize: 18
  13851. // },
  13852. // emphasis: {
  13853. // label: {
  13854. // show: true
  13855. // }
  13856. // }
  13857. // },
  13858. // where properties of `emphasis` may not appear in `normal`. We previously use
  13859. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13860. // But consider rich text and setOption in merge mode, it is impossible to cover
  13861. // all properties in merge. So we use merge mode when setting style here, where
  13862. // only properties that is not `null/undefined` can be set. The disadventage:
  13863. // null/undefined can not be used to remove style any more in `emphasis`.
  13864. style.extendFrom(el.__hoverStl);
  13865. // Do not save `insideRollback`.
  13866. if (insideRollbackOpt) {
  13867. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13868. // textFill may be rollbacked to null.
  13869. if (style.textFill == null) {
  13870. style.textFill = insideRollbackOpt.autoColor;
  13871. }
  13872. }
  13873. el.dirty(false);
  13874. el.z2 += 1;
  13875. }
  13876. el.__isHover = true;
  13877. }
  13878. /**
  13879. * @inner
  13880. */
  13881. function doSingleLeaveHover(el) {
  13882. if (!el.__isHover) {
  13883. return;
  13884. }
  13885. var normalStl = el.__normalStl;
  13886. if (el.useHoverLayer) {
  13887. el.__zr && el.__zr.removeHover(el);
  13888. }
  13889. else {
  13890. // Consider null/undefined value, should use
  13891. // `setStyle` but not `extendFrom(stl, true)`.
  13892. normalStl && el.setStyle(normalStl);
  13893. el.z2 -= 1;
  13894. }
  13895. el.__isHover = false;
  13896. }
  13897. /**
  13898. * @inner
  13899. */
  13900. function doEnterHover(el) {
  13901. el.type === 'group'
  13902. ? el.traverse(function (child) {
  13903. if (child.type !== 'group') {
  13904. doSingleEnterHover(child);
  13905. }
  13906. })
  13907. : doSingleEnterHover(el);
  13908. }
  13909. function doLeaveHover(el) {
  13910. el.type === 'group'
  13911. ? el.traverse(function (child) {
  13912. if (child.type !== 'group') {
  13913. doSingleLeaveHover(child);
  13914. }
  13915. })
  13916. : doSingleLeaveHover(el);
  13917. }
  13918. /**
  13919. * @inner
  13920. */
  13921. function setElementHoverStl(el, hoverStl) {
  13922. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13923. // Often used when item group has a label element and it's hoverStyle is different
  13924. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13925. el.__hoverStlDirty = true;
  13926. if (el.__isHover) {
  13927. cacheElementStl(el);
  13928. }
  13929. }
  13930. /**
  13931. * @inner
  13932. */
  13933. function onElementMouseOver(e) {
  13934. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13935. return;
  13936. }
  13937. // Only if element is not in emphasis status
  13938. !this.__isEmphasis && doEnterHover(this);
  13939. }
  13940. /**
  13941. * @inner
  13942. */
  13943. function onElementMouseOut(e) {
  13944. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13945. return;
  13946. }
  13947. // Only if element is not in emphasis status
  13948. !this.__isEmphasis && doLeaveHover(this);
  13949. }
  13950. /**
  13951. * @inner
  13952. */
  13953. function enterEmphasis() {
  13954. this.__isEmphasis = true;
  13955. doEnterHover(this);
  13956. }
  13957. /**
  13958. * @inner
  13959. */
  13960. function leaveEmphasis() {
  13961. this.__isEmphasis = false;
  13962. doLeaveHover(this);
  13963. }
  13964. /**
  13965. * Set hover style of element.
  13966. * This method can be called repeatly without side-effects.
  13967. * @param {module:zrender/Element} el
  13968. * @param {Object} [hoverStyle]
  13969. * @param {Object} [opt]
  13970. * @param {boolean} [opt.hoverSilentOnTouch=false]
  13971. * In touch device, mouseover event will be trigger on touchstart event
  13972. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  13973. * conviniently use hoverStyle when tap on touch screen without additional
  13974. * code for compatibility.
  13975. * But if the chart/component has select feature, which usually also use
  13976. * hoverStyle, there might be conflict between 'select-highlight' and
  13977. * 'hover-highlight' especially when roam is enabled (see geo for example).
  13978. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  13979. * on touch device.
  13980. */
  13981. function setHoverStyle(el, hoverStyle, opt) {
  13982. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  13983. el.type === 'group'
  13984. ? el.traverse(function (child) {
  13985. if (child.type !== 'group') {
  13986. setElementHoverStl(child, hoverStyle);
  13987. }
  13988. })
  13989. : setElementHoverStl(el, hoverStyle);
  13990. // Duplicated function will be auto-ignored, see Eventful.js.
  13991. el.on('mouseover', onElementMouseOver)
  13992. .on('mouseout', onElementMouseOut);
  13993. // Emphasis, normal can be triggered manually
  13994. el.on('emphasis', enterEmphasis)
  13995. .on('normal', leaveEmphasis);
  13996. }
  13997. /**
  13998. * @param {Object|module:zrender/graphic/Style} normalStyle
  13999. * @param {Object} emphasisStyle
  14000. * @param {module:echarts/model/Model} normalModel
  14001. * @param {module:echarts/model/Model} emphasisModel
  14002. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14003. * @param {string|Function} [opt.defaultText]
  14004. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14005. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14006. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14007. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14008. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14009. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14010. * @param {Object} [normalSpecified]
  14011. * @param {Object} [emphasisSpecified]
  14012. */
  14013. function setLabelStyle(
  14014. normalStyle, emphasisStyle,
  14015. normalModel, emphasisModel,
  14016. opt,
  14017. normalSpecified, emphasisSpecified
  14018. ) {
  14019. opt = opt || EMPTY_OBJ;
  14020. var labelFetcher = opt.labelFetcher;
  14021. var labelDataIndex = opt.labelDataIndex;
  14022. var labelDimIndex = opt.labelDimIndex;
  14023. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14024. // is not supported util someone requests.
  14025. var showNormal = normalModel.getShallow('show');
  14026. var showEmphasis = emphasisModel.getShallow('show');
  14027. // Consider performance, only fetch label when necessary.
  14028. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14029. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14030. var baseText;
  14031. if (showNormal || showEmphasis) {
  14032. if (labelFetcher) {
  14033. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14034. }
  14035. if (baseText == null) {
  14036. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14037. }
  14038. }
  14039. var normalStyleText = showNormal ? baseText : null;
  14040. var emphasisStyleText = showEmphasis
  14041. ? retrieve2(
  14042. labelFetcher
  14043. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14044. : null,
  14045. baseText
  14046. )
  14047. : null;
  14048. // Optimize: If style.text is null, text will not be drawn.
  14049. if (normalStyleText != null || emphasisStyleText != null) {
  14050. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14051. // values have to be set on `normalStyle`.
  14052. // If we set default values on `emphasisStyle`, consider case:
  14053. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14054. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14055. // Then the 'red' will not work on emphasis.
  14056. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14057. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14058. }
  14059. normalStyle.text = normalStyleText;
  14060. emphasisStyle.text = emphasisStyleText;
  14061. }
  14062. /**
  14063. * Set basic textStyle properties.
  14064. * @param {Object|module:zrender/graphic/Style} textStyle
  14065. * @param {module:echarts/model/Model} model
  14066. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14067. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14068. * @param {boolean} [isEmphasis]
  14069. */
  14070. function setTextStyle(
  14071. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14072. ) {
  14073. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14074. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14075. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14076. return textStyle;
  14077. }
  14078. /**
  14079. * Set text option in the style.
  14080. * @deprecated
  14081. * @param {Object} textStyle
  14082. * @param {module:echarts/model/Model} labelModel
  14083. * @param {string|boolean} defaultColor Default text color.
  14084. * If set as false, it will be processed as a emphasis style.
  14085. */
  14086. function setText(textStyle, labelModel, defaultColor) {
  14087. var opt = {isRectText: true};
  14088. var isEmphasis;
  14089. if (defaultColor === false) {
  14090. isEmphasis = true;
  14091. }
  14092. else {
  14093. // Support setting color as 'auto' to get visual color.
  14094. opt.autoColor = defaultColor;
  14095. }
  14096. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14097. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14098. }
  14099. /**
  14100. * {
  14101. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14102. * isRectText: boolean,
  14103. * autoColor: string, specify a color when color is 'auto',
  14104. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14105. * If autoColor specified, it is used as default textFill.
  14106. * useInsideStyle:
  14107. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14108. * if `textFill` is not specified.
  14109. * `false`: Do not use inside style.
  14110. * `null/undefined`: use inside style if `isRectText` is true and
  14111. * `textFill` is not specified and textPosition contains `'inside'`.
  14112. * forceRich: boolean
  14113. * }
  14114. */
  14115. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14116. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14117. opt = opt || EMPTY_OBJ;
  14118. if (opt.isRectText) {
  14119. var textPosition = textStyleModel.getShallow('position')
  14120. || (isEmphasis ? null : 'inside');
  14121. // 'outside' is not a valid zr textPostion value, but used
  14122. // in bar series, and magric type should be considered.
  14123. textPosition === 'outside' && (textPosition = 'top');
  14124. textStyle.textPosition = textPosition;
  14125. textStyle.textOffset = textStyleModel.getShallow('offset');
  14126. var labelRotate = textStyleModel.getShallow('rotate');
  14127. labelRotate != null && (labelRotate *= Math.PI / 180);
  14128. textStyle.textRotation = labelRotate;
  14129. textStyle.textDistance = retrieve2(
  14130. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14131. );
  14132. }
  14133. var ecModel = textStyleModel.ecModel;
  14134. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14135. // Consider case:
  14136. // {
  14137. // data: [{
  14138. // value: 12,
  14139. // label: {
  14140. // rich: {
  14141. // // no 'a' here but using parent 'a'.
  14142. // }
  14143. // }
  14144. // }],
  14145. // rich: {
  14146. // a: { ... }
  14147. // }
  14148. // }
  14149. var richItemNames = getRichItemNames(textStyleModel);
  14150. var richResult;
  14151. if (richItemNames) {
  14152. richResult = {};
  14153. for (var name in richItemNames) {
  14154. if (richItemNames.hasOwnProperty(name)) {
  14155. // Cascade is supported in rich.
  14156. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14157. // In rich, never `disableBox`.
  14158. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14159. }
  14160. }
  14161. }
  14162. textStyle.rich = richResult;
  14163. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14164. if (opt.forceRich && !opt.textStyle) {
  14165. opt.textStyle = {};
  14166. }
  14167. return textStyle;
  14168. }
  14169. // Consider case:
  14170. // {
  14171. // data: [{
  14172. // value: 12,
  14173. // label: {
  14174. // rich: {
  14175. // // no 'a' here but using parent 'a'.
  14176. // }
  14177. // }
  14178. // }],
  14179. // rich: {
  14180. // a: { ... }
  14181. // }
  14182. // }
  14183. function getRichItemNames(textStyleModel) {
  14184. // Use object to remove duplicated names.
  14185. var richItemNameMap;
  14186. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14187. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14188. if (rich) {
  14189. richItemNameMap = richItemNameMap || {};
  14190. for (var name in rich) {
  14191. if (rich.hasOwnProperty(name)) {
  14192. richItemNameMap[name] = 1;
  14193. }
  14194. }
  14195. }
  14196. textStyleModel = textStyleModel.parentModel;
  14197. }
  14198. return richItemNameMap;
  14199. }
  14200. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14201. // In merge mode, default value should not be given.
  14202. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14203. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14204. || globalTextStyle.color;
  14205. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14206. || globalTextStyle.textBorderColor;
  14207. textStyle.textStrokeWidth = retrieve2(
  14208. textStyleModel.getShallow('textBorderWidth'),
  14209. globalTextStyle.textBorderWidth
  14210. );
  14211. if (!isEmphasis) {
  14212. if (isBlock) {
  14213. // Always set `insideRollback`, for clearing previous.
  14214. var originalTextPosition = textStyle.textPosition;
  14215. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14216. // Save original textPosition, because style.textPosition will be repalced by
  14217. // real location (like [10, 30]) in zrender.
  14218. textStyle.insideOriginalTextPosition = originalTextPosition;
  14219. textStyle.insideRollbackOpt = opt;
  14220. }
  14221. // Set default finally.
  14222. if (textStyle.textFill == null) {
  14223. textStyle.textFill = opt.autoColor;
  14224. }
  14225. }
  14226. // Do not use `getFont` here, because merge should be supported, where
  14227. // part of these properties may be changed in emphasis style, and the
  14228. // others should remain their original value got from normal style.
  14229. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14230. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14231. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14232. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14233. textStyle.textAlign = textStyleModel.getShallow('align');
  14234. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14235. || textStyleModel.getShallow('baseline');
  14236. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14237. textStyle.textWidth = textStyleModel.getShallow('width');
  14238. textStyle.textHeight = textStyleModel.getShallow('height');
  14239. textStyle.textTag = textStyleModel.getShallow('tag');
  14240. if (!isBlock || !opt.disableBox) {
  14241. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14242. textStyle.textPadding = textStyleModel.getShallow('padding');
  14243. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14244. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14245. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14246. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14247. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14248. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14249. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14250. }
  14251. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14252. || globalTextStyle.textShadowColor;
  14253. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14254. || globalTextStyle.textShadowBlur;
  14255. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14256. || globalTextStyle.textShadowOffsetX;
  14257. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14258. || globalTextStyle.textShadowOffsetY;
  14259. }
  14260. function getAutoColor(color, opt) {
  14261. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14262. }
  14263. function applyInsideStyle(textStyle, textPosition, opt) {
  14264. var useInsideStyle = opt.useInsideStyle;
  14265. var insideRollback;
  14266. if (textStyle.textFill == null
  14267. && useInsideStyle !== false
  14268. && (useInsideStyle === true
  14269. || (opt.isRectText
  14270. && textPosition
  14271. // textPosition can be [10, 30]
  14272. && typeof textPosition === 'string'
  14273. && textPosition.indexOf('inside') >= 0
  14274. )
  14275. )
  14276. ) {
  14277. insideRollback = {
  14278. textFill: null,
  14279. textStroke: textStyle.textStroke,
  14280. textStrokeWidth: textStyle.textStrokeWidth
  14281. };
  14282. textStyle.textFill = '#fff';
  14283. // Consider text with #fff overflow its container.
  14284. if (textStyle.textStroke == null) {
  14285. textStyle.textStroke = opt.autoColor;
  14286. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14287. }
  14288. }
  14289. return insideRollback;
  14290. }
  14291. function rollbackInsideStyle(style) {
  14292. var insideRollback = style.insideRollback;
  14293. if (insideRollback) {
  14294. style.textFill = insideRollback.textFill;
  14295. style.textStroke = insideRollback.textStroke;
  14296. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14297. }
  14298. }
  14299. function getFont(opt, ecModel) {
  14300. // ecModel or default text style model.
  14301. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14302. return trim([
  14303. // FIXME in node-canvas fontWeight is before fontStyle
  14304. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14305. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14306. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14307. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14308. ].join(' '));
  14309. }
  14310. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14311. if (typeof dataIndex === 'function') {
  14312. cb = dataIndex;
  14313. dataIndex = null;
  14314. }
  14315. // Do not check 'animation' property directly here. Consider this case:
  14316. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14317. // but its parent model (`seriesModel`) does.
  14318. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14319. if (animationEnabled) {
  14320. var postfix = isUpdate ? 'Update' : '';
  14321. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14322. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14323. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14324. if (typeof animationDelay === 'function') {
  14325. animationDelay = animationDelay(
  14326. dataIndex,
  14327. animatableModel.getAnimationDelayParams
  14328. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14329. : null
  14330. );
  14331. }
  14332. if (typeof duration === 'function') {
  14333. duration = duration(dataIndex);
  14334. }
  14335. duration > 0
  14336. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14337. : (el.stopAnimation(), el.attr(props), cb && cb());
  14338. }
  14339. else {
  14340. el.stopAnimation();
  14341. el.attr(props);
  14342. cb && cb();
  14343. }
  14344. }
  14345. /**
  14346. * Update graphic element properties with or without animation according to the
  14347. * configuration in series.
  14348. *
  14349. * Caution: this method will stop previous animation.
  14350. * So if do not use this method to one element twice before
  14351. * animation starts, unless you know what you are doing.
  14352. *
  14353. * @param {module:zrender/Element} el
  14354. * @param {Object} props
  14355. * @param {module:echarts/model/Model} [animatableModel]
  14356. * @param {number} [dataIndex]
  14357. * @param {Function} [cb]
  14358. * @example
  14359. * graphic.updateProps(el, {
  14360. * position: [100, 100]
  14361. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14362. * // Or
  14363. * graphic.updateProps(el, {
  14364. * position: [100, 100]
  14365. * }, seriesModel, function () { console.log('Animation done!'); });
  14366. */
  14367. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14368. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14369. }
  14370. /**
  14371. * Init graphic element properties with or without animation according to the
  14372. * configuration in series.
  14373. *
  14374. * Caution: this method will stop previous animation.
  14375. * So if do not use this method to one element twice before
  14376. * animation starts, unless you know what you are doing.
  14377. *
  14378. * @param {module:zrender/Element} el
  14379. * @param {Object} props
  14380. * @param {module:echarts/model/Model} [animatableModel]
  14381. * @param {number} [dataIndex]
  14382. * @param {Function} cb
  14383. */
  14384. function initProps(el, props, animatableModel, dataIndex, cb) {
  14385. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14386. }
  14387. /**
  14388. * Get transform matrix of target (param target),
  14389. * in coordinate of its ancestor (param ancestor)
  14390. *
  14391. * @param {module:zrender/mixin/Transformable} target
  14392. * @param {module:zrender/mixin/Transformable} [ancestor]
  14393. */
  14394. function getTransform(target, ancestor) {
  14395. var mat = identity([]);
  14396. while (target && target !== ancestor) {
  14397. mul$1(mat, target.getLocalTransform(), mat);
  14398. target = target.parent;
  14399. }
  14400. return mat;
  14401. }
  14402. /**
  14403. * Apply transform to an vertex.
  14404. * @param {Array.<number>} target [x, y]
  14405. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14406. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14407. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14408. * @param {boolean=} invert Whether use invert matrix.
  14409. * @return {Array.<number>} [x, y]
  14410. */
  14411. function applyTransform$1(target, transform, invert$$1) {
  14412. if (transform && !isArrayLike(transform)) {
  14413. transform = Transformable.getLocalTransform(transform);
  14414. }
  14415. if (invert$$1) {
  14416. transform = invert([], transform);
  14417. }
  14418. return applyTransform([], target, transform);
  14419. }
  14420. /**
  14421. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14422. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14423. * @param {boolean=} invert Whether use invert matrix.
  14424. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14425. */
  14426. function transformDirection(direction, transform, invert$$1) {
  14427. // Pick a base, ensure that transform result will not be (0, 0).
  14428. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14429. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14430. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14431. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14432. var vertex = [
  14433. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14434. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14435. ];
  14436. vertex = applyTransform$1(vertex, transform, invert$$1);
  14437. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14438. ? (vertex[0] > 0 ? 'right' : 'left')
  14439. : (vertex[1] > 0 ? 'bottom' : 'top');
  14440. }
  14441. /**
  14442. * Apply group transition animation from g1 to g2.
  14443. * If no animatableModel, no animation.
  14444. */
  14445. function groupTransition(g1, g2, animatableModel, cb) {
  14446. if (!g1 || !g2) {
  14447. return;
  14448. }
  14449. function getElMap(g) {
  14450. var elMap = {};
  14451. g.traverse(function (el) {
  14452. if (!el.isGroup && el.anid) {
  14453. elMap[el.anid] = el;
  14454. }
  14455. });
  14456. return elMap;
  14457. }
  14458. function getAnimatableProps(el) {
  14459. var obj = {
  14460. position: clone$1(el.position),
  14461. rotation: el.rotation
  14462. };
  14463. if (el.shape) {
  14464. obj.shape = extend({}, el.shape);
  14465. }
  14466. return obj;
  14467. }
  14468. var elMap1 = getElMap(g1);
  14469. g2.traverse(function (el) {
  14470. if (!el.isGroup && el.anid) {
  14471. var oldEl = elMap1[el.anid];
  14472. if (oldEl) {
  14473. var newProp = getAnimatableProps(el);
  14474. el.attr(getAnimatableProps(oldEl));
  14475. updateProps(el, newProp, animatableModel, el.dataIndex);
  14476. }
  14477. // else {
  14478. // if (el.previousProps) {
  14479. // graphic.updateProps
  14480. // }
  14481. // }
  14482. }
  14483. });
  14484. }
  14485. /**
  14486. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14487. * @param {Object} rect {x, y, width, height}
  14488. * @return {Array.<Array.<number>>} A new clipped points.
  14489. */
  14490. function clipPointsByRect(points, rect) {
  14491. return map(points, function (point) {
  14492. var x = point[0];
  14493. x = mathMax$1(x, rect.x);
  14494. x = mathMin$1(x, rect.x + rect.width);
  14495. var y = point[1];
  14496. y = mathMax$1(y, rect.y);
  14497. y = mathMin$1(y, rect.y + rect.height);
  14498. return [x, y];
  14499. });
  14500. }
  14501. /**
  14502. * @param {Object} targetRect {x, y, width, height}
  14503. * @param {Object} rect {x, y, width, height}
  14504. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14505. */
  14506. function clipRectByRect(targetRect, rect) {
  14507. var x = mathMax$1(targetRect.x, rect.x);
  14508. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14509. var y = mathMax$1(targetRect.y, rect.y);
  14510. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14511. if (x2 >= x && y2 >= y) {
  14512. return {
  14513. x: x,
  14514. y: y,
  14515. width: x2 - x,
  14516. height: y2 - y
  14517. };
  14518. }
  14519. }
  14520. /**
  14521. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14522. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14523. * @param {Object} [rect] {x, y, width, height}
  14524. * @return {module:zrender/Element} Icon path or image element.
  14525. */
  14526. function createIcon(iconStr, opt, rect) {
  14527. opt = extend({rectHover: true}, opt);
  14528. var style = opt.style = {strokeNoScale: true};
  14529. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14530. if (iconStr) {
  14531. return iconStr.indexOf('image://') === 0
  14532. ? (
  14533. style.image = iconStr.slice(8),
  14534. defaults(style, rect),
  14535. new ZImage(opt)
  14536. )
  14537. : (
  14538. makePath(
  14539. iconStr.replace('path://', ''),
  14540. opt,
  14541. rect,
  14542. 'center'
  14543. )
  14544. );
  14545. }
  14546. }
  14547. var graphic = (Object.freeze || Object)({
  14548. extendShape: extendShape,
  14549. extendPath: extendPath,
  14550. makePath: makePath,
  14551. makeImage: makeImage,
  14552. mergePath: mergePath,
  14553. resizePath: resizePath,
  14554. subPixelOptimizeLine: subPixelOptimizeLine,
  14555. subPixelOptimizeRect: subPixelOptimizeRect,
  14556. subPixelOptimize: subPixelOptimize,
  14557. setHoverStyle: setHoverStyle,
  14558. setLabelStyle: setLabelStyle,
  14559. setTextStyle: setTextStyle,
  14560. setText: setText,
  14561. getFont: getFont,
  14562. updateProps: updateProps,
  14563. initProps: initProps,
  14564. getTransform: getTransform,
  14565. applyTransform: applyTransform$1,
  14566. transformDirection: transformDirection,
  14567. groupTransition: groupTransition,
  14568. clipPointsByRect: clipPointsByRect,
  14569. clipRectByRect: clipRectByRect,
  14570. createIcon: createIcon,
  14571. Group: Group,
  14572. Image: ZImage,
  14573. Text: Text,
  14574. Circle: Circle,
  14575. Sector: Sector,
  14576. Ring: Ring,
  14577. Polygon: Polygon,
  14578. Polyline: Polyline,
  14579. Rect: Rect,
  14580. Line: Line,
  14581. BezierCurve: BezierCurve,
  14582. Arc: Arc,
  14583. IncrementalDisplayable: IncrementalDisplayble,
  14584. CompoundPath: CompoundPath,
  14585. LinearGradient: LinearGradient,
  14586. RadialGradient: RadialGradient,
  14587. BoundingRect: BoundingRect
  14588. });
  14589. var PATH_COLOR = ['textStyle', 'color'];
  14590. var textStyleMixin = {
  14591. /**
  14592. * Get color property or get color from option.textStyle.color
  14593. * @param {boolean} [isEmphasis]
  14594. * @return {string}
  14595. */
  14596. getTextColor: function (isEmphasis) {
  14597. var ecModel = this.ecModel;
  14598. return this.getShallow('color')
  14599. || (
  14600. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14601. );
  14602. },
  14603. /**
  14604. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14605. * @return {string}
  14606. */
  14607. getFont: function () {
  14608. return getFont({
  14609. fontStyle: this.getShallow('fontStyle'),
  14610. fontWeight: this.getShallow('fontWeight'),
  14611. fontSize: this.getShallow('fontSize'),
  14612. fontFamily: this.getShallow('fontFamily')
  14613. }, this.ecModel);
  14614. },
  14615. getTextRect: function (text) {
  14616. return getBoundingRect(
  14617. text,
  14618. this.getFont(),
  14619. this.getShallow('align'),
  14620. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14621. this.getShallow('padding'),
  14622. this.getShallow('rich'),
  14623. this.getShallow('truncateText')
  14624. );
  14625. }
  14626. };
  14627. var getItemStyle = makeStyleMapper(
  14628. [
  14629. ['fill', 'color'],
  14630. ['stroke', 'borderColor'],
  14631. ['lineWidth', 'borderWidth'],
  14632. ['opacity'],
  14633. ['shadowBlur'],
  14634. ['shadowOffsetX'],
  14635. ['shadowOffsetY'],
  14636. ['shadowColor'],
  14637. ['textPosition'],
  14638. ['textAlign']
  14639. ]
  14640. );
  14641. var itemStyleMixin = {
  14642. getItemStyle: function (excludes, includes) {
  14643. var style = getItemStyle(this, excludes, includes);
  14644. var lineDash = this.getBorderLineDash();
  14645. lineDash && (style.lineDash = lineDash);
  14646. return style;
  14647. },
  14648. getBorderLineDash: function () {
  14649. var lineType = this.get('borderType');
  14650. return (lineType === 'solid' || lineType == null) ? null
  14651. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14652. }
  14653. };
  14654. /**
  14655. * @module echarts/model/Model
  14656. */
  14657. var mixin$1 = mixin;
  14658. var inner = makeInner();
  14659. /**
  14660. * @alias module:echarts/model/Model
  14661. * @constructor
  14662. * @param {Object} option
  14663. * @param {module:echarts/model/Model} [parentModel]
  14664. * @param {module:echarts/model/Global} [ecModel]
  14665. */
  14666. function Model(option, parentModel, ecModel) {
  14667. /**
  14668. * @type {module:echarts/model/Model}
  14669. * @readOnly
  14670. */
  14671. this.parentModel = parentModel;
  14672. /**
  14673. * @type {module:echarts/model/Global}
  14674. * @readOnly
  14675. */
  14676. this.ecModel = ecModel;
  14677. /**
  14678. * @type {Object}
  14679. * @protected
  14680. */
  14681. this.option = option;
  14682. // Simple optimization
  14683. // if (this.init) {
  14684. // if (arguments.length <= 4) {
  14685. // this.init(option, parentModel, ecModel, extraOpt);
  14686. // }
  14687. // else {
  14688. // this.init.apply(this, arguments);
  14689. // }
  14690. // }
  14691. }
  14692. Model.prototype = {
  14693. constructor: Model,
  14694. /**
  14695. * Model 的初始化函数
  14696. * @param {Object} option
  14697. */
  14698. init: null,
  14699. /**
  14700. * 从新的 Option merge
  14701. */
  14702. mergeOption: function (option) {
  14703. merge(this.option, option, true);
  14704. },
  14705. /**
  14706. * @param {string|Array.<string>} path
  14707. * @param {boolean} [ignoreParent=false]
  14708. * @return {*}
  14709. */
  14710. get: function (path, ignoreParent) {
  14711. if (path == null) {
  14712. return this.option;
  14713. }
  14714. return doGet(
  14715. this.option,
  14716. this.parsePath(path),
  14717. !ignoreParent && getParent(this, path)
  14718. );
  14719. },
  14720. /**
  14721. * @param {string} key
  14722. * @param {boolean} [ignoreParent=false]
  14723. * @return {*}
  14724. */
  14725. getShallow: function (key, ignoreParent) {
  14726. var option = this.option;
  14727. var val = option == null ? option : option[key];
  14728. var parentModel = !ignoreParent && getParent(this, key);
  14729. if (val == null && parentModel) {
  14730. val = parentModel.getShallow(key);
  14731. }
  14732. return val;
  14733. },
  14734. /**
  14735. * @param {string|Array.<string>} [path]
  14736. * @param {module:echarts/model/Model} [parentModel]
  14737. * @return {module:echarts/model/Model}
  14738. */
  14739. getModel: function (path, parentModel) {
  14740. var obj = path == null
  14741. ? this.option
  14742. : doGet(this.option, path = this.parsePath(path));
  14743. var thisParentModel;
  14744. parentModel = parentModel || (
  14745. (thisParentModel = getParent(this, path))
  14746. && thisParentModel.getModel(path)
  14747. );
  14748. return new Model(obj, parentModel, this.ecModel);
  14749. },
  14750. /**
  14751. * If model has option
  14752. */
  14753. isEmpty: function () {
  14754. return this.option == null;
  14755. },
  14756. restoreData: function () {},
  14757. // Pending
  14758. clone: function () {
  14759. var Ctor = this.constructor;
  14760. return new Ctor(clone(this.option));
  14761. },
  14762. setReadOnly: function (properties) {
  14763. // clazzUtil.setReadOnly(this, properties);
  14764. },
  14765. // If path is null/undefined, return null/undefined.
  14766. parsePath: function(path) {
  14767. if (typeof path === 'string') {
  14768. path = path.split('.');
  14769. }
  14770. return path;
  14771. },
  14772. /**
  14773. * @param {Function} getParentMethod
  14774. * param {Array.<string>|string} path
  14775. * return {module:echarts/model/Model}
  14776. */
  14777. customizeGetParent: function (getParentMethod) {
  14778. inner(this).getParent = getParentMethod;
  14779. },
  14780. isAnimationEnabled: function () {
  14781. if (!env$1.node) {
  14782. if (this.option.animation != null) {
  14783. return !!this.option.animation;
  14784. }
  14785. else if (this.parentModel) {
  14786. return this.parentModel.isAnimationEnabled();
  14787. }
  14788. }
  14789. }
  14790. };
  14791. function doGet(obj, pathArr, parentModel) {
  14792. for (var i = 0; i < pathArr.length; i++) {
  14793. // Ignore empty
  14794. if (!pathArr[i]) {
  14795. continue;
  14796. }
  14797. // obj could be number/string/... (like 0)
  14798. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14799. if (obj == null) {
  14800. break;
  14801. }
  14802. }
  14803. if (obj == null && parentModel) {
  14804. obj = parentModel.get(pathArr);
  14805. }
  14806. return obj;
  14807. }
  14808. // `path` can be null/undefined
  14809. function getParent(model, path) {
  14810. var getParentMethod = inner(model).getParent;
  14811. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14812. }
  14813. // Enable Model.extend.
  14814. enableClassExtend(Model);
  14815. enableClassCheck(Model);
  14816. mixin$1(Model, lineStyleMixin);
  14817. mixin$1(Model, areaStyleMixin);
  14818. mixin$1(Model, textStyleMixin);
  14819. mixin$1(Model, itemStyleMixin);
  14820. var base = 0;
  14821. /**
  14822. * @public
  14823. * @param {string} type
  14824. * @return {string}
  14825. */
  14826. function getUID(type) {
  14827. // Considering the case of crossing js context,
  14828. // use Math.random to make id as unique as possible.
  14829. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14830. }
  14831. /**
  14832. * @inner
  14833. */
  14834. function enableSubTypeDefaulter(entity) {
  14835. var subTypeDefaulters = {};
  14836. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14837. componentType = parseClassType$1(componentType);
  14838. subTypeDefaulters[componentType.main] = defaulter;
  14839. };
  14840. entity.determineSubType = function (componentType, option) {
  14841. var type = option.type;
  14842. if (!type) {
  14843. var componentTypeMain = parseClassType$1(componentType).main;
  14844. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14845. type = subTypeDefaulters[componentTypeMain](option);
  14846. }
  14847. }
  14848. return type;
  14849. };
  14850. return entity;
  14851. }
  14852. /**
  14853. * Topological travel on Activity Network (Activity On Vertices).
  14854. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14855. *
  14856. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14857. *
  14858. * If there is circle dependencey, Error will be thrown.
  14859. *
  14860. */
  14861. function enableTopologicalTravel(entity, dependencyGetter) {
  14862. /**
  14863. * @public
  14864. * @param {Array.<string>} targetNameList Target Component type list.
  14865. * Can be ['aa', 'bb', 'aa.xx']
  14866. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14867. * @param {Function} callback Params: componentType, dependencies.
  14868. * @param {Object} context Scope of callback.
  14869. */
  14870. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14871. if (!targetNameList.length) {
  14872. return;
  14873. }
  14874. var result = makeDepndencyGraph(fullNameList);
  14875. var graph = result.graph;
  14876. var stack = result.noEntryList;
  14877. var targetNameSet = {};
  14878. each$1(targetNameList, function (name) {
  14879. targetNameSet[name] = true;
  14880. });
  14881. while (stack.length) {
  14882. var currComponentType = stack.pop();
  14883. var currVertex = graph[currComponentType];
  14884. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14885. if (isInTargetNameSet) {
  14886. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14887. delete targetNameSet[currComponentType];
  14888. }
  14889. each$1(
  14890. currVertex.successor,
  14891. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14892. );
  14893. }
  14894. each$1(targetNameSet, function () {
  14895. throw new Error('Circle dependency may exists');
  14896. });
  14897. function removeEdge(succComponentType) {
  14898. graph[succComponentType].entryCount--;
  14899. if (graph[succComponentType].entryCount === 0) {
  14900. stack.push(succComponentType);
  14901. }
  14902. }
  14903. // Consider this case: legend depends on series, and we call
  14904. // chart.setOption({series: [...]}), where only series is in option.
  14905. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14906. // not be called, but only sereis.mergeOption is called. Thus legend
  14907. // have no chance to update its local record about series (like which
  14908. // name of series is available in legend).
  14909. function removeEdgeAndAdd(succComponentType) {
  14910. targetNameSet[succComponentType] = true;
  14911. removeEdge(succComponentType);
  14912. }
  14913. };
  14914. /**
  14915. * DepndencyGraph: {Object}
  14916. * key: conponentType,
  14917. * value: {
  14918. * successor: [conponentTypes...],
  14919. * originalDeps: [conponentTypes...],
  14920. * entryCount: {number}
  14921. * }
  14922. */
  14923. function makeDepndencyGraph(fullNameList) {
  14924. var graph = {};
  14925. var noEntryList = [];
  14926. each$1(fullNameList, function (name) {
  14927. var thisItem = createDependencyGraphItem(graph, name);
  14928. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14929. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14930. thisItem.entryCount = availableDeps.length;
  14931. if (thisItem.entryCount === 0) {
  14932. noEntryList.push(name);
  14933. }
  14934. each$1(availableDeps, function (dependentName) {
  14935. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14936. thisItem.predecessor.push(dependentName);
  14937. }
  14938. var thatItem = createDependencyGraphItem(graph, dependentName);
  14939. if (indexOf(thatItem.successor, dependentName) < 0) {
  14940. thatItem.successor.push(name);
  14941. }
  14942. });
  14943. });
  14944. return {graph: graph, noEntryList: noEntryList};
  14945. }
  14946. function createDependencyGraphItem(graph, name) {
  14947. if (!graph[name]) {
  14948. graph[name] = {predecessor: [], successor: []};
  14949. }
  14950. return graph[name];
  14951. }
  14952. function getAvailableDependencies(originalDeps, fullNameList) {
  14953. var availableDeps = [];
  14954. each$1(originalDeps, function (dep) {
  14955. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14956. });
  14957. return availableDeps;
  14958. }
  14959. }
  14960. var RADIAN_EPSILON = 1e-4;
  14961. function _trim(str) {
  14962. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  14963. }
  14964. /**
  14965. * Linear mapping a value from domain to range
  14966. * @memberOf module:echarts/util/number
  14967. * @param {(number|Array.<number>)} val
  14968. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  14969. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  14970. * @param {boolean} clamp
  14971. * @return {(number|Array.<number>}
  14972. */
  14973. function linearMap(val, domain, range, clamp) {
  14974. var subDomain = domain[1] - domain[0];
  14975. var subRange = range[1] - range[0];
  14976. if (subDomain === 0) {
  14977. return subRange === 0
  14978. ? range[0]
  14979. : (range[0] + range[1]) / 2;
  14980. }
  14981. // Avoid accuracy problem in edge, such as
  14982. // 146.39 - 62.83 === 83.55999999999999.
  14983. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  14984. // It is a little verbose for efficiency considering this method
  14985. // is a hotspot.
  14986. if (clamp) {
  14987. if (subDomain > 0) {
  14988. if (val <= domain[0]) {
  14989. return range[0];
  14990. }
  14991. else if (val >= domain[1]) {
  14992. return range[1];
  14993. }
  14994. }
  14995. else {
  14996. if (val >= domain[0]) {
  14997. return range[0];
  14998. }
  14999. else if (val <= domain[1]) {
  15000. return range[1];
  15001. }
  15002. }
  15003. }
  15004. else {
  15005. if (val === domain[0]) {
  15006. return range[0];
  15007. }
  15008. if (val === domain[1]) {
  15009. return range[1];
  15010. }
  15011. }
  15012. return (val - domain[0]) / subDomain * subRange + range[0];
  15013. }
  15014. /**
  15015. * Convert a percent string to absolute number.
  15016. * Returns NaN if percent is not a valid string or number
  15017. * @memberOf module:echarts/util/number
  15018. * @param {string|number} percent
  15019. * @param {number} all
  15020. * @return {number}
  15021. */
  15022. function parsePercent$1(percent, all) {
  15023. switch (percent) {
  15024. case 'center':
  15025. case 'middle':
  15026. percent = '50%';
  15027. break;
  15028. case 'left':
  15029. case 'top':
  15030. percent = '0%';
  15031. break;
  15032. case 'right':
  15033. case 'bottom':
  15034. percent = '100%';
  15035. break;
  15036. }
  15037. if (typeof percent === 'string') {
  15038. if (_trim(percent).match(/%$/)) {
  15039. return parseFloat(percent) / 100 * all;
  15040. }
  15041. return parseFloat(percent);
  15042. }
  15043. return percent == null ? NaN : +percent;
  15044. }
  15045. /**
  15046. * (1) Fix rounding error of float numbers.
  15047. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15048. *
  15049. * @param {number} x
  15050. * @param {number} [precision]
  15051. * @param {boolean} [returnStr]
  15052. * @return {number|string}
  15053. */
  15054. function round$1(x, precision, returnStr) {
  15055. if (precision == null) {
  15056. precision = 10;
  15057. }
  15058. // Avoid range error
  15059. precision = Math.min(Math.max(0, precision), 20);
  15060. x = (+x).toFixed(precision);
  15061. return returnStr ? x : +x;
  15062. }
  15063. function asc(arr) {
  15064. arr.sort(function (a, b) {
  15065. return a - b;
  15066. });
  15067. return arr;
  15068. }
  15069. /**
  15070. * Get precision
  15071. * @param {number} val
  15072. */
  15073. function getPrecision(val) {
  15074. val = +val;
  15075. if (isNaN(val)) {
  15076. return 0;
  15077. }
  15078. // It is much faster than methods converting number to string as follows
  15079. // var tmp = val.toString();
  15080. // return tmp.length - 1 - tmp.indexOf('.');
  15081. // especially when precision is low
  15082. var e = 1;
  15083. var count = 0;
  15084. while (Math.round(val * e) / e !== val) {
  15085. e *= 10;
  15086. count++;
  15087. }
  15088. return count;
  15089. }
  15090. /**
  15091. * @param {string|number} val
  15092. * @return {number}
  15093. */
  15094. function getPrecisionSafe(val) {
  15095. var str = val.toString();
  15096. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15097. var eIndex = str.indexOf('e');
  15098. if (eIndex > 0) {
  15099. var precision = +str.slice(eIndex + 1);
  15100. return precision < 0 ? -precision : 0;
  15101. }
  15102. else {
  15103. var dotIndex = str.indexOf('.');
  15104. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15105. }
  15106. }
  15107. /**
  15108. * Minimal dicernible data precisioin according to a single pixel.
  15109. *
  15110. * @param {Array.<number>} dataExtent
  15111. * @param {Array.<number>} pixelExtent
  15112. * @return {number} precision
  15113. */
  15114. function getPixelPrecision(dataExtent, pixelExtent) {
  15115. var log = Math.log;
  15116. var LN10 = Math.LN10;
  15117. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15118. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15119. // toFixed() digits argument must be between 0 and 20.
  15120. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15121. return !isFinite(precision) ? 20 : precision;
  15122. }
  15123. /**
  15124. * Get a data of given precision, assuring the sum of percentages
  15125. * in valueList is 1.
  15126. * The largest remainer method is used.
  15127. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15128. *
  15129. * @param {Array.<number>} valueList a list of all data
  15130. * @param {number} idx index of the data to be processed in valueList
  15131. * @param {number} precision integer number showing digits of precision
  15132. * @return {number} percent ranging from 0 to 100
  15133. */
  15134. function getPercentWithPrecision(valueList, idx, precision) {
  15135. if (!valueList[idx]) {
  15136. return 0;
  15137. }
  15138. var sum = reduce(valueList, function (acc, val) {
  15139. return acc + (isNaN(val) ? 0 : val);
  15140. }, 0);
  15141. if (sum === 0) {
  15142. return 0;
  15143. }
  15144. var digits = Math.pow(10, precision);
  15145. var votesPerQuota = map(valueList, function (val) {
  15146. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15147. });
  15148. var targetSeats = digits * 100;
  15149. var seats = map(votesPerQuota, function (votes) {
  15150. // Assign automatic seats.
  15151. return Math.floor(votes);
  15152. });
  15153. var currentSum = reduce(seats, function (acc, val) {
  15154. return acc + val;
  15155. }, 0);
  15156. var remainder = map(votesPerQuota, function (votes, idx) {
  15157. return votes - seats[idx];
  15158. });
  15159. // Has remainding votes.
  15160. while (currentSum < targetSeats) {
  15161. // Find next largest remainder.
  15162. var max = Number.NEGATIVE_INFINITY;
  15163. var maxId = null;
  15164. for (var i = 0, len = remainder.length; i < len; ++i) {
  15165. if (remainder[i] > max) {
  15166. max = remainder[i];
  15167. maxId = i;
  15168. }
  15169. }
  15170. // Add a vote to max remainder.
  15171. ++seats[maxId];
  15172. remainder[maxId] = 0;
  15173. ++currentSum;
  15174. }
  15175. return seats[idx] / digits;
  15176. }
  15177. // Number.MAX_SAFE_INTEGER, ie do not support.
  15178. var MAX_SAFE_INTEGER = 9007199254740991;
  15179. /**
  15180. * To 0 - 2 * PI, considering negative radian.
  15181. * @param {number} radian
  15182. * @return {number}
  15183. */
  15184. function remRadian(radian) {
  15185. var pi2 = Math.PI * 2;
  15186. return (radian % pi2 + pi2) % pi2;
  15187. }
  15188. /**
  15189. * @param {type} radian
  15190. * @return {boolean}
  15191. */
  15192. function isRadianAroundZero(val) {
  15193. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15194. }
  15195. 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
  15196. /**
  15197. * @param {string|Date|number} value These values can be accepted:
  15198. * + An instance of Date, represent a time in its own time zone.
  15199. * + Or string in a subset of ISO 8601, only including:
  15200. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15201. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15202. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15203. * all of which will be treated as local time if time zone is not specified
  15204. * (see <https://momentjs.com/>).
  15205. * + Or other string format, including (all of which will be treated as loacal time):
  15206. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15207. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15208. * + a timestamp, which represent a time in UTC.
  15209. * @return {Date} date
  15210. */
  15211. function parseDate(value) {
  15212. if (value instanceof Date) {
  15213. return value;
  15214. }
  15215. else if (typeof value === 'string') {
  15216. // Different browsers parse date in different way, so we parse it manually.
  15217. // Some other issues:
  15218. // new Date('1970-01-01') is UTC,
  15219. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15220. // See issue #3623
  15221. var match = TIME_REG.exec(value);
  15222. if (!match) {
  15223. // return Invalid Date.
  15224. return new Date(NaN);
  15225. }
  15226. // Use local time when no timezone offset specifed.
  15227. if (!match[8]) {
  15228. // match[n] can only be string or undefined.
  15229. // But take care of '12' + 1 => '121'.
  15230. return new Date(
  15231. +match[1],
  15232. +(match[2] || 1) - 1,
  15233. +match[3] || 1,
  15234. +match[4] || 0,
  15235. +(match[5] || 0),
  15236. +match[6] || 0,
  15237. +match[7] || 0
  15238. );
  15239. }
  15240. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15241. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15242. // For example, system timezone is set as "Time Zone: America/Toronto",
  15243. // then these code will get different result:
  15244. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15245. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15246. // So we should not use `new Date`, but use `Date.UTC`.
  15247. else {
  15248. var hour = +match[4] || 0;
  15249. if (match[8].toUpperCase() !== 'Z') {
  15250. hour -= match[8].slice(0, 3);
  15251. }
  15252. return new Date(Date.UTC(
  15253. +match[1],
  15254. +(match[2] || 1) - 1,
  15255. +match[3] || 1,
  15256. hour,
  15257. +(match[5] || 0),
  15258. +match[6] || 0,
  15259. +match[7] || 0
  15260. ));
  15261. }
  15262. }
  15263. else if (value == null) {
  15264. return new Date(NaN);
  15265. }
  15266. return new Date(Math.round(value));
  15267. }
  15268. /**
  15269. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15270. *
  15271. * @param {number} val
  15272. * @return {number}
  15273. */
  15274. function quantity(val) {
  15275. return Math.pow(10, quantityExponent(val));
  15276. }
  15277. function quantityExponent(val) {
  15278. return Math.floor(Math.log(val) / Math.LN10);
  15279. }
  15280. /**
  15281. * find a “nice” number approximately equal to x. Round the number if round = true,
  15282. * take ceiling if round = false. The primary observation is that the “nicest”
  15283. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15284. *
  15285. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15286. *
  15287. * @param {number} val Non-negative value.
  15288. * @param {boolean} round
  15289. * @return {number}
  15290. */
  15291. function nice(val, round) {
  15292. var exponent = quantityExponent(val);
  15293. var exp10 = Math.pow(10, exponent);
  15294. var f = val / exp10; // 1 <= f < 10
  15295. var nf;
  15296. if (round) {
  15297. if (f < 1.5) { nf = 1; }
  15298. else if (f < 2.5) { nf = 2; }
  15299. else if (f < 4) { nf = 3; }
  15300. else if (f < 7) { nf = 5; }
  15301. else { nf = 10; }
  15302. }
  15303. else {
  15304. if (f < 1) { nf = 1; }
  15305. else if (f < 2) { nf = 2; }
  15306. else if (f < 3) { nf = 3; }
  15307. else if (f < 5) { nf = 5; }
  15308. else { nf = 10; }
  15309. }
  15310. val = nf * exp10;
  15311. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15312. // 20 is the uppper bound of toFixed.
  15313. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15314. }
  15315. /**
  15316. * Order intervals asc, and split them when overlap.
  15317. * expect(numberUtil.reformIntervals([
  15318. * {interval: [18, 62], close: [1, 1]},
  15319. * {interval: [-Infinity, -70], close: [0, 0]},
  15320. * {interval: [-70, -26], close: [1, 1]},
  15321. * {interval: [-26, 18], close: [1, 1]},
  15322. * {interval: [62, 150], close: [1, 1]},
  15323. * {interval: [106, 150], close: [1, 1]},
  15324. * {interval: [150, Infinity], close: [0, 0]}
  15325. * ])).toEqual([
  15326. * {interval: [-Infinity, -70], close: [0, 0]},
  15327. * {interval: [-70, -26], close: [1, 1]},
  15328. * {interval: [-26, 18], close: [0, 1]},
  15329. * {interval: [18, 62], close: [0, 1]},
  15330. * {interval: [62, 150], close: [0, 1]},
  15331. * {interval: [150, Infinity], close: [0, 0]}
  15332. * ]);
  15333. * @param {Array.<Object>} list, where `close` mean open or close
  15334. * of the interval, and Infinity can be used.
  15335. * @return {Array.<Object>} The origin list, which has been reformed.
  15336. */
  15337. function reformIntervals(list) {
  15338. list.sort(function (a, b) {
  15339. return littleThan(a, b, 0) ? -1 : 1;
  15340. });
  15341. var curr = -Infinity;
  15342. var currClose = 1;
  15343. for (var i = 0; i < list.length;) {
  15344. var interval = list[i].interval;
  15345. var close = list[i].close;
  15346. for (var lg = 0; lg < 2; lg++) {
  15347. if (interval[lg] <= curr) {
  15348. interval[lg] = curr;
  15349. close[lg] = !lg ? 1 - currClose : 1;
  15350. }
  15351. curr = interval[lg];
  15352. currClose = close[lg];
  15353. }
  15354. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15355. list.splice(i, 1);
  15356. }
  15357. else {
  15358. i++;
  15359. }
  15360. }
  15361. return list;
  15362. function littleThan(a, b, lg) {
  15363. return a.interval[lg] < b.interval[lg]
  15364. || (
  15365. a.interval[lg] === b.interval[lg]
  15366. && (
  15367. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15368. || (!lg && littleThan(a, b, 1))
  15369. )
  15370. );
  15371. }
  15372. }
  15373. /**
  15374. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15375. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15376. * subtraction forces infinities to NaN
  15377. *
  15378. * @param {*} v
  15379. * @return {boolean}
  15380. */
  15381. function isNumeric(v) {
  15382. return v - parseFloat(v) >= 0;
  15383. }
  15384. var number = (Object.freeze || Object)({
  15385. linearMap: linearMap,
  15386. parsePercent: parsePercent$1,
  15387. round: round$1,
  15388. asc: asc,
  15389. getPrecision: getPrecision,
  15390. getPrecisionSafe: getPrecisionSafe,
  15391. getPixelPrecision: getPixelPrecision,
  15392. getPercentWithPrecision: getPercentWithPrecision,
  15393. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15394. remRadian: remRadian,
  15395. isRadianAroundZero: isRadianAroundZero,
  15396. parseDate: parseDate,
  15397. quantity: quantity,
  15398. nice: nice,
  15399. reformIntervals: reformIntervals,
  15400. isNumeric: isNumeric
  15401. });
  15402. /**
  15403. * 每三位默认加,格式化
  15404. * @param {string|number} x
  15405. * @return {string}
  15406. */
  15407. function addCommas(x) {
  15408. if (isNaN(x)) {
  15409. return '-';
  15410. }
  15411. x = (x + '').split('.');
  15412. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15413. + (x.length > 1 ? ('.' + x[1]) : '');
  15414. }
  15415. /**
  15416. * @param {string} str
  15417. * @param {boolean} [upperCaseFirst=false]
  15418. * @return {string} str
  15419. */
  15420. function toCamelCase(str, upperCaseFirst) {
  15421. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15422. return group1.toUpperCase();
  15423. });
  15424. if (upperCaseFirst && str) {
  15425. str = str.charAt(0).toUpperCase() + str.slice(1);
  15426. }
  15427. return str;
  15428. }
  15429. var normalizeCssArray$1 = normalizeCssArray;
  15430. function encodeHTML(source) {
  15431. return String(source)
  15432. .replace(/&/g, '&amp;')
  15433. .replace(/</g, '&lt;')
  15434. .replace(/>/g, '&gt;')
  15435. .replace(/"/g, '&quot;')
  15436. .replace(/'/g, '&#39;');
  15437. }
  15438. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15439. var wrapVar = function (varName, seriesIdx) {
  15440. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15441. };
  15442. /**
  15443. * Template formatter
  15444. * @param {string} tpl
  15445. * @param {Array.<Object>|Object} paramsList
  15446. * @param {boolean} [encode=false]
  15447. * @return {string}
  15448. */
  15449. function formatTpl(tpl, paramsList, encode) {
  15450. if (!isArray(paramsList)) {
  15451. paramsList = [paramsList];
  15452. }
  15453. var seriesLen = paramsList.length;
  15454. if (!seriesLen) {
  15455. return '';
  15456. }
  15457. var $vars = paramsList[0].$vars || [];
  15458. for (var i = 0; i < $vars.length; i++) {
  15459. var alias = TPL_VAR_ALIAS[i];
  15460. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15461. }
  15462. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15463. for (var k = 0; k < $vars.length; k++) {
  15464. var val = paramsList[seriesIdx][$vars[k]];
  15465. tpl = tpl.replace(
  15466. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15467. encode ? encodeHTML(val) : val
  15468. );
  15469. }
  15470. }
  15471. return tpl;
  15472. }
  15473. /**
  15474. * simple Template formatter
  15475. *
  15476. * @param {string} tpl
  15477. * @param {Object} param
  15478. * @param {boolean} [encode=false]
  15479. * @return {string}
  15480. */
  15481. function formatTplSimple(tpl, param, encode) {
  15482. each$1(param, function (value, key) {
  15483. tpl = tpl.replace(
  15484. '{' + key + '}',
  15485. encode ? encodeHTML(value) : value
  15486. );
  15487. });
  15488. return tpl;
  15489. }
  15490. /**
  15491. * @param {Object|string} [opt] If string, means color.
  15492. * @param {string} [opt.color]
  15493. * @param {string} [opt.extraCssText]
  15494. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15495. * @return {string}
  15496. */
  15497. function getTooltipMarker(opt, extraCssText) {
  15498. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15499. var color = opt.color;
  15500. var type = opt.type;
  15501. var extraCssText = opt.extraCssText;
  15502. if (!color) {
  15503. return '';
  15504. }
  15505. return type === 'subItem'
  15506. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15507. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15508. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15509. : '<span style="display:inline-block;margin-right:5px;'
  15510. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15511. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15512. }
  15513. /**
  15514. * @param {string} str
  15515. * @return {string}
  15516. * @inner
  15517. */
  15518. var s2d = function (str) {
  15519. return str < 10 ? ('0' + str) : str;
  15520. };
  15521. /**
  15522. * ISO Date format
  15523. * @param {string} tpl
  15524. * @param {number} value
  15525. * @param {boolean} [isUTC=false] Default in local time.
  15526. * see `module:echarts/scale/Time`
  15527. * and `module:echarts/util/number#parseDate`.
  15528. * @inner
  15529. */
  15530. function formatTime(tpl, value, isUTC) {
  15531. if (tpl === 'week'
  15532. || tpl === 'month'
  15533. || tpl === 'quarter'
  15534. || tpl === 'half-year'
  15535. || tpl === 'year'
  15536. ) {
  15537. tpl = 'MM-dd\nyyyy';
  15538. }
  15539. var date = parseDate(value);
  15540. var utc = isUTC ? 'UTC' : '';
  15541. var y = date['get' + utc + 'FullYear']();
  15542. var M = date['get' + utc + 'Month']() + 1;
  15543. var d = date['get' + utc + 'Date']();
  15544. var h = date['get' + utc + 'Hours']();
  15545. var m = date['get' + utc + 'Minutes']();
  15546. var s = date['get' + utc + 'Seconds']();
  15547. tpl = tpl.replace('MM', s2d(M))
  15548. .replace('M', M)
  15549. .replace('yyyy', y)
  15550. .replace('yy', y % 100)
  15551. .replace('dd', s2d(d))
  15552. .replace('d', d)
  15553. .replace('hh', s2d(h))
  15554. .replace('h', h)
  15555. .replace('mm', s2d(m))
  15556. .replace('m', m)
  15557. .replace('ss', s2d(s))
  15558. .replace('s', s);
  15559. return tpl;
  15560. }
  15561. /**
  15562. * Capital first
  15563. * @param {string} str
  15564. * @return {string}
  15565. */
  15566. function capitalFirst(str) {
  15567. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15568. }
  15569. var truncateText$1 = truncateText;
  15570. var getTextRect = getBoundingRect;
  15571. var format = (Object.freeze || Object)({
  15572. addCommas: addCommas,
  15573. toCamelCase: toCamelCase,
  15574. normalizeCssArray: normalizeCssArray$1,
  15575. encodeHTML: encodeHTML,
  15576. formatTpl: formatTpl,
  15577. formatTplSimple: formatTplSimple,
  15578. getTooltipMarker: getTooltipMarker,
  15579. formatTime: formatTime,
  15580. capitalFirst: capitalFirst,
  15581. truncateText: truncateText$1,
  15582. getTextRect: getTextRect
  15583. });
  15584. // Layout helpers for each component positioning
  15585. var each$3 = each$1;
  15586. /**
  15587. * @public
  15588. */
  15589. var LOCATION_PARAMS = [
  15590. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15591. ];
  15592. /**
  15593. * @public
  15594. */
  15595. var HV_NAMES = [
  15596. ['width', 'left', 'right'],
  15597. ['height', 'top', 'bottom']
  15598. ];
  15599. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15600. var x = 0;
  15601. var y = 0;
  15602. if (maxWidth == null) {
  15603. maxWidth = Infinity;
  15604. }
  15605. if (maxHeight == null) {
  15606. maxHeight = Infinity;
  15607. }
  15608. var currentLineMaxSize = 0;
  15609. group.eachChild(function (child, idx) {
  15610. var position = child.position;
  15611. var rect = child.getBoundingRect();
  15612. var nextChild = group.childAt(idx + 1);
  15613. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15614. var nextX;
  15615. var nextY;
  15616. if (orient === 'horizontal') {
  15617. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15618. nextX = x + moveX;
  15619. // Wrap when width exceeds maxWidth or meet a `newline` group
  15620. // FIXME compare before adding gap?
  15621. if (nextX > maxWidth || child.newline) {
  15622. x = 0;
  15623. nextX = moveX;
  15624. y += currentLineMaxSize + gap;
  15625. currentLineMaxSize = rect.height;
  15626. }
  15627. else {
  15628. // FIXME: consider rect.y is not `0`?
  15629. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15630. }
  15631. }
  15632. else {
  15633. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15634. nextY = y + moveY;
  15635. // Wrap when width exceeds maxHeight or meet a `newline` group
  15636. if (nextY > maxHeight || child.newline) {
  15637. x += currentLineMaxSize + gap;
  15638. y = 0;
  15639. nextY = moveY;
  15640. currentLineMaxSize = rect.width;
  15641. }
  15642. else {
  15643. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15644. }
  15645. }
  15646. if (child.newline) {
  15647. return;
  15648. }
  15649. position[0] = x;
  15650. position[1] = y;
  15651. orient === 'horizontal'
  15652. ? (x = nextX + gap)
  15653. : (y = nextY + gap);
  15654. });
  15655. }
  15656. /**
  15657. * VBox or HBox layouting
  15658. * @param {string} orient
  15659. * @param {module:zrender/container/Group} group
  15660. * @param {number} gap
  15661. * @param {number} [width=Infinity]
  15662. * @param {number} [height=Infinity]
  15663. */
  15664. var box = boxLayout;
  15665. /**
  15666. * VBox layouting
  15667. * @param {module:zrender/container/Group} group
  15668. * @param {number} gap
  15669. * @param {number} [width=Infinity]
  15670. * @param {number} [height=Infinity]
  15671. */
  15672. var vbox = curry(boxLayout, 'vertical');
  15673. /**
  15674. * HBox layouting
  15675. * @param {module:zrender/container/Group} group
  15676. * @param {number} gap
  15677. * @param {number} [width=Infinity]
  15678. * @param {number} [height=Infinity]
  15679. */
  15680. var hbox = curry(boxLayout, 'horizontal');
  15681. /**
  15682. * If x or x2 is not specified or 'center' 'left' 'right',
  15683. * the width would be as long as possible.
  15684. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15685. * the height would be as long as possible.
  15686. *
  15687. * @param {Object} positionInfo
  15688. * @param {number|string} [positionInfo.x]
  15689. * @param {number|string} [positionInfo.y]
  15690. * @param {number|string} [positionInfo.x2]
  15691. * @param {number|string} [positionInfo.y2]
  15692. * @param {Object} containerRect {width, height}
  15693. * @param {string|number} margin
  15694. * @return {Object} {width, height}
  15695. */
  15696. function getAvailableSize(positionInfo, containerRect, margin) {
  15697. var containerWidth = containerRect.width;
  15698. var containerHeight = containerRect.height;
  15699. var x = parsePercent$1(positionInfo.x, containerWidth);
  15700. var y = parsePercent$1(positionInfo.y, containerHeight);
  15701. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  15702. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  15703. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  15704. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  15705. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  15706. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  15707. margin = normalizeCssArray$1(margin || 0);
  15708. return {
  15709. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15710. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15711. };
  15712. }
  15713. /**
  15714. * Parse position info.
  15715. *
  15716. * @param {Object} positionInfo
  15717. * @param {number|string} [positionInfo.left]
  15718. * @param {number|string} [positionInfo.top]
  15719. * @param {number|string} [positionInfo.right]
  15720. * @param {number|string} [positionInfo.bottom]
  15721. * @param {number|string} [positionInfo.width]
  15722. * @param {number|string} [positionInfo.height]
  15723. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15724. * @param {Object} containerRect
  15725. * @param {string|number} [margin]
  15726. *
  15727. * @return {module:zrender/core/BoundingRect}
  15728. */
  15729. function getLayoutRect(
  15730. positionInfo, containerRect, margin
  15731. ) {
  15732. margin = normalizeCssArray$1(margin || 0);
  15733. var containerWidth = containerRect.width;
  15734. var containerHeight = containerRect.height;
  15735. var left = parsePercent$1(positionInfo.left, containerWidth);
  15736. var top = parsePercent$1(positionInfo.top, containerHeight);
  15737. var right = parsePercent$1(positionInfo.right, containerWidth);
  15738. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15739. var width = parsePercent$1(positionInfo.width, containerWidth);
  15740. var height = parsePercent$1(positionInfo.height, containerHeight);
  15741. var verticalMargin = margin[2] + margin[0];
  15742. var horizontalMargin = margin[1] + margin[3];
  15743. var aspect = positionInfo.aspect;
  15744. // If width is not specified, calculate width from left and right
  15745. if (isNaN(width)) {
  15746. width = containerWidth - right - horizontalMargin - left;
  15747. }
  15748. if (isNaN(height)) {
  15749. height = containerHeight - bottom - verticalMargin - top;
  15750. }
  15751. if (aspect != null) {
  15752. // If width and height are not given
  15753. // 1. Graph should not exceeds the container
  15754. // 2. Aspect must be keeped
  15755. // 3. Graph should take the space as more as possible
  15756. // FIXME
  15757. // Margin is not considered, because there is no case that both
  15758. // using margin and aspect so far.
  15759. if (isNaN(width) && isNaN(height)) {
  15760. if (aspect > containerWidth / containerHeight) {
  15761. width = containerWidth * 0.8;
  15762. }
  15763. else {
  15764. height = containerHeight * 0.8;
  15765. }
  15766. }
  15767. // Calculate width or height with given aspect
  15768. if (isNaN(width)) {
  15769. width = aspect * height;
  15770. }
  15771. if (isNaN(height)) {
  15772. height = width / aspect;
  15773. }
  15774. }
  15775. // If left is not specified, calculate left from right and width
  15776. if (isNaN(left)) {
  15777. left = containerWidth - right - width - horizontalMargin;
  15778. }
  15779. if (isNaN(top)) {
  15780. top = containerHeight - bottom - height - verticalMargin;
  15781. }
  15782. // Align left and top
  15783. switch (positionInfo.left || positionInfo.right) {
  15784. case 'center':
  15785. left = containerWidth / 2 - width / 2 - margin[3];
  15786. break;
  15787. case 'right':
  15788. left = containerWidth - width - horizontalMargin;
  15789. break;
  15790. }
  15791. switch (positionInfo.top || positionInfo.bottom) {
  15792. case 'middle':
  15793. case 'center':
  15794. top = containerHeight / 2 - height / 2 - margin[0];
  15795. break;
  15796. case 'bottom':
  15797. top = containerHeight - height - verticalMargin;
  15798. break;
  15799. }
  15800. // If something is wrong and left, top, width, height are calculated as NaN
  15801. left = left || 0;
  15802. top = top || 0;
  15803. if (isNaN(width)) {
  15804. // Width may be NaN if only one value is given except width
  15805. width = containerWidth - horizontalMargin - left - (right || 0);
  15806. }
  15807. if (isNaN(height)) {
  15808. // Height may be NaN if only one value is given except height
  15809. height = containerHeight - verticalMargin - top - (bottom || 0);
  15810. }
  15811. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15812. rect.margin = margin;
  15813. return rect;
  15814. }
  15815. /**
  15816. * Position a zr element in viewport
  15817. * Group position is specified by either
  15818. * {left, top}, {right, bottom}
  15819. * If all properties exists, right and bottom will be igonred.
  15820. *
  15821. * Logic:
  15822. * 1. Scale (against origin point in parent coord)
  15823. * 2. Rotate (against origin point in parent coord)
  15824. * 3. Traslate (with el.position by this method)
  15825. * So this method only fixes the last step 'Traslate', which does not affect
  15826. * scaling and rotating.
  15827. *
  15828. * If be called repeatly with the same input el, the same result will be gotten.
  15829. *
  15830. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15831. * @param {Object} positionInfo
  15832. * @param {number|string} [positionInfo.left]
  15833. * @param {number|string} [positionInfo.top]
  15834. * @param {number|string} [positionInfo.right]
  15835. * @param {number|string} [positionInfo.bottom]
  15836. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15837. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15838. * @param {Object} containerRect
  15839. * @param {string|number} margin
  15840. * @param {Object} [opt]
  15841. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15842. * @param {Array.<number>} [opt.boundingMode='all']
  15843. * Specify how to calculate boundingRect when locating.
  15844. * 'all': Position the boundingRect that is transformed and uioned
  15845. * both itself and its descendants.
  15846. * This mode simplies confine the elements in the bounding
  15847. * of their container (e.g., using 'right: 0').
  15848. * 'raw': Position the boundingRect that is not transformed and only itself.
  15849. * This mode is useful when you want a element can overflow its
  15850. * container. (Consider a rotated circle needs to be located in a corner.)
  15851. * In this mode positionInfo.width/height can only be number.
  15852. */
  15853. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15854. var h = !opt || !opt.hv || opt.hv[0];
  15855. var v = !opt || !opt.hv || opt.hv[1];
  15856. var boundingMode = opt && opt.boundingMode || 'all';
  15857. if (!h && !v) {
  15858. return;
  15859. }
  15860. var rect;
  15861. if (boundingMode === 'raw') {
  15862. rect = el.type === 'group'
  15863. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15864. : el.getBoundingRect();
  15865. }
  15866. else {
  15867. rect = el.getBoundingRect();
  15868. if (el.needLocalTransform()) {
  15869. var transform = el.getLocalTransform();
  15870. // Notice: raw rect may be inner object of el,
  15871. // which should not be modified.
  15872. rect = rect.clone();
  15873. rect.applyTransform(transform);
  15874. }
  15875. }
  15876. // The real width and height can not be specified but calculated by the given el.
  15877. positionInfo = getLayoutRect(
  15878. defaults(
  15879. {width: rect.width, height: rect.height},
  15880. positionInfo
  15881. ),
  15882. containerRect,
  15883. margin
  15884. );
  15885. // Because 'tranlate' is the last step in transform
  15886. // (see zrender/core/Transformable#getLocalTransform),
  15887. // we can just only modify el.position to get final result.
  15888. var elPos = el.position;
  15889. var dx = h ? positionInfo.x - rect.x : 0;
  15890. var dy = v ? positionInfo.y - rect.y : 0;
  15891. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15892. }
  15893. /**
  15894. * @param {Object} option Contains some of the properties in HV_NAMES.
  15895. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15896. */
  15897. function sizeCalculable(option, hvIdx) {
  15898. return option[HV_NAMES[hvIdx][0]] != null
  15899. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  15900. }
  15901. /**
  15902. * Consider Case:
  15903. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15904. * through setOption or media query, using normal zrUtil.merge will cause
  15905. * {right: 0} does not take effect.
  15906. *
  15907. * @example
  15908. * ComponentModel.extend({
  15909. * init: function () {
  15910. * ...
  15911. * var inputPositionParams = layout.getLayoutParams(option);
  15912. * this.mergeOption(inputPositionParams);
  15913. * },
  15914. * mergeOption: function (newOption) {
  15915. * newOption && zrUtil.merge(thisOption, newOption, true);
  15916. * layout.mergeLayoutParam(thisOption, newOption);
  15917. * }
  15918. * });
  15919. *
  15920. * @param {Object} targetOption
  15921. * @param {Object} newOption
  15922. * @param {Object|string} [opt]
  15923. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15924. * that width (or height) should not be calculated by left and right (or top and bottom).
  15925. */
  15926. function mergeLayoutParam(targetOption, newOption, opt) {
  15927. !isObject$1(opt) && (opt = {});
  15928. var ignoreSize = opt.ignoreSize;
  15929. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15930. var hResult = merge$$1(HV_NAMES[0], 0);
  15931. var vResult = merge$$1(HV_NAMES[1], 1);
  15932. copy(HV_NAMES[0], targetOption, hResult);
  15933. copy(HV_NAMES[1], targetOption, vResult);
  15934. function merge$$1(names, hvIdx) {
  15935. var newParams = {};
  15936. var newValueCount = 0;
  15937. var merged = {};
  15938. var mergedValueCount = 0;
  15939. var enoughParamNumber = 2;
  15940. each$3(names, function (name) {
  15941. merged[name] = targetOption[name];
  15942. });
  15943. each$3(names, function (name) {
  15944. // Consider case: newOption.width is null, which is
  15945. // set by user for removing width setting.
  15946. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15947. hasValue(newParams, name) && newValueCount++;
  15948. hasValue(merged, name) && mergedValueCount++;
  15949. });
  15950. if (ignoreSize[hvIdx]) {
  15951. // Only one of left/right is premitted to exist.
  15952. if (hasValue(newOption, names[1])) {
  15953. merged[names[2]] = null;
  15954. }
  15955. else if (hasValue(newOption, names[2])) {
  15956. merged[names[1]] = null;
  15957. }
  15958. return merged;
  15959. }
  15960. // Case: newOption: {width: ..., right: ...},
  15961. // or targetOption: {right: ...} and newOption: {width: ...},
  15962. // There is no conflict when merged only has params count
  15963. // little than enoughParamNumber.
  15964. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15965. return merged;
  15966. }
  15967. // Case: newOption: {width: ..., right: ...},
  15968. // Than we can make sure user only want those two, and ignore
  15969. // all origin params in targetOption.
  15970. else if (newValueCount >= enoughParamNumber) {
  15971. return newParams;
  15972. }
  15973. else {
  15974. // Chose another param from targetOption by priority.
  15975. for (var i = 0; i < names.length; i++) {
  15976. var name = names[i];
  15977. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  15978. newParams[name] = targetOption[name];
  15979. break;
  15980. }
  15981. }
  15982. return newParams;
  15983. }
  15984. }
  15985. function hasProp(obj, name) {
  15986. return obj.hasOwnProperty(name);
  15987. }
  15988. function hasValue(obj, name) {
  15989. return obj[name] != null && obj[name] !== 'auto';
  15990. }
  15991. function copy(names, target, source) {
  15992. each$3(names, function (name) {
  15993. target[name] = source[name];
  15994. });
  15995. }
  15996. }
  15997. /**
  15998. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15999. * @param {Object} source
  16000. * @return {Object} Result contains those props.
  16001. */
  16002. function getLayoutParams(source) {
  16003. return copyLayoutParams({}, source);
  16004. }
  16005. /**
  16006. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16007. * @param {Object} source
  16008. * @return {Object} Result contains those props.
  16009. */
  16010. function copyLayoutParams(target, source) {
  16011. source && target && each$3(LOCATION_PARAMS, function (name) {
  16012. source.hasOwnProperty(name) && (target[name] = source[name]);
  16013. });
  16014. return target;
  16015. }
  16016. var boxLayoutMixin = {
  16017. getBoxLayoutParams: function () {
  16018. return {
  16019. left: this.get('left'),
  16020. top: this.get('top'),
  16021. right: this.get('right'),
  16022. bottom: this.get('bottom'),
  16023. width: this.get('width'),
  16024. height: this.get('height')
  16025. };
  16026. }
  16027. };
  16028. /**
  16029. * Component model
  16030. *
  16031. * @module echarts/model/Component
  16032. */
  16033. var inner$1 = makeInner();
  16034. /**
  16035. * @alias module:echarts/model/Component
  16036. * @constructor
  16037. * @param {Object} option
  16038. * @param {module:echarts/model/Model} parentModel
  16039. * @param {module:echarts/model/Model} ecModel
  16040. */
  16041. var ComponentModel = Model.extend({
  16042. type: 'component',
  16043. /**
  16044. * @readOnly
  16045. * @type {string}
  16046. */
  16047. id: '',
  16048. /**
  16049. * Because simplified concept is probably better, series.name (or component.name)
  16050. * has been having too many resposibilities:
  16051. * (1) Generating id (which requires name in option should not be modified).
  16052. * (2) As an index to mapping series when merging option or calling API (a name
  16053. * can refer to more then one components, which is convinient is some case).
  16054. * (3) Display.
  16055. * @readOnly
  16056. */
  16057. name: '',
  16058. /**
  16059. * @readOnly
  16060. * @type {string}
  16061. */
  16062. mainType: '',
  16063. /**
  16064. * @readOnly
  16065. * @type {string}
  16066. */
  16067. subType: '',
  16068. /**
  16069. * @readOnly
  16070. * @type {number}
  16071. */
  16072. componentIndex: 0,
  16073. /**
  16074. * @type {Object}
  16075. * @protected
  16076. */
  16077. defaultOption: null,
  16078. /**
  16079. * @type {module:echarts/model/Global}
  16080. * @readOnly
  16081. */
  16082. ecModel: null,
  16083. /**
  16084. * key: componentType
  16085. * value: Component model list, can not be null.
  16086. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16087. * @readOnly
  16088. */
  16089. dependentModels: [],
  16090. /**
  16091. * @type {string}
  16092. * @readOnly
  16093. */
  16094. uid: null,
  16095. /**
  16096. * Support merge layout params.
  16097. * Only support 'box' now (left/right/top/bottom/width/height).
  16098. * @type {string|Object} Object can be {ignoreSize: true}
  16099. * @readOnly
  16100. */
  16101. layoutMode: null,
  16102. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16103. Model.call(this, option, parentModel, ecModel, extraOpt);
  16104. this.uid = getUID('ec_cpt_model');
  16105. },
  16106. init: function (option, parentModel, ecModel, extraOpt) {
  16107. this.mergeDefaultAndTheme(option, ecModel);
  16108. },
  16109. mergeDefaultAndTheme: function (option, ecModel) {
  16110. var layoutMode = this.layoutMode;
  16111. var inputPositionParams = layoutMode
  16112. ? getLayoutParams(option) : {};
  16113. var themeModel = ecModel.getTheme();
  16114. merge(option, themeModel.get(this.mainType));
  16115. merge(option, this.getDefaultOption());
  16116. if (layoutMode) {
  16117. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16118. }
  16119. },
  16120. mergeOption: function (option, extraOpt) {
  16121. merge(this.option, option, true);
  16122. var layoutMode = this.layoutMode;
  16123. if (layoutMode) {
  16124. mergeLayoutParam(this.option, option, layoutMode);
  16125. }
  16126. },
  16127. // Hooker after init or mergeOption
  16128. optionUpdated: function (newCptOption, isInit) {},
  16129. getDefaultOption: function () {
  16130. var fields = inner$1(this);
  16131. if (!fields.defaultOption) {
  16132. var optList = [];
  16133. var Class = this.constructor;
  16134. while (Class) {
  16135. var opt = Class.prototype.defaultOption;
  16136. opt && optList.push(opt);
  16137. Class = Class.superClass;
  16138. }
  16139. var defaultOption = {};
  16140. for (var i = optList.length - 1; i >= 0; i--) {
  16141. defaultOption = merge(defaultOption, optList[i], true);
  16142. }
  16143. fields.defaultOption = defaultOption;
  16144. }
  16145. return fields.defaultOption;
  16146. },
  16147. getReferringComponents: function (mainType) {
  16148. return this.ecModel.queryComponents({
  16149. mainType: mainType,
  16150. index: this.get(mainType + 'Index', true),
  16151. id: this.get(mainType + 'Id', true)
  16152. });
  16153. }
  16154. });
  16155. // Reset ComponentModel.extend, add preConstruct.
  16156. // clazzUtil.enableClassExtend(
  16157. // ComponentModel,
  16158. // function (option, parentModel, ecModel, extraOpt) {
  16159. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16160. // zrUtil.extend(this, extraOpt);
  16161. // this.uid = componentUtil.getUID('componentModel');
  16162. // // this.setReadOnly([
  16163. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16164. // // 'dependentModels', 'componentIndex'
  16165. // // ]);
  16166. // }
  16167. // );
  16168. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16169. enableClassManagement(
  16170. ComponentModel, {registerWhenExtend: true}
  16171. );
  16172. enableSubTypeDefaulter(ComponentModel);
  16173. // Add capability of ComponentModel.topologicalTravel.
  16174. enableTopologicalTravel(ComponentModel, getDependencies);
  16175. function getDependencies(componentType) {
  16176. var deps = [];
  16177. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16178. deps = deps.concat(Clazz.prototype.dependencies || []);
  16179. });
  16180. // Ensure main type.
  16181. deps = map(deps, function (type) {
  16182. return parseClassType$1(type).main;
  16183. });
  16184. // Hack dataset for convenience.
  16185. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16186. deps.unshift('dataset');
  16187. }
  16188. return deps;
  16189. }
  16190. mixin(ComponentModel, boxLayoutMixin);
  16191. var platform = '';
  16192. // Navigator not exists in node
  16193. if (typeof navigator !== 'undefined') {
  16194. platform = navigator.platform || '';
  16195. }
  16196. var globalDefault = {
  16197. // 全图默认背景
  16198. // backgroundColor: 'rgba(0,0,0,0)',
  16199. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16200. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16201. // 浅色
  16202. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16203. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16204. // 深色
  16205. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16206. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16207. // 默认需要 Grid 配置项
  16208. // grid: {},
  16209. // 主题,主题
  16210. textStyle: {
  16211. // color: '#000',
  16212. // decoration: 'none',
  16213. // PENDING
  16214. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16215. // fontFamily: 'Arial, Verdana, sans-serif',
  16216. fontSize: 12,
  16217. fontStyle: 'normal',
  16218. fontWeight: 'normal'
  16219. },
  16220. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16221. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16222. // Default is source-over
  16223. blendMode: null,
  16224. animation: 'auto',
  16225. animationDuration: 1000,
  16226. animationDurationUpdate: 300,
  16227. animationEasing: 'exponentialOut',
  16228. animationEasingUpdate: 'cubicOut',
  16229. animationThreshold: 2000,
  16230. // Configuration for progressive/incremental rendering
  16231. progressiveThreshold: 3000,
  16232. progressive: 400,
  16233. // Threshold of if use single hover layer to optimize.
  16234. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16235. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16236. // which is unexpected.
  16237. // see example <echarts/test/heatmap-large.html>.
  16238. hoverLayerThreshold: 3000,
  16239. // See: module:echarts/scale/Time
  16240. useUTC: false
  16241. };
  16242. var inner$2 = makeInner();
  16243. function getNearestColorPalette(colors, requestColorNum) {
  16244. var paletteNum = colors.length;
  16245. // TODO colors must be in order
  16246. for (var i = 0; i < paletteNum; i++) {
  16247. if (colors[i].length > requestColorNum) {
  16248. return colors[i];
  16249. }
  16250. }
  16251. return colors[paletteNum - 1];
  16252. }
  16253. var colorPaletteMixin = {
  16254. clearColorPalette: function () {
  16255. inner$2(this).colorIdx = 0;
  16256. inner$2(this).colorNameMap = {};
  16257. },
  16258. getColorFromPalette: function (name, scope, requestColorNum) {
  16259. scope = scope || this;
  16260. var scopeFields = inner$2(scope);
  16261. var colorIdx = scopeFields.colorIdx || 0;
  16262. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16263. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16264. if (colorNameMap.hasOwnProperty(name)) {
  16265. return colorNameMap[name];
  16266. }
  16267. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16268. var layeredColorPalette = this.get('colorLayer', true);
  16269. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16270. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16271. // In case can't find in layered color palette.
  16272. colorPalette = colorPalette || defaultColorPalette;
  16273. if (!colorPalette || !colorPalette.length) {
  16274. return;
  16275. }
  16276. var color = colorPalette[colorIdx];
  16277. if (name) {
  16278. colorNameMap[name] = color;
  16279. }
  16280. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16281. return color;
  16282. }
  16283. };
  16284. /**
  16285. * Helper for model references.
  16286. * There are many manners to refer axis/coordSys.
  16287. */
  16288. // TODO
  16289. // merge relevant logic to this file?
  16290. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16291. /**
  16292. * @return {Object} For example:
  16293. * {
  16294. * coordSysName: 'cartesian2d',
  16295. * coordSysDims: ['x', 'y', ...],
  16296. * axisMap: HashMap({
  16297. * x: xAxisModel,
  16298. * y: yAxisModel
  16299. * }),
  16300. * categoryAxisMap: HashMap({
  16301. * x: xAxisModel,
  16302. * y: undefined
  16303. * }),
  16304. * // It also indicate that whether there is category axis.
  16305. * firstCategoryDimIndex: 1,
  16306. * // To replace user specified encode.
  16307. * }
  16308. */
  16309. function getCoordSysDefineBySeries(seriesModel) {
  16310. var coordSysName = seriesModel.get('coordinateSystem');
  16311. var result = {
  16312. coordSysName: coordSysName,
  16313. coordSysDims: [],
  16314. axisMap: createHashMap(),
  16315. categoryAxisMap: createHashMap()
  16316. };
  16317. var fetch = fetchers[coordSysName];
  16318. if (fetch) {
  16319. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16320. return result;
  16321. }
  16322. }
  16323. var fetchers = {
  16324. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16325. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16326. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16327. if (__DEV__) {
  16328. if (!xAxisModel) {
  16329. throw new Error('xAxis "' + retrieve(
  16330. seriesModel.get('xAxisIndex'),
  16331. seriesModel.get('xAxisId'),
  16332. 0
  16333. ) + '" not found');
  16334. }
  16335. if (!yAxisModel) {
  16336. throw new Error('yAxis "' + retrieve(
  16337. seriesModel.get('xAxisIndex'),
  16338. seriesModel.get('yAxisId'),
  16339. 0
  16340. ) + '" not found');
  16341. }
  16342. }
  16343. result.coordSysDims = ['x', 'y'];
  16344. axisMap.set('x', xAxisModel);
  16345. axisMap.set('y', yAxisModel);
  16346. if (isCategory(xAxisModel)) {
  16347. categoryAxisMap.set('x', xAxisModel);
  16348. result.firstCategoryDimIndex = 0;
  16349. }
  16350. if (isCategory(yAxisModel)) {
  16351. categoryAxisMap.set('y', yAxisModel);
  16352. result.firstCategoryDimIndex = 1;
  16353. }
  16354. },
  16355. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16356. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16357. if (__DEV__) {
  16358. if (!singleAxisModel) {
  16359. throw new Error('singleAxis should be specified.');
  16360. }
  16361. }
  16362. result.coordSysDims = ['single'];
  16363. axisMap.set('single', singleAxisModel);
  16364. if (isCategory(singleAxisModel)) {
  16365. categoryAxisMap.set('single', singleAxisModel);
  16366. result.firstCategoryDimIndex = 0;
  16367. }
  16368. },
  16369. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16370. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16371. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16372. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16373. if (__DEV__) {
  16374. if (!angleAxisModel) {
  16375. throw new Error('angleAxis option not found');
  16376. }
  16377. if (!radiusAxisModel) {
  16378. throw new Error('radiusAxis option not found');
  16379. }
  16380. }
  16381. result.coordSysDims = ['radius', 'angle'];
  16382. axisMap.set('radius', radiusAxisModel);
  16383. axisMap.set('angle', angleAxisModel);
  16384. if (isCategory(radiusAxisModel)) {
  16385. categoryAxisMap.set('radius', radiusAxisModel);
  16386. result.firstCategoryDimIndex = 0;
  16387. }
  16388. if (isCategory(angleAxisModel)) {
  16389. categoryAxisMap.set('angle', angleAxisModel);
  16390. result.firstCategoryDimIndex = 1;
  16391. }
  16392. },
  16393. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16394. result.coordSysDims = ['lng', 'lat'];
  16395. },
  16396. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16397. var ecModel = seriesModel.ecModel;
  16398. var parallelModel = ecModel.getComponent(
  16399. 'parallel', seriesModel.get('parallelIndex')
  16400. );
  16401. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16402. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16403. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16404. var axisDim = coordSysDims[index];
  16405. axisMap.set(axisDim, axisModel);
  16406. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16407. categoryAxisMap.set(axisDim, axisModel);
  16408. result.firstCategoryDimIndex = index;
  16409. }
  16410. });
  16411. }
  16412. };
  16413. function isCategory(axisModel) {
  16414. return axisModel.get('type') === 'category';
  16415. }
  16416. // Avoid typo.
  16417. var SOURCE_FORMAT_ORIGINAL = 'original';
  16418. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16419. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16420. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16421. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16422. // ??? CHANGE A NAME
  16423. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16424. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16425. var SERIES_LAYOUT_BY_ROW = 'row';
  16426. /**
  16427. * [sourceFormat]
  16428. *
  16429. * + "original":
  16430. * This format is only used in series.data, where
  16431. * itemStyle can be specified in data item.
  16432. *
  16433. * + "arrayRows":
  16434. * [
  16435. * ['product', 'score', 'amount'],
  16436. * ['Matcha Latte', 89.3, 95.8],
  16437. * ['Milk Tea', 92.1, 89.4],
  16438. * ['Cheese Cocoa', 94.4, 91.2],
  16439. * ['Walnut Brownie', 85.4, 76.9]
  16440. * ]
  16441. *
  16442. * + "objectRows":
  16443. * [
  16444. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16445. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16446. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16447. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16448. * ]
  16449. *
  16450. * + "keyedColumns":
  16451. * {
  16452. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16453. * 'count': [823, 235, 1042, 988],
  16454. * 'score': [95.8, 81.4, 91.2, 76.9]
  16455. * }
  16456. *
  16457. * + "typedArray"
  16458. *
  16459. * + "unknown"
  16460. */
  16461. /**
  16462. * @constructor
  16463. * @param {Object} fields
  16464. * @param {string} fields.sourceFormat
  16465. * @param {Array|Object} fields.fromDataset
  16466. * @param {Array|Object} [fields.data]
  16467. * @param {string} [seriesLayoutBy='column']
  16468. * @param {Array.<Object|string>} [dimensionsDefine]
  16469. * @param {Objet|HashMap} [encodeDefine]
  16470. * @param {number} [startIndex=0]
  16471. * @param {number} [dimensionsDetectCount]
  16472. */
  16473. function Source(fields) {
  16474. /**
  16475. * @type {boolean}
  16476. */
  16477. this.fromDataset = fields.fromDataset;
  16478. /**
  16479. * Not null/undefined.
  16480. * @type {Array|Object}
  16481. */
  16482. this.data = fields.data || (
  16483. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16484. );
  16485. /**
  16486. * See also "detectSourceFormat".
  16487. * Not null/undefined.
  16488. * @type {string}
  16489. */
  16490. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16491. /**
  16492. * 'row' or 'column'
  16493. * Not null/undefined.
  16494. * @type {string} seriesLayoutBy
  16495. */
  16496. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16497. /**
  16498. * dimensions definition in option.
  16499. * can be null/undefined.
  16500. * @type {Array.<Object|string>}
  16501. */
  16502. this.dimensionsDefine = fields.dimensionsDefine;
  16503. /**
  16504. * encode definition in option.
  16505. * can be null/undefined.
  16506. * @type {Objet|HashMap}
  16507. */
  16508. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16509. /**
  16510. * Not null/undefined, uint.
  16511. * @type {number}
  16512. */
  16513. this.startIndex = fields.startIndex || 0;
  16514. /**
  16515. * Can be null/undefined (when unknown), uint.
  16516. * @type {number}
  16517. */
  16518. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16519. }
  16520. /**
  16521. * Wrap original series data for some compatibility cases.
  16522. */
  16523. Source.seriesDataToSource = function (data) {
  16524. return new Source({
  16525. data: data,
  16526. sourceFormat: isTypedArray(data)
  16527. ? SOURCE_FORMAT_TYPED_ARRAY
  16528. : SOURCE_FORMAT_ORIGINAL,
  16529. fromDataset: false
  16530. });
  16531. };
  16532. enableClassCheck(Source);
  16533. var inner$3 = makeInner();
  16534. /**
  16535. * @see {module:echarts/data/Source}
  16536. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  16537. * @return {string} sourceFormat
  16538. */
  16539. function detectSourceFormat(datasetModel) {
  16540. var data = datasetModel.option.source;
  16541. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  16542. if (isTypedArray(data)) {
  16543. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  16544. }
  16545. else if (isArray(data)) {
  16546. // FIXME Whether tolerate null in top level array?
  16547. for (var i = 0, len = data.length; i < len; i++) {
  16548. var item = data[i];
  16549. if (item == null) {
  16550. continue;
  16551. }
  16552. else if (isArray(item)) {
  16553. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  16554. break;
  16555. }
  16556. else if (isObject$1(item)) {
  16557. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  16558. break;
  16559. }
  16560. }
  16561. }
  16562. else if (isObject$1(data)) {
  16563. for (var key in data) {
  16564. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  16565. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  16566. break;
  16567. }
  16568. }
  16569. }
  16570. else if (data != null) {
  16571. throw new Error('Invalid data');
  16572. }
  16573. inner$3(datasetModel).sourceFormat = sourceFormat;
  16574. }
  16575. /**
  16576. * [Scenarios]:
  16577. * (1) Provide source data directly:
  16578. * series: {
  16579. * encode: {...},
  16580. * dimensions: [...]
  16581. * seriesLayoutBy: 'row',
  16582. * data: [[...]]
  16583. * }
  16584. * (2) Refer to datasetModel.
  16585. * series: [{
  16586. * encode: {...}
  16587. * // Ignore datasetIndex means `datasetIndex: 0`
  16588. * // and the dimensions defination in dataset is used
  16589. * }, {
  16590. * encode: {...},
  16591. * seriesLayoutBy: 'column',
  16592. * datasetIndex: 1
  16593. * }]
  16594. *
  16595. * Get data from series itself or datset.
  16596. * @return {module:echarts/data/Source} source
  16597. */
  16598. function getSource(seriesModel) {
  16599. return inner$3(seriesModel).source;
  16600. }
  16601. /**
  16602. * MUST be called before mergeOption of all series.
  16603. * @param {module:echarts/model/Global} ecModel
  16604. */
  16605. function resetSourceDefaulter(ecModel) {
  16606. // `datasetMap` is used to make default encode.
  16607. inner$3(ecModel).datasetMap = createHashMap();
  16608. }
  16609. /**
  16610. * [Caution]:
  16611. * MUST be called after series option merged and
  16612. * before "series.getInitailData()" called.
  16613. *
  16614. * [The rule of making default encode]:
  16615. * Category axis (if exists) alway map to the first dimension.
  16616. * Each other axis occupies a subsequent dimension.
  16617. *
  16618. * [Why make default encode]:
  16619. * Simplify the typing of encode in option, avoiding the case like that:
  16620. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16621. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16622. *
  16623. * @param {module:echarts/model/Series} seriesModel
  16624. */
  16625. function prepareSource(seriesModel) {
  16626. var seriesOption = seriesModel.option;
  16627. var data = seriesOption.data;
  16628. var sourceFormat = isTypedArray(data)
  16629. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16630. var fromDataset = false;
  16631. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16632. var sourceHeader = seriesOption.sourceHeader;
  16633. var dimensionsDefine = seriesOption.dimensions;
  16634. var datasetModel = getDatasetModel(seriesModel);
  16635. if (datasetModel) {
  16636. var datasetOption = datasetModel.option;
  16637. data = datasetOption.source;
  16638. sourceFormat = inner$3(datasetModel).sourceFormat;
  16639. fromDataset = true;
  16640. // These settings from series has higher priority.
  16641. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16642. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16643. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16644. }
  16645. var completeResult = completeBySourceData(
  16646. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16647. );
  16648. // Note: dataset option does not have `encode`.
  16649. var encodeDefine = seriesOption.encode;
  16650. if (!encodeDefine && datasetModel) {
  16651. encodeDefine = makeDefaultEncode(
  16652. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16653. );
  16654. }
  16655. inner$3(seriesModel).source = new Source({
  16656. data: data,
  16657. fromDataset: fromDataset,
  16658. seriesLayoutBy: seriesLayoutBy,
  16659. sourceFormat: sourceFormat,
  16660. dimensionsDefine: completeResult.dimensionsDefine,
  16661. startIndex: completeResult.startIndex,
  16662. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16663. encodeDefine: encodeDefine
  16664. });
  16665. }
  16666. // return {startIndex, dimensionsDefine, dimensionsCount}
  16667. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16668. if (!data) {
  16669. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16670. }
  16671. var dimensionsDetectCount;
  16672. var startIndex;
  16673. var findPotentialName;
  16674. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16675. // Rule: Most of the first line are string: it is header.
  16676. // Caution: consider a line with 5 string and 1 number,
  16677. // it still can not be sure it is a head, because the
  16678. // 5 string may be 5 values of category columns.
  16679. if (sourceHeader === 'auto' || sourceHeader == null) {
  16680. arrayRowsTravelFirst(function (val) {
  16681. // '-' is regarded as null/undefined.
  16682. if (val != null && val !== '-') {
  16683. if (isString(val)) {
  16684. startIndex == null && (startIndex = 1);
  16685. }
  16686. else {
  16687. startIndex = 0;
  16688. }
  16689. }
  16690. // 10 is an experience number, avoid long loop.
  16691. }, seriesLayoutBy, data, 10);
  16692. }
  16693. else {
  16694. startIndex = sourceHeader ? 1 : 0;
  16695. }
  16696. if (!dimensionsDefine && startIndex === 1) {
  16697. dimensionsDefine = [];
  16698. arrayRowsTravelFirst(function (val, index) {
  16699. dimensionsDefine[index] = val != null ? val : '';
  16700. }, seriesLayoutBy, data);
  16701. }
  16702. dimensionsDetectCount = dimensionsDefine
  16703. ? dimensionsDefine.length
  16704. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16705. ? data.length
  16706. : data[0]
  16707. ? data[0].length
  16708. : null;
  16709. }
  16710. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16711. if (!dimensionsDefine) {
  16712. dimensionsDefine = objectRowsCollectDimensions(data);
  16713. findPotentialName = true;
  16714. }
  16715. }
  16716. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16717. if (!dimensionsDefine) {
  16718. dimensionsDefine = [];
  16719. findPotentialName = true;
  16720. each$1(data, function (colArr, key) {
  16721. dimensionsDefine.push(key);
  16722. });
  16723. }
  16724. }
  16725. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16726. var value0 = getDataItemValue(data[0]);
  16727. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16728. }
  16729. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16730. if (__DEV__) {
  16731. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16732. }
  16733. }
  16734. var potentialNameDimIndex;
  16735. if (findPotentialName) {
  16736. each$1(dimensionsDefine, function (dim, idx) {
  16737. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16738. potentialNameDimIndex = idx;
  16739. }
  16740. });
  16741. }
  16742. return {
  16743. startIndex: startIndex,
  16744. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16745. dimensionsDetectCount: dimensionsDetectCount,
  16746. potentialNameDimIndex: potentialNameDimIndex
  16747. // TODO: potentialIdDimIdx
  16748. };
  16749. }
  16750. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16751. // which is reasonable. But dimension name is duplicated.
  16752. // Returns undefined or an array contains only object without null/undefiend or string.
  16753. function normalizeDimensionsDefine(dimensionsDefine) {
  16754. if (!dimensionsDefine) {
  16755. // The meaning of null/undefined is different from empty array.
  16756. return;
  16757. }
  16758. var nameMap = createHashMap();
  16759. return map(dimensionsDefine, function (item, index) {
  16760. item = extend({}, isObject$1(item) ? item : {name: item});
  16761. // User can set null in dimensions.
  16762. // We dont auto specify name, othewise a given name may
  16763. // cause it be refered unexpectedly.
  16764. if (item.name == null) {
  16765. return item;
  16766. }
  16767. // Also consider number form like 2012.
  16768. item.name += '';
  16769. // User may also specify displayName.
  16770. // displayName will always exists except user not
  16771. // specified or dim name is not specified or detected.
  16772. // (A auto generated dim name will not be used as
  16773. // displayName).
  16774. if (item.displayName == null) {
  16775. item.displayName = item.name;
  16776. }
  16777. var exist = nameMap.get(item.name);
  16778. if (!exist) {
  16779. nameMap.set(item.name, {count: 1});
  16780. }
  16781. else {
  16782. item.name += '-' + exist.count++;
  16783. }
  16784. return item;
  16785. });
  16786. }
  16787. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16788. maxLoop == null && (maxLoop = Infinity);
  16789. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16790. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16791. cb(data[i] ? data[i][0] : null, i);
  16792. }
  16793. }
  16794. else {
  16795. var value0 = data[0] || [];
  16796. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16797. cb(value0[i], i);
  16798. }
  16799. }
  16800. }
  16801. function objectRowsCollectDimensions(data) {
  16802. var firstIndex = 0;
  16803. var obj;
  16804. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16805. if (obj) {
  16806. var dimensions = [];
  16807. each$1(obj, function (value, key) {
  16808. dimensions.push(key);
  16809. });
  16810. return dimensions;
  16811. }
  16812. }
  16813. // ??? TODO merge to completedimensions, where also has
  16814. // default encode making logic. And the default rule
  16815. // should depends on series? consider 'map'.
  16816. function makeDefaultEncode(
  16817. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16818. ) {
  16819. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16820. var encode = {};
  16821. // var encodeTooltip = [];
  16822. // var encodeLabel = [];
  16823. var encodeItemName = [];
  16824. var encodeSeriesName = [];
  16825. var seriesType = seriesModel.subType;
  16826. // ??? TODO refactor: provide by series itself.
  16827. // Consider the case: 'map' series is based on geo coordSys,
  16828. // 'graph', 'heatmap' can be based on cartesian. But can not
  16829. // give default rule simply here.
  16830. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16831. var cSeriesMap = createHashMap([
  16832. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16833. ]);
  16834. // Usually in this case series will use the first data
  16835. // dimension as the "value" dimension, or other default
  16836. // processes respectively.
  16837. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16838. var ecModel = seriesModel.ecModel;
  16839. var datasetMap = inner$3(ecModel).datasetMap;
  16840. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16841. var datasetRecord = datasetMap.get(key)
  16842. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16843. // TODO
  16844. // Auto detect first time axis and do arrangement.
  16845. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16846. // In value way.
  16847. if (coordSysDefine.firstCategoryDimIndex == null) {
  16848. var dataDim = datasetRecord.valueWayDim++;
  16849. encode[coordDim] = dataDim;
  16850. // ??? TODO give a better default series name rule?
  16851. // especially when encode x y specified.
  16852. // consider: when mutiple series share one dimension
  16853. // category axis, series name should better use
  16854. // the other dimsion name. On the other hand, use
  16855. // both dimensions name.
  16856. encodeSeriesName.push(dataDim);
  16857. // encodeTooltip.push(dataDim);
  16858. // encodeLabel.push(dataDim);
  16859. }
  16860. // In category way, category axis.
  16861. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16862. encode[coordDim] = 0;
  16863. encodeItemName.push(0);
  16864. }
  16865. // In category way, non-category axis.
  16866. else {
  16867. var dataDim = datasetRecord.categoryWayDim++;
  16868. encode[coordDim] = dataDim;
  16869. // encodeTooltip.push(dataDim);
  16870. // encodeLabel.push(dataDim);
  16871. encodeSeriesName.push(dataDim);
  16872. }
  16873. });
  16874. }
  16875. // Do not make a complex rule! Hard to code maintain and not necessary.
  16876. // ??? TODO refactor: provide by series itself.
  16877. // [{name: ..., value: ...}, ...] like:
  16878. else if (nSeriesMap.get(seriesType) != null) {
  16879. // Find the first not ordinal. (5 is an experience value)
  16880. var firstNotOrdinal;
  16881. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16882. if (!doGuessOrdinal(
  16883. data, sourceFormat, seriesLayoutBy,
  16884. completeResult.dimensionsDefine, completeResult.startIndex, i
  16885. )) {
  16886. firstNotOrdinal = i;
  16887. }
  16888. }
  16889. if (firstNotOrdinal != null) {
  16890. encode.value = firstNotOrdinal;
  16891. var nameDimIndex = completeResult.potentialNameDimIndex
  16892. || Math.max(firstNotOrdinal - 1, 0);
  16893. // By default, label use itemName in charts.
  16894. // So we dont set encodeLabel here.
  16895. encodeSeriesName.push(nameDimIndex);
  16896. encodeItemName.push(nameDimIndex);
  16897. // encodeTooltip.push(firstNotOrdinal);
  16898. }
  16899. }
  16900. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16901. // encodeLabel.length && (encode.label = encodeLabel);
  16902. encodeItemName.length && (encode.itemName = encodeItemName);
  16903. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16904. return encode;
  16905. }
  16906. /**
  16907. * If return null/undefined, indicate that should not use datasetModel.
  16908. */
  16909. function getDatasetModel(seriesModel) {
  16910. var option = seriesModel.option;
  16911. // Caution: consider the scenario:
  16912. // A dataset is declared and a series is not expected to use the dataset,
  16913. // and at the beginning `setOption({series: { noData })` (just prepare other
  16914. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16915. // the user should set an empty array to avoid that dataset is used by default.
  16916. var thisData = option.data;
  16917. if (!thisData) {
  16918. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  16919. }
  16920. }
  16921. /**
  16922. * The rule should not be complex, otherwise user might not
  16923. * be able to known where the data is wrong.
  16924. * The code is ugly, but how to make it neat?
  16925. *
  16926. * @param {module:echars/data/Source} source
  16927. * @param {number} dimIndex
  16928. * @return {boolean} Whether ordinal.
  16929. */
  16930. function guessOrdinal(source, dimIndex) {
  16931. return doGuessOrdinal(
  16932. source.data,
  16933. source.sourceFormat,
  16934. source.seriesLayoutBy,
  16935. source.dimensionsDefine,
  16936. source.startIndex,
  16937. dimIndex
  16938. );
  16939. }
  16940. // dimIndex may be overflow source data.
  16941. function doGuessOrdinal(
  16942. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  16943. ) {
  16944. var result;
  16945. // Experience value.
  16946. var maxLoop = 5;
  16947. if (isTypedArray(data)) {
  16948. return false;
  16949. }
  16950. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16951. // always exists in source.
  16952. var dimName;
  16953. if (dimensionsDefine) {
  16954. dimName = dimensionsDefine[dimIndex];
  16955. dimName = isObject$1(dimName) ? dimName.name : dimName;
  16956. }
  16957. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16958. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16959. var sample = data[dimIndex];
  16960. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16961. if ((result = detectValue(sample[startIndex + i])) != null) {
  16962. return result;
  16963. }
  16964. }
  16965. }
  16966. else {
  16967. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16968. var row = data[startIndex + i];
  16969. if (row && (result = detectValue(row[dimIndex])) != null) {
  16970. return result;
  16971. }
  16972. }
  16973. }
  16974. }
  16975. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16976. if (!dimName) {
  16977. return;
  16978. }
  16979. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16980. var item = data[i];
  16981. if (item && (result = detectValue(item[dimName])) != null) {
  16982. return result;
  16983. }
  16984. }
  16985. }
  16986. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16987. if (!dimName) {
  16988. return;
  16989. }
  16990. var sample = data[dimName];
  16991. if (!sample || isTypedArray(sample)) {
  16992. return false;
  16993. }
  16994. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16995. if ((result = detectValue(sample[i])) != null) {
  16996. return result;
  16997. }
  16998. }
  16999. }
  17000. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17001. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17002. var item = data[i];
  17003. var val = getDataItemValue(item);
  17004. if (!isArray(val)) {
  17005. return false;
  17006. }
  17007. if ((result = detectValue(val[dimIndex])) != null) {
  17008. return result;
  17009. }
  17010. }
  17011. }
  17012. function detectValue(val) {
  17013. // Consider usage convenience, '1', '2' will be treated as "number".
  17014. // `isFinit('')` get `true`.
  17015. if (val != null && isFinite(val) && val !== '') {
  17016. return false;
  17017. }
  17018. else if (isString(val) && val !== '-') {
  17019. return true;
  17020. }
  17021. }
  17022. return false;
  17023. }
  17024. /**
  17025. * ECharts global model
  17026. *
  17027. * @module {echarts/model/Global}
  17028. */
  17029. /**
  17030. * Caution: If the mechanism should be changed some day, these cases
  17031. * should be considered:
  17032. *
  17033. * (1) In `merge option` mode, if using the same option to call `setOption`
  17034. * many times, the result should be the same (try our best to ensure that).
  17035. * (2) In `merge option` mode, if a component has no id/name specified, it
  17036. * will be merged by index, and the result sequence of the components is
  17037. * consistent to the original sequence.
  17038. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17039. * `mergeOption` in module:echarts/model/OptionManager.
  17040. */
  17041. var OPTION_INNER_KEY = '\0_ec_inner';
  17042. /**
  17043. * @alias module:echarts/model/Global
  17044. *
  17045. * @param {Object} option
  17046. * @param {module:echarts/model/Model} parentModel
  17047. * @param {Object} theme
  17048. */
  17049. var GlobalModel = Model.extend({
  17050. constructor: GlobalModel,
  17051. init: function (option, parentModel, theme, optionManager) {
  17052. theme = theme || {};
  17053. this.option = null; // Mark as not initialized.
  17054. /**
  17055. * @type {module:echarts/model/Model}
  17056. * @private
  17057. */
  17058. this._theme = new Model(theme);
  17059. /**
  17060. * @type {module:echarts/model/OptionManager}
  17061. */
  17062. this._optionManager = optionManager;
  17063. },
  17064. setOption: function (option, optionPreprocessorFuncs) {
  17065. assert$1(
  17066. !(OPTION_INNER_KEY in option),
  17067. 'please use chart.getOption()'
  17068. );
  17069. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17070. this.resetOption(null);
  17071. },
  17072. /**
  17073. * @param {string} type null/undefined: reset all.
  17074. * 'recreate': force recreate all.
  17075. * 'timeline': only reset timeline option
  17076. * 'media': only reset media query option
  17077. * @return {boolean} Whether option changed.
  17078. */
  17079. resetOption: function (type) {
  17080. var optionChanged = false;
  17081. var optionManager = this._optionManager;
  17082. if (!type || type === 'recreate') {
  17083. var baseOption = optionManager.mountOption(type === 'recreate');
  17084. if (!this.option || type === 'recreate') {
  17085. initBase.call(this, baseOption);
  17086. }
  17087. else {
  17088. this.restoreData();
  17089. this.mergeOption(baseOption);
  17090. }
  17091. optionChanged = true;
  17092. }
  17093. if (type === 'timeline' || type === 'media') {
  17094. this.restoreData();
  17095. }
  17096. if (!type || type === 'recreate' || type === 'timeline') {
  17097. var timelineOption = optionManager.getTimelineOption(this);
  17098. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17099. }
  17100. if (!type || type === 'recreate' || type === 'media') {
  17101. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17102. if (mediaOptions.length) {
  17103. each$1(mediaOptions, function (mediaOption) {
  17104. this.mergeOption(mediaOption, optionChanged = true);
  17105. }, this);
  17106. }
  17107. }
  17108. return optionChanged;
  17109. },
  17110. /**
  17111. * @protected
  17112. */
  17113. mergeOption: function (newOption) {
  17114. var option = this.option;
  17115. var componentsMap = this._componentsMap;
  17116. var newCptTypes = [];
  17117. resetSourceDefaulter(this);
  17118. // If no component class, merge directly.
  17119. // For example: color, animaiton options, etc.
  17120. each$1(newOption, function (componentOption, mainType) {
  17121. if (componentOption == null) {
  17122. return;
  17123. }
  17124. if (!ComponentModel.hasClass(mainType)) {
  17125. // globalSettingTask.dirty();
  17126. option[mainType] = option[mainType] == null
  17127. ? clone(componentOption)
  17128. : merge(option[mainType], componentOption, true);
  17129. }
  17130. else if (mainType) {
  17131. newCptTypes.push(mainType);
  17132. }
  17133. });
  17134. ComponentModel.topologicalTravel(
  17135. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17136. );
  17137. function visitComponent(mainType, dependencies) {
  17138. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17139. var mapResult = mappingToExists(
  17140. componentsMap.get(mainType), newCptOptionList
  17141. );
  17142. makeIdAndName(mapResult);
  17143. // Set mainType and complete subType.
  17144. each$1(mapResult, function (item, index) {
  17145. var opt = item.option;
  17146. if (isObject$1(opt)) {
  17147. item.keyInfo.mainType = mainType;
  17148. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17149. }
  17150. });
  17151. var dependentModels = getComponentsByTypes(
  17152. componentsMap, dependencies
  17153. );
  17154. option[mainType] = [];
  17155. componentsMap.set(mainType, []);
  17156. each$1(mapResult, function (resultItem, index) {
  17157. var componentModel = resultItem.exist;
  17158. var newCptOption = resultItem.option;
  17159. assert$1(
  17160. isObject$1(newCptOption) || componentModel,
  17161. 'Empty component definition'
  17162. );
  17163. // Consider where is no new option and should be merged using {},
  17164. // see removeEdgeAndAdd in topologicalTravel and
  17165. // ComponentModel.getAllClassMainTypes.
  17166. if (!newCptOption) {
  17167. componentModel.mergeOption({}, this);
  17168. componentModel.optionUpdated({}, false);
  17169. }
  17170. else {
  17171. var ComponentModelClass = ComponentModel.getClass(
  17172. mainType, resultItem.keyInfo.subType, true
  17173. );
  17174. if (componentModel && componentModel instanceof ComponentModelClass) {
  17175. componentModel.name = resultItem.keyInfo.name;
  17176. // componentModel.settingTask && componentModel.settingTask.dirty();
  17177. componentModel.mergeOption(newCptOption, this);
  17178. componentModel.optionUpdated(newCptOption, false);
  17179. }
  17180. else {
  17181. // PENDING Global as parent ?
  17182. var extraOpt = extend(
  17183. {
  17184. dependentModels: dependentModels,
  17185. componentIndex: index
  17186. },
  17187. resultItem.keyInfo
  17188. );
  17189. componentModel = new ComponentModelClass(
  17190. newCptOption, this, this, extraOpt
  17191. );
  17192. extend(componentModel, extraOpt);
  17193. componentModel.init(newCptOption, this, this, extraOpt);
  17194. // Call optionUpdated after init.
  17195. // newCptOption has been used as componentModel.option
  17196. // and may be merged with theme and default, so pass null
  17197. // to avoid confusion.
  17198. componentModel.optionUpdated(null, true);
  17199. }
  17200. }
  17201. componentsMap.get(mainType)[index] = componentModel;
  17202. option[mainType][index] = componentModel.option;
  17203. }, this);
  17204. // Backup series for filtering.
  17205. if (mainType === 'series') {
  17206. createSeriesIndices(this, componentsMap.get('series'));
  17207. }
  17208. }
  17209. this._seriesIndicesMap = createHashMap(
  17210. this._seriesIndices = this._seriesIndices || []
  17211. );
  17212. },
  17213. /**
  17214. * Get option for output (cloned option and inner info removed)
  17215. * @public
  17216. * @return {Object}
  17217. */
  17218. getOption: function () {
  17219. var option = clone(this.option);
  17220. each$1(option, function (opts, mainType) {
  17221. if (ComponentModel.hasClass(mainType)) {
  17222. var opts = normalizeToArray(opts);
  17223. for (var i = opts.length - 1; i >= 0; i--) {
  17224. // Remove options with inner id.
  17225. if (isIdInner(opts[i])) {
  17226. opts.splice(i, 1);
  17227. }
  17228. }
  17229. option[mainType] = opts;
  17230. }
  17231. });
  17232. delete option[OPTION_INNER_KEY];
  17233. return option;
  17234. },
  17235. /**
  17236. * @return {module:echarts/model/Model}
  17237. */
  17238. getTheme: function () {
  17239. return this._theme;
  17240. },
  17241. /**
  17242. * @param {string} mainType
  17243. * @param {number} [idx=0]
  17244. * @return {module:echarts/model/Component}
  17245. */
  17246. getComponent: function (mainType, idx) {
  17247. var list = this._componentsMap.get(mainType);
  17248. if (list) {
  17249. return list[idx || 0];
  17250. }
  17251. },
  17252. /**
  17253. * If none of index and id and name used, return all components with mainType.
  17254. * @param {Object} condition
  17255. * @param {string} condition.mainType
  17256. * @param {string} [condition.subType] If ignore, only query by mainType
  17257. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17258. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17259. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17260. * @return {Array.<module:echarts/model/Component>}
  17261. */
  17262. queryComponents: function (condition) {
  17263. var mainType = condition.mainType;
  17264. if (!mainType) {
  17265. return [];
  17266. }
  17267. var index = condition.index;
  17268. var id = condition.id;
  17269. var name = condition.name;
  17270. var cpts = this._componentsMap.get(mainType);
  17271. if (!cpts || !cpts.length) {
  17272. return [];
  17273. }
  17274. var result;
  17275. if (index != null) {
  17276. if (!isArray(index)) {
  17277. index = [index];
  17278. }
  17279. result = filter(map(index, function (idx) {
  17280. return cpts[idx];
  17281. }), function (val) {
  17282. return !!val;
  17283. });
  17284. }
  17285. else if (id != null) {
  17286. var isIdArray = isArray(id);
  17287. result = filter(cpts, function (cpt) {
  17288. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17289. || (!isIdArray && cpt.id === id);
  17290. });
  17291. }
  17292. else if (name != null) {
  17293. var isNameArray = isArray(name);
  17294. result = filter(cpts, function (cpt) {
  17295. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17296. || (!isNameArray && cpt.name === name);
  17297. });
  17298. }
  17299. else {
  17300. // Return all components with mainType
  17301. result = cpts.slice();
  17302. }
  17303. return filterBySubType(result, condition);
  17304. },
  17305. /**
  17306. * The interface is different from queryComponents,
  17307. * which is convenient for inner usage.
  17308. *
  17309. * @usage
  17310. * var result = findComponents(
  17311. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17312. * );
  17313. * var result = findComponents(
  17314. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17315. * );
  17316. * var result = findComponents(
  17317. * {mainType: 'series'},
  17318. * function (model, index) {...}
  17319. * );
  17320. * // result like [component0, componnet1, ...]
  17321. *
  17322. * @param {Object} condition
  17323. * @param {string} condition.mainType Mandatory.
  17324. * @param {string} [condition.subType] Optional.
  17325. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17326. * where xxx is mainType.
  17327. * If query attribute is null/undefined or has no index/id/name,
  17328. * do not filtering by query conditions, which is convenient for
  17329. * no-payload situations or when target of action is global.
  17330. * @param {Function} [condition.filter] parameter: component, return boolean.
  17331. * @return {Array.<module:echarts/model/Component>}
  17332. */
  17333. findComponents: function (condition) {
  17334. var query = condition.query;
  17335. var mainType = condition.mainType;
  17336. var queryCond = getQueryCond(query);
  17337. var result = queryCond
  17338. ? this.queryComponents(queryCond)
  17339. : this._componentsMap.get(mainType);
  17340. return doFilter(filterBySubType(result, condition));
  17341. function getQueryCond(q) {
  17342. var indexAttr = mainType + 'Index';
  17343. var idAttr = mainType + 'Id';
  17344. var nameAttr = mainType + 'Name';
  17345. return q && (
  17346. q[indexAttr] != null
  17347. || q[idAttr] != null
  17348. || q[nameAttr] != null
  17349. )
  17350. ? {
  17351. mainType: mainType,
  17352. // subType will be filtered finally.
  17353. index: q[indexAttr],
  17354. id: q[idAttr],
  17355. name: q[nameAttr]
  17356. }
  17357. : null;
  17358. }
  17359. function doFilter(res) {
  17360. return condition.filter
  17361. ? filter(res, condition.filter)
  17362. : res;
  17363. }
  17364. },
  17365. /**
  17366. * @usage
  17367. * eachComponent('legend', function (legendModel, index) {
  17368. * ...
  17369. * });
  17370. * eachComponent(function (componentType, model, index) {
  17371. * // componentType does not include subType
  17372. * // (componentType is 'xxx' but not 'xxx.aa')
  17373. * });
  17374. * eachComponent(
  17375. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17376. * function (model, index) {...}
  17377. * );
  17378. * eachComponent(
  17379. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17380. * function (model, index) {...}
  17381. * );
  17382. *
  17383. * @param {string|Object=} mainType When mainType is object, the definition
  17384. * is the same as the method 'findComponents'.
  17385. * @param {Function} cb
  17386. * @param {*} context
  17387. */
  17388. eachComponent: function (mainType, cb, context) {
  17389. var componentsMap = this._componentsMap;
  17390. if (typeof mainType === 'function') {
  17391. context = cb;
  17392. cb = mainType;
  17393. componentsMap.each(function (components, componentType) {
  17394. each$1(components, function (component, index) {
  17395. cb.call(context, componentType, component, index);
  17396. });
  17397. });
  17398. }
  17399. else if (isString(mainType)) {
  17400. each$1(componentsMap.get(mainType), cb, context);
  17401. }
  17402. else if (isObject$1(mainType)) {
  17403. var queryResult = this.findComponents(mainType);
  17404. each$1(queryResult, cb, context);
  17405. }
  17406. },
  17407. /**
  17408. * @param {string} name
  17409. * @return {Array.<module:echarts/model/Series>}
  17410. */
  17411. getSeriesByName: function (name) {
  17412. var series = this._componentsMap.get('series');
  17413. return filter(series, function (oneSeries) {
  17414. return oneSeries.name === name;
  17415. });
  17416. },
  17417. /**
  17418. * @param {number} seriesIndex
  17419. * @return {module:echarts/model/Series}
  17420. */
  17421. getSeriesByIndex: function (seriesIndex) {
  17422. return this._componentsMap.get('series')[seriesIndex];
  17423. },
  17424. /**
  17425. * @param {string} subType
  17426. * @return {Array.<module:echarts/model/Series>}
  17427. */
  17428. getSeriesByType: function (subType) {
  17429. var series = this._componentsMap.get('series');
  17430. return filter(series, function (oneSeries) {
  17431. return oneSeries.subType === subType;
  17432. });
  17433. },
  17434. /**
  17435. * @return {Array.<module:echarts/model/Series>}
  17436. */
  17437. getSeries: function () {
  17438. return this._componentsMap.get('series').slice();
  17439. },
  17440. /**
  17441. * @return {number}
  17442. */
  17443. getSeriesCount: function () {
  17444. return this._componentsMap.get('series').length;
  17445. },
  17446. /**
  17447. * After filtering, series may be different
  17448. * frome raw series.
  17449. *
  17450. * @param {Function} cb
  17451. * @param {*} context
  17452. */
  17453. eachSeries: function (cb, context) {
  17454. assertSeriesInitialized(this);
  17455. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17456. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17457. cb.call(context, series, rawSeriesIndex);
  17458. }, this);
  17459. },
  17460. /**
  17461. * Iterate raw series before filtered.
  17462. *
  17463. * @param {Function} cb
  17464. * @param {*} context
  17465. */
  17466. eachRawSeries: function (cb, context) {
  17467. each$1(this._componentsMap.get('series'), cb, context);
  17468. },
  17469. /**
  17470. * After filtering, series may be different.
  17471. * frome raw series.
  17472. *
  17473. * @parma {string} subType
  17474. * @param {Function} cb
  17475. * @param {*} context
  17476. */
  17477. eachSeriesByType: function (subType, cb, context) {
  17478. assertSeriesInitialized(this);
  17479. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17480. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17481. if (series.subType === subType) {
  17482. cb.call(context, series, rawSeriesIndex);
  17483. }
  17484. }, this);
  17485. },
  17486. /**
  17487. * Iterate raw series before filtered of given type.
  17488. *
  17489. * @parma {string} subType
  17490. * @param {Function} cb
  17491. * @param {*} context
  17492. */
  17493. eachRawSeriesByType: function (subType, cb, context) {
  17494. return each$1(this.getSeriesByType(subType), cb, context);
  17495. },
  17496. /**
  17497. * @param {module:echarts/model/Series} seriesModel
  17498. */
  17499. isSeriesFiltered: function (seriesModel) {
  17500. assertSeriesInitialized(this);
  17501. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17502. },
  17503. /**
  17504. * @return {Array.<number>}
  17505. */
  17506. getCurrentSeriesIndices: function () {
  17507. return (this._seriesIndices || []).slice();
  17508. },
  17509. /**
  17510. * @param {Function} cb
  17511. * @param {*} context
  17512. */
  17513. filterSeries: function (cb, context) {
  17514. assertSeriesInitialized(this);
  17515. var filteredSeries = filter(
  17516. this._componentsMap.get('series'), cb, context
  17517. );
  17518. createSeriesIndices(this, filteredSeries);
  17519. },
  17520. restoreData: function (payload) {
  17521. var componentsMap = this._componentsMap;
  17522. createSeriesIndices(this, componentsMap.get('series'));
  17523. var componentTypes = [];
  17524. componentsMap.each(function (components, componentType) {
  17525. componentTypes.push(componentType);
  17526. });
  17527. ComponentModel.topologicalTravel(
  17528. componentTypes,
  17529. ComponentModel.getAllClassMainTypes(),
  17530. function (componentType, dependencies) {
  17531. each$1(componentsMap.get(componentType), function (component) {
  17532. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  17533. && component.restoreData();
  17534. });
  17535. }
  17536. );
  17537. }
  17538. });
  17539. function isNotTargetSeries(seriesModel, payload) {
  17540. if (payload) {
  17541. var index = payload.seiresIndex;
  17542. var id = payload.seriesId;
  17543. var name = payload.seriesName;
  17544. return (index != null && seriesModel.componentIndex !== index)
  17545. || (id != null && seriesModel.id !== id)
  17546. || (name != null && seriesModel.name !== name);
  17547. }
  17548. }
  17549. /**
  17550. * @inner
  17551. */
  17552. function mergeTheme(option, theme) {
  17553. each$1(theme, function (themeItem, name) {
  17554. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  17555. if (!ComponentModel.hasClass(name)) {
  17556. if (typeof themeItem === 'object') {
  17557. option[name] = !option[name]
  17558. ? clone(themeItem)
  17559. : merge(option[name], themeItem, false);
  17560. }
  17561. else {
  17562. if (option[name] == null) {
  17563. option[name] = themeItem;
  17564. }
  17565. }
  17566. }
  17567. });
  17568. }
  17569. function initBase(baseOption) {
  17570. baseOption = baseOption;
  17571. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17572. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17573. this.option = {};
  17574. this.option[OPTION_INNER_KEY] = 1;
  17575. /**
  17576. * Init with series: [], in case of calling findSeries method
  17577. * before series initialized.
  17578. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17579. * @private
  17580. */
  17581. this._componentsMap = createHashMap({series: []});
  17582. /**
  17583. * Mapping between filtered series list and raw series list.
  17584. * key: filtered series indices, value: raw series indices.
  17585. * @type {Array.<nubmer>}
  17586. * @private
  17587. */
  17588. this._seriesIndices;
  17589. this._seriesIndicesMap;
  17590. mergeTheme(baseOption, this._theme.option);
  17591. // TODO Needs clone when merging to the unexisted property
  17592. merge(baseOption, globalDefault, false);
  17593. this.mergeOption(baseOption);
  17594. }
  17595. /**
  17596. * @inner
  17597. * @param {Array.<string>|string} types model types
  17598. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17599. */
  17600. function getComponentsByTypes(componentsMap, types) {
  17601. if (!isArray(types)) {
  17602. types = types ? [types] : [];
  17603. }
  17604. var ret = {};
  17605. each$1(types, function (type) {
  17606. ret[type] = (componentsMap.get(type) || []).slice();
  17607. });
  17608. return ret;
  17609. }
  17610. /**
  17611. * @inner
  17612. */
  17613. function determineSubType(mainType, newCptOption, existComponent) {
  17614. var subType = newCptOption.type
  17615. ? newCptOption.type
  17616. : existComponent
  17617. ? existComponent.subType
  17618. // Use determineSubType only when there is no existComponent.
  17619. : ComponentModel.determineSubType(mainType, newCptOption);
  17620. // tooltip, markline, markpoint may always has no subType
  17621. return subType;
  17622. }
  17623. /**
  17624. * @inner
  17625. */
  17626. function createSeriesIndices(ecModel, seriesModels) {
  17627. ecModel._seriesIndicesMap = createHashMap(
  17628. ecModel._seriesIndices = map(seriesModels, function (series) {
  17629. return series.componentIndex;
  17630. }) || []
  17631. );
  17632. }
  17633. /**
  17634. * @inner
  17635. */
  17636. function filterBySubType(components, condition) {
  17637. // Using hasOwnProperty for restrict. Consider
  17638. // subType is undefined in user payload.
  17639. return condition.hasOwnProperty('subType')
  17640. ? filter(components, function (cpt) {
  17641. return cpt.subType === condition.subType;
  17642. })
  17643. : components;
  17644. }
  17645. /**
  17646. * @inner
  17647. */
  17648. function assertSeriesInitialized(ecModel) {
  17649. // Components that use _seriesIndices should depends on series component,
  17650. // which make sure that their initialization is after series.
  17651. if (__DEV__) {
  17652. if (!ecModel._seriesIndices) {
  17653. throw new Error('Option should contains series.');
  17654. }
  17655. }
  17656. }
  17657. mixin(GlobalModel, colorPaletteMixin);
  17658. var echartsAPIList = [
  17659. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17660. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17661. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17662. ];
  17663. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17664. function ExtensionAPI(chartInstance) {
  17665. each$1(echartsAPIList, function (name) {
  17666. this[name] = bind(chartInstance[name], chartInstance);
  17667. }, this);
  17668. }
  17669. var coordinateSystemCreators = {};
  17670. function CoordinateSystemManager() {
  17671. this._coordinateSystems = [];
  17672. }
  17673. CoordinateSystemManager.prototype = {
  17674. constructor: CoordinateSystemManager,
  17675. create: function (ecModel, api) {
  17676. var coordinateSystems = [];
  17677. each$1(coordinateSystemCreators, function (creater, type) {
  17678. var list = creater.create(ecModel, api);
  17679. coordinateSystems = coordinateSystems.concat(list || []);
  17680. });
  17681. this._coordinateSystems = coordinateSystems;
  17682. },
  17683. update: function (ecModel, api) {
  17684. each$1(this._coordinateSystems, function (coordSys) {
  17685. coordSys.update && coordSys.update(ecModel, api);
  17686. });
  17687. },
  17688. getCoordinateSystems: function () {
  17689. return this._coordinateSystems.slice();
  17690. }
  17691. };
  17692. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17693. coordinateSystemCreators[type] = coordinateSystemCreator;
  17694. };
  17695. CoordinateSystemManager.get = function (type) {
  17696. return coordinateSystemCreators[type];
  17697. };
  17698. /**
  17699. * ECharts option manager
  17700. *
  17701. * @module {echarts/model/OptionManager}
  17702. */
  17703. var each$4 = each$1;
  17704. var clone$3 = clone;
  17705. var map$1 = map;
  17706. var merge$1 = merge;
  17707. var QUERY_REG = /^(min|max)?(.+)$/;
  17708. /**
  17709. * TERM EXPLANATIONS:
  17710. *
  17711. * [option]:
  17712. *
  17713. * An object that contains definitions of components. For example:
  17714. * var option = {
  17715. * title: {...},
  17716. * legend: {...},
  17717. * visualMap: {...},
  17718. * series: [
  17719. * {data: [...]},
  17720. * {data: [...]},
  17721. * ...
  17722. * ]
  17723. * };
  17724. *
  17725. * [rawOption]:
  17726. *
  17727. * An object input to echarts.setOption. 'rawOption' may be an
  17728. * 'option', or may be an object contains multi-options. For example:
  17729. * var option = {
  17730. * baseOption: {
  17731. * title: {...},
  17732. * legend: {...},
  17733. * series: [
  17734. * {data: [...]},
  17735. * {data: [...]},
  17736. * ...
  17737. * ]
  17738. * },
  17739. * timeline: {...},
  17740. * options: [
  17741. * {title: {...}, series: {data: [...]}},
  17742. * {title: {...}, series: {data: [...]}},
  17743. * ...
  17744. * ],
  17745. * media: [
  17746. * {
  17747. * query: {maxWidth: 320},
  17748. * option: {series: {x: 20}, visualMap: {show: false}}
  17749. * },
  17750. * {
  17751. * query: {minWidth: 320, maxWidth: 720},
  17752. * option: {series: {x: 500}, visualMap: {show: true}}
  17753. * },
  17754. * {
  17755. * option: {series: {x: 1200}, visualMap: {show: true}}
  17756. * }
  17757. * ]
  17758. * };
  17759. *
  17760. * @alias module:echarts/model/OptionManager
  17761. * @param {module:echarts/ExtensionAPI} api
  17762. */
  17763. function OptionManager(api) {
  17764. /**
  17765. * @private
  17766. * @type {module:echarts/ExtensionAPI}
  17767. */
  17768. this._api = api;
  17769. /**
  17770. * @private
  17771. * @type {Array.<number>}
  17772. */
  17773. this._timelineOptions = [];
  17774. /**
  17775. * @private
  17776. * @type {Array.<Object>}
  17777. */
  17778. this._mediaList = [];
  17779. /**
  17780. * @private
  17781. * @type {Object}
  17782. */
  17783. this._mediaDefault;
  17784. /**
  17785. * -1, means default.
  17786. * empty means no media.
  17787. * @private
  17788. * @type {Array.<number>}
  17789. */
  17790. this._currentMediaIndices = [];
  17791. /**
  17792. * @private
  17793. * @type {Object}
  17794. */
  17795. this._optionBackup;
  17796. /**
  17797. * @private
  17798. * @type {Object}
  17799. */
  17800. this._newBaseOption;
  17801. }
  17802. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17803. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17804. // rawOption cloned and backuped when timeline changed, which does no
  17805. // good to performance. What's more, that both timeline and setOption
  17806. // method supply 'notMerge' brings complex and some problems.
  17807. // Consider this case:
  17808. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17809. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17810. OptionManager.prototype = {
  17811. constructor: OptionManager,
  17812. /**
  17813. * @public
  17814. * @param {Object} rawOption Raw option.
  17815. * @param {module:echarts/model/Global} ecModel
  17816. * @param {Array.<Function>} optionPreprocessorFuncs
  17817. * @return {Object} Init option
  17818. */
  17819. setOption: function (rawOption, optionPreprocessorFuncs) {
  17820. if (rawOption) {
  17821. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17822. each$1(normalizeToArray(rawOption.series), function (series) {
  17823. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17824. });
  17825. }
  17826. // Caution: some series modify option data, if do not clone,
  17827. // it should ensure that the repeat modify correctly
  17828. // (create a new object when modify itself).
  17829. rawOption = clone$3(rawOption, true);
  17830. // FIXME
  17831. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17832. var oldOptionBackup = this._optionBackup;
  17833. var newParsedOption = parseRawOption.call(
  17834. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17835. );
  17836. this._newBaseOption = newParsedOption.baseOption;
  17837. // For setOption at second time (using merge mode);
  17838. if (oldOptionBackup) {
  17839. // Only baseOption can be merged.
  17840. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17841. // For simplicity, timeline options and media options do not support merge,
  17842. // that is, if you `setOption` twice and both has timeline options, the latter
  17843. // timeline opitons will not be merged to the formers, but just substitude them.
  17844. if (newParsedOption.timelineOptions.length) {
  17845. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17846. }
  17847. if (newParsedOption.mediaList.length) {
  17848. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17849. }
  17850. if (newParsedOption.mediaDefault) {
  17851. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17852. }
  17853. }
  17854. else {
  17855. this._optionBackup = newParsedOption;
  17856. }
  17857. },
  17858. /**
  17859. * @param {boolean} isRecreate
  17860. * @return {Object}
  17861. */
  17862. mountOption: function (isRecreate) {
  17863. var optionBackup = this._optionBackup;
  17864. // TODO
  17865. // 如果没有reset功能则不clone。
  17866. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17867. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17868. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17869. this._currentMediaIndices = [];
  17870. return clone$3(isRecreate
  17871. // this._optionBackup.baseOption, which is created at the first `setOption`
  17872. // called, and is merged into every new option by inner method `mergeOption`
  17873. // each time `setOption` called, can be only used in `isRecreate`, because
  17874. // its reliability is under suspicion. In other cases option merge is
  17875. // performed by `model.mergeOption`.
  17876. ? optionBackup.baseOption : this._newBaseOption
  17877. );
  17878. },
  17879. /**
  17880. * @param {module:echarts/model/Global} ecModel
  17881. * @return {Object}
  17882. */
  17883. getTimelineOption: function (ecModel) {
  17884. var option;
  17885. var timelineOptions = this._timelineOptions;
  17886. if (timelineOptions.length) {
  17887. // getTimelineOption can only be called after ecModel inited,
  17888. // so we can get currentIndex from timelineModel.
  17889. var timelineModel = ecModel.getComponent('timeline');
  17890. if (timelineModel) {
  17891. option = clone$3(
  17892. timelineOptions[timelineModel.getCurrentIndex()],
  17893. true
  17894. );
  17895. }
  17896. }
  17897. return option;
  17898. },
  17899. /**
  17900. * @param {module:echarts/model/Global} ecModel
  17901. * @return {Array.<Object>}
  17902. */
  17903. getMediaOption: function (ecModel) {
  17904. var ecWidth = this._api.getWidth();
  17905. var ecHeight = this._api.getHeight();
  17906. var mediaList = this._mediaList;
  17907. var mediaDefault = this._mediaDefault;
  17908. var indices = [];
  17909. var result = [];
  17910. // No media defined.
  17911. if (!mediaList.length && !mediaDefault) {
  17912. return result;
  17913. }
  17914. // Multi media may be applied, the latter defined media has higher priority.
  17915. for (var i = 0, len = mediaList.length; i < len; i++) {
  17916. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17917. indices.push(i);
  17918. }
  17919. }
  17920. // FIXME
  17921. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17922. if (!indices.length && mediaDefault) {
  17923. indices = [-1];
  17924. }
  17925. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17926. result = map$1(indices, function (index) {
  17927. return clone$3(
  17928. index === -1 ? mediaDefault.option : mediaList[index].option
  17929. );
  17930. });
  17931. }
  17932. // Otherwise return nothing.
  17933. this._currentMediaIndices = indices;
  17934. return result;
  17935. }
  17936. };
  17937. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17938. var timelineOptions = [];
  17939. var mediaList = [];
  17940. var mediaDefault;
  17941. var baseOption;
  17942. // Compatible with ec2.
  17943. var timelineOpt = rawOption.timeline;
  17944. if (rawOption.baseOption) {
  17945. baseOption = rawOption.baseOption;
  17946. }
  17947. // For timeline
  17948. if (timelineOpt || rawOption.options) {
  17949. baseOption = baseOption || {};
  17950. timelineOptions = (rawOption.options || []).slice();
  17951. }
  17952. // For media query
  17953. if (rawOption.media) {
  17954. baseOption = baseOption || {};
  17955. var media = rawOption.media;
  17956. each$4(media, function (singleMedia) {
  17957. if (singleMedia && singleMedia.option) {
  17958. if (singleMedia.query) {
  17959. mediaList.push(singleMedia);
  17960. }
  17961. else if (!mediaDefault) {
  17962. // Use the first media default.
  17963. mediaDefault = singleMedia;
  17964. }
  17965. }
  17966. });
  17967. }
  17968. // For normal option
  17969. if (!baseOption) {
  17970. baseOption = rawOption;
  17971. }
  17972. // Set timelineOpt to baseOption in ec3,
  17973. // which is convenient for merge option.
  17974. if (!baseOption.timeline) {
  17975. baseOption.timeline = timelineOpt;
  17976. }
  17977. // Preprocess.
  17978. each$4([baseOption].concat(timelineOptions)
  17979. .concat(map(mediaList, function (media) {
  17980. return media.option;
  17981. })),
  17982. function (option) {
  17983. each$4(optionPreprocessorFuncs, function (preProcess) {
  17984. preProcess(option, isNew);
  17985. });
  17986. }
  17987. );
  17988. return {
  17989. baseOption: baseOption,
  17990. timelineOptions: timelineOptions,
  17991. mediaDefault: mediaDefault,
  17992. mediaList: mediaList
  17993. };
  17994. }
  17995. /**
  17996. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17997. * Support: width, height, aspectRatio
  17998. * Can use max or min as prefix.
  17999. */
  18000. function applyMediaQuery(query, ecWidth, ecHeight) {
  18001. var realMap = {
  18002. width: ecWidth,
  18003. height: ecHeight,
  18004. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18005. };
  18006. var applicatable = true;
  18007. each$1(query, function (value, attr) {
  18008. var matched = attr.match(QUERY_REG);
  18009. if (!matched || !matched[1] || !matched[2]) {
  18010. return;
  18011. }
  18012. var operator = matched[1];
  18013. var realAttr = matched[2].toLowerCase();
  18014. if (!compare(realMap[realAttr], value, operator)) {
  18015. applicatable = false;
  18016. }
  18017. });
  18018. return applicatable;
  18019. }
  18020. function compare(real, expect, operator) {
  18021. if (operator === 'min') {
  18022. return real >= expect;
  18023. }
  18024. else if (operator === 'max') {
  18025. return real <= expect;
  18026. }
  18027. else { // Equals
  18028. return real === expect;
  18029. }
  18030. }
  18031. function indicesEquals(indices1, indices2) {
  18032. // indices is always order by asc and has only finite number.
  18033. return indices1.join(',') === indices2.join(',');
  18034. }
  18035. /**
  18036. * Consider case:
  18037. * `chart.setOption(opt1);`
  18038. * Then user do some interaction like dataZoom, dataView changing.
  18039. * `chart.setOption(opt2);`
  18040. * Then user press 'reset button' in toolbox.
  18041. *
  18042. * After doing that all of the interaction effects should be reset, the
  18043. * chart should be the same as the result of invoke
  18044. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18045. *
  18046. * Although it is not able ensure that
  18047. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18048. * `chart.setOption(merge(opt1, opt2));` exactly,
  18049. * this might be the only simple way to implement that feature.
  18050. *
  18051. * MEMO: We've considered some other approaches:
  18052. * 1. Each model handle its self restoration but not uniform treatment.
  18053. * (Too complex in logic and error-prone)
  18054. * 2. Use a shadow ecModel. (Performace expensive)
  18055. */
  18056. function mergeOption(oldOption, newOption) {
  18057. newOption = newOption || {};
  18058. each$4(newOption, function (newCptOpt, mainType) {
  18059. if (newCptOpt == null) {
  18060. return;
  18061. }
  18062. var oldCptOpt = oldOption[mainType];
  18063. if (!ComponentModel.hasClass(mainType)) {
  18064. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18065. }
  18066. else {
  18067. newCptOpt = normalizeToArray(newCptOpt);
  18068. oldCptOpt = normalizeToArray(oldCptOpt);
  18069. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18070. oldOption[mainType] = map$1(mapResult, function (item) {
  18071. return (item.option && item.exist)
  18072. ? merge$1(item.exist, item.option, true)
  18073. : (item.exist || item.option);
  18074. });
  18075. }
  18076. });
  18077. }
  18078. var each$5 = each$1;
  18079. var isObject$3 = isObject$1;
  18080. var POSSIBLE_STYLES = [
  18081. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18082. 'chordStyle', 'label', 'labelLine'
  18083. ];
  18084. function compatEC2ItemStyle(opt) {
  18085. var itemStyleOpt = opt && opt.itemStyle;
  18086. if (!itemStyleOpt) {
  18087. return;
  18088. }
  18089. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18090. var styleName = POSSIBLE_STYLES[i];
  18091. var normalItemStyleOpt = itemStyleOpt.normal;
  18092. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18093. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18094. opt[styleName] = opt[styleName] || {};
  18095. if (!opt[styleName].normal) {
  18096. opt[styleName].normal = normalItemStyleOpt[styleName];
  18097. }
  18098. else {
  18099. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18100. }
  18101. normalItemStyleOpt[styleName] = null;
  18102. }
  18103. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18104. opt[styleName] = opt[styleName] || {};
  18105. if (!opt[styleName].emphasis) {
  18106. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18107. }
  18108. else {
  18109. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18110. }
  18111. emphasisItemStyleOpt[styleName] = null;
  18112. }
  18113. }
  18114. }
  18115. function convertNormalEmphasis(opt, optType, useExtend) {
  18116. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18117. var normalOpt = opt[optType].normal;
  18118. var emphasisOpt = opt[optType].emphasis;
  18119. if (normalOpt) {
  18120. // Timeline controlStyle has other properties besides normal and emphasis
  18121. if (useExtend) {
  18122. opt[optType].normal = opt[optType].emphasis = null;
  18123. defaults(opt[optType], normalOpt);
  18124. }
  18125. else {
  18126. opt[optType] = normalOpt;
  18127. }
  18128. }
  18129. if (emphasisOpt) {
  18130. opt.emphasis = opt.emphasis || {};
  18131. opt.emphasis[optType] = emphasisOpt;
  18132. }
  18133. }
  18134. }
  18135. function removeEC3NormalStatus(opt) {
  18136. convertNormalEmphasis(opt, 'itemStyle');
  18137. convertNormalEmphasis(opt, 'lineStyle');
  18138. convertNormalEmphasis(opt, 'areaStyle');
  18139. convertNormalEmphasis(opt, 'label');
  18140. convertNormalEmphasis(opt, 'labelLine');
  18141. // treemap
  18142. convertNormalEmphasis(opt, 'upperLabel');
  18143. // graph
  18144. convertNormalEmphasis(opt, 'edgeLabel');
  18145. }
  18146. function compatTextStyle(labelOpt) {
  18147. var textStyle = isObject$3(labelOpt) && labelOpt.textStyle;
  18148. if (textStyle) {
  18149. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18150. var propName = TEXT_STYLE_OPTIONS[i];
  18151. if (textStyle.hasOwnProperty(propName)) {
  18152. labelOpt[propName] = textStyle[propName];
  18153. }
  18154. }
  18155. }
  18156. }
  18157. function compatEC3CommonStyles(opt) {
  18158. if (opt) {
  18159. removeEC3NormalStatus(opt);
  18160. compatTextStyle(opt.label);
  18161. opt.emphasis && compatTextStyle(opt.emphasis.label);
  18162. }
  18163. }
  18164. function processSeries(seriesOpt) {
  18165. if (!isObject$3(seriesOpt)) {
  18166. return;
  18167. }
  18168. compatEC2ItemStyle(seriesOpt);
  18169. removeEC3NormalStatus(seriesOpt);
  18170. compatTextStyle(seriesOpt.label);
  18171. // treemap
  18172. compatTextStyle(seriesOpt.upperLabel);
  18173. // graph
  18174. compatTextStyle(seriesOpt.edgeLabel);
  18175. if (seriesOpt.emphasis) {
  18176. compatTextStyle(seriesOpt.emphasis.label);
  18177. // treemap
  18178. compatTextStyle(seriesOpt.emphasis.upperLabel);
  18179. // graph
  18180. compatTextStyle(seriesOpt.emphasis.edgeLabel);
  18181. }
  18182. var markPoint = seriesOpt.markPoint;
  18183. if (markPoint) {
  18184. compatEC2ItemStyle(markPoint);
  18185. compatEC3CommonStyles(markPoint);
  18186. }
  18187. var markLine = seriesOpt.markLine;
  18188. if (markLine) {
  18189. compatEC2ItemStyle(markLine);
  18190. compatEC3CommonStyles(markLine);
  18191. }
  18192. var markArea = seriesOpt.markArea;
  18193. if (markArea) {
  18194. compatEC3CommonStyles(markArea);
  18195. }
  18196. var data = seriesOpt.data;
  18197. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18198. // then the backward compat based on option type will not be performed.
  18199. if (seriesOpt.type === 'graph') {
  18200. data = data || seriesOpt.nodes;
  18201. var edgeData = seriesOpt.links || seriesOpt.edges;
  18202. if (edgeData && !isTypedArray(edgeData)) {
  18203. for (var i = 0; i < edgeData.length; i++) {
  18204. compatEC3CommonStyles(edgeData[i]);
  18205. }
  18206. }
  18207. each$1(seriesOpt.categories, function (opt) {
  18208. removeEC3NormalStatus(opt);
  18209. });
  18210. }
  18211. if (data && !isTypedArray(data)) {
  18212. for (var i = 0; i < data.length; i++) {
  18213. compatEC3CommonStyles(data[i]);
  18214. }
  18215. }
  18216. // mark point data
  18217. var markPoint = seriesOpt.markPoint;
  18218. if (markPoint && markPoint.data) {
  18219. var mpData = markPoint.data;
  18220. for (var i = 0; i < mpData.length; i++) {
  18221. compatEC3CommonStyles(mpData[i]);
  18222. }
  18223. }
  18224. // mark line data
  18225. var markLine = seriesOpt.markLine;
  18226. if (markLine && markLine.data) {
  18227. var mlData = markLine.data;
  18228. for (var i = 0; i < mlData.length; i++) {
  18229. if (isArray(mlData[i])) {
  18230. compatEC3CommonStyles(mlData[i][0]);
  18231. compatEC3CommonStyles(mlData[i][1]);
  18232. }
  18233. else {
  18234. compatEC3CommonStyles(mlData[i]);
  18235. }
  18236. }
  18237. }
  18238. // Series
  18239. if (seriesOpt.type === 'gauge') {
  18240. compatTextStyle(seriesOpt, 'axisLabel');
  18241. compatTextStyle(seriesOpt, 'title');
  18242. compatTextStyle(seriesOpt, 'detail');
  18243. }
  18244. else if (seriesOpt.type === 'treemap') {
  18245. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18246. each$1(seriesOpt.levels, function (opt) {
  18247. removeEC3NormalStatus(opt);
  18248. });
  18249. }
  18250. // sunburst starts from ec4, so it does not need to compat levels.
  18251. }
  18252. function toArr(o) {
  18253. return isArray(o) ? o : o ? [o] : [];
  18254. }
  18255. function toObj(o) {
  18256. return (isArray(o) ? o[0] : o) || {};
  18257. }
  18258. var compatStyle = function (option, isTheme) {
  18259. each$5(toArr(option.series), function (seriesOpt) {
  18260. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18261. });
  18262. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18263. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18264. each$5(
  18265. axes,
  18266. function (axisName) {
  18267. each$5(toArr(option[axisName]), function (axisOpt) {
  18268. if (axisOpt) {
  18269. compatTextStyle(axisOpt, 'axisLabel');
  18270. compatTextStyle(axisOpt.axisPointer, 'label');
  18271. }
  18272. });
  18273. }
  18274. );
  18275. each$5(toArr(option.parallel), function (parallelOpt) {
  18276. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18277. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18278. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18279. });
  18280. each$5(toArr(option.calendar), function (calendarOpt) {
  18281. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18282. compatTextStyle(calendarOpt, 'dayLabel');
  18283. compatTextStyle(calendarOpt, 'monthLabel');
  18284. compatTextStyle(calendarOpt, 'yearLabel');
  18285. });
  18286. // radar.name.textStyle
  18287. each$5(toArr(option.radar), function (radarOpt) {
  18288. compatTextStyle(radarOpt, 'name');
  18289. });
  18290. each$5(toArr(option.geo), function (geoOpt) {
  18291. if (isObject$3(geoOpt)) {
  18292. compatEC3CommonStyles(geoOpt);
  18293. each$5(toArr(geoOpt.regions), function (regionObj) {
  18294. compatEC3CommonStyles(regionObj);
  18295. });
  18296. }
  18297. });
  18298. each$5(toArr(option.timeline), function (timelineOpt) {
  18299. compatEC3CommonStyles(timelineOpt);
  18300. convertNormalEmphasis(timelineOpt, 'label');
  18301. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18302. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18303. convertNormalEmphasis(timelineOpt, 'checkpointStyle');
  18304. var data = timelineOpt.data;
  18305. isArray(data) && each$1(data, function (item) {
  18306. if (isObject$1(item)) {
  18307. convertNormalEmphasis(item, 'label');
  18308. convertNormalEmphasis(item, 'itemStyle');
  18309. }
  18310. });
  18311. });
  18312. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18313. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18314. each$5(toolboxOpt.feature, function (featureOpt) {
  18315. convertNormalEmphasis(featureOpt, 'iconStyle');
  18316. });
  18317. });
  18318. compatTextStyle(toObj(option.axisPointer), 'label');
  18319. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18320. };
  18321. // Compatitable with 2.0
  18322. function get(opt, path) {
  18323. path = path.split(',');
  18324. var obj = opt;
  18325. for (var i = 0; i < path.length; i++) {
  18326. obj = obj && obj[path[i]];
  18327. if (obj == null) {
  18328. break;
  18329. }
  18330. }
  18331. return obj;
  18332. }
  18333. function set$1(opt, path, val, overwrite) {
  18334. path = path.split(',');
  18335. var obj = opt;
  18336. var key;
  18337. for (var i = 0; i < path.length - 1; i++) {
  18338. key = path[i];
  18339. if (obj[key] == null) {
  18340. obj[key] = {};
  18341. }
  18342. obj = obj[key];
  18343. }
  18344. if (overwrite || obj[path[i]] == null) {
  18345. obj[path[i]] = val;
  18346. }
  18347. }
  18348. function compatLayoutProperties(option) {
  18349. each$1(LAYOUT_PROPERTIES, function (prop) {
  18350. if (prop[0] in option && !(prop[1] in option)) {
  18351. option[prop[1]] = option[prop[0]];
  18352. }
  18353. });
  18354. }
  18355. var LAYOUT_PROPERTIES = [
  18356. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18357. ];
  18358. var COMPATITABLE_COMPONENTS = [
  18359. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18360. ];
  18361. var backwardCompat = function (option, isTheme) {
  18362. compatStyle(option, isTheme);
  18363. // Make sure series array for model initialization.
  18364. option.series = normalizeToArray(option.series);
  18365. each$1(option.series, function (seriesOpt) {
  18366. if (!isObject$1(seriesOpt)) {
  18367. return;
  18368. }
  18369. var seriesType = seriesOpt.type;
  18370. if (seriesType === 'pie' || seriesType === 'gauge') {
  18371. if (seriesOpt.clockWise != null) {
  18372. seriesOpt.clockwise = seriesOpt.clockWise;
  18373. }
  18374. }
  18375. if (seriesType === 'gauge') {
  18376. var pointerColor = get(seriesOpt, 'pointer.color');
  18377. pointerColor != null
  18378. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18379. }
  18380. compatLayoutProperties(seriesOpt);
  18381. });
  18382. // dataRange has changed to visualMap
  18383. if (option.dataRange) {
  18384. option.visualMap = option.dataRange;
  18385. }
  18386. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18387. var options = option[componentName];
  18388. if (options) {
  18389. if (!isArray(options)) {
  18390. options = [options];
  18391. }
  18392. each$1(options, function (option) {
  18393. compatLayoutProperties(option);
  18394. });
  18395. }
  18396. });
  18397. };
  18398. // TODO
  18399. // ??? refactor? check the outer usage of data provider.
  18400. // merge with defaultDimValueGetter?
  18401. /**
  18402. * If normal array used, mutable chunk size is supported.
  18403. * If typed array used, chunk size must be fixed.
  18404. */
  18405. function DefaultDataProvider(source, dimSize) {
  18406. if (!Source.isInstance(source)) {
  18407. source = Source.seriesDataToSource(source);
  18408. }
  18409. this._source = source;
  18410. var data = this._data = source.data;
  18411. var sourceFormat = source.sourceFormat;
  18412. // Typed array. TODO IE10+?
  18413. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18414. if (__DEV__) {
  18415. if (dimSize == null) {
  18416. throw new Error('Typed array data must specify dimension size');
  18417. }
  18418. }
  18419. this._offset = 0;
  18420. this._dimSize = dimSize;
  18421. this._data = data;
  18422. }
  18423. var methods = providerMethods[
  18424. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  18425. ? sourceFormat + '_' + source.seriesLayoutBy
  18426. : sourceFormat
  18427. ];
  18428. if (__DEV__) {
  18429. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18430. }
  18431. extend(this, methods);
  18432. }
  18433. var providerProto = DefaultDataProvider.prototype;
  18434. // If data is pure without style configuration
  18435. providerProto.pure = false;
  18436. // If data is persistent and will not be released after use.
  18437. providerProto.persistent = true;
  18438. // ???! FIXME legacy data provider do not has method getSource
  18439. providerProto.getSource = function () {
  18440. return this._source;
  18441. };
  18442. var providerMethods = {
  18443. 'arrayRows_column': {
  18444. pure: true,
  18445. count: function () {
  18446. return Math.max(0, this._data.length - this._source.startIndex);
  18447. },
  18448. getItem: function (idx) {
  18449. return this._data[idx + this._source.startIndex];
  18450. },
  18451. appendData: appendDataSimply
  18452. },
  18453. 'arrayRows_row': {
  18454. pure: true,
  18455. count: function () {
  18456. var row = this._data[0];
  18457. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  18458. },
  18459. getItem: function (idx) {
  18460. idx += this._source.startIndex;
  18461. var item = [];
  18462. var data = this._data;
  18463. for (var i = 0; i < data.length; i++) {
  18464. var row = data[i];
  18465. item.push(row ? row[idx] : null);
  18466. }
  18467. return item;
  18468. },
  18469. appendData: function () {
  18470. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18471. }
  18472. },
  18473. 'objectRows': {
  18474. pure: true,
  18475. count: countSimply,
  18476. getItem: getItemSimply,
  18477. appendData: appendDataSimply
  18478. },
  18479. 'keyedColumns': {
  18480. pure: true,
  18481. count: function () {
  18482. var dimName = this._source.dimensionsDefine[0].name;
  18483. var col = this._data[dimName];
  18484. return col ? col.length : 0;
  18485. },
  18486. getItem: function (idx) {
  18487. var item = [];
  18488. var dims = this._source.dimensionsDefine;
  18489. for (var i = 0; i < dims.length; i++) {
  18490. var col = this._data[dims[i].name];
  18491. item.push(col ? col[idx] : null);
  18492. }
  18493. return item;
  18494. },
  18495. appendData: function (newData) {
  18496. var data = this._data;
  18497. each$1(newData, function (newCol, key) {
  18498. var oldCol = data[key] || (data[key] = []);
  18499. for (var i = 0; i < (newCol || []).length; i++) {
  18500. oldCol.push(newCol[i]);
  18501. }
  18502. });
  18503. }
  18504. },
  18505. 'original': {
  18506. count: countSimply,
  18507. getItem: getItemSimply,
  18508. appendData: appendDataSimply
  18509. },
  18510. 'typedArray': {
  18511. persistent: false,
  18512. pure: true,
  18513. count: function () {
  18514. return this._data ? (this._data.length / this._dimSize) : 0;
  18515. },
  18516. getItem: function (idx) {
  18517. idx = idx - this._offset;
  18518. var item = [];
  18519. var offset = this._dimSize * idx;
  18520. for (var i = 0; i < this._dimSize; i++) {
  18521. item[i] = this._data[offset + i];
  18522. }
  18523. return item;
  18524. },
  18525. appendData: function (newData) {
  18526. if (__DEV__) {
  18527. assert$1(
  18528. isTypedArray(newData),
  18529. 'Added data must be TypedArray if data in initialization is TypedArray'
  18530. );
  18531. }
  18532. this._data = newData;
  18533. },
  18534. // Clean self if data is already used.
  18535. clean: function () {
  18536. // PENDING
  18537. this._offset += this.count();
  18538. this._data = null;
  18539. }
  18540. }
  18541. };
  18542. function countSimply() {
  18543. return this._data.length;
  18544. }
  18545. function getItemSimply(idx) {
  18546. return this._data[idx];
  18547. }
  18548. function appendDataSimply(newData) {
  18549. for (var i = 0; i < newData.length; i++) {
  18550. this._data.push(newData[i]);
  18551. }
  18552. }
  18553. var rawValueGetters = {
  18554. arrayRows: getRawValueSimply,
  18555. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  18556. return dimIndex != null ? dataItem[dimName] : dataItem;
  18557. },
  18558. keyedColumns: getRawValueSimply,
  18559. original: function (dataItem, dataIndex, dimIndex, dimName) {
  18560. // FIXME
  18561. // In some case (markpoint in geo (geo-map.html)), dataItem
  18562. // is {coord: [...]}
  18563. var value = getDataItemValue(dataItem);
  18564. return (dimIndex == null || !(value instanceof Array))
  18565. ? value
  18566. : value[dimIndex];
  18567. },
  18568. typedArray: getRawValueSimply
  18569. };
  18570. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18571. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18572. }
  18573. var defaultDimValueGetters = {
  18574. arrayRows: getDimValueSimply,
  18575. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18576. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18577. },
  18578. keyedColumns: getDimValueSimply,
  18579. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18580. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18581. // If dataItem is an plain object with no value field, the var `value`
  18582. // will be assigned with the object, but it will be tread correctly
  18583. // in the `convertDataValue`.
  18584. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18585. // If any dataItem is like { value: 10 }
  18586. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18587. this.hasItemOption = true;
  18588. }
  18589. return converDataValue(
  18590. (value instanceof Array)
  18591. ? value[dimIndex]
  18592. // If value is a single number or something else not array.
  18593. : value,
  18594. this._dimensionInfos[dimName]
  18595. );
  18596. },
  18597. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18598. return dataItem[dimIndex];
  18599. }
  18600. };
  18601. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18602. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18603. }
  18604. /**
  18605. * This helper method convert value in data.
  18606. * @param {string|number|Date} value
  18607. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18608. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18609. */
  18610. function converDataValue(value, dimInfo) {
  18611. // Performance sensitive.
  18612. var dimType = dimInfo && dimInfo.type;
  18613. if (dimType === 'ordinal') {
  18614. // If given value is a category string
  18615. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18616. return ordinalMeta
  18617. ? ordinalMeta.parseAndCollect(value)
  18618. : value;
  18619. }
  18620. if (dimType === 'time'
  18621. // spead up when using timestamp
  18622. && typeof value !== 'number'
  18623. && value != null
  18624. && value !== '-'
  18625. ) {
  18626. value = +parseDate(value);
  18627. }
  18628. // dimType defaults 'number'.
  18629. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18630. // parse to NaN.
  18631. return (value == null || value === '')
  18632. ? NaN
  18633. // If string (like '-'), using '+' parse to NaN
  18634. // If object, also parse to NaN
  18635. : +value;
  18636. }
  18637. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18638. // Consider persistent.
  18639. // Caution: why use raw value to display on label or tooltip?
  18640. // A reason is to avoid format. For example time value we do not know
  18641. // how to format is expected. More over, if stack is used, calculated
  18642. // value may be 0.91000000001, which have brings trouble to display.
  18643. // TODO: consider how to treat null/undefined/NaN when display?
  18644. /**
  18645. * @param {module:echarts/data/List} data
  18646. * @param {number} dataIndex
  18647. * @param {string|number} [dim] dimName or dimIndex
  18648. * @return {Array.<number>|string|number} can be null/undefined.
  18649. */
  18650. function retrieveRawValue(data, dataIndex, dim) {
  18651. if (!data) {
  18652. return;
  18653. }
  18654. // Consider data may be not persistent.
  18655. var dataItem = data.getRawDataItem(dataIndex);
  18656. if (dataItem == null) {
  18657. return;
  18658. }
  18659. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18660. var dimName;
  18661. var dimIndex;
  18662. var dimInfo = data.getDimensionInfo(dim);
  18663. if (dimInfo) {
  18664. dimName = dimInfo.name;
  18665. dimIndex = dimInfo.index;
  18666. }
  18667. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18668. }
  18669. /**
  18670. * Compatible with some cases (in pie, map) like:
  18671. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18672. * where only sourceFormat is 'original' and 'objectRows' supported.
  18673. *
  18674. * ??? TODO
  18675. * Supported detail options in data item when using 'arrayRows'.
  18676. *
  18677. * @param {module:echarts/data/List} data
  18678. * @param {number} dataIndex
  18679. * @param {string} attr like 'selected'
  18680. */
  18681. function retrieveRawAttr(data, dataIndex, attr) {
  18682. if (!data) {
  18683. return;
  18684. }
  18685. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18686. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18687. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18688. ) {
  18689. return;
  18690. }
  18691. var dataItem = data.getRawDataItem(dataIndex);
  18692. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18693. dataItem = null;
  18694. }
  18695. if (dataItem) {
  18696. return dataItem[attr];
  18697. }
  18698. }
  18699. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18700. // PENDING A little ugly
  18701. var dataFormatMixin = {
  18702. /**
  18703. * Get params for formatter
  18704. * @param {number} dataIndex
  18705. * @param {string} [dataType]
  18706. * @return {Object}
  18707. */
  18708. getDataParams: function (dataIndex, dataType) {
  18709. var data = this.getData(dataType);
  18710. var rawValue = this.getRawValue(dataIndex, dataType);
  18711. var rawDataIndex = data.getRawIndex(dataIndex);
  18712. var name = data.getName(dataIndex, true);
  18713. var itemOpt = data.getRawDataItem(dataIndex);
  18714. var color = data.getItemVisual(dataIndex, 'color');
  18715. return {
  18716. componentType: this.mainType,
  18717. componentSubType: this.subType,
  18718. seriesType: this.mainType === 'series' ? this.subType : null,
  18719. seriesIndex: this.seriesIndex,
  18720. seriesId: this.id,
  18721. seriesName: this.name,
  18722. name: name,
  18723. dataIndex: rawDataIndex,
  18724. data: itemOpt,
  18725. dataType: dataType,
  18726. value: rawValue,
  18727. color: color,
  18728. marker: getTooltipMarker(color),
  18729. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18730. $vars: ['seriesName', 'name', 'value']
  18731. };
  18732. },
  18733. /**
  18734. * Format label
  18735. * @param {number} dataIndex
  18736. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18737. * @param {string} [dataType]
  18738. * @param {number} [dimIndex]
  18739. * @param {string} [labelProp='label']
  18740. * @return {string} If not formatter, return null/undefined
  18741. */
  18742. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18743. status = status || 'normal';
  18744. var data = this.getData(dataType);
  18745. var itemModel = data.getItemModel(dataIndex);
  18746. var params = this.getDataParams(dataIndex, dataType);
  18747. if (dimIndex != null && (params.value instanceof Array)) {
  18748. params.value = params.value[dimIndex];
  18749. }
  18750. var formatter = itemModel.get(
  18751. status === 'normal'
  18752. ? [labelProp || 'label', 'formatter']
  18753. : [status, labelProp || 'label', 'formatter']
  18754. );
  18755. if (typeof formatter === 'function') {
  18756. params.status = status;
  18757. return formatter(params);
  18758. }
  18759. else if (typeof formatter === 'string') {
  18760. var str = formatTpl(formatter, params);
  18761. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18762. // Do not support '}' in dim name util have to.
  18763. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18764. var len = dim.length;
  18765. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18766. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18767. }
  18768. return retrieveRawValue(data, dataIndex, dim);
  18769. });
  18770. }
  18771. },
  18772. /**
  18773. * Get raw value in option
  18774. * @param {number} idx
  18775. * @param {string} [dataType]
  18776. * @return {Array|number|string}
  18777. */
  18778. getRawValue: function (idx, dataType) {
  18779. return retrieveRawValue(this.getData(dataType), idx);
  18780. },
  18781. /**
  18782. * Should be implemented.
  18783. * @param {number} dataIndex
  18784. * @param {boolean} [multipleSeries=false]
  18785. * @param {number} [dataType]
  18786. * @return {string} tooltip string
  18787. */
  18788. formatTooltip: function () {
  18789. // Empty function
  18790. }
  18791. };
  18792. /**
  18793. * @param {Object} define
  18794. * @return See the return of `createTask`.
  18795. */
  18796. function createTask(define) {
  18797. return new Task(define);
  18798. }
  18799. /**
  18800. * @constructor
  18801. * @param {Object} define
  18802. * @param {Function} define.reset Custom reset
  18803. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18804. * @param {Function} [define.count] count is used to determin data task.
  18805. * @param {Function} [define.onDirty] count is used to determin data task.
  18806. */
  18807. function Task(define) {
  18808. define = define || {};
  18809. this._reset = define.reset;
  18810. this._plan = define.plan;
  18811. this._count = define.count;
  18812. this._onDirty = define.onDirty;
  18813. this._dirty = true;
  18814. // Context must be specified implicitly, to
  18815. // avoid miss update context when model changed.
  18816. this.context;
  18817. }
  18818. var taskProto = Task.prototype;
  18819. /**
  18820. * @param {Object} performArgs
  18821. * @param {number} [performArgs.step] Specified step.
  18822. * @param {number} [performArgs.skip] Skip customer perform call.
  18823. */
  18824. taskProto.perform = function (performArgs) {
  18825. var upTask = this._upstream;
  18826. var skip = performArgs && performArgs.skip;
  18827. // TODO some refactor.
  18828. // Pull data. Must pull data each time, because context.data
  18829. // may be updated by Series.setData.
  18830. if (this._dirty && upTask) {
  18831. var context = this.context;
  18832. context.data = context.outputData = upTask.context.outputData;
  18833. }
  18834. if (this.__pipeline) {
  18835. this.__pipeline.currentTask = this;
  18836. }
  18837. var planResult;
  18838. if (this._plan && !skip) {
  18839. planResult = this._plan(this.context);
  18840. }
  18841. if (this._dirty || planResult === 'reset') {
  18842. this._dirty = false;
  18843. reset(this, skip);
  18844. }
  18845. var step = performArgs && performArgs.step;
  18846. if (upTask) {
  18847. if (__DEV__) {
  18848. assert$1(upTask._outputDueEnd != null);
  18849. }
  18850. // ??? FIXME move to schedueler?
  18851. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  18852. this._dueEnd = upTask._outputDueEnd;
  18853. }
  18854. // DataTask or overallTask
  18855. else {
  18856. if (__DEV__) {
  18857. assert$1(!this._progress || this._count);
  18858. }
  18859. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18860. }
  18861. // Note: Stubs, that its host overall task let it has progress, has progress.
  18862. // If no progress, pass index from upstream to downstream each time plan called.
  18863. if (this._progress) {
  18864. var start = this._dueIndex;
  18865. var end = Math.min(
  18866. step != null ? this._dueIndex + step : Infinity,
  18867. this._dueEnd
  18868. );
  18869. !skip && start < end && (
  18870. this._progress({start: start, end: end}, this.context)
  18871. );
  18872. this._dueIndex = end;
  18873. // If no `outputDueEnd`, assume that output data and
  18874. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18875. var outputDueEnd = this._settedOutputEnd != null
  18876. ? this._settedOutputEnd : end;
  18877. if (__DEV__) {
  18878. // ??? Can not rollback.
  18879. assert$1(outputDueEnd >= this._outputDueEnd);
  18880. }
  18881. this._outputDueEnd = outputDueEnd;
  18882. }
  18883. else {
  18884. // (1) Some overall task has no progress.
  18885. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18886. // This should always be performed so it can be passed to downstream.
  18887. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  18888. ? this._settedOutputEnd : this._dueEnd;
  18889. }
  18890. return this.unfinished();
  18891. };
  18892. taskProto.dirty = function () {
  18893. this._dirty = true;
  18894. this._onDirty && this._onDirty(this.context);
  18895. };
  18896. /**
  18897. * @param {Object} [params]
  18898. */
  18899. function reset(taskIns, skip) {
  18900. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  18901. taskIns._settedOutputEnd = null;
  18902. taskIns._progress = !skip && taskIns._reset && taskIns._reset(
  18903. taskIns.context
  18904. );
  18905. var downstream = taskIns._downstream;
  18906. downstream && downstream.dirty();
  18907. }
  18908. /**
  18909. * @return {boolean}
  18910. */
  18911. taskProto.unfinished = function () {
  18912. return this._progress && this._dueIndex < this._dueEnd;
  18913. };
  18914. /**
  18915. * @param {Object} downTask The downstream task.
  18916. * @return {Object} The downstream task.
  18917. */
  18918. taskProto.pipe = function (downTask) {
  18919. if (__DEV__) {
  18920. assert$1(downTask && !downTask._disposed && downTask !== this);
  18921. }
  18922. // If already downstream, do not dirty downTask.
  18923. if (this._downstream !== downTask || this._dirty) {
  18924. this._downstream = downTask;
  18925. downTask._upstream = this;
  18926. downTask.dirty();
  18927. }
  18928. };
  18929. taskProto.dispose = function () {
  18930. if (this._disposed) {
  18931. return;
  18932. }
  18933. this._upstream && (this._upstream._downstream = null);
  18934. this._downstream && (this._downstream._upstream = null);
  18935. this._dirty = false;
  18936. this._disposed = true;
  18937. };
  18938. taskProto.getUpstream = function () {
  18939. return this._upstream;
  18940. };
  18941. taskProto.getDownstream = function () {
  18942. return this._downstream;
  18943. };
  18944. taskProto.setOutputEnd = function (end) {
  18945. // ??? FIXME: check
  18946. // This only happend in dataTask, dataZoom, map, currently.
  18947. // where dataZoom do not set end each time, but only set
  18948. // when reset. So we should record the setted end, in case
  18949. // that the stub of dataZoom perform again and earse the
  18950. // setted end by upstream.
  18951. this._outputDueEnd = this._settedOutputEnd = end;
  18952. // this._outputDueEnd = end;
  18953. };
  18954. var inner$4 = makeInner();
  18955. var SeriesModel = ComponentModel.extend({
  18956. type: 'series.__base__',
  18957. /**
  18958. * @readOnly
  18959. */
  18960. seriesIndex: 0,
  18961. // coodinateSystem will be injected in the echarts/CoordinateSystem
  18962. coordinateSystem: null,
  18963. /**
  18964. * @type {Object}
  18965. * @protected
  18966. */
  18967. defaultOption: null,
  18968. /**
  18969. * Data provided for legend
  18970. * @type {Function}
  18971. */
  18972. // PENDING
  18973. legendDataProvider: null,
  18974. /**
  18975. * Access path of color for visual
  18976. */
  18977. visualColorAccessPath: 'itemStyle.color',
  18978. /**
  18979. * Support merge layout params.
  18980. * Only support 'box' now (left/right/top/bottom/width/height).
  18981. * @type {string|Object} Object can be {ignoreSize: true}
  18982. * @readOnly
  18983. */
  18984. layoutMode: null,
  18985. init: function (option, parentModel, ecModel, extraOpt) {
  18986. /**
  18987. * @type {number}
  18988. * @readOnly
  18989. */
  18990. this.seriesIndex = this.componentIndex;
  18991. this.dataTask = createTask({
  18992. count: dataTaskCount,
  18993. reset: dataTaskReset
  18994. });
  18995. this.dataTask.context = {model: this};
  18996. this.mergeDefaultAndTheme(option, ecModel);
  18997. prepareSource(this);
  18998. var data = this.getInitialData(option, ecModel);
  18999. wrapData(data, this);
  19000. this.dataTask.context.data = data;
  19001. if (__DEV__) {
  19002. assert$1(data, 'getInitialData returned invalid data.');
  19003. }
  19004. /**
  19005. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19006. * @private
  19007. */
  19008. inner$4(this).dataBeforeProcessed = data;
  19009. // If we reverse the order (make data firstly, and then make
  19010. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19011. // cause data.graph.data !== data when using
  19012. // module:echarts/data/Graph or module:echarts/data/Tree.
  19013. // See module:echarts/data/helper/linkList
  19014. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19015. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19016. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19017. // Call `seriesModel.getRawData()` instead.
  19018. // this.restoreData();
  19019. autoSeriesName(this);
  19020. },
  19021. /**
  19022. * Util for merge default and theme to option
  19023. * @param {Object} option
  19024. * @param {module:echarts/model/Global} ecModel
  19025. */
  19026. mergeDefaultAndTheme: function (option, ecModel) {
  19027. var layoutMode = this.layoutMode;
  19028. var inputPositionParams = layoutMode
  19029. ? getLayoutParams(option) : {};
  19030. // Backward compat: using subType on theme.
  19031. // But if name duplicate between series subType
  19032. // (for example: parallel) add component mainType,
  19033. // add suffix 'Series'.
  19034. var themeSubType = this.subType;
  19035. if (ComponentModel.hasClass(themeSubType)) {
  19036. themeSubType += 'Series';
  19037. }
  19038. merge(
  19039. option,
  19040. ecModel.getTheme().get(this.subType)
  19041. );
  19042. merge(option, this.getDefaultOption());
  19043. // Default label emphasis `show`
  19044. defaultEmphasis(option, 'label', ['show']);
  19045. this.fillDataTextStyle(option.data);
  19046. if (layoutMode) {
  19047. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19048. }
  19049. },
  19050. mergeOption: function (newSeriesOption, ecModel) {
  19051. // this.settingTask.dirty();
  19052. newSeriesOption = merge(this.option, newSeriesOption, true);
  19053. this.fillDataTextStyle(newSeriesOption.data);
  19054. var layoutMode = this.layoutMode;
  19055. if (layoutMode) {
  19056. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19057. }
  19058. prepareSource(this);
  19059. var data = this.getInitialData(newSeriesOption, ecModel);
  19060. wrapData(data, this);
  19061. this.dataTask.dirty();
  19062. this.dataTask.context.data = data;
  19063. inner$4(this).dataBeforeProcessed = data;
  19064. autoSeriesName(this);
  19065. },
  19066. fillDataTextStyle: function (data) {
  19067. // Default data label emphasis `show`
  19068. // FIXME Tree structure data ?
  19069. // FIXME Performance ?
  19070. if (data) {
  19071. var props = ['show'];
  19072. for (var i = 0; i < data.length; i++) {
  19073. if (data[i] && data[i].label) {
  19074. defaultEmphasis(data[i], 'label', props);
  19075. }
  19076. }
  19077. }
  19078. },
  19079. /**
  19080. * Init a data structure from data related option in series
  19081. * Must be overwritten
  19082. */
  19083. getInitialData: function () {},
  19084. /**
  19085. * Append data to list
  19086. * @param {Object} params
  19087. * @param {Array|TypedArray} params.data
  19088. */
  19089. appendData: function (params) {
  19090. // FIXME ???
  19091. // (1) If data from dataset, forbidden append.
  19092. // (2) support append data of dataset.
  19093. var data = this.getRawData();
  19094. data.appendData(params.data);
  19095. },
  19096. /**
  19097. * Consider some method like `filter`, `map` need make new data,
  19098. * We should make sure that `seriesModel.getData()` get correct
  19099. * data in the stream procedure. So we fetch data from upstream
  19100. * each time `task.perform` called.
  19101. * @param {string} [dataType]
  19102. * @return {module:echarts/data/List}
  19103. */
  19104. getData: function (dataType) {
  19105. var task = getCurrentTask(this);
  19106. if (task) {
  19107. var data = task.context.data;
  19108. return dataType == null ? data : data.getLinkedData(dataType);
  19109. }
  19110. else {
  19111. // When series is not alive (that may happen when click toolbox
  19112. // restore or setOption with not merge mode), series data may
  19113. // be still need to judge animation or something when graphic
  19114. // elements want to know whether fade out.
  19115. return inner$4(this).data;
  19116. }
  19117. },
  19118. /**
  19119. * @param {module:echarts/data/List} data
  19120. */
  19121. setData: function (data) {
  19122. var task = getCurrentTask(this);
  19123. if (task) {
  19124. var context = task.context;
  19125. // Consider case: filter, data sample.
  19126. if (context.data !== data && task.isOverallFilter) {
  19127. task.setOutputEnd(data.count());
  19128. }
  19129. context.outputData = data;
  19130. // Caution: setData should update context.data,
  19131. // Because getData may be called multiply in a
  19132. // single stage and expect to get the data just
  19133. // set. (For example, AxisProxy, x y both call
  19134. // getData and setDate sequentially).
  19135. // So the context.data should be fetched from
  19136. // upstream each time when a stage starts to be
  19137. // performed.
  19138. if (task !== this.dataTask) {
  19139. context.data = data;
  19140. }
  19141. }
  19142. inner$4(this).data = data;
  19143. },
  19144. /**
  19145. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19146. * @return {module:echarts/data/Source} source
  19147. */
  19148. getSource: function () {
  19149. return getSource(this);
  19150. },
  19151. /**
  19152. * Get data before processed
  19153. * @return {module:echarts/data/List}
  19154. */
  19155. getRawData: function () {
  19156. return inner$4(this).dataBeforeProcessed;
  19157. },
  19158. /**
  19159. * Get base axis if has coordinate system and has axis.
  19160. * By default use coordSys.getBaseAxis();
  19161. * Can be overrided for some chart.
  19162. * @return {type} description
  19163. */
  19164. getBaseAxis: function () {
  19165. var coordSys = this.coordinateSystem;
  19166. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19167. },
  19168. // FIXME
  19169. /**
  19170. * Default tooltip formatter
  19171. *
  19172. * @param {number} dataIndex
  19173. * @param {boolean} [multipleSeries=false]
  19174. * @param {number} [dataType]
  19175. */
  19176. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  19177. function formatArrayValue(value) {
  19178. // ??? TODO refactor these logic.
  19179. // check: category-no-encode-has-axis-data in dataset.html
  19180. var vertially = reduce(value, function (vertially, val, idx) {
  19181. var dimItem = data.getDimensionInfo(idx);
  19182. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19183. }, 0);
  19184. var result = [];
  19185. tooltipDims.length
  19186. ? each$1(tooltipDims, function (dim) {
  19187. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19188. })
  19189. // By default, all dims is used on tooltip.
  19190. : each$1(value, setEachItem);
  19191. function setEachItem(val, dim) {
  19192. var dimInfo = data.getDimensionInfo(dim);
  19193. // If `dimInfo.tooltip` is not set, show tooltip.
  19194. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19195. return;
  19196. }
  19197. var dimType = dimInfo.type;
  19198. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  19199. var valStr = (vertially
  19200. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  19201. : ''
  19202. )
  19203. // FIXME should not format time for raw data?
  19204. + encodeHTML(dimType === 'ordinal'
  19205. ? val + ''
  19206. : dimType === 'time'
  19207. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  19208. : addCommas(val)
  19209. );
  19210. valStr && result.push(valStr);
  19211. }
  19212. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  19213. }
  19214. function formatSingleValue(val) {
  19215. return encodeHTML(addCommas(val));
  19216. }
  19217. var data = this.getData();
  19218. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19219. var tooltipDimLen = tooltipDims.length;
  19220. var value = this.getRawValue(dataIndex);
  19221. var isValueArr = isArray(value);
  19222. var color = data.getItemVisual(dataIndex, 'color');
  19223. if (isObject$1(color) && color.colorStops) {
  19224. color = (color.colorStops[0] || {}).color;
  19225. }
  19226. color = color || 'transparent';
  19227. // Complicated rule for pretty tooltip.
  19228. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  19229. ? formatArrayValue(value)
  19230. : tooltipDimLen
  19231. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  19232. : formatSingleValue(isValueArr ? value[0] : value);
  19233. var colorEl = getTooltipMarker(color);
  19234. var name = data.getName(dataIndex);
  19235. var seriesName = this.name;
  19236. if (seriesName === DEFAULT_COMPONENT_NAME) {
  19237. // Not show '-'
  19238. seriesName = '';
  19239. }
  19240. seriesName = seriesName
  19241. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  19242. : '';
  19243. return !multipleSeries
  19244. ? seriesName + colorEl
  19245. + (name
  19246. ? encodeHTML(name) + ': ' + formattedValue
  19247. : formattedValue
  19248. )
  19249. : colorEl + seriesName + formattedValue;
  19250. },
  19251. /**
  19252. * @return {boolean}
  19253. */
  19254. isAnimationEnabled: function () {
  19255. if (env$1.node) {
  19256. return false;
  19257. }
  19258. var animationEnabled = this.getShallow('animation');
  19259. if (animationEnabled) {
  19260. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19261. animationEnabled = false;
  19262. }
  19263. }
  19264. return animationEnabled;
  19265. },
  19266. restoreData: function () {
  19267. this.dataTask.dirty();
  19268. },
  19269. getColorFromPalette: function (name, scope, requestColorNum) {
  19270. var ecModel = this.ecModel;
  19271. // PENDING
  19272. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19273. if (!color) {
  19274. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19275. }
  19276. return color;
  19277. },
  19278. /**
  19279. * Use `data.mapDimension(coordDim, true)` instead.
  19280. * @deprecated
  19281. */
  19282. coordDimToDataDim: function (coordDim) {
  19283. return this.getRawData().mapDimension(coordDim, true);
  19284. },
  19285. /**
  19286. * Get progressive rendering count each step
  19287. * @return {number}
  19288. */
  19289. getProgressive: function () {
  19290. return this.get('progressive');
  19291. },
  19292. /**
  19293. * Get progressive rendering count each step
  19294. * @return {number}
  19295. */
  19296. getProgressiveThreshold: function () {
  19297. return this.get('progressiveThreshold');
  19298. },
  19299. /**
  19300. * Get data indices for show tooltip content. See tooltip.
  19301. * @abstract
  19302. * @param {Array.<string>|string} dim
  19303. * @param {Array.<number>} value
  19304. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  19305. * @return {Object} {dataIndices, nestestValue}.
  19306. */
  19307. getAxisTooltipData: null,
  19308. /**
  19309. * See tooltip.
  19310. * @abstract
  19311. * @param {number} dataIndex
  19312. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  19313. */
  19314. getTooltipPosition: null,
  19315. /**
  19316. * @see {module:echarts/stream/Scheduler}
  19317. */
  19318. pipeTask: null,
  19319. /**
  19320. * Convinient for override in extended class.
  19321. * @protected
  19322. * @type {Function}
  19323. */
  19324. preventIncremental: null,
  19325. /**
  19326. * @public
  19327. * @readOnly
  19328. * @type {Object}
  19329. */
  19330. pipelineContext: null
  19331. });
  19332. mixin(SeriesModel, dataFormatMixin);
  19333. mixin(SeriesModel, colorPaletteMixin);
  19334. /**
  19335. * MUST be called after `prepareSource` called
  19336. * Here we need to make auto series, especially for auto legend. But we
  19337. * do not modify series.name in option to avoid side effects.
  19338. */
  19339. function autoSeriesName(seriesModel) {
  19340. // User specified name has higher priority, otherwise it may cause
  19341. // series can not be queried unexpectedly.
  19342. var name = seriesModel.name;
  19343. if (DEFAULT_COMPONENT_NAME === name) {
  19344. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19345. }
  19346. }
  19347. function getSeriesAutoName(seriesModel) {
  19348. var data = seriesModel.getRawData();
  19349. var dataDims = data.mapDimension('seriesName', true);
  19350. var nameArr = [];
  19351. each$1(dataDims, function (dataDim) {
  19352. var dimInfo = data.getDimensionInfo(dataDim);
  19353. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19354. });
  19355. return nameArr.join(' ');
  19356. }
  19357. function dataTaskCount(context) {
  19358. return context.model.getRawData().count();
  19359. }
  19360. function dataTaskReset(context) {
  19361. var seriesModel = context.model;
  19362. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19363. return dataTaskProgress;
  19364. }
  19365. function dataTaskProgress(param, context) {
  19366. // Avoid repead cloneShallow when data just created in reset.
  19367. if (param.end > context.outputData.count()) {
  19368. context.model.getRawData().cloneShallow(context.outputData);
  19369. }
  19370. }
  19371. // TODO refactor
  19372. function wrapData(data, seriesModel) {
  19373. each$1(data.CHANGABLE_METHODS, function (methodName) {
  19374. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  19375. });
  19376. }
  19377. function onDataSelfChange(seriesModel) {
  19378. var task = getCurrentTask(seriesModel);
  19379. if (task) {
  19380. // Consider case: filter, selectRange
  19381. task.setOutputEnd(this.count());
  19382. }
  19383. }
  19384. function getCurrentTask(seriesModel) {
  19385. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19386. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19387. if (pipeline) {
  19388. // When pipline finished, the currrentTask keep the last
  19389. // task (renderTask).
  19390. var task = pipeline.currentTask;
  19391. if (task) {
  19392. var agentStubMap = task.agentStubMap;
  19393. if (agentStubMap) {
  19394. task = agentStubMap.get(seriesModel.uid);
  19395. }
  19396. }
  19397. return task;
  19398. }
  19399. }
  19400. var Component = function () {
  19401. /**
  19402. * @type {module:zrender/container/Group}
  19403. * @readOnly
  19404. */
  19405. this.group = new Group();
  19406. /**
  19407. * @type {string}
  19408. * @readOnly
  19409. */
  19410. this.uid = getUID('viewComponent');
  19411. };
  19412. Component.prototype = {
  19413. constructor: Component,
  19414. init: function (ecModel, api) {},
  19415. render: function (componentModel, ecModel, api, payload) {},
  19416. dispose: function () {}
  19417. };
  19418. var componentProto = Component.prototype;
  19419. componentProto.updateView
  19420. = componentProto.updateLayout
  19421. = componentProto.updateVisual
  19422. = function (seriesModel, ecModel, api, payload) {
  19423. // Do nothing;
  19424. };
  19425. // Enable Component.extend.
  19426. enableClassExtend(Component);
  19427. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19428. enableClassManagement(Component, {registerWhenExtend: true});
  19429. /**
  19430. * @return {string} If large mode changed, return string 'reset';
  19431. */
  19432. var createRenderPlanner = function () {
  19433. var inner = makeInner();
  19434. return function (seriesModel) {
  19435. var fields = inner(seriesModel);
  19436. var pipelineContext = seriesModel.pipelineContext;
  19437. var originalLarge = fields.large;
  19438. var originalIncremental = fields.incrementalRender;
  19439. var large = fields.large = pipelineContext.large;
  19440. var incremental = fields.incrementalRender = pipelineContext.incrementalRender;
  19441. return ((originalLarge ^ large) || (originalIncremental ^ incremental)) && 'reset';
  19442. };
  19443. };
  19444. var inner$5 = makeInner();
  19445. var renderPlanner = createRenderPlanner();
  19446. function Chart() {
  19447. /**
  19448. * @type {module:zrender/container/Group}
  19449. * @readOnly
  19450. */
  19451. this.group = new Group();
  19452. /**
  19453. * @type {string}
  19454. * @readOnly
  19455. */
  19456. this.uid = getUID('viewChart');
  19457. this.renderTask = createTask({
  19458. plan: renderTaskPlan,
  19459. reset: renderTaskReset
  19460. });
  19461. this.renderTask.context = {view: this};
  19462. }
  19463. Chart.prototype = {
  19464. type: 'chart',
  19465. /**
  19466. * Init the chart.
  19467. * @param {module:echarts/model/Global} ecModel
  19468. * @param {module:echarts/ExtensionAPI} api
  19469. */
  19470. init: function (ecModel, api) {},
  19471. /**
  19472. * Render the chart.
  19473. * @param {module:echarts/model/Series} seriesModel
  19474. * @param {module:echarts/model/Global} ecModel
  19475. * @param {module:echarts/ExtensionAPI} api
  19476. * @param {Object} payload
  19477. */
  19478. render: function (seriesModel, ecModel, api, payload) {},
  19479. /**
  19480. * Highlight series or specified data item.
  19481. * @param {module:echarts/model/Series} seriesModel
  19482. * @param {module:echarts/model/Global} ecModel
  19483. * @param {module:echarts/ExtensionAPI} api
  19484. * @param {Object} payload
  19485. */
  19486. highlight: function (seriesModel, ecModel, api, payload) {
  19487. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  19488. },
  19489. /**
  19490. * Downplay series or specified data item.
  19491. * @param {module:echarts/model/Series} seriesModel
  19492. * @param {module:echarts/model/Global} ecModel
  19493. * @param {module:echarts/ExtensionAPI} api
  19494. * @param {Object} payload
  19495. */
  19496. downplay: function (seriesModel, ecModel, api, payload) {
  19497. toggleHighlight(seriesModel.getData(), payload, 'normal');
  19498. },
  19499. /**
  19500. * Remove self.
  19501. * @param {module:echarts/model/Global} ecModel
  19502. * @param {module:echarts/ExtensionAPI} api
  19503. */
  19504. remove: function (ecModel, api) {
  19505. this.group.removeAll();
  19506. },
  19507. /**
  19508. * Dispose self.
  19509. * @param {module:echarts/model/Global} ecModel
  19510. * @param {module:echarts/ExtensionAPI} api
  19511. */
  19512. dispose: function () {},
  19513. /**
  19514. * Rendering preparation in progressive mode.
  19515. * @param {module:echarts/model/Series} seriesModel
  19516. * @param {module:echarts/model/Global} ecModel
  19517. * @param {module:echarts/ExtensionAPI} api
  19518. * @param {Object} payload
  19519. */
  19520. incrementalPrepareRender: null,
  19521. /**
  19522. * Render in progressive mode.
  19523. * @param {module:echarts/model/Series} seriesModel
  19524. * @param {module:echarts/model/Global} ecModel
  19525. * @param {module:echarts/ExtensionAPI} api
  19526. * @param {Object} payload
  19527. */
  19528. incrementalRender: null,
  19529. /**
  19530. * Update transform directly.
  19531. * @param {module:echarts/model/Series} seriesModel
  19532. * @param {module:echarts/model/Global} ecModel
  19533. * @param {module:echarts/ExtensionAPI} api
  19534. * @param {Object} payload
  19535. * @return {Object} {update: true}
  19536. */
  19537. updateTransform: null
  19538. /**
  19539. * The view contains the given point.
  19540. * @interface
  19541. * @param {Array.<number>} point
  19542. * @return {boolean}
  19543. */
  19544. // containPoint: function () {}
  19545. };
  19546. var chartProto = Chart.prototype;
  19547. chartProto.updateView
  19548. = chartProto.updateLayout
  19549. = chartProto.updateVisual
  19550. = function (seriesModel, ecModel, api, payload) {
  19551. this.render(seriesModel, ecModel, api, payload);
  19552. };
  19553. /**
  19554. * Set state of single element
  19555. * @param {module:zrender/Element} el
  19556. * @param {string} state
  19557. */
  19558. function elSetState(el, state) {
  19559. if (el) {
  19560. el.trigger(state);
  19561. if (el.type === 'group') {
  19562. for (var i = 0; i < el.childCount(); i++) {
  19563. elSetState(el.childAt(i), state);
  19564. }
  19565. }
  19566. }
  19567. }
  19568. /**
  19569. * @param {module:echarts/data/List} data
  19570. * @param {Object} payload
  19571. * @param {string} state 'normal'|'emphasis'
  19572. */
  19573. function toggleHighlight(data, payload, state) {
  19574. var dataIndex = queryDataIndex(data, payload);
  19575. if (dataIndex != null) {
  19576. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19577. elSetState(data.getItemGraphicEl(dataIdx), state);
  19578. });
  19579. }
  19580. else {
  19581. data.eachItemGraphicEl(function (el) {
  19582. elSetState(el, state);
  19583. });
  19584. }
  19585. }
  19586. // Enable Chart.extend.
  19587. enableClassExtend(Chart, ['dispose']);
  19588. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19589. enableClassManagement(Chart, {registerWhenExtend: true});
  19590. Chart.markUpdateMethod = function (payload, methodName) {
  19591. inner$5(payload).updateMethod = methodName;
  19592. };
  19593. function renderTaskPlan(context) {
  19594. return renderPlanner(context.model);
  19595. }
  19596. function renderTaskReset(context) {
  19597. var seriesModel = context.model;
  19598. var ecModel = context.ecModel;
  19599. var api = context.api;
  19600. var payload = context.payload;
  19601. // ???! remove updateView updateVisual
  19602. var incremental = seriesModel.pipelineContext.incrementalRender;
  19603. var view = context.view;
  19604. var updateMethod = payload && inner$5(payload).updateMethod;
  19605. var methodName = (incremental && view.incrementalPrepareRender)
  19606. ? 'incrementalPrepareRender'
  19607. : (updateMethod && view[updateMethod])
  19608. ? updateMethod
  19609. : 'render';
  19610. view[methodName](seriesModel, ecModel, api, payload);
  19611. return incremental ? renderTaskProgress : null;
  19612. }
  19613. function renderTaskProgress(params, context) {
  19614. context.view.incrementalRender(
  19615. params, context.model, context.ecModel, context.api, context.payload
  19616. );
  19617. }
  19618. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  19619. var RATE = '\0__throttleRate';
  19620. var THROTTLE_TYPE = '\0__throttleType';
  19621. /**
  19622. * @public
  19623. * @param {(Function)} fn
  19624. * @param {number} [delay=0] Unit: ms.
  19625. * @param {boolean} [debounce=false]
  19626. * true: If call interval less than `delay`, only the last call works.
  19627. * false: If call interval less than `delay, call works on fixed rate.
  19628. * @return {(Function)} throttled fn.
  19629. */
  19630. function throttle(fn, delay, debounce) {
  19631. var currCall;
  19632. var lastCall = 0;
  19633. var lastExec = 0;
  19634. var timer = null;
  19635. var diff;
  19636. var scope;
  19637. var args;
  19638. var debounceNextCall;
  19639. delay = delay || 0;
  19640. function exec() {
  19641. lastExec = (new Date()).getTime();
  19642. timer = null;
  19643. fn.apply(scope, args || []);
  19644. }
  19645. var cb = function () {
  19646. currCall = (new Date()).getTime();
  19647. scope = this;
  19648. args = arguments;
  19649. var thisDelay = debounceNextCall || delay;
  19650. var thisDebounce = debounceNextCall || debounce;
  19651. debounceNextCall = null;
  19652. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19653. clearTimeout(timer);
  19654. if (thisDebounce) {
  19655. timer = setTimeout(exec, thisDelay);
  19656. }
  19657. else {
  19658. if (diff >= 0) {
  19659. exec();
  19660. }
  19661. else {
  19662. timer = setTimeout(exec, -diff);
  19663. }
  19664. }
  19665. lastCall = currCall;
  19666. };
  19667. /**
  19668. * Clear throttle.
  19669. * @public
  19670. */
  19671. cb.clear = function () {
  19672. if (timer) {
  19673. clearTimeout(timer);
  19674. timer = null;
  19675. }
  19676. };
  19677. /**
  19678. * Enable debounce once.
  19679. */
  19680. cb.debounceNextCall = function (debounceDelay) {
  19681. debounceNextCall = debounceDelay;
  19682. };
  19683. return cb;
  19684. }
  19685. /**
  19686. * Create throttle method or update throttle rate.
  19687. *
  19688. * @example
  19689. * ComponentView.prototype.render = function () {
  19690. * ...
  19691. * throttle.createOrUpdate(
  19692. * this,
  19693. * '_dispatchAction',
  19694. * this.model.get('throttle'),
  19695. * 'fixRate'
  19696. * );
  19697. * };
  19698. * ComponentView.prototype.remove = function () {
  19699. * throttle.clear(this, '_dispatchAction');
  19700. * };
  19701. * ComponentView.prototype.dispose = function () {
  19702. * throttle.clear(this, '_dispatchAction');
  19703. * };
  19704. *
  19705. * @public
  19706. * @param {Object} obj
  19707. * @param {string} fnAttr
  19708. * @param {number} [rate]
  19709. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19710. * @return {Function} throttled function.
  19711. */
  19712. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  19713. var fn = obj[fnAttr];
  19714. if (!fn) {
  19715. return;
  19716. }
  19717. var originFn = fn[ORIGIN_METHOD] || fn;
  19718. var lastThrottleType = fn[THROTTLE_TYPE];
  19719. var lastRate = fn[RATE];
  19720. if (lastRate !== rate || lastThrottleType !== throttleType) {
  19721. if (rate == null || !throttleType) {
  19722. return (obj[fnAttr] = originFn);
  19723. }
  19724. fn = obj[fnAttr] = throttle(
  19725. originFn, rate, throttleType === 'debounce'
  19726. );
  19727. fn[ORIGIN_METHOD] = originFn;
  19728. fn[THROTTLE_TYPE] = throttleType;
  19729. fn[RATE] = rate;
  19730. }
  19731. return fn;
  19732. }
  19733. /**
  19734. * Clear throttle. Example see throttle.createOrUpdate.
  19735. *
  19736. * @public
  19737. * @param {Object} obj
  19738. * @param {string} fnAttr
  19739. */
  19740. function clear(obj, fnAttr) {
  19741. var fn = obj[fnAttr];
  19742. if (fn && fn[ORIGIN_METHOD]) {
  19743. obj[fnAttr] = fn[ORIGIN_METHOD];
  19744. }
  19745. }
  19746. var seriesColor = {
  19747. createOnAllSeries: true,
  19748. performRawSeries: true,
  19749. reset: function (seriesModel, ecModel) {
  19750. var data = seriesModel.getData();
  19751. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  19752. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  19753. || seriesModel.getColorFromPalette(
  19754. // TODO series count changed.
  19755. seriesModel.get('name'), null, ecModel.getSeriesCount()
  19756. ); // Default color
  19757. // FIXME Set color function or use the platte color
  19758. data.setVisual('color', color);
  19759. // Only visible series has each data be visual encoded
  19760. if (!ecModel.isSeriesFiltered(seriesModel)) {
  19761. if (typeof color === 'function' && !(color instanceof Gradient)) {
  19762. data.each(function (idx) {
  19763. data.setItemVisual(
  19764. idx, 'color', color(seriesModel.getDataParams(idx))
  19765. );
  19766. });
  19767. }
  19768. // itemStyle in each data item
  19769. var dataEach = function (data, idx) {
  19770. var itemModel = data.getItemModel(idx);
  19771. var color = itemModel.get(colorAccessPath, true);
  19772. if (color != null) {
  19773. data.setItemVisual(idx, 'color', color);
  19774. }
  19775. };
  19776. return { dataEach: data.hasItemOption ? dataEach : null };
  19777. }
  19778. }
  19779. };
  19780. var lang = {
  19781. toolbox: {
  19782. brush: {
  19783. title: {
  19784. rect: 'Box Select',
  19785. polygon: 'Lasso Select',
  19786. lineX: 'Horizontally Select',
  19787. lineY: 'Vertically Select',
  19788. keep: 'Keep Selections',
  19789. clear: 'Clear Selections'
  19790. }
  19791. },
  19792. dataView: {
  19793. title: 'Data View',
  19794. lang: ['Data View', 'Close', 'Refresh']
  19795. },
  19796. dataZoom: {
  19797. title: {
  19798. zoom: 'Zoom',
  19799. back: 'Zoom Reset'
  19800. }
  19801. },
  19802. magicType: {
  19803. title: {
  19804. line: 'Switch to Line Chart',
  19805. bar: 'Switch to Bar Chart',
  19806. stack: 'Stack',
  19807. tiled: 'Tile'
  19808. }
  19809. },
  19810. restore: {
  19811. title: 'Restore'
  19812. },
  19813. saveAsImage: {
  19814. title: 'Save as Image',
  19815. lang: ['Right Click to Save Image']
  19816. }
  19817. }
  19818. };
  19819. var aria = function (dom, ecModel) {
  19820. var ariaModel = ecModel.getModel('aria');
  19821. if (!ariaModel.get('show')) {
  19822. return;
  19823. }
  19824. else if (ariaModel.get('description')) {
  19825. dom.setAttribute('aria-label', ariaModel.get('description'));
  19826. return;
  19827. }
  19828. var seriesCnt = 0;
  19829. ecModel.eachSeries(function (seriesModel, idx) {
  19830. ++seriesCnt;
  19831. }, this);
  19832. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  19833. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  19834. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  19835. var ariaLabel;
  19836. if (seriesCnt < 1) {
  19837. // No series, no aria label
  19838. return;
  19839. }
  19840. else {
  19841. var title = getTitle();
  19842. if (title) {
  19843. ariaLabel = replace(getConfig('general.withTitle'), {
  19844. title: title
  19845. });
  19846. }
  19847. else {
  19848. ariaLabel = getConfig('general.withoutTitle');
  19849. }
  19850. var seriesLabels = [];
  19851. var prefix = seriesCnt > 1
  19852. ? 'series.multiple.prefix'
  19853. : 'series.single.prefix';
  19854. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  19855. ecModel.eachSeries(function (seriesModel, idx) {
  19856. if (idx < displaySeriesCnt) {
  19857. var seriesLabel;
  19858. var seriesName = seriesModel.get('name');
  19859. var seriesTpl = 'series.'
  19860. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  19861. seriesLabel = getConfig(seriesName
  19862. ? seriesTpl + 'withName'
  19863. : seriesTpl + 'withoutName');
  19864. seriesLabel = replace(seriesLabel, {
  19865. seriesId: seriesModel.seriesIndex,
  19866. seriesName: seriesModel.get('name'),
  19867. seriesType: getSeriesTypeName(seriesModel.subType)
  19868. });
  19869. var data = seriesModel.getData();
  19870. window.data = data;
  19871. if (data.count() > maxDataCnt) {
  19872. // Show part of data
  19873. seriesLabel += replace(getConfig('data.partialData'), {
  19874. displayCnt: maxDataCnt
  19875. });
  19876. }
  19877. else {
  19878. seriesLabel += getConfig('data.allData');
  19879. }
  19880. var dataLabels = [];
  19881. for (var i = 0; i < data.count(); i++) {
  19882. if (i < maxDataCnt) {
  19883. var name = data.getName(i);
  19884. var value = retrieveRawValue(data, i);
  19885. dataLabels.push(
  19886. replace(
  19887. name
  19888. ? getConfig('data.withName')
  19889. : getConfig('data.withoutName'),
  19890. {
  19891. name: name,
  19892. value: value
  19893. }
  19894. )
  19895. );
  19896. }
  19897. }
  19898. seriesLabel += dataLabels
  19899. .join(getConfig('data.separator.middle'))
  19900. + getConfig('data.separator.end');
  19901. seriesLabels.push(seriesLabel);
  19902. }
  19903. });
  19904. ariaLabel += seriesLabels
  19905. .join(getConfig('series.multiple.separator.middle'))
  19906. + getConfig('series.multiple.separator.end');
  19907. dom.setAttribute('aria-label', ariaLabel);
  19908. }
  19909. function replace(str, keyValues) {
  19910. if (typeof str !== 'string') {
  19911. return str;
  19912. }
  19913. var result = str;
  19914. each$1(keyValues, function (value, key) {
  19915. result = result.replace(
  19916. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  19917. value
  19918. );
  19919. });
  19920. return result;
  19921. }
  19922. function getConfig(path) {
  19923. var userConfig = ariaModel.get(path);
  19924. if (userConfig == null) {
  19925. var pathArr = path.split('.');
  19926. var result = lang.aria;
  19927. for (var i = 0; i < pathArr.length; ++i) {
  19928. result = result[pathArr[i]];
  19929. }
  19930. return result;
  19931. }
  19932. else {
  19933. return userConfig;
  19934. }
  19935. }
  19936. function getTitle() {
  19937. var title = ecModel.getModel('title').option;
  19938. if (title && title.length) {
  19939. title = title[0];
  19940. }
  19941. return title && title.text;
  19942. }
  19943. function getSeriesTypeName(type) {
  19944. return lang.series.typeNames[type] || '自定义图';
  19945. }
  19946. };
  19947. var PI$1 = Math.PI;
  19948. /**
  19949. * @param {module:echarts/ExtensionAPI} api
  19950. * @param {Object} [opts]
  19951. * @param {string} [opts.text]
  19952. * @param {string} [opts.color]
  19953. * @param {string} [opts.textColor]
  19954. * @return {module:zrender/Element}
  19955. */
  19956. var loadingDefault = function (api, opts) {
  19957. opts = opts || {};
  19958. defaults(opts, {
  19959. text: 'loading',
  19960. color: '#c23531',
  19961. textColor: '#000',
  19962. maskColor: 'rgba(255, 255, 255, 0.8)',
  19963. zlevel: 0
  19964. });
  19965. var mask = new Rect({
  19966. style: {
  19967. fill: opts.maskColor
  19968. },
  19969. zlevel: opts.zlevel,
  19970. z: 10000
  19971. });
  19972. var arc = new Arc({
  19973. shape: {
  19974. startAngle: -PI$1 / 2,
  19975. endAngle: -PI$1 / 2 + 0.1,
  19976. r: 10
  19977. },
  19978. style: {
  19979. stroke: opts.color,
  19980. lineCap: 'round',
  19981. lineWidth: 5
  19982. },
  19983. zlevel: opts.zlevel,
  19984. z: 10001
  19985. });
  19986. var labelRect = new Rect({
  19987. style: {
  19988. fill: 'none',
  19989. text: opts.text,
  19990. textPosition: 'right',
  19991. textDistance: 10,
  19992. textFill: opts.textColor
  19993. },
  19994. zlevel: opts.zlevel,
  19995. z: 10001
  19996. });
  19997. arc.animateShape(true)
  19998. .when(1000, {
  19999. endAngle: PI$1 * 3 / 2
  20000. })
  20001. .start('circularInOut');
  20002. arc.animateShape(true)
  20003. .when(1000, {
  20004. startAngle: PI$1 * 3 / 2
  20005. })
  20006. .delay(300)
  20007. .start('circularInOut');
  20008. var group = new Group();
  20009. group.add(arc);
  20010. group.add(labelRect);
  20011. group.add(mask);
  20012. // Inject resize
  20013. group.resize = function () {
  20014. var cx = api.getWidth() / 2;
  20015. var cy = api.getHeight() / 2;
  20016. arc.setShape({
  20017. cx: cx,
  20018. cy: cy
  20019. });
  20020. var r = arc.shape.r;
  20021. labelRect.setShape({
  20022. x: cx - r,
  20023. y: cy - r,
  20024. width: r * 2,
  20025. height: r * 2
  20026. });
  20027. mask.setShape({
  20028. x: 0,
  20029. y: 0,
  20030. width: api.getWidth(),
  20031. height: api.getHeight()
  20032. });
  20033. };
  20034. group.resize();
  20035. return group;
  20036. };
  20037. /**
  20038. * @module echarts/stream/Scheduler
  20039. */
  20040. /**
  20041. * @constructor
  20042. */
  20043. function Scheduler(ecInstance, api) {
  20044. // this._pipelineMap = createHashMap();
  20045. this.ecInstance = ecInstance;
  20046. this.api = api;
  20047. this.unfinished;
  20048. /**
  20049. * @private
  20050. * @type {
  20051. * [handlerUID: string]: {
  20052. * seriesTaskMap?: {
  20053. * [seriesUID: string]: Task
  20054. * },
  20055. * overallTask?: Task
  20056. * }
  20057. * }
  20058. */
  20059. this._stageTaskMap = createHashMap();
  20060. }
  20061. var proto = Scheduler.prototype;
  20062. // If seriesModel provided, incremental threshold is check by series data.
  20063. proto.getPerformArgs = function (task, isBlock) {
  20064. // For overall task
  20065. if (!task.__pipeline) {
  20066. return;
  20067. }
  20068. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20069. var pCtx = pipeline.context;
  20070. var incremental = !isBlock
  20071. && pipeline.progressiveEnabled
  20072. && (!pCtx || pCtx.incrementalRender)
  20073. && task.__idxInPipeline > pipeline.bockIndex;
  20074. return {step: incremental ? pipeline.step : null};
  20075. };
  20076. proto.getPipeline = function (pipelineId) {
  20077. return this._pipelineMap.get(pipelineId);
  20078. };
  20079. /**
  20080. * Current, progressive rendering starts from visual and layout.
  20081. * Always detect render mode in the same stage, avoiding that incorrect
  20082. * detection caused by data filtering.
  20083. * Caution:
  20084. * `updateStreamModes` use `seriesModel.getData()`.
  20085. */
  20086. proto.updateStreamModes = function (seriesModel, view) {
  20087. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20088. var data = seriesModel.getData();
  20089. var dataLen = data.count();
  20090. var incrementalRender = pipeline.progressiveEnabled
  20091. && view.incrementalPrepareRender
  20092. && dataLen >= pipeline.threshold;
  20093. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20094. seriesModel.pipelineContext = pipeline.context = {
  20095. incrementalRender: incrementalRender,
  20096. large: large
  20097. };
  20098. };
  20099. proto.restorePipelines = function (ecModel) {
  20100. var scheduler = this;
  20101. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20102. ecModel.eachSeries(function (seriesModel) {
  20103. var progressive = seriesModel.getProgressive();
  20104. var pipelineId = seriesModel.uid;
  20105. pipelineMap.set(pipelineId, {
  20106. id: pipelineId,
  20107. head: null,
  20108. tail: null,
  20109. threshold: seriesModel.getProgressiveThreshold(),
  20110. progressiveEnabled: progressive
  20111. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20112. bockIndex: -1,
  20113. step: progressive || 700, // ??? Temporarily number
  20114. count: 0
  20115. });
  20116. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20117. });
  20118. };
  20119. proto.prepareStageTasks = function (stageHandlers, useClearVisual) {
  20120. var stageTaskMap = this._stageTaskMap;
  20121. var ecModel = this.ecInstance.getModel();
  20122. var api = this.api;
  20123. each$1(stageHandlers, function (handler) {
  20124. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20125. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20126. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20127. }, this);
  20128. };
  20129. proto.prepareView = function (view, model, ecModel, api) {
  20130. var renderTask = view.renderTask;
  20131. var context = renderTask.context;
  20132. context.model = model;
  20133. context.ecModel = ecModel;
  20134. context.api = api;
  20135. renderTask.__block = !view.incrementalPrepareRender;
  20136. pipe(this, model, renderTask);
  20137. };
  20138. proto.performDataProcessorTasks = function (stageHandlers, ecModel, payload) {
  20139. // If we do not use `block` here, it should be considered when to update modes.
  20140. performStageTasks(this, stageHandlers, ecModel, payload, {block: true});
  20141. };
  20142. // opt
  20143. // opt.visualType: 'visual' or 'layout'
  20144. // opt.setDirty
  20145. proto.performVisualTasks = function (stageHandlers, ecModel, payload, opt) {
  20146. performStageTasks(this, stageHandlers, ecModel, payload, opt);
  20147. };
  20148. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20149. opt = opt || {};
  20150. var unfinished;
  20151. each$1(stageHandlers, function (stageHandler, idx) {
  20152. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20153. return;
  20154. }
  20155. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20156. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20157. var overallTask = stageHandlerRecord.overallTask;
  20158. if (overallTask) {
  20159. var overallNeedDirty;
  20160. var agentStubMap = overallTask.agentStubMap;
  20161. agentStubMap.each(function (stub) {
  20162. if (needSetDirty(opt, stub)) {
  20163. stub.dirty();
  20164. overallNeedDirty = true;
  20165. }
  20166. });
  20167. overallNeedDirty && overallTask.dirty();
  20168. updatePayload(overallTask, payload);
  20169. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20170. // Execute stubs firstly, which may set the overall task dirty,
  20171. // then execute the overall task. And stub will call seriesModel.setData,
  20172. // which ensures that in the overallTask seriesModel.getData() will not
  20173. // return incorrect data.
  20174. agentStubMap.each(function (stub) {
  20175. stub.perform(performArgs);
  20176. });
  20177. unfinished |= overallTask.perform(performArgs);
  20178. }
  20179. else if (seriesTaskMap) {
  20180. seriesTaskMap.each(function (task, pipelineId) {
  20181. if (needSetDirty(opt, task)) {
  20182. task.dirty();
  20183. }
  20184. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20185. performArgs.skip = !stageHandler.performRawSeries
  20186. && ecModel.isSeriesFiltered(task.context.model);
  20187. updatePayload(task, payload);
  20188. unfinished |= task.perform(performArgs);
  20189. });
  20190. }
  20191. });
  20192. function needSetDirty(opt, task) {
  20193. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20194. }
  20195. scheduler.unfinished |= unfinished;
  20196. }
  20197. proto.performSeriesTasks = function (ecModel) {
  20198. var unfinished;
  20199. ecModel.eachSeries(function (seriesModel) {
  20200. // Progress to the end for dataInit and dataRestore.
  20201. unfinished |= seriesModel.dataTask.perform();
  20202. });
  20203. this.unfinished |= unfinished;
  20204. };
  20205. proto.plan = function () {
  20206. // Travel pipelines, check block.
  20207. this._pipelineMap.each(function (pipeline) {
  20208. var task = pipeline.tail;
  20209. do {
  20210. if (task.__block) {
  20211. pipeline.bockIndex = task.__idxInPipeline;
  20212. break;
  20213. }
  20214. task = task.getUpstream();
  20215. }
  20216. while (task);
  20217. });
  20218. };
  20219. var updatePayload = proto.updatePayload = function (task, payload) {
  20220. payload !== 'remain' && (task.context.payload = payload);
  20221. };
  20222. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20223. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20224. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20225. var seriesType = stageHandler.seriesType;
  20226. var getTargetSeries = stageHandler.getTargetSeries;
  20227. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20228. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20229. // it works but it may cause other irrelevant charts blocked.
  20230. if (stageHandler.createOnAllSeries) {
  20231. ecModel.eachRawSeries(create);
  20232. }
  20233. else if (seriesType) {
  20234. ecModel.eachRawSeriesByType(seriesType, create);
  20235. }
  20236. else if (getTargetSeries) {
  20237. getTargetSeries(ecModel, api).each(create);
  20238. }
  20239. function create(seriesModel) {
  20240. var pipelineId = seriesModel.uid;
  20241. // Init tasks for each seriesModel only once.
  20242. // Reuse original task instance.
  20243. var task = seriesTaskMap.get(pipelineId)
  20244. || seriesTaskMap.set(pipelineId, createTask({
  20245. plan: seriesTaskPlan,
  20246. reset: seriesTaskReset,
  20247. count: seriesTaskCount
  20248. }));
  20249. task.context = {
  20250. model: seriesModel,
  20251. ecModel: ecModel,
  20252. api: api,
  20253. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20254. plan: stageHandler.plan,
  20255. reset: stageHandler.reset,
  20256. scheduler: scheduler
  20257. };
  20258. pipe(scheduler, seriesModel, task);
  20259. }
  20260. // Clear unused series tasks.
  20261. var pipelineMap = scheduler._pipelineMap;
  20262. seriesTaskMap.each(function (task, pipelineId) {
  20263. if (!pipelineMap.get(pipelineId)) {
  20264. task.dispose();
  20265. seriesTaskMap.removeKey(pipelineId);
  20266. }
  20267. });
  20268. }
  20269. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20270. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20271. // For overall task, the function only be called on reset stage.
  20272. || createTask({reset: overallTaskReset});
  20273. overallTask.context = {
  20274. ecModel: ecModel,
  20275. api: api,
  20276. overallReset: stageHandler.overallReset,
  20277. scheduler: scheduler
  20278. };
  20279. // Reuse orignal stubs.
  20280. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20281. var seriesType = stageHandler.seriesType;
  20282. var getTargetSeries = stageHandler.getTargetSeries;
  20283. var overallProgress = true;
  20284. var isOverallFilter = stageHandler.isOverallFilter;
  20285. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20286. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20287. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20288. // we set the pipeline block.
  20289. if (seriesType) {
  20290. ecModel.eachRawSeriesByType(seriesType, createStub);
  20291. }
  20292. else if (getTargetSeries) {
  20293. getTargetSeries(ecModel, api).each(createStub);
  20294. }
  20295. // Otherwise, (usually it is legancy case), the overall task will only be
  20296. // executed when upstream dirty. Otherwise the progressive rendering of all
  20297. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20298. // dirty info from upsteam.
  20299. else {
  20300. overallProgress = false;
  20301. each$1(ecModel.getSeries(), createStub);
  20302. }
  20303. function createStub(seriesModel) {
  20304. var pipelineId = seriesModel.uid;
  20305. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20306. {reset: stubReset, onDirty: stubOnDirty}
  20307. ));
  20308. stub.context = {
  20309. model: seriesModel,
  20310. overallProgress: overallProgress,
  20311. isOverallFilter: isOverallFilter
  20312. };
  20313. stub.agent = overallTask;
  20314. stub.__block = overallProgress;
  20315. pipe(scheduler, seriesModel, stub);
  20316. }
  20317. // Clear unused stubs.
  20318. var pipelineMap = scheduler._pipelineMap;
  20319. agentStubMap.each(function (stub, pipelineId) {
  20320. if (!pipelineMap.get(pipelineId)) {
  20321. stub.dispose();
  20322. agentStubMap.removeKey(pipelineId);
  20323. }
  20324. });
  20325. }
  20326. function overallTaskReset(context) {
  20327. context.overallReset(
  20328. context.ecModel, context.api, context.payload
  20329. );
  20330. }
  20331. function stubReset(context, upstreamContext) {
  20332. return context.overallProgress && stubProgress;
  20333. }
  20334. function stubProgress() {
  20335. this.agent.dirty();
  20336. this.getDownstream().dirty();
  20337. }
  20338. function stubOnDirty() {
  20339. this.agent && this.agent.dirty();
  20340. }
  20341. function seriesTaskPlan(context) {
  20342. return context.plan && context.plan(
  20343. context.model, context.ecModel, context.api, context.payload
  20344. );
  20345. }
  20346. function seriesTaskReset(context) {
  20347. if (context.useClearVisual) {
  20348. context.data.clearAllVisual();
  20349. }
  20350. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20351. context.model, context.ecModel, context.api, context.payload
  20352. ));
  20353. if (resetDefines.length) {
  20354. return seriesTaskProgress;
  20355. }
  20356. }
  20357. function seriesTaskProgress(params, context) {
  20358. var data = context.data;
  20359. var resetDefines = context.resetDefines;
  20360. for (var k = 0; k < resetDefines.length; k++) {
  20361. var resetDefine = resetDefines[k];
  20362. if (resetDefine && resetDefine.dataEach) {
  20363. for (var i = params.start; i < params.end; i++) {
  20364. resetDefine.dataEach(data, i);
  20365. }
  20366. }
  20367. else if (resetDefine && resetDefine.progress) {
  20368. resetDefine.progress(params, data);
  20369. }
  20370. }
  20371. }
  20372. function seriesTaskCount(context) {
  20373. return context.data.count();
  20374. }
  20375. function pipe(scheduler, seriesModel, task) {
  20376. var pipelineId = seriesModel.uid;
  20377. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20378. !pipeline.head && (pipeline.head = task);
  20379. pipeline.tail && pipeline.tail.pipe(task);
  20380. pipeline.tail = task;
  20381. task.__idxInPipeline = pipeline.count++;
  20382. task.__pipeline = pipeline;
  20383. }
  20384. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20385. if (isFunction$1(stageHandler)) {
  20386. stageHandler = {
  20387. overallReset: stageHandler,
  20388. seriesType: detectSeriseType(stageHandler)
  20389. };
  20390. }
  20391. stageHandler.uid = getUID('stageHandler');
  20392. visualType && (stageHandler.visualType = visualType);
  20393. return stageHandler;
  20394. };
  20395. /**
  20396. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20397. * To ensure that they can work normally, they should work in block mode, that is,
  20398. * they should not be started util the previous tasks finished. So they cause the
  20399. * progressive rendering disabled. We try to detect the series type, to narrow down
  20400. * the block range to only the series type they concern, but not all series.
  20401. */
  20402. function detectSeriseType(legacyFunc) {
  20403. seriesType = null;
  20404. try {
  20405. // Assume there is no async when calling `eachSeriesByType`.
  20406. legacyFunc(ecModelMock, apiMock);
  20407. }
  20408. catch (e) {
  20409. }
  20410. return seriesType;
  20411. }
  20412. var ecModelMock = {};
  20413. var apiMock = {};
  20414. var seriesType;
  20415. mockMethods(ecModelMock, GlobalModel);
  20416. mockMethods(apiMock, ExtensionAPI);
  20417. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20418. seriesType = type;
  20419. };
  20420. ecModelMock.eachComponent = function (cond) {
  20421. if (cond.mainType === 'series' && cond.subType) {
  20422. seriesType = cond.subType;
  20423. }
  20424. };
  20425. function mockMethods(target, Clz) {
  20426. for (var name in Clz.prototype) {
  20427. // Do not use hasOwnProperty
  20428. target[name] = noop;
  20429. }
  20430. }
  20431. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20432. var lightTheme = {
  20433. color: colorAll,
  20434. colorLayer: [
  20435. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20436. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20437. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20438. colorAll
  20439. ]
  20440. };
  20441. var contrastColor = '#eee';
  20442. var axisCommon = function () {
  20443. return {
  20444. axisLine: {
  20445. lineStyle: {
  20446. color: contrastColor
  20447. }
  20448. },
  20449. axisTick: {
  20450. lineStyle: {
  20451. color: contrastColor
  20452. }
  20453. },
  20454. axisLabel: {
  20455. textStyle: {
  20456. color: contrastColor
  20457. }
  20458. },
  20459. splitLine: {
  20460. lineStyle: {
  20461. type: 'dashed',
  20462. color: '#aaa'
  20463. }
  20464. },
  20465. splitArea: {
  20466. areaStyle: {
  20467. color: contrastColor
  20468. }
  20469. }
  20470. };
  20471. };
  20472. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20473. var theme = {
  20474. color: colorPalette,
  20475. backgroundColor: '#333',
  20476. tooltip: {
  20477. axisPointer: {
  20478. lineStyle: {
  20479. color: contrastColor
  20480. },
  20481. crossStyle: {
  20482. color: contrastColor
  20483. }
  20484. }
  20485. },
  20486. legend: {
  20487. textStyle: {
  20488. color: contrastColor
  20489. }
  20490. },
  20491. textStyle: {
  20492. color: contrastColor
  20493. },
  20494. title: {
  20495. textStyle: {
  20496. color: contrastColor
  20497. }
  20498. },
  20499. toolbox: {
  20500. iconStyle: {
  20501. normal: {
  20502. borderColor: contrastColor
  20503. }
  20504. }
  20505. },
  20506. dataZoom: {
  20507. textStyle: {
  20508. color: contrastColor
  20509. }
  20510. },
  20511. visualMap: {
  20512. textStyle: {
  20513. color: contrastColor
  20514. }
  20515. },
  20516. timeline: {
  20517. lineStyle: {
  20518. color: contrastColor
  20519. },
  20520. itemStyle: {
  20521. normal: {
  20522. color: colorPalette[1]
  20523. }
  20524. },
  20525. label: {
  20526. normal: {
  20527. textStyle: {
  20528. color: contrastColor
  20529. }
  20530. }
  20531. },
  20532. controlStyle: {
  20533. normal: {
  20534. color: contrastColor,
  20535. borderColor: contrastColor
  20536. }
  20537. }
  20538. },
  20539. timeAxis: axisCommon(),
  20540. logAxis: axisCommon(),
  20541. valueAxis: axisCommon(),
  20542. categoryAxis: axisCommon(),
  20543. line: {
  20544. symbol: 'circle'
  20545. },
  20546. graph: {
  20547. color: colorPalette
  20548. },
  20549. gauge: {
  20550. title: {
  20551. textStyle: {
  20552. color: contrastColor
  20553. }
  20554. }
  20555. },
  20556. candlestick: {
  20557. itemStyle: {
  20558. normal: {
  20559. color: '#FD1050',
  20560. color0: '#0CF49B',
  20561. borderColor: '#FD1050',
  20562. borderColor0: '#0CF49B'
  20563. }
  20564. }
  20565. }
  20566. };
  20567. theme.categoryAxis.splitLine.show = false;
  20568. /*!
  20569. * ECharts, a free, powerful charting and visualization library.
  20570. *
  20571. * Copyright (c) 2017, Baidu Inc.
  20572. * All rights reserved.
  20573. *
  20574. * LICENSE
  20575. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20576. */
  20577. var assert = assert$1;
  20578. var each = each$1;
  20579. var isFunction = isFunction$1;
  20580. var isObject = isObject$1;
  20581. var parseClassType = ComponentModel.parseClassType;
  20582. var version = '4.0.2';
  20583. var dependencies = {
  20584. zrender: '4.0.1'
  20585. };
  20586. var TEST_FRAME_REMAIN_TIME = 1;
  20587. var PRIORITY_PROCESSOR_FILTER = 1000;
  20588. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20589. var PRIORITY_VISUAL_LAYOUT = 1000;
  20590. var PRIORITY_VISUAL_GLOBAL = 2000;
  20591. var PRIORITY_VISUAL_CHART = 3000;
  20592. var PRIORITY_VISUAL_COMPONENT = 4000;
  20593. // FIXME
  20594. // necessary?
  20595. var PRIORITY_VISUAL_BRUSH = 5000;
  20596. var PRIORITY = {
  20597. PROCESSOR: {
  20598. FILTER: PRIORITY_PROCESSOR_FILTER,
  20599. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20600. },
  20601. VISUAL: {
  20602. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20603. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20604. CHART: PRIORITY_VISUAL_CHART,
  20605. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20606. BRUSH: PRIORITY_VISUAL_BRUSH
  20607. }
  20608. };
  20609. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20610. // where they must not be invoked nestedly, except the only case: invoke
  20611. // dispatchAction with updateMethod "none" in main process.
  20612. // This flag is used to carry out this rule.
  20613. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20614. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20615. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  20616. var OPTION_UPDATED = '__optionUpdated';
  20617. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20618. function createRegisterEventWithLowercaseName(method) {
  20619. return function (eventName, handler, context) {
  20620. // Event name is all lowercase
  20621. eventName = eventName && eventName.toLowerCase();
  20622. Eventful.prototype[method].call(this, eventName, handler, context);
  20623. };
  20624. }
  20625. /**
  20626. * @module echarts~MessageCenter
  20627. */
  20628. function MessageCenter() {
  20629. Eventful.call(this);
  20630. }
  20631. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20632. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20633. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20634. mixin(MessageCenter, Eventful);
  20635. /**
  20636. * @module echarts~ECharts
  20637. */
  20638. function ECharts(dom, theme$$1, opts) {
  20639. opts = opts || {};
  20640. // Get theme by name
  20641. if (typeof theme$$1 === 'string') {
  20642. theme$$1 = themeStorage[theme$$1];
  20643. }
  20644. /**
  20645. * @type {string}
  20646. */
  20647. this.id;
  20648. /**
  20649. * Group id
  20650. * @type {string}
  20651. */
  20652. this.group;
  20653. /**
  20654. * @type {HTMLElement}
  20655. * @private
  20656. */
  20657. this._dom = dom;
  20658. var defaultRenderer = 'canvas';
  20659. if (__DEV__) {
  20660. defaultRenderer = (
  20661. typeof window === 'undefined' ? global : window
  20662. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20663. }
  20664. /**
  20665. * @type {module:zrender/ZRender}
  20666. * @private
  20667. */
  20668. var zr = this._zr = init$1(dom, {
  20669. renderer: opts.renderer || defaultRenderer,
  20670. devicePixelRatio: opts.devicePixelRatio,
  20671. width: opts.width,
  20672. height: opts.height
  20673. });
  20674. /**
  20675. * Expect 60 pfs.
  20676. * @type {Function}
  20677. * @private
  20678. */
  20679. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20680. var theme$$1 = clone(theme$$1);
  20681. theme$$1 && backwardCompat(theme$$1, true);
  20682. /**
  20683. * @type {Object}
  20684. * @private
  20685. */
  20686. this._theme = theme$$1;
  20687. /**
  20688. * @type {Array.<module:echarts/view/Chart>}
  20689. * @private
  20690. */
  20691. this._chartsViews = [];
  20692. /**
  20693. * @type {Object.<string, module:echarts/view/Chart>}
  20694. * @private
  20695. */
  20696. this._chartsMap = {};
  20697. /**
  20698. * @type {Array.<module:echarts/view/Component>}
  20699. * @private
  20700. */
  20701. this._componentsViews = [];
  20702. /**
  20703. * @type {Object.<string, module:echarts/view/Component>}
  20704. * @private
  20705. */
  20706. this._componentsMap = {};
  20707. /**
  20708. * @type {module:echarts/CoordinateSystem}
  20709. * @private
  20710. */
  20711. this._coordSysMgr = new CoordinateSystemManager();
  20712. /**
  20713. * @type {module:echarts/ExtensionAPI}
  20714. * @private
  20715. */
  20716. var api = this._api = createExtensionAPI(this);
  20717. /**
  20718. * @type {module:echarts/stream/Scheduler}
  20719. */
  20720. this._scheduler = new Scheduler(this, api);
  20721. Eventful.call(this);
  20722. /**
  20723. * @type {module:echarts~MessageCenter}
  20724. * @private
  20725. */
  20726. this._messageCenter = new MessageCenter();
  20727. // this._scheduler = new Scheduler();
  20728. // Init mouse events
  20729. this._initEvents();
  20730. // In case some people write `window.onresize = chart.resize`
  20731. this.resize = bind(this.resize, this);
  20732. // Can't dispatch action during rendering procedure
  20733. this._pendingActions = [];
  20734. // Sort on demand
  20735. function prioritySortFunc(a, b) {
  20736. return a.__prio - b.__prio;
  20737. }
  20738. sort(visualFuncs, prioritySortFunc);
  20739. sort(dataProcessorFuncs, prioritySortFunc);
  20740. zr.animation.on('frame', this._onframe, this);
  20741. // ECharts instance can be used as value.
  20742. setAsPrimitive(this);
  20743. }
  20744. var echartsProto = ECharts.prototype;
  20745. echartsProto._onframe = function () {
  20746. if (this._disposed) {
  20747. return;
  20748. }
  20749. var scheduler = this._scheduler;
  20750. // Lazy update
  20751. if (this[OPTION_UPDATED]) {
  20752. var silent = this[OPTION_UPDATED].silent;
  20753. this[IN_MAIN_PROCESS] = true;
  20754. prepare(this);
  20755. updateMethods.update.call(this);
  20756. this[IN_MAIN_PROCESS] = false;
  20757. this[OPTION_UPDATED] = false;
  20758. flushPendingActions.call(this, silent);
  20759. triggerUpdatedEvent.call(this, silent);
  20760. }
  20761. // Avoid do both lazy update and progress in one frame.
  20762. else if (scheduler.unfinished) {
  20763. // Stream progress.
  20764. var remainTime = TEST_FRAME_REMAIN_TIME;
  20765. var ecModel = this._model;
  20766. var api = this._api;
  20767. scheduler.unfinished = false;
  20768. do {
  20769. var startTime = +new Date();
  20770. scheduler.performSeriesTasks(ecModel);
  20771. // Currently dataProcessorFuncs do not check threshold.
  20772. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel);
  20773. updateStreamModes(this, ecModel);
  20774. // Do not update coordinate system here. Because that coord system update in
  20775. // each frame is not a good user experience. So we follow the rule that
  20776. // the extent of the coordinate system is determin in the first frame (the
  20777. // frame is executed immedietely after task reset.
  20778. // this._coordSysMgr.update(ecModel, api);
  20779. // console.log('--- ec frame visual ---', remainTime);
  20780. scheduler.performVisualTasks(visualFuncs, ecModel);
  20781. renderSeries(this, this._model, api, 'remain');
  20782. remainTime -= (+new Date() - startTime);
  20783. }
  20784. while (remainTime > 0 && scheduler.unfinished);
  20785. if (!scheduler.unfinished) {
  20786. this._zr && this._zr.flush();
  20787. this.trigger('finished');
  20788. }
  20789. // Else, zr flushing be ensue within the same frame,
  20790. // because zr flushing is after onframe event.
  20791. }
  20792. };
  20793. /**
  20794. * @return {HTMLElement}
  20795. */
  20796. echartsProto.getDom = function () {
  20797. return this._dom;
  20798. };
  20799. /**
  20800. * @return {module:zrender~ZRender}
  20801. */
  20802. echartsProto.getZr = function () {
  20803. return this._zr;
  20804. };
  20805. /**
  20806. * Usage:
  20807. * chart.setOption(option, notMerge, lazyUpdate);
  20808. * chart.setOption(option, {
  20809. * notMerge: ...,
  20810. * lazyUpdate: ...,
  20811. * silent: ...
  20812. * });
  20813. *
  20814. * @param {Object} option
  20815. * @param {Object|boolean} [opts] opts or notMerge.
  20816. * @param {boolean} [opts.notMerge=false]
  20817. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  20818. */
  20819. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  20820. if (__DEV__) {
  20821. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  20822. }
  20823. var silent;
  20824. if (isObject(notMerge)) {
  20825. lazyUpdate = notMerge.lazyUpdate;
  20826. silent = notMerge.silent;
  20827. notMerge = notMerge.notMerge;
  20828. }
  20829. this[IN_MAIN_PROCESS] = true;
  20830. if (!this._model || notMerge) {
  20831. var optionManager = new OptionManager(this._api);
  20832. var theme$$1 = this._theme;
  20833. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  20834. ecModel.scheduler = this._scheduler;
  20835. ecModel.init(null, null, theme$$1, optionManager);
  20836. }
  20837. this._model.setOption(option, optionPreprocessorFuncs);
  20838. if (lazyUpdate) {
  20839. this[OPTION_UPDATED] = {silent: silent};
  20840. this[IN_MAIN_PROCESS] = false;
  20841. }
  20842. else {
  20843. prepare(this);
  20844. updateMethods.update.call(this);
  20845. // Ensure zr refresh sychronously, and then pixel in canvas can be
  20846. // fetched after `setOption`.
  20847. this._zr.flush();
  20848. this[OPTION_UPDATED] = false;
  20849. this[IN_MAIN_PROCESS] = false;
  20850. flushPendingActions.call(this, silent);
  20851. triggerUpdatedEvent.call(this, silent);
  20852. }
  20853. };
  20854. /**
  20855. * @DEPRECATED
  20856. */
  20857. echartsProto.setTheme = function () {
  20858. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  20859. };
  20860. /**
  20861. * @return {module:echarts/model/Global}
  20862. */
  20863. echartsProto.getModel = function () {
  20864. return this._model;
  20865. };
  20866. /**
  20867. * @return {Object}
  20868. */
  20869. echartsProto.getOption = function () {
  20870. return this._model && this._model.getOption();
  20871. };
  20872. /**
  20873. * @return {number}
  20874. */
  20875. echartsProto.getWidth = function () {
  20876. return this._zr.getWidth();
  20877. };
  20878. /**
  20879. * @return {number}
  20880. */
  20881. echartsProto.getHeight = function () {
  20882. return this._zr.getHeight();
  20883. };
  20884. /**
  20885. * @return {number}
  20886. */
  20887. echartsProto.getDevicePixelRatio = function () {
  20888. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  20889. };
  20890. /**
  20891. * Get canvas which has all thing rendered
  20892. * @param {Object} opts
  20893. * @param {string} [opts.backgroundColor]
  20894. * @return {string}
  20895. */
  20896. echartsProto.getRenderedCanvas = function (opts) {
  20897. if (!env$1.canvasSupported) {
  20898. return;
  20899. }
  20900. opts = opts || {};
  20901. opts.pixelRatio = opts.pixelRatio || 1;
  20902. opts.backgroundColor = opts.backgroundColor
  20903. || this._model.get('backgroundColor');
  20904. var zr = this._zr;
  20905. var list = zr.storage.getDisplayList();
  20906. // Stop animations
  20907. each$1(list, function (el) {
  20908. el.stopAnimation(true);
  20909. });
  20910. return zr.painter.getRenderedCanvas(opts);
  20911. };
  20912. /**
  20913. * Get svg data url
  20914. * @return {string}
  20915. */
  20916. echartsProto.getSvgDataUrl = function () {
  20917. if (!env$1.svgSupported) {
  20918. return;
  20919. }
  20920. var zr = this._zr;
  20921. var list = zr.storage.getDisplayList();
  20922. // Stop animations
  20923. each$1(list, function (el) {
  20924. el.stopAnimation(true);
  20925. });
  20926. return zr.painter.pathToSvg();
  20927. };
  20928. /**
  20929. * @return {string}
  20930. * @param {Object} opts
  20931. * @param {string} [opts.type='png']
  20932. * @param {string} [opts.pixelRatio=1]
  20933. * @param {string} [opts.backgroundColor]
  20934. * @param {string} [opts.excludeComponents]
  20935. */
  20936. echartsProto.getDataURL = function (opts) {
  20937. opts = opts || {};
  20938. var excludeComponents = opts.excludeComponents;
  20939. var ecModel = this._model;
  20940. var excludesComponentViews = [];
  20941. var self = this;
  20942. each(excludeComponents, function (componentType) {
  20943. ecModel.eachComponent({
  20944. mainType: componentType
  20945. }, function (component) {
  20946. var view = self._componentsMap[component.__viewId];
  20947. if (!view.group.ignore) {
  20948. excludesComponentViews.push(view);
  20949. view.group.ignore = true;
  20950. }
  20951. });
  20952. });
  20953. var url = this._zr.painter.getType() === 'svg'
  20954. ? this.getSvgDataUrl()
  20955. : this.getRenderedCanvas(opts).toDataURL(
  20956. 'image/' + (opts && opts.type || 'png')
  20957. );
  20958. each(excludesComponentViews, function (view) {
  20959. view.group.ignore = false;
  20960. });
  20961. return url;
  20962. };
  20963. /**
  20964. * @return {string}
  20965. * @param {Object} opts
  20966. * @param {string} [opts.type='png']
  20967. * @param {string} [opts.pixelRatio=1]
  20968. * @param {string} [opts.backgroundColor]
  20969. */
  20970. echartsProto.getConnectedDataURL = function (opts) {
  20971. if (!env$1.canvasSupported) {
  20972. return;
  20973. }
  20974. var groupId = this.group;
  20975. var mathMin = Math.min;
  20976. var mathMax = Math.max;
  20977. var MAX_NUMBER = Infinity;
  20978. if (connectedGroups[groupId]) {
  20979. var left = MAX_NUMBER;
  20980. var top = MAX_NUMBER;
  20981. var right = -MAX_NUMBER;
  20982. var bottom = -MAX_NUMBER;
  20983. var canvasList = [];
  20984. var dpr = (opts && opts.pixelRatio) || 1;
  20985. each$1(instances, function (chart, id) {
  20986. if (chart.group === groupId) {
  20987. var canvas = chart.getRenderedCanvas(
  20988. clone(opts)
  20989. );
  20990. var boundingRect = chart.getDom().getBoundingClientRect();
  20991. left = mathMin(boundingRect.left, left);
  20992. top = mathMin(boundingRect.top, top);
  20993. right = mathMax(boundingRect.right, right);
  20994. bottom = mathMax(boundingRect.bottom, bottom);
  20995. canvasList.push({
  20996. dom: canvas,
  20997. left: boundingRect.left,
  20998. top: boundingRect.top
  20999. });
  21000. }
  21001. });
  21002. left *= dpr;
  21003. top *= dpr;
  21004. right *= dpr;
  21005. bottom *= dpr;
  21006. var width = right - left;
  21007. var height = bottom - top;
  21008. var targetCanvas = createCanvas();
  21009. targetCanvas.width = width;
  21010. targetCanvas.height = height;
  21011. var zr = init$1(targetCanvas);
  21012. each(canvasList, function (item) {
  21013. var img = new ZImage({
  21014. style: {
  21015. x: item.left * dpr - left,
  21016. y: item.top * dpr - top,
  21017. image: item.dom
  21018. }
  21019. });
  21020. zr.add(img);
  21021. });
  21022. zr.refreshImmediately();
  21023. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21024. }
  21025. else {
  21026. return this.getDataURL(opts);
  21027. }
  21028. };
  21029. /**
  21030. * Convert from logical coordinate system to pixel coordinate system.
  21031. * See CoordinateSystem#convertToPixel.
  21032. * @param {string|Object} finder
  21033. * If string, e.g., 'geo', means {geoIndex: 0}.
  21034. * If Object, could contain some of these properties below:
  21035. * {
  21036. * seriesIndex / seriesId / seriesName,
  21037. * geoIndex / geoId, geoName,
  21038. * bmapIndex / bmapId / bmapName,
  21039. * xAxisIndex / xAxisId / xAxisName,
  21040. * yAxisIndex / yAxisId / yAxisName,
  21041. * gridIndex / gridId / gridName,
  21042. * ... (can be extended)
  21043. * }
  21044. * @param {Array|number} value
  21045. * @return {Array|number} result
  21046. */
  21047. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21048. /**
  21049. * Convert from pixel coordinate system to logical coordinate system.
  21050. * See CoordinateSystem#convertFromPixel.
  21051. * @param {string|Object} finder
  21052. * If string, e.g., 'geo', means {geoIndex: 0}.
  21053. * If Object, could contain some of these properties below:
  21054. * {
  21055. * seriesIndex / seriesId / seriesName,
  21056. * geoIndex / geoId / geoName,
  21057. * bmapIndex / bmapId / bmapName,
  21058. * xAxisIndex / xAxisId / xAxisName,
  21059. * yAxisIndex / yAxisId / yAxisName
  21060. * gridIndex / gridId / gridName,
  21061. * ... (can be extended)
  21062. * }
  21063. * @param {Array|number} value
  21064. * @return {Array|number} result
  21065. */
  21066. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21067. function doConvertPixel(methodName, finder, value) {
  21068. var ecModel = this._model;
  21069. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21070. var result;
  21071. finder = parseFinder(ecModel, finder);
  21072. for (var i = 0; i < coordSysList.length; i++) {
  21073. var coordSys = coordSysList[i];
  21074. if (coordSys[methodName]
  21075. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21076. ) {
  21077. return result;
  21078. }
  21079. }
  21080. if (__DEV__) {
  21081. console.warn(
  21082. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21083. );
  21084. }
  21085. }
  21086. /**
  21087. * Is the specified coordinate systems or components contain the given pixel point.
  21088. * @param {string|Object} finder
  21089. * If string, e.g., 'geo', means {geoIndex: 0}.
  21090. * If Object, could contain some of these properties below:
  21091. * {
  21092. * seriesIndex / seriesId / seriesName,
  21093. * geoIndex / geoId / geoName,
  21094. * bmapIndex / bmapId / bmapName,
  21095. * xAxisIndex / xAxisId / xAxisName,
  21096. * yAxisIndex / yAxisId / yAxisName,
  21097. * gridIndex / gridId / gridName,
  21098. * ... (can be extended)
  21099. * }
  21100. * @param {Array|number} value
  21101. * @return {boolean} result
  21102. */
  21103. echartsProto.containPixel = function (finder, value) {
  21104. var ecModel = this._model;
  21105. var result;
  21106. finder = parseFinder(ecModel, finder);
  21107. each$1(finder, function (models, key) {
  21108. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21109. var coordSys = model.coordinateSystem;
  21110. if (coordSys && coordSys.containPoint) {
  21111. result |= !!coordSys.containPoint(value);
  21112. }
  21113. else if (key === 'seriesModels') {
  21114. var view = this._chartsMap[model.__viewId];
  21115. if (view && view.containPoint) {
  21116. result |= view.containPoint(value, model);
  21117. }
  21118. else {
  21119. if (__DEV__) {
  21120. console.warn(key + ': ' + (view
  21121. ? 'The found component do not support containPoint.'
  21122. : 'No view mapping to the found component.'
  21123. ));
  21124. }
  21125. }
  21126. }
  21127. else {
  21128. if (__DEV__) {
  21129. console.warn(key + ': containPoint is not supported');
  21130. }
  21131. }
  21132. }, this);
  21133. }, this);
  21134. return !!result;
  21135. };
  21136. /**
  21137. * Get visual from series or data.
  21138. * @param {string|Object} finder
  21139. * If string, e.g., 'series', means {seriesIndex: 0}.
  21140. * If Object, could contain some of these properties below:
  21141. * {
  21142. * seriesIndex / seriesId / seriesName,
  21143. * dataIndex / dataIndexInside
  21144. * }
  21145. * If dataIndex is not specified, series visual will be fetched,
  21146. * but not data item visual.
  21147. * If all of seriesIndex, seriesId, seriesName are not specified,
  21148. * visual will be fetched from first series.
  21149. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21150. */
  21151. echartsProto.getVisual = function (finder, visualType) {
  21152. var ecModel = this._model;
  21153. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21154. var seriesModel = finder.seriesModel;
  21155. if (__DEV__) {
  21156. if (!seriesModel) {
  21157. console.warn('There is no specified seires model');
  21158. }
  21159. }
  21160. var data = seriesModel.getData();
  21161. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21162. ? finder.dataIndexInside
  21163. : finder.hasOwnProperty('dataIndex')
  21164. ? data.indexOfRawIndex(finder.dataIndex)
  21165. : null;
  21166. return dataIndexInside != null
  21167. ? data.getItemVisual(dataIndexInside, visualType)
  21168. : data.getVisual(visualType);
  21169. };
  21170. /**
  21171. * Get view of corresponding component model
  21172. * @param {module:echarts/model/Component} componentModel
  21173. * @return {module:echarts/view/Component}
  21174. */
  21175. echartsProto.getViewOfComponentModel = function (componentModel) {
  21176. return this._componentsMap[componentModel.__viewId];
  21177. };
  21178. /**
  21179. * Get view of corresponding series model
  21180. * @param {module:echarts/model/Series} seriesModel
  21181. * @return {module:echarts/view/Chart}
  21182. */
  21183. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21184. return this._chartsMap[seriesModel.__viewId];
  21185. };
  21186. var updateMethods = {
  21187. prepareAndUpdate: function (payload) {
  21188. prepare(this);
  21189. updateMethods.update.call(this, payload);
  21190. },
  21191. /**
  21192. * @param {Object} payload
  21193. * @private
  21194. */
  21195. update: function (payload) {
  21196. // console.profile && console.profile('update');
  21197. var ecModel = this._model;
  21198. var api = this._api;
  21199. var zr = this._zr;
  21200. var coordSysMgr = this._coordSysMgr;
  21201. var scheduler = this._scheduler;
  21202. // update before setOption
  21203. if (!ecModel) {
  21204. return;
  21205. }
  21206. ecModel.restoreData(payload);
  21207. scheduler.performSeriesTasks(ecModel);
  21208. // TODO
  21209. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21210. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21211. // Create new coordinate system each update
  21212. // In LineView may save the old coordinate system and use it to get the orignal point
  21213. coordSysMgr.create(ecModel, api);
  21214. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);
  21215. // Current stream render is not supported in data process. So we can update
  21216. // stream modes after data processing, where the filtered data is used to
  21217. // deteming whether use progressive rendering.
  21218. updateStreamModes(this, ecModel);
  21219. stackSeriesData(ecModel);
  21220. coordSysMgr.update(ecModel, api);
  21221. clearColorPalette(ecModel);
  21222. scheduler.performVisualTasks(visualFuncs, ecModel, payload);
  21223. render(this, ecModel, api, payload);
  21224. // Set background
  21225. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21226. var painter = zr.painter;
  21227. // TODO all use clearColor ?
  21228. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  21229. zr.configLayer(0, {
  21230. clearColor: backgroundColor
  21231. });
  21232. }
  21233. else {
  21234. // In IE8
  21235. if (!env$1.canvasSupported) {
  21236. var colorArr = parse(backgroundColor);
  21237. backgroundColor = stringify(colorArr, 'rgb');
  21238. if (colorArr[3] === 0) {
  21239. backgroundColor = 'transparent';
  21240. }
  21241. }
  21242. if (backgroundColor.colorStops || backgroundColor.image) {
  21243. // Gradient background
  21244. // FIXME Fixed layer?
  21245. zr.configLayer(0, {
  21246. clearColor: backgroundColor
  21247. });
  21248. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  21249. this._dom.style.background = 'transparent';
  21250. }
  21251. else {
  21252. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  21253. zr.configLayer(0, {
  21254. clearColor: null
  21255. });
  21256. }
  21257. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  21258. this._dom.style.background = backgroundColor;
  21259. }
  21260. }
  21261. performPostUpdateFuncs(ecModel, api);
  21262. // console.profile && console.profileEnd('update');
  21263. },
  21264. /**
  21265. * @param {Object} payload
  21266. * @private
  21267. */
  21268. updateTransform: function (payload) {
  21269. var ecModel = this._model;
  21270. var ecIns = this;
  21271. var api = this._api;
  21272. // update before setOption
  21273. if (!ecModel) {
  21274. return;
  21275. }
  21276. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21277. var componentDirtyList = [];
  21278. ecModel.eachComponent(function (componentType, componentModel) {
  21279. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21280. if (componentView && componentView.__alive) {
  21281. if (componentView.updateTransform) {
  21282. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21283. result && result.update && componentDirtyList.push(componentView);
  21284. }
  21285. else {
  21286. componentDirtyList.push(componentView);
  21287. }
  21288. }
  21289. });
  21290. var seriesDirtyMap = createHashMap();
  21291. ecModel.eachSeries(function (seriesModel) {
  21292. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21293. if (chartView.updateTransform) {
  21294. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21295. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21296. }
  21297. else {
  21298. seriesDirtyMap.set(seriesModel.uid, 1);
  21299. }
  21300. });
  21301. clearColorPalette(ecModel);
  21302. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21303. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21304. this._scheduler.performVisualTasks(
  21305. visualFuncs, ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21306. );
  21307. // Currently, not call render of components. Geo render cost a lot.
  21308. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21309. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21310. performPostUpdateFuncs(ecModel, this._api);
  21311. },
  21312. /**
  21313. * @param {Object} payload
  21314. * @private
  21315. */
  21316. updateView: function (payload) {
  21317. var ecModel = this._model;
  21318. // update before setOption
  21319. if (!ecModel) {
  21320. return;
  21321. }
  21322. Chart.markUpdateMethod(payload, 'updateView');
  21323. clearColorPalette(ecModel);
  21324. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21325. this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21326. render(this, this._model, this._api, payload);
  21327. performPostUpdateFuncs(ecModel, this._api);
  21328. },
  21329. /**
  21330. * @param {Object} payload
  21331. * @private
  21332. */
  21333. updateVisual: function (payload) {
  21334. updateMethods.update.call(this, payload);
  21335. // var ecModel = this._model;
  21336. // // update before setOption
  21337. // if (!ecModel) {
  21338. // return;
  21339. // }
  21340. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21341. // clearColorPalette(ecModel);
  21342. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21343. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {visualType: 'visual', setDirty: true});
  21344. // render(this, this._model, this._api, payload);
  21345. // performPostUpdateFuncs(ecModel, this._api);
  21346. },
  21347. /**
  21348. * @param {Object} payload
  21349. * @private
  21350. */
  21351. updateLayout: function (payload) {
  21352. updateMethods.update.call(this, payload);
  21353. // var ecModel = this._model;
  21354. // // update before setOption
  21355. // if (!ecModel) {
  21356. // return;
  21357. // }
  21358. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21359. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21360. // // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  21361. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  21362. // render(this, this._model, this._api, payload);
  21363. // performPostUpdateFuncs(ecModel, this._api);
  21364. }
  21365. };
  21366. function prepare(ecIns) {
  21367. var ecModel = ecIns._model;
  21368. var scheduler = ecIns._scheduler;
  21369. scheduler.restorePipelines(ecModel);
  21370. scheduler.prepareStageTasks(dataProcessorFuncs);
  21371. scheduler.prepareStageTasks(visualFuncs);
  21372. prepareView(ecIns, 'component', ecModel, scheduler);
  21373. prepareView(ecIns, 'chart', ecModel, scheduler);
  21374. scheduler.plan();
  21375. }
  21376. /**
  21377. * @private
  21378. */
  21379. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21380. var ecModel = ecIns._model;
  21381. // broadcast
  21382. if (!mainType) {
  21383. // FIXME
  21384. // Chart will not be update directly here, except set dirty.
  21385. // But there is no such scenario now.
  21386. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21387. return;
  21388. }
  21389. var query = {};
  21390. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21391. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21392. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21393. var condition = {mainType: mainType, query: query};
  21394. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21395. // If dispatchAction before setOption, do nothing.
  21396. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21397. callView(ecIns[
  21398. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21399. ][model.__viewId]);
  21400. }, ecIns);
  21401. function callView(view) {
  21402. view && view.__alive && view[method] && view[method](
  21403. view.__model, ecModel, ecIns._api, payload
  21404. );
  21405. }
  21406. }
  21407. /**
  21408. * Resize the chart
  21409. * @param {Object} opts
  21410. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21411. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21412. * @param {boolean} [opts.silent=false]
  21413. */
  21414. echartsProto.resize = function (opts) {
  21415. if (__DEV__) {
  21416. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21417. }
  21418. this._zr.resize(opts);
  21419. var ecModel = this._model;
  21420. // Resize loading effect
  21421. this._loadingFX && this._loadingFX.resize();
  21422. if (!ecModel) {
  21423. return;
  21424. }
  21425. var optionChanged = ecModel.resetOption('media');
  21426. refresh(this, optionChanged, opts && opts.silent);
  21427. };
  21428. function refresh(ecIns, needPrepare, silent) {
  21429. ecIns[IN_MAIN_PROCESS] = true;
  21430. needPrepare && prepare(ecIns);
  21431. updateMethods.update.call(ecIns);
  21432. ecIns[IN_MAIN_PROCESS] = false;
  21433. flushPendingActions.call(ecIns, silent);
  21434. triggerUpdatedEvent.call(ecIns, silent);
  21435. }
  21436. function updateStreamModes(ecIns, ecModel) {
  21437. var chartsMap = ecIns._chartsMap;
  21438. var scheduler = ecIns._scheduler;
  21439. ecModel.eachSeries(function (seriesModel) {
  21440. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21441. });
  21442. }
  21443. /**
  21444. * Show loading effect
  21445. * @param {string} [name='default']
  21446. * @param {Object} [cfg]
  21447. */
  21448. echartsProto.showLoading = function (name, cfg) {
  21449. if (isObject(name)) {
  21450. cfg = name;
  21451. name = '';
  21452. }
  21453. name = name || 'default';
  21454. this.hideLoading();
  21455. if (!loadingEffects[name]) {
  21456. if (__DEV__) {
  21457. console.warn('Loading effects ' + name + ' not exists.');
  21458. }
  21459. return;
  21460. }
  21461. var el = loadingEffects[name](this._api, cfg);
  21462. var zr = this._zr;
  21463. this._loadingFX = el;
  21464. zr.add(el);
  21465. };
  21466. /**
  21467. * Hide loading effect
  21468. */
  21469. echartsProto.hideLoading = function () {
  21470. this._loadingFX && this._zr.remove(this._loadingFX);
  21471. this._loadingFX = null;
  21472. };
  21473. /**
  21474. * @param {Object} eventObj
  21475. * @return {Object}
  21476. */
  21477. echartsProto.makeActionFromEvent = function (eventObj) {
  21478. var payload = extend({}, eventObj);
  21479. payload.type = eventActionMap[eventObj.type];
  21480. return payload;
  21481. };
  21482. /**
  21483. * @pubilc
  21484. * @param {Object} payload
  21485. * @param {string} [payload.type] Action type
  21486. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21487. * @param {boolean} [opt.silent=false] Whether trigger events.
  21488. * @param {boolean} [opt.flush=undefined]
  21489. * true: Flush immediately, and then pixel in canvas can be fetched
  21490. * immediately. Caution: it might affect performance.
  21491. * false: Not not flush.
  21492. * undefined: Auto decide whether perform flush.
  21493. */
  21494. echartsProto.dispatchAction = function (payload, opt) {
  21495. if (!isObject(opt)) {
  21496. opt = {silent: !!opt};
  21497. }
  21498. if (!actions[payload.type]) {
  21499. return;
  21500. }
  21501. // Avoid dispatch action before setOption. Especially in `connect`.
  21502. if (!this._model) {
  21503. return;
  21504. }
  21505. // May dispatchAction in rendering procedure
  21506. if (this[IN_MAIN_PROCESS]) {
  21507. this._pendingActions.push(payload);
  21508. return;
  21509. }
  21510. doDispatchAction.call(this, payload, opt.silent);
  21511. if (opt.flush) {
  21512. this._zr.flush(true);
  21513. }
  21514. else if (opt.flush !== false && env$1.browser.weChat) {
  21515. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21516. // hang when sliding page (on touch event), which cause that zr does not
  21517. // refresh util user interaction finished, which is not expected.
  21518. // But `dispatchAction` may be called too frequently when pan on touch
  21519. // screen, which impacts performance if do not throttle them.
  21520. this._throttledZrFlush();
  21521. }
  21522. flushPendingActions.call(this, opt.silent);
  21523. triggerUpdatedEvent.call(this, opt.silent);
  21524. };
  21525. function doDispatchAction(payload, silent) {
  21526. var payloadType = payload.type;
  21527. var escapeConnect = payload.escapeConnect;
  21528. var actionWrap = actions[payloadType];
  21529. var actionInfo = actionWrap.actionInfo;
  21530. var cptType = (actionInfo.update || 'update').split(':');
  21531. var updateMethod = cptType.pop();
  21532. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21533. this[IN_MAIN_PROCESS] = true;
  21534. var payloads = [payload];
  21535. var batched = false;
  21536. // Batch action
  21537. if (payload.batch) {
  21538. batched = true;
  21539. payloads = map(payload.batch, function (item) {
  21540. item = defaults(extend({}, item), payload);
  21541. item.batch = null;
  21542. return item;
  21543. });
  21544. }
  21545. var eventObjBatch = [];
  21546. var eventObj;
  21547. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21548. each(payloads, function (batchItem) {
  21549. // Action can specify the event by return it.
  21550. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21551. // Emit event outside
  21552. eventObj = eventObj || extend({}, batchItem);
  21553. // Convert type to eventType
  21554. eventObj.type = actionInfo.event || eventObj.type;
  21555. eventObjBatch.push(eventObj);
  21556. // light update does not perform data process, layout and visual.
  21557. if (isHighDown) {
  21558. // method, payload, mainType, subType
  21559. updateDirectly(this, updateMethod, batchItem, 'series');
  21560. }
  21561. else if (cptType) {
  21562. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21563. }
  21564. }, this);
  21565. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21566. // Still dirty
  21567. if (this[OPTION_UPDATED]) {
  21568. // FIXME Pass payload ?
  21569. prepare(this);
  21570. updateMethods.update.call(this, payload);
  21571. this[OPTION_UPDATED] = false;
  21572. }
  21573. else {
  21574. updateMethods[updateMethod].call(this, payload);
  21575. }
  21576. }
  21577. // Follow the rule of action batch
  21578. if (batched) {
  21579. eventObj = {
  21580. type: actionInfo.event || payloadType,
  21581. escapeConnect: escapeConnect,
  21582. batch: eventObjBatch
  21583. };
  21584. }
  21585. else {
  21586. eventObj = eventObjBatch[0];
  21587. }
  21588. this[IN_MAIN_PROCESS] = false;
  21589. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21590. }
  21591. function flushPendingActions(silent) {
  21592. var pendingActions = this._pendingActions;
  21593. while (pendingActions.length) {
  21594. var payload = pendingActions.shift();
  21595. doDispatchAction.call(this, payload, silent);
  21596. }
  21597. }
  21598. function triggerUpdatedEvent(silent) {
  21599. !silent && this.trigger('updated');
  21600. }
  21601. /**
  21602. * @param {Object} params
  21603. * @param {number} params.seriesIndex
  21604. * @param {Array|TypedArray} params.data
  21605. */
  21606. echartsProto.appendData = function (params) {
  21607. var seriesIndex = params.seriesIndex;
  21608. var ecModel = this.getModel();
  21609. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21610. if (__DEV__) {
  21611. assert(params.data && seriesModel);
  21612. }
  21613. seriesModel.appendData(params);
  21614. this._scheduler.unfinished = true;
  21615. };
  21616. /**
  21617. * Register event
  21618. * @method
  21619. */
  21620. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21621. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21622. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21623. /**
  21624. * Prepare view instances of charts and components
  21625. * @param {module:echarts/model/Global} ecModel
  21626. * @private
  21627. */
  21628. function prepareView(ecIns, type, ecModel, scheduler) {
  21629. var isComponent = type === 'component';
  21630. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21631. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21632. var zr = ecIns._zr;
  21633. var api = ecIns._api;
  21634. for (var i = 0; i < viewList.length; i++) {
  21635. viewList[i].__alive = false;
  21636. }
  21637. isComponent
  21638. ? ecModel.eachComponent(function (componentType, model) {
  21639. componentType !== 'series' && doPrepare(model);
  21640. })
  21641. : ecModel.eachSeries(doPrepare);
  21642. function doPrepare(model) {
  21643. // Consider: id same and type changed.
  21644. var viewId = '_ec_' + model.id + '_' + model.type;
  21645. var view = viewMap[viewId];
  21646. if (!view) {
  21647. var classType = parseClassType(model.type);
  21648. var Clazz = isComponent
  21649. ? Component.getClass(classType.main, classType.sub)
  21650. : Chart.getClass(classType.sub);
  21651. if (__DEV__) {
  21652. assert(Clazz, classType.sub + ' does not exist.');
  21653. }
  21654. view = new Clazz();
  21655. view.init(ecModel, api);
  21656. viewMap[viewId] = view;
  21657. viewList.push(view);
  21658. zr.add(view.group);
  21659. }
  21660. model.__viewId = view.__id = viewId;
  21661. view.__alive = true;
  21662. view.__model = model;
  21663. view.group.__ecComponentInfo = {
  21664. mainType: model.mainType,
  21665. index: model.componentIndex
  21666. };
  21667. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21668. }
  21669. for (var i = 0; i < viewList.length;) {
  21670. var view = viewList[i];
  21671. if (!view.__alive) {
  21672. !isComponent && view.renderTask.dispose();
  21673. zr.remove(view.group);
  21674. view.dispose(ecModel, api);
  21675. viewList.splice(i, 1);
  21676. delete viewMap[view.__id];
  21677. view.__id = view.group.__ecComponentInfo = null;
  21678. }
  21679. else {
  21680. i++;
  21681. }
  21682. }
  21683. }
  21684. /**
  21685. * @private
  21686. */
  21687. function stackSeriesData(ecModel) {
  21688. var stackedDataMap = {};
  21689. ecModel.eachSeries(function (series) {
  21690. var stack = series.get('stack');
  21691. var data = series.getData();
  21692. if (stack && data.type === 'list') {
  21693. var previousStack = stackedDataMap[stack];
  21694. // Avoid conflict with Object.prototype
  21695. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  21696. data.stackedOn = previousStack;
  21697. }
  21698. stackedDataMap[stack] = data;
  21699. }
  21700. });
  21701. }
  21702. // /**
  21703. // * Encode visual infomation from data after data processing
  21704. // *
  21705. // * @param {module:echarts/model/Global} ecModel
  21706. // * @param {object} layout
  21707. // * @param {boolean} [layoutFilter] `true`: only layout,
  21708. // * `false`: only not layout,
  21709. // * `null`/`undefined`: all.
  21710. // * @param {string} taskBaseTag
  21711. // * @private
  21712. // */
  21713. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21714. // each(visualFuncs, function (visual, index) {
  21715. // var isLayout = visual.isLayout;
  21716. // if (layoutFilter == null
  21717. // || (layoutFilter === false && !isLayout)
  21718. // || (layoutFilter === true && isLayout)
  21719. // ) {
  21720. // visual.func(ecModel, api, payload);
  21721. // }
  21722. // });
  21723. // }
  21724. function clearColorPalette(ecModel) {
  21725. ecModel.clearColorPalette();
  21726. ecModel.eachSeries(function (seriesModel) {
  21727. seriesModel.clearColorPalette();
  21728. });
  21729. }
  21730. function render(ecIns, ecModel, api, payload) {
  21731. renderComponents(ecIns, ecModel, api, payload);
  21732. each(ecIns._chartsViews, function (chart) {
  21733. chart.__alive = false;
  21734. });
  21735. renderSeries(ecIns, ecModel, api, payload);
  21736. // Remove groups of unrendered charts
  21737. each(ecIns._chartsViews, function (chart) {
  21738. if (!chart.__alive) {
  21739. chart.remove(ecModel, api);
  21740. }
  21741. });
  21742. }
  21743. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  21744. each(dirtyList || ecIns._componentsViews, function (componentView) {
  21745. var componentModel = componentView.__model;
  21746. componentView.render(componentModel, ecModel, api, payload);
  21747. updateZ(componentModel, componentView);
  21748. });
  21749. }
  21750. /**
  21751. * Render each chart and component
  21752. * @private
  21753. */
  21754. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  21755. // Render all charts
  21756. var scheduler = ecIns._scheduler;
  21757. var unfinished;
  21758. ecModel.eachSeries(function (seriesModel) {
  21759. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21760. chartView.__alive = true;
  21761. var renderTask = chartView.renderTask;
  21762. scheduler.updatePayload(renderTask, payload);
  21763. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  21764. renderTask.dirty();
  21765. }
  21766. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  21767. chartView.group.silent = !!seriesModel.get('silent');
  21768. updateZ(seriesModel, chartView);
  21769. updateBlend(seriesModel, chartView);
  21770. });
  21771. scheduler.unfinished |= unfinished;
  21772. // If use hover layer
  21773. updateHoverLayerStatus(ecIns._zr, ecModel);
  21774. // Add aria
  21775. aria(ecIns._zr.dom, ecModel);
  21776. }
  21777. function performPostUpdateFuncs(ecModel, api) {
  21778. each(postUpdateFuncs, function (func) {
  21779. func(ecModel, api);
  21780. });
  21781. }
  21782. var MOUSE_EVENT_NAMES = [
  21783. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  21784. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  21785. ];
  21786. /**
  21787. * @private
  21788. */
  21789. echartsProto._initEvents = function () {
  21790. each(MOUSE_EVENT_NAMES, function (eveName) {
  21791. this._zr.on(eveName, function (e) {
  21792. var ecModel = this.getModel();
  21793. var el = e.target;
  21794. var params;
  21795. // no e.target when 'globalout'.
  21796. if (eveName === 'globalout') {
  21797. params = {};
  21798. }
  21799. else if (el && el.dataIndex != null) {
  21800. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  21801. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  21802. }
  21803. // If element has custom eventData of components
  21804. else if (el && el.eventData) {
  21805. params = extend({}, el.eventData);
  21806. }
  21807. if (params) {
  21808. params.event = e;
  21809. params.type = eveName;
  21810. this.trigger(eveName, params);
  21811. }
  21812. }, this);
  21813. }, this);
  21814. each(eventActionMap, function (actionType, eventType) {
  21815. this._messageCenter.on(eventType, function (event) {
  21816. this.trigger(eventType, event);
  21817. }, this);
  21818. }, this);
  21819. };
  21820. /**
  21821. * @return {boolean}
  21822. */
  21823. echartsProto.isDisposed = function () {
  21824. return this._disposed;
  21825. };
  21826. /**
  21827. * Clear
  21828. */
  21829. echartsProto.clear = function () {
  21830. this.setOption({ series: [] }, true);
  21831. };
  21832. /**
  21833. * Dispose instance
  21834. */
  21835. echartsProto.dispose = function () {
  21836. if (this._disposed) {
  21837. if (__DEV__) {
  21838. console.warn('Instance ' + this.id + ' has been disposed');
  21839. }
  21840. return;
  21841. }
  21842. this._disposed = true;
  21843. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  21844. var api = this._api;
  21845. var ecModel = this._model;
  21846. each(this._componentsViews, function (component) {
  21847. component.dispose(ecModel, api);
  21848. });
  21849. each(this._chartsViews, function (chart) {
  21850. chart.dispose(ecModel, api);
  21851. });
  21852. // Dispose after all views disposed
  21853. this._zr.dispose();
  21854. delete instances[this.id];
  21855. };
  21856. mixin(ECharts, Eventful);
  21857. function updateHoverLayerStatus(zr, ecModel) {
  21858. var storage = zr.storage;
  21859. var elCount = 0;
  21860. storage.traverse(function (el) {
  21861. if (!el.isGroup) {
  21862. elCount++;
  21863. }
  21864. });
  21865. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  21866. storage.traverse(function (el) {
  21867. if (!el.isGroup) {
  21868. // Don't switch back.
  21869. el.useHoverLayer = true;
  21870. }
  21871. });
  21872. }
  21873. }
  21874. /**
  21875. * Update chart progressive and blend.
  21876. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21877. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21878. */
  21879. function updateBlend(seriesModel, chartView) {
  21880. var blendMode = seriesModel.get('blendMode') || null;
  21881. if (__DEV__) {
  21882. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  21883. console.warn('Only canvas support blendMode');
  21884. }
  21885. }
  21886. chartView.group.traverse(function (el) {
  21887. // FIXME marker and other components
  21888. if (!el.isGroup) {
  21889. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  21890. if (el.style.blend !== blendMode) {
  21891. el.setStyle('blend', blendMode);
  21892. }
  21893. }
  21894. if (el.eachPendingDisplayable) {
  21895. el.eachPendingDisplayable(function (displayable) {
  21896. displayable.setStyle('blend', blendMode);
  21897. });
  21898. }
  21899. });
  21900. }
  21901. /**
  21902. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21903. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21904. */
  21905. function updateZ(model, view) {
  21906. var z = model.get('z');
  21907. var zlevel = model.get('zlevel');
  21908. // Set z and zlevel
  21909. view.group.traverse(function (el) {
  21910. if (el.type !== 'group') {
  21911. z != null && (el.z = z);
  21912. zlevel != null && (el.zlevel = zlevel);
  21913. }
  21914. });
  21915. }
  21916. function createExtensionAPI(ecInstance) {
  21917. var coordSysMgr = ecInstance._coordSysMgr;
  21918. return extend(new ExtensionAPI(ecInstance), {
  21919. // Inject methods
  21920. getCoordinateSystems: bind(
  21921. coordSysMgr.getCoordinateSystems, coordSysMgr
  21922. ),
  21923. getComponentByElement: function (el) {
  21924. while (el) {
  21925. var modelInfo = el.__ecComponentInfo;
  21926. if (modelInfo != null) {
  21927. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  21928. }
  21929. el = el.parent;
  21930. }
  21931. }
  21932. });
  21933. }
  21934. /**
  21935. * @type {Object} key: actionType.
  21936. * @inner
  21937. */
  21938. var actions = {};
  21939. /**
  21940. * Map eventType to actionType
  21941. * @type {Object}
  21942. */
  21943. var eventActionMap = {};
  21944. /**
  21945. * Data processor functions of each stage
  21946. * @type {Array.<Object.<string, Function>>}
  21947. * @inner
  21948. */
  21949. var dataProcessorFuncs = [];
  21950. /**
  21951. * @type {Array.<Function>}
  21952. * @inner
  21953. */
  21954. var optionPreprocessorFuncs = [];
  21955. /**
  21956. * @type {Array.<Function>}
  21957. * @inner
  21958. */
  21959. var postUpdateFuncs = [];
  21960. /**
  21961. * Visual encoding functions of each stage
  21962. * @type {Array.<Object.<string, Function>>}
  21963. */
  21964. var visualFuncs = [];
  21965. /**
  21966. * Theme storage
  21967. * @type {Object.<key, Object>}
  21968. */
  21969. var themeStorage = {};
  21970. /**
  21971. * Loading effects
  21972. */
  21973. var loadingEffects = {};
  21974. var instances = {};
  21975. var connectedGroups = {};
  21976. var idBase = new Date() - 0;
  21977. var groupIdBase = new Date() - 0;
  21978. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  21979. var mapDataStores = {};
  21980. function enableConnect(chart) {
  21981. var STATUS_PENDING = 0;
  21982. var STATUS_UPDATING = 1;
  21983. var STATUS_UPDATED = 2;
  21984. var STATUS_KEY = '__connectUpdateStatus';
  21985. function updateConnectedChartsStatus(charts, status) {
  21986. for (var i = 0; i < charts.length; i++) {
  21987. var otherChart = charts[i];
  21988. otherChart[STATUS_KEY] = status;
  21989. }
  21990. }
  21991. each(eventActionMap, function (actionType, eventType) {
  21992. chart._messageCenter.on(eventType, function (event) {
  21993. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  21994. if (event && event.escapeConnect) {
  21995. return;
  21996. }
  21997. var action = chart.makeActionFromEvent(event);
  21998. var otherCharts = [];
  21999. each(instances, function (otherChart) {
  22000. if (otherChart !== chart && otherChart.group === chart.group) {
  22001. otherCharts.push(otherChart);
  22002. }
  22003. });
  22004. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22005. each(otherCharts, function (otherChart) {
  22006. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22007. otherChart.dispatchAction(action);
  22008. }
  22009. });
  22010. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22011. }
  22012. });
  22013. });
  22014. }
  22015. /**
  22016. * @param {HTMLElement} dom
  22017. * @param {Object} [theme]
  22018. * @param {Object} opts
  22019. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22020. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22021. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22022. * Can be 'auto' (the same as null/undefined)
  22023. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22024. * Can be 'auto' (the same as null/undefined)
  22025. */
  22026. function init(dom, theme$$1, opts) {
  22027. if (__DEV__) {
  22028. // Check version
  22029. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22030. throw new Error(
  22031. 'zrender/src ' + version$1
  22032. + ' is too old for ECharts ' + version
  22033. + '. Current version need ZRender '
  22034. + dependencies.zrender + '+'
  22035. );
  22036. }
  22037. if (!dom) {
  22038. throw new Error('Initialize failed: invalid dom.');
  22039. }
  22040. }
  22041. var existInstance = getInstanceByDom(dom);
  22042. if (existInstance) {
  22043. if (__DEV__) {
  22044. console.warn('There is a chart instance already initialized on the dom.');
  22045. }
  22046. return existInstance;
  22047. }
  22048. if (__DEV__) {
  22049. if (isDom(dom)
  22050. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22051. && (
  22052. (!dom.clientWidth && (!opts || opts.width == null))
  22053. || (!dom.clientHeight && (!opts || opts.height == null))
  22054. )
  22055. ) {
  22056. console.warn('Can\'t get dom width or height');
  22057. }
  22058. }
  22059. var chart = new ECharts(dom, theme$$1, opts);
  22060. chart.id = 'ec_' + idBase++;
  22061. instances[chart.id] = chart;
  22062. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22063. enableConnect(chart);
  22064. return chart;
  22065. }
  22066. /**
  22067. * @return {string|Array.<module:echarts~ECharts>} groupId
  22068. */
  22069. function connect(groupId) {
  22070. // Is array of charts
  22071. if (isArray(groupId)) {
  22072. var charts = groupId;
  22073. groupId = null;
  22074. // If any chart has group
  22075. each(charts, function (chart) {
  22076. if (chart.group != null) {
  22077. groupId = chart.group;
  22078. }
  22079. });
  22080. groupId = groupId || ('g_' + groupIdBase++);
  22081. each(charts, function (chart) {
  22082. chart.group = groupId;
  22083. });
  22084. }
  22085. connectedGroups[groupId] = true;
  22086. return groupId;
  22087. }
  22088. /**
  22089. * @DEPRECATED
  22090. * @return {string} groupId
  22091. */
  22092. function disConnect(groupId) {
  22093. connectedGroups[groupId] = false;
  22094. }
  22095. /**
  22096. * @return {string} groupId
  22097. */
  22098. var disconnect = disConnect;
  22099. /**
  22100. * Dispose a chart instance
  22101. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22102. */
  22103. function dispose(chart) {
  22104. if (typeof chart === 'string') {
  22105. chart = instances[chart];
  22106. }
  22107. else if (!(chart instanceof ECharts)){
  22108. // Try to treat as dom
  22109. chart = getInstanceByDom(chart);
  22110. }
  22111. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22112. chart.dispose();
  22113. }
  22114. }
  22115. /**
  22116. * @param {HTMLElement} dom
  22117. * @return {echarts~ECharts}
  22118. */
  22119. function getInstanceByDom(dom) {
  22120. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22121. }
  22122. /**
  22123. * @param {string} key
  22124. * @return {echarts~ECharts}
  22125. */
  22126. function getInstanceById(key) {
  22127. return instances[key];
  22128. }
  22129. /**
  22130. * Register theme
  22131. */
  22132. function registerTheme(name, theme$$1) {
  22133. themeStorage[name] = theme$$1;
  22134. }
  22135. /**
  22136. * Register option preprocessor
  22137. * @param {Function} preprocessorFunc
  22138. */
  22139. function registerPreprocessor(preprocessorFunc) {
  22140. optionPreprocessorFuncs.push(preprocessorFunc);
  22141. }
  22142. /**
  22143. * @param {number} [priority=1000]
  22144. * @param {Object|Function} processor
  22145. */
  22146. function registerProcessor(priority, processor) {
  22147. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22148. }
  22149. /**
  22150. * Register postUpdater
  22151. * @param {Function} postUpdateFunc
  22152. */
  22153. function registerPostUpdate(postUpdateFunc) {
  22154. postUpdateFuncs.push(postUpdateFunc);
  22155. }
  22156. /**
  22157. * Usage:
  22158. * registerAction('someAction', 'someEvent', function () { ... });
  22159. * registerAction('someAction', function () { ... });
  22160. * registerAction(
  22161. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22162. * function () { ... }
  22163. * );
  22164. *
  22165. * @param {(string|Object)} actionInfo
  22166. * @param {string} actionInfo.type
  22167. * @param {string} [actionInfo.event]
  22168. * @param {string} [actionInfo.update]
  22169. * @param {string} [eventName]
  22170. * @param {Function} action
  22171. */
  22172. function registerAction(actionInfo, eventName, action) {
  22173. if (typeof eventName === 'function') {
  22174. action = eventName;
  22175. eventName = '';
  22176. }
  22177. var actionType = isObject(actionInfo)
  22178. ? actionInfo.type
  22179. : ([actionInfo, actionInfo = {
  22180. event: eventName
  22181. }][0]);
  22182. // Event name is all lowercase
  22183. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22184. eventName = actionInfo.event;
  22185. // Validate action type and event name.
  22186. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22187. if (!actions[actionType]) {
  22188. actions[actionType] = {action: action, actionInfo: actionInfo};
  22189. }
  22190. eventActionMap[eventName] = actionType;
  22191. }
  22192. /**
  22193. * @param {string} type
  22194. * @param {*} CoordinateSystem
  22195. */
  22196. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22197. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22198. }
  22199. /**
  22200. * Get dimensions of specified coordinate system.
  22201. * @param {string} type
  22202. * @return {Array.<string|Object>}
  22203. */
  22204. function getCoordinateSystemDimensions(type) {
  22205. var coordSysCreator = CoordinateSystemManager.get(type);
  22206. if (coordSysCreator) {
  22207. return coordSysCreator.getDimensionsInfo
  22208. ? coordSysCreator.getDimensionsInfo()
  22209. : coordSysCreator.dimensions.slice();
  22210. }
  22211. }
  22212. /**
  22213. * Layout is a special stage of visual encoding
  22214. * Most visual encoding like color are common for different chart
  22215. * But each chart has it's own layout algorithm
  22216. *
  22217. * @param {number} [priority=1000]
  22218. * @param {Function} layoutTask
  22219. */
  22220. function registerLayout(priority, layoutTask) {
  22221. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22222. }
  22223. /**
  22224. * @param {number} [priority=3000]
  22225. * @param {module:echarts/stream/Task} visualTask
  22226. */
  22227. function registerVisual(priority, visualTask) {
  22228. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22229. }
  22230. /**
  22231. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22232. */
  22233. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22234. if (isFunction(priority) || isObject(priority)) {
  22235. fn = priority;
  22236. priority = defaultPriority;
  22237. }
  22238. if (__DEV__) {
  22239. if (isNaN(priority) || priority == null) {
  22240. throw new Error('Illegal priority');
  22241. }
  22242. // Check duplicate
  22243. each(targetList, function (wrap) {
  22244. assert(wrap.__raw !== fn);
  22245. });
  22246. }
  22247. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22248. stageHandler.__prio = priority;
  22249. stageHandler.__raw = fn;
  22250. targetList.push(stageHandler);
  22251. return stageHandler;
  22252. }
  22253. /**
  22254. * @param {string} name
  22255. */
  22256. function registerLoading(name, loadingFx) {
  22257. loadingEffects[name] = loadingFx;
  22258. }
  22259. /**
  22260. * @param {Object} opts
  22261. * @param {string} [superClass]
  22262. */
  22263. function extendComponentModel(opts/*, superClass*/) {
  22264. // var Clazz = ComponentModel;
  22265. // if (superClass) {
  22266. // var classType = parseClassType(superClass);
  22267. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22268. // }
  22269. return ComponentModel.extend(opts);
  22270. }
  22271. /**
  22272. * @param {Object} opts
  22273. * @param {string} [superClass]
  22274. */
  22275. function extendComponentView(opts/*, superClass*/) {
  22276. // var Clazz = ComponentView;
  22277. // if (superClass) {
  22278. // var classType = parseClassType(superClass);
  22279. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22280. // }
  22281. return Component.extend(opts);
  22282. }
  22283. /**
  22284. * @param {Object} opts
  22285. * @param {string} [superClass]
  22286. */
  22287. function extendSeriesModel(opts/*, superClass*/) {
  22288. // var Clazz = SeriesModel;
  22289. // if (superClass) {
  22290. // superClass = 'series.' + superClass.replace('series.', '');
  22291. // var classType = parseClassType(superClass);
  22292. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22293. // }
  22294. return SeriesModel.extend(opts);
  22295. }
  22296. /**
  22297. * @param {Object} opts
  22298. * @param {string} [superClass]
  22299. */
  22300. function extendChartView(opts/*, superClass*/) {
  22301. // var Clazz = ChartView;
  22302. // if (superClass) {
  22303. // superClass = superClass.replace('series.', '');
  22304. // var classType = parseClassType(superClass);
  22305. // Clazz = ChartView.getClass(classType.main, true);
  22306. // }
  22307. return Chart.extend(opts);
  22308. }
  22309. /**
  22310. * ZRender need a canvas context to do measureText.
  22311. * But in node environment canvas may be created by node-canvas.
  22312. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22313. *
  22314. * Be careful of using it in the browser.
  22315. *
  22316. * @param {Function} creator
  22317. * @example
  22318. * var Canvas = require('canvas');
  22319. * var echarts = require('echarts');
  22320. * echarts.setCanvasCreator(function () {
  22321. * // Small size is enough.
  22322. * return new Canvas(32, 32);
  22323. * });
  22324. */
  22325. function setCanvasCreator(creator) {
  22326. $override('createCanvas', creator);
  22327. }
  22328. /**
  22329. * @param {string} mapName
  22330. * @param {Object|string} geoJson
  22331. * @param {Object} [specialAreas]
  22332. *
  22333. * @example
  22334. * $.get('USA.json', function (geoJson) {
  22335. * echarts.registerMap('USA', geoJson);
  22336. * // Or
  22337. * echarts.registerMap('USA', {
  22338. * geoJson: geoJson,
  22339. * specialAreas: {}
  22340. * })
  22341. * });
  22342. */
  22343. function registerMap(mapName, geoJson, specialAreas) {
  22344. if (geoJson.geoJson && !geoJson.features) {
  22345. specialAreas = geoJson.specialAreas;
  22346. geoJson = geoJson.geoJson;
  22347. }
  22348. if (typeof geoJson === 'string') {
  22349. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22350. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22351. }
  22352. mapDataStores[mapName] = {
  22353. geoJson: geoJson,
  22354. specialAreas: specialAreas
  22355. };
  22356. }
  22357. /**
  22358. * @param {string} mapName
  22359. * @return {Object}
  22360. */
  22361. function getMap(mapName) {
  22362. return mapDataStores[mapName];
  22363. }
  22364. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22365. registerPreprocessor(backwardCompat);
  22366. registerLoading('default', loadingDefault);
  22367. // Default actions
  22368. registerAction({
  22369. type: 'highlight',
  22370. event: 'highlight',
  22371. update: 'highlight'
  22372. }, noop);
  22373. registerAction({
  22374. type: 'downplay',
  22375. event: 'downplay',
  22376. update: 'downplay'
  22377. }, noop);
  22378. // Default theme
  22379. registerTheme('light', lightTheme);
  22380. registerTheme('dark', theme);
  22381. // For backward compatibility, where the namespace `dataTool` will
  22382. // be mounted on `echarts` is the extension `dataTool` is imported.
  22383. var dataTool = {};
  22384. function defaultKeyGetter(item) {
  22385. return item;
  22386. }
  22387. /**
  22388. * @param {Array} oldArr
  22389. * @param {Array} newArr
  22390. * @param {Function} oldKeyGetter
  22391. * @param {Function} newKeyGetter
  22392. * @param {Object} [context] Can be visited by this.context in callback.
  22393. */
  22394. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22395. this._old = oldArr;
  22396. this._new = newArr;
  22397. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22398. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22399. this.context = context;
  22400. }
  22401. DataDiffer.prototype = {
  22402. constructor: DataDiffer,
  22403. /**
  22404. * Callback function when add a data
  22405. */
  22406. add: function (func) {
  22407. this._add = func;
  22408. return this;
  22409. },
  22410. /**
  22411. * Callback function when update a data
  22412. */
  22413. update: function (func) {
  22414. this._update = func;
  22415. return this;
  22416. },
  22417. /**
  22418. * Callback function when remove a data
  22419. */
  22420. remove: function (func) {
  22421. this._remove = func;
  22422. return this;
  22423. },
  22424. execute: function () {
  22425. var oldArr = this._old;
  22426. var newArr = this._new;
  22427. var oldDataIndexMap = {};
  22428. var newDataIndexMap = {};
  22429. var oldDataKeyArr = [];
  22430. var newDataKeyArr = [];
  22431. var i;
  22432. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22433. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22434. // Travel by inverted order to make sure order consistency
  22435. // when duplicate keys exists (consider newDataIndex.pop() below).
  22436. // For performance consideration, these code below do not look neat.
  22437. for (i = 0; i < oldArr.length; i++) {
  22438. var key = oldDataKeyArr[i];
  22439. var idx = newDataIndexMap[key];
  22440. // idx can never be empty array here. see 'set null' logic below.
  22441. if (idx != null) {
  22442. // Consider there is duplicate key (for example, use dataItem.name as key).
  22443. // We should make sure every item in newArr and oldArr can be visited.
  22444. var len = idx.length;
  22445. if (len) {
  22446. len === 1 && (newDataIndexMap[key] = null);
  22447. idx = idx.unshift();
  22448. }
  22449. else {
  22450. newDataIndexMap[key] = null;
  22451. }
  22452. this._update && this._update(idx, i);
  22453. }
  22454. else {
  22455. this._remove && this._remove(i);
  22456. }
  22457. }
  22458. for (var i = 0; i < newDataKeyArr.length; i++) {
  22459. var key = newDataKeyArr[i];
  22460. if (newDataIndexMap.hasOwnProperty(key)) {
  22461. var idx = newDataIndexMap[key];
  22462. if (idx == null) {
  22463. continue;
  22464. }
  22465. // idx can never be empty array here. see 'set null' logic above.
  22466. if (!idx.length) {
  22467. this._add && this._add(idx);
  22468. }
  22469. else {
  22470. for (var j = 0, len = idx.length; j < len; j++) {
  22471. this._add && this._add(idx[j]);
  22472. }
  22473. }
  22474. }
  22475. }
  22476. }
  22477. };
  22478. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22479. for (var i = 0; i < arr.length; i++) {
  22480. // Add prefix to avoid conflict with Object.prototype.
  22481. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22482. var existence = map[key];
  22483. if (existence == null) {
  22484. keyArr.push(key);
  22485. map[key] = i;
  22486. }
  22487. else {
  22488. if (!existence.length) {
  22489. map[key] = existence = [existence];
  22490. }
  22491. existence.push(i);
  22492. }
  22493. }
  22494. }
  22495. var OTHER_DIMENSIONS = createHashMap([
  22496. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22497. ]);
  22498. function summarizeDimensions(data) {
  22499. var summary = {};
  22500. var encode = summary.encode = {};
  22501. var coordDimMap = summary.coordDimMap = createHashMap();
  22502. var defaultedLabel = [];
  22503. each$1(data.dimensions, function (dimName) {
  22504. var dimItem = data.getDimensionInfo(dimName);
  22505. var coordDim = dimItem.coordDim;
  22506. if (coordDim) {
  22507. if (__DEV__) {
  22508. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22509. }
  22510. var coordDimArr = encode[coordDim];
  22511. if (!encode.hasOwnProperty(coordDim)) {
  22512. coordDimArr = encode[coordDim] = [];
  22513. }
  22514. coordDimArr[dimItem.coordDimIndex] = dimName;
  22515. if (dimItem.isSysCoord && mayLabelDimType(dimItem.type)) {
  22516. // Use the last coord dim (and label friendly) as default label,
  22517. // because both show x, y on label is not look good, and usually
  22518. // y axis is more focusd conventionally.
  22519. defaultedLabel[0] = dimName;
  22520. }
  22521. coordDimMap.set(coordDim, 1);
  22522. }
  22523. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22524. var otherDimArr = encode[otherDim];
  22525. if (!encode.hasOwnProperty(otherDim)) {
  22526. otherDimArr = encode[otherDim] = [];
  22527. }
  22528. var dimIndex = dimItem.otherDims[otherDim];
  22529. if (dimIndex != null && dimIndex !== false) {
  22530. otherDimArr[dimIndex] = dimItem.name;
  22531. }
  22532. });
  22533. });
  22534. var dataDimsOnCoord = [];
  22535. coordDimMap.each(function (v, coordDim) {
  22536. dataDimsOnCoord = dataDimsOnCoord.concat(encode[coordDim]);
  22537. });
  22538. summary.dataDimsOnCoord = dataDimsOnCoord;
  22539. var encodeLabel = encode.label;
  22540. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22541. // in this way. Use label.formatter instead. May be remove this approach someday.
  22542. if (encodeLabel && encodeLabel.length) {
  22543. defaultedLabel = encodeLabel.slice();
  22544. }
  22545. var defaultedTooltip = defaultedLabel.slice();
  22546. var encodeTooltip = encode.tooltip;
  22547. if (encodeTooltip && encodeTooltip.length) {
  22548. defaultedTooltip = encodeTooltip.slice();
  22549. }
  22550. encode.defaultedLabel = defaultedLabel;
  22551. encode.defaultedTooltip = defaultedTooltip;
  22552. return summary;
  22553. }
  22554. function getDimensionTypeByAxis(axisType) {
  22555. return axisType === 'category'
  22556. ? 'ordinal'
  22557. : axisType === 'time'
  22558. ? 'time'
  22559. : 'float';
  22560. }
  22561. function mayLabelDimType(dimType) {
  22562. // In most cases, ordinal and time do not suitable for label.
  22563. // Ordinal info can be displayed on axis. Time is too long.
  22564. return !(dimType === 'ordinal' || dimType === 'time');
  22565. }
  22566. // function findTheLastDimMayLabel(data) {
  22567. // // Get last value dim
  22568. // var dimensions = data.dimensions.slice();
  22569. // var valueType;
  22570. // var valueDim;
  22571. // while (dimensions.length && (
  22572. // valueDim = dimensions.pop(),
  22573. // valueType = data.getDimensionInfo(valueDim).type,
  22574. // valueType === 'ordinal' || valueType === 'time'
  22575. // )) {} // jshint ignore:line
  22576. // return valueDim;
  22577. // }
  22578. /**
  22579. * List for data storage
  22580. * @module echarts/data/List
  22581. */
  22582. var isObject$4 = isObject$1;
  22583. var UNDEFINED = 'undefined';
  22584. var globalObj = typeof window === UNDEFINED ? global : window;
  22585. // Use prefix to avoid index to be the same as otherIdList[idx],
  22586. // which will cause weird udpate animation.
  22587. var ID_PREFIX = 'e\0\0';
  22588. var dataCtors = {
  22589. 'float': typeof globalObj.Float64Array === UNDEFINED
  22590. ? Array : globalObj.Float64Array,
  22591. 'int': typeof globalObj.Int32Array === UNDEFINED
  22592. ? Array : globalObj.Int32Array,
  22593. // Ordinal data type can be string or int
  22594. 'ordinal': Array,
  22595. 'number': Array,
  22596. 'time': Array
  22597. };
  22598. function getIndicesCtor(list) {
  22599. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22600. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22601. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22602. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22603. }
  22604. function cloneChunk(originalChunk) {
  22605. var Ctor = originalChunk.constructor;
  22606. // Only shallow clone is enough when Array.
  22607. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22608. }
  22609. var TRANSFERABLE_PROPERTIES = [
  22610. 'stackedOn', 'hasItemOption', '_nameList', '_idList',
  22611. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22612. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22613. ];
  22614. function transferProperties(a, b) {
  22615. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22616. if (b.hasOwnProperty(propName)) {
  22617. a[propName] = b[propName];
  22618. }
  22619. });
  22620. a.__wrappedMethods = b.__wrappedMethods;
  22621. }
  22622. /**
  22623. * @constructor
  22624. * @alias module:echarts/data/List
  22625. *
  22626. * @param {Array.<string|Object>} dimensions
  22627. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22628. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22629. * Spetial fields: {
  22630. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22631. * }
  22632. * @param {module:echarts/model/Model} hostModel
  22633. */
  22634. var List = function (dimensions, hostModel) {
  22635. dimensions = dimensions || ['x', 'y'];
  22636. var dimensionInfos = {};
  22637. var dimensionNames = [];
  22638. for (var i = 0; i < dimensions.length; i++) {
  22639. var dimensionName;
  22640. var dimensionInfo = {};
  22641. if (typeof dimensions[i] === 'string') {
  22642. dimensionName = dimensions[i];
  22643. dimensionInfo = {
  22644. name: dimensionName,
  22645. coordDim: dimensionName,
  22646. coordDimIndex: 0,
  22647. stackable: false,
  22648. // Type can be 'float', 'int', 'number'
  22649. // Default is float64
  22650. type: 'float'
  22651. };
  22652. }
  22653. else {
  22654. dimensionInfo = dimensions[i];
  22655. dimensionName = dimensionInfo.name;
  22656. dimensionInfo.type = dimensionInfo.type || 'float';
  22657. if (!dimensionInfo.coordDim) {
  22658. dimensionInfo.coordDim = dimensionName;
  22659. dimensionInfo.coordDimIndex = 0;
  22660. }
  22661. }
  22662. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22663. dimensionNames.push(dimensionName);
  22664. dimensionInfos[dimensionName] = dimensionInfo;
  22665. dimensionInfo.index = i;
  22666. }
  22667. /**
  22668. * @readOnly
  22669. * @type {Array.<string>}
  22670. */
  22671. this.dimensions = dimensionNames;
  22672. /**
  22673. * Infomation of each data dimension, like data type.
  22674. * @type {Object}
  22675. */
  22676. this._dimensionInfos = dimensionInfos;
  22677. /**
  22678. * @type {module:echarts/model/Model}
  22679. */
  22680. this.hostModel = hostModel;
  22681. /**
  22682. * @type {module:echarts/model/Model}
  22683. */
  22684. this.dataType;
  22685. /**
  22686. * Indices stores the indices of data subset after filtered.
  22687. * This data subset will be used in chart.
  22688. * @type {Array.<number>}
  22689. * @readOnly
  22690. */
  22691. this._indices = null;
  22692. this._count = 0;
  22693. this._rawCount = 0;
  22694. /**
  22695. * Data storage
  22696. * @type {Object.<key, Array.<TypedArray|Array>>}
  22697. * @private
  22698. */
  22699. this._storage = {};
  22700. /**
  22701. * @type {Array.<string>}
  22702. */
  22703. this._nameList = [];
  22704. /**
  22705. * @type {Array.<string>}
  22706. */
  22707. this._idList = [];
  22708. /**
  22709. * Models of data option is stored sparse for optimizing memory cost
  22710. * @type {Array.<module:echarts/model/Model>}
  22711. * @private
  22712. */
  22713. this._optionModels = [];
  22714. /**
  22715. * @param {module:echarts/data/List}
  22716. */
  22717. this.stackedOn = null;
  22718. /**
  22719. * Global visual properties after visual coding
  22720. * @type {Object}
  22721. * @private
  22722. */
  22723. this._visual = {};
  22724. /**
  22725. * Globel layout properties.
  22726. * @type {Object}
  22727. * @private
  22728. */
  22729. this._layout = {};
  22730. /**
  22731. * Item visual properties after visual coding
  22732. * @type {Array.<Object>}
  22733. * @private
  22734. */
  22735. this._itemVisuals = [];
  22736. /**
  22737. * Key: visual type, Value: boolean
  22738. * @type {Object}
  22739. * @readOnly
  22740. */
  22741. this.hasItemVisual = {};
  22742. /**
  22743. * Item layout properties after layout
  22744. * @type {Array.<Object>}
  22745. * @private
  22746. */
  22747. this._itemLayouts = [];
  22748. /**
  22749. * Graphic elemnents
  22750. * @type {Array.<module:zrender/Element>}
  22751. * @private
  22752. */
  22753. this._graphicEls = [];
  22754. /**
  22755. * Max size of each chunk.
  22756. * @type {number}
  22757. * @private
  22758. */
  22759. this._chunkSize = 1e5;
  22760. /**
  22761. * @type {number}
  22762. * @private
  22763. */
  22764. this._chunkCount = 0;
  22765. /**
  22766. * @type {Array.<Array|Object>}
  22767. * @private
  22768. */
  22769. this._rawData;
  22770. /**
  22771. * Raw extent will not be cloned, but only transfered.
  22772. * It will not be calculated util needed.
  22773. * key: dim,
  22774. * value: {end: number, extent: Array.<number>}
  22775. * @type {Object}
  22776. * @private
  22777. */
  22778. this._rawExtent = {};
  22779. /**
  22780. * @type {Object}
  22781. * @private
  22782. */
  22783. this._extent = {};
  22784. /**
  22785. * key: dim
  22786. * value: extent
  22787. * @type {Object}
  22788. * @private
  22789. */
  22790. this._approximateExtent = {};
  22791. /**
  22792. * Cache summary info for fast visit. See "dimensionHelper".
  22793. * @type {Object}
  22794. * @private
  22795. */
  22796. this._dimensionsSummary = summarizeDimensions(this);
  22797. };
  22798. var listProto = List.prototype;
  22799. listProto.type = 'list';
  22800. /**
  22801. * If each data item has it's own option
  22802. * @type {boolean}
  22803. */
  22804. listProto.hasItemOption = true;
  22805. /**
  22806. * Get dimension name
  22807. * @param {string|number} dim
  22808. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22809. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22810. * @return {string} Concrete dim name.
  22811. */
  22812. listProto.getDimension = function (dim) {
  22813. if (!isNaN(dim)) {
  22814. dim = this.dimensions[dim] || dim;
  22815. }
  22816. return dim;
  22817. };
  22818. /**
  22819. * Get type and stackable info of particular dimension
  22820. * @param {string|number} dim
  22821. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22822. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22823. */
  22824. listProto.getDimensionInfo = function (dim) {
  22825. // Do not clone, because there may be categories in dimInfo.
  22826. return this._dimensionInfos[this.getDimension(dim)];
  22827. };
  22828. /**
  22829. * @return {Array.<string>} concrete dimension name list on coord.
  22830. */
  22831. listProto.getDimensionsOnCoord = function () {
  22832. return this._dimensionsSummary.dataDimsOnCoord.slice();
  22833. };
  22834. /**
  22835. * @param {string} coordDim
  22836. * @param {number|Array} [idx=0] A coordDim may map to more than one data dim.
  22837. * If idx is `true`, return a array of all mapped dims.
  22838. * @return {string|Array.<string>} concrete data dim.
  22839. * If idx is number, and not found, return null/undefined.
  22840. * If idx is `true`, and not found, return empty array.
  22841. */
  22842. listProto.mapDimension = function (coordDim, idx) {
  22843. var dims = this._dimensionsSummary.encode[coordDim];
  22844. return idx === true
  22845. ? (dims && dims.slice() || [])
  22846. : dims
  22847. ? dims[idx || 0]
  22848. : null;
  22849. };
  22850. /**
  22851. * Initialize from data
  22852. * @param {Array.<Object|number|Array>} data source or data or data provider.
  22853. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  22854. * defualt label/tooltip.
  22855. * A name can be specified in encode.itemName,
  22856. * or dataItem.name (only for series option data),
  22857. * or provided in nameList from outside.
  22858. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  22859. */
  22860. listProto.initData = function (data, nameList, dimValueGetter) {
  22861. var notProvider = Source.isInstance(data) || isArrayLike(data);
  22862. if (notProvider) {
  22863. data = new DefaultDataProvider(data, this.dimensions.length);
  22864. }
  22865. if (__DEV__) {
  22866. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  22867. throw new Error('Inavlid data provider.');
  22868. }
  22869. }
  22870. this._rawData = data;
  22871. // Clear
  22872. this._storage = {};
  22873. this._indices = null;
  22874. this._nameList = nameList || [];
  22875. this._idList = [];
  22876. this._nameRepeatCount = {};
  22877. if (!dimValueGetter) {
  22878. this.hasItemOption = false;
  22879. }
  22880. /**
  22881. * @readOnly
  22882. */
  22883. this.defaultDimValueGetter = defaultDimValueGetters[
  22884. this._rawData.getSource().sourceFormat
  22885. ];
  22886. // Default dim value getter
  22887. this._dimValueGetter = dimValueGetter = dimValueGetter
  22888. || this.defaultDimValueGetter;
  22889. // Reset raw extent.
  22890. this._rawExtent = {};
  22891. this._initDataFromProvider(0, data.count());
  22892. // If data has no item option.
  22893. if (data.pure) {
  22894. this.hasItemOption = false;
  22895. }
  22896. };
  22897. listProto.getProvider = function () {
  22898. return this._rawData;
  22899. };
  22900. listProto.appendData = function (data) {
  22901. if (__DEV__) {
  22902. assert$1(!this._indices, 'appendData can only be called on raw data.');
  22903. }
  22904. var rawData = this._rawData;
  22905. var start = this.count();
  22906. rawData.appendData(data);
  22907. var end = rawData.count();
  22908. if (!rawData.persistent) {
  22909. end += start;
  22910. }
  22911. this._initDataFromProvider(start, end);
  22912. };
  22913. listProto._initDataFromProvider = function (start, end) {
  22914. // Optimize.
  22915. if (start >= end) {
  22916. return;
  22917. }
  22918. var chunkSize = this._chunkSize;
  22919. var rawData = this._rawData;
  22920. var storage = this._storage;
  22921. var dimensions = this.dimensions;
  22922. var dimensionInfoMap = this._dimensionInfos;
  22923. var nameList = this._nameList;
  22924. var idList = this._idList;
  22925. var rawExtent = this._rawExtent;
  22926. var nameRepeatCount = this._nameRepeatCount = {};
  22927. var nameDimIdx;
  22928. var chunkCount = this._chunkCount;
  22929. var lastChunkIndex = chunkCount - 1;
  22930. for (var i = 0; i < dimensions.length; i++) {
  22931. var dim = dimensions[i];
  22932. if (!rawExtent[dim]) {
  22933. rawExtent[dim] = [Infinity, -Infinity];
  22934. }
  22935. var dimInfo = dimensionInfoMap[dim];
  22936. if (dimInfo.otherDims.itemName === 0) {
  22937. nameDimIdx = this._nameDimIdx = i;
  22938. }
  22939. if (dimInfo.otherDims.itemId === 0) {
  22940. this._idDimIdx = i;
  22941. }
  22942. var DataCtor = dataCtors[dimInfo.type];
  22943. if (!storage[dim]) {
  22944. storage[dim] = [];
  22945. }
  22946. var resizeChunkArray = storage[dim][lastChunkIndex];
  22947. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  22948. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  22949. // The cost of the copy is probably inconsiderable
  22950. // within the initial chunkSize.
  22951. for (var j = 0; j < resizeChunkArray.length; j++) {
  22952. newStore[j] = resizeChunkArray[j];
  22953. }
  22954. storage[dim][lastChunkIndex] = newStore;
  22955. }
  22956. // Create new chunks.
  22957. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  22958. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  22959. }
  22960. this._chunkCount = storage[dim].length;
  22961. }
  22962. for (var idx = start; idx < end; idx++) {
  22963. // NOTICE: Try not to write things into dataItem
  22964. var dataItem = rawData.getItem(idx);
  22965. // Each data item is value
  22966. // [1, 2]
  22967. // 2
  22968. // Bar chart, line chart which uses category axis
  22969. // only gives the 'y' value. 'x' value is the indices of category
  22970. // Use a tempValue to normalize the value to be a (x, y) value
  22971. var chunkIndex = Math.floor(idx / chunkSize);
  22972. var chunkOffset = idx % chunkSize;
  22973. // Store the data by dimensions
  22974. for (var k = 0; k < dimensions.length; k++) {
  22975. var dim = dimensions[k];
  22976. var dimStorage = storage[dim][chunkIndex];
  22977. // PENDING NULL is empty or zero
  22978. var val = this._dimValueGetter(dataItem, dim, idx, k);
  22979. dimStorage[chunkOffset] = val;
  22980. if (val < rawExtent[dim][0]) {
  22981. rawExtent[dim][0] = val;
  22982. }
  22983. if (val > rawExtent[dim][1]) {
  22984. rawExtent[dim][1] = val;
  22985. }
  22986. }
  22987. // ??? FIXME not check by pure but sourceFormat?
  22988. // TODO refactor these logic.
  22989. if (!rawData.pure) {
  22990. var name = nameList[idx];
  22991. if (dataItem && !name) {
  22992. if (nameDimIdx != null) {
  22993. name = this._getNameFromStore(idx);
  22994. }
  22995. else if (dataItem.name != null) {
  22996. // There is no other place to persistent dataItem.name,
  22997. // so save it to nameList.
  22998. nameList[idx] = name = dataItem.name;
  22999. }
  23000. }
  23001. // Try using the id in option
  23002. // id or name is used on dynamical data, mapping old and new items.
  23003. var id = dataItem == null ? null : dataItem.id;
  23004. if (id == null && name != null) {
  23005. // Use name as id and add counter to avoid same name
  23006. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23007. id = name;
  23008. if (nameRepeatCount[name] > 0) {
  23009. id += '__ec__' + nameRepeatCount[name];
  23010. }
  23011. nameRepeatCount[name]++;
  23012. }
  23013. id != null && (idList[idx] = id);
  23014. }
  23015. }
  23016. if (!rawData.persistent && rawData.clean) {
  23017. // Clean unused data if data source is typed array.
  23018. rawData.clean();
  23019. }
  23020. this._rawCount = this._count = end;
  23021. // Reset data extent
  23022. this._extent = {};
  23023. };
  23024. // TODO refactor
  23025. listProto._getNameFromStore = function (rawIndex) {
  23026. var nameDimIdx = this._nameDimIdx;
  23027. if (nameDimIdx != null) {
  23028. var chunkSize = this._chunkSize;
  23029. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23030. var chunkOffset = rawIndex % chunkSize;
  23031. var dim = this.dimensions[nameDimIdx];
  23032. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23033. if (ordinalMeta) {
  23034. return ordinalMeta.categories[rawIndex];
  23035. }
  23036. else {
  23037. var chunk = this._storage[dim][chunkIndex];
  23038. return chunk && chunk[chunkOffset];
  23039. }
  23040. }
  23041. };
  23042. // TODO refactor
  23043. listProto._getIdFromStore = function (rawIndex) {
  23044. var idDimIdx = this._idDimIdx;
  23045. if (idDimIdx != null) {
  23046. var chunkSize = this._chunkSize;
  23047. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23048. var chunkOffset = rawIndex % chunkSize;
  23049. var dim = this.dimensions[idDimIdx];
  23050. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23051. if (ordinalMeta) {
  23052. return ordinalMeta.categories[rawIndex];
  23053. }
  23054. else {
  23055. var chunk = this._storage[dim][chunkIndex];
  23056. return chunk && chunk[chunkOffset];
  23057. }
  23058. }
  23059. };
  23060. /**
  23061. * @return {number}
  23062. */
  23063. listProto.count = function () {
  23064. return this._count;
  23065. };
  23066. listProto.getIndices = function () {
  23067. if (this._indices) {
  23068. var Ctor = this._indices.constructor;
  23069. return new Ctor(this._indices.buffer, 0, this._count);
  23070. }
  23071. var Ctor = getIndicesCtor(this);
  23072. var arr = new Ctor(this.count());
  23073. for (var i = 0; i < arr.length; i++) {
  23074. arr[i] = i;
  23075. }
  23076. return arr;
  23077. };
  23078. /**
  23079. * Get value. Return NaN if idx is out of range.
  23080. * @param {string} dim Dim must be concrete name.
  23081. * @param {number} idx
  23082. * @param {boolean} stack
  23083. * @return {number}
  23084. */
  23085. listProto.get = function (dim, idx, stack) {
  23086. if (!(idx >= 0 && idx < this._count)) {
  23087. return NaN;
  23088. }
  23089. var storage = this._storage;
  23090. if (!storage[dim]) {
  23091. // TODO Warn ?
  23092. return NaN;
  23093. }
  23094. idx = this.getRawIndex(idx);
  23095. var chunkIndex = Math.floor(idx / this._chunkSize);
  23096. var chunkOffset = idx % this._chunkSize;
  23097. var chunkStore = storage[dim][chunkIndex];
  23098. var value = chunkStore[chunkOffset];
  23099. // FIXME ordinal data type is not stackable
  23100. if (stack) {
  23101. var dimensionInfo = this._dimensionInfos[dim];
  23102. if (dimensionInfo && dimensionInfo.stackable) {
  23103. var stackedOn = this.stackedOn;
  23104. while (stackedOn) {
  23105. // Get no stacked data of stacked on
  23106. var stackedValue = stackedOn.get(dim, idx);
  23107. // Considering positive stack, negative stack and empty data
  23108. if ((value >= 0 && stackedValue > 0) // Positive stack
  23109. || (value <= 0 && stackedValue < 0) // Negative stack
  23110. ) {
  23111. value += stackedValue;
  23112. }
  23113. stackedOn = stackedOn.stackedOn;
  23114. }
  23115. }
  23116. }
  23117. return value;
  23118. };
  23119. // FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23120. // Hack a much simpler _getFast
  23121. listProto._getFast = function (dim, rawIdx) {
  23122. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23123. var chunkOffset = rawIdx % this._chunkSize;
  23124. var chunkStore = this._storage[dim][chunkIndex];
  23125. return chunkStore[chunkOffset];
  23126. };
  23127. /**
  23128. * Get value for multi dimensions.
  23129. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23130. * @param {number} idx
  23131. * @param {boolean} stack
  23132. * @return {number}
  23133. */
  23134. listProto.getValues = function (dimensions, idx, stack) {
  23135. var values = [];
  23136. if (!isArray(dimensions)) {
  23137. stack = idx;
  23138. idx = dimensions;
  23139. dimensions = this.dimensions;
  23140. }
  23141. for (var i = 0, len = dimensions.length; i < len; i++) {
  23142. values.push(this.get(dimensions[i], idx, stack));
  23143. }
  23144. return values;
  23145. };
  23146. /**
  23147. * If value is NaN. Inlcuding '-'
  23148. * Only check the coord dimensions.
  23149. * @param {string} dim
  23150. * @param {number} idx
  23151. * @return {number}
  23152. */
  23153. listProto.hasValue = function (idx) {
  23154. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23155. var dimensionInfos = this._dimensionInfos;
  23156. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23157. if (
  23158. // Ordinal type can be string or number
  23159. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23160. // FIXME check ordinal when using index?
  23161. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23162. ) {
  23163. return false;
  23164. }
  23165. }
  23166. return true;
  23167. };
  23168. /**
  23169. * Get extent of data in one dimension
  23170. * @param {string} dim
  23171. * @param {boolean} stack
  23172. */
  23173. listProto.getDataExtent = function (dim, stack) {
  23174. // Make sure use concrete dim as cache name.
  23175. dim = this.getDimension(dim);
  23176. var dimData = this._storage[dim];
  23177. var initialExtent = [Infinity, -Infinity];
  23178. stack = (stack || false) && this.isStacked(dim);
  23179. if (!dimData) {
  23180. return initialExtent;
  23181. }
  23182. // Make more strict checkings to ensure hitting cache.
  23183. var currEnd = this.count();
  23184. var cacheName = [dim, !!stack].join('_');
  23185. // Consider the most cases when using data zoom, `getDataExtent`
  23186. // happened before filtering. We cache raw extent, which is not
  23187. // necessary to be cleared and recalculated when restore data.
  23188. var useRaw = !this._indices && !stack;
  23189. var dimExtent;
  23190. if (useRaw) {
  23191. return this._rawExtent[dim].slice();
  23192. }
  23193. dimExtent = this._extent[cacheName];
  23194. if (dimExtent) {
  23195. return dimExtent.slice();
  23196. }
  23197. dimExtent = initialExtent;
  23198. var min = dimExtent[0];
  23199. var max = dimExtent[1];
  23200. for (var i = 0; i < currEnd; i++) {
  23201. var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23202. value < min && (min = value);
  23203. value > max && (max = value);
  23204. }
  23205. dimExtent = [min, max];
  23206. this._extent[cacheName] = dimExtent;
  23207. return dimExtent;
  23208. };
  23209. /**
  23210. * Optimize for the scenario that data is filtered by a given extent.
  23211. * Consider that if data amount is more than hundreds of thousand,
  23212. * extent calculation will cost more than 10ms and the cache will
  23213. * be erased because of the filtering.
  23214. */
  23215. listProto.getApproximateExtent = function (dim, stack) {
  23216. dim = this.getDimension(dim);
  23217. return this._approximateExtent[dim] || this.getDataExtent(dim, stack);
  23218. };
  23219. listProto.setApproximateExtent = function (extent, dim, stack) {
  23220. dim = this.getDimension(dim);
  23221. this._approximateExtent[dim] = extent.slice();
  23222. };
  23223. listProto.isStacked = function (concreteDim) {
  23224. var dimensionInfo = this._dimensionInfos[concreteDim];
  23225. return dimensionInfo && dimensionInfo.stackable && this.stackedOn;
  23226. };
  23227. /**
  23228. * Get sum of data in one dimension
  23229. * @param {string} dim
  23230. * @param {boolean} stack
  23231. */
  23232. listProto.getSum = function (dim, stack) {
  23233. var dimData = this._storage[dim];
  23234. var sum = 0;
  23235. if (dimData) {
  23236. for (var i = 0, len = this.count(); i < len; i++) {
  23237. var value = this.get(dim, i, stack);
  23238. if (!isNaN(value)) {
  23239. sum += value;
  23240. }
  23241. }
  23242. }
  23243. return sum;
  23244. };
  23245. /**
  23246. * Retreive the index with given value
  23247. * @param {number} idx
  23248. * @param {number} value
  23249. * @return {number}
  23250. */
  23251. // FIXME Precision of float value
  23252. listProto.indexOf = function (dim, value) {
  23253. var storage = this._storage;
  23254. var dimData = storage[dim];
  23255. var chunkSize = this._chunkSize;
  23256. if (dimData) {
  23257. for (var i = 0, len = this.count(); i < len; i++) {
  23258. var chunkIndex = Math.floor(i / chunkSize);
  23259. var chunkOffset = i % chunkSize;
  23260. if (dimData[chunkIndex][chunkOffset] === value) {
  23261. return i;
  23262. }
  23263. }
  23264. }
  23265. return -1;
  23266. };
  23267. /**
  23268. * Retreive the index with given name
  23269. * @param {number} idx
  23270. * @param {number} name
  23271. * @return {number}
  23272. */
  23273. listProto.indexOfName = function (name) {
  23274. for (var i = 0, len = this.count(); i < len; i++) {
  23275. if (this.getName(i) === name) {
  23276. return i;
  23277. }
  23278. }
  23279. return -1;
  23280. };
  23281. /**
  23282. * Retreive the index with given raw data index
  23283. * @param {number} idx
  23284. * @param {number} name
  23285. * @return {number}
  23286. */
  23287. listProto.indexOfRawIndex = function (rawIndex) {
  23288. if (!this._indices) {
  23289. return rawIndex;
  23290. }
  23291. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23292. return -1;
  23293. }
  23294. // Indices are ascending
  23295. var indices = this._indices;
  23296. // If rawIndex === dataIndex
  23297. var rawDataIndex = indices[rawIndex];
  23298. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23299. return rawIndex;
  23300. }
  23301. var left = 0;
  23302. var right = this._count - 1;
  23303. while (left <= right) {
  23304. var mid = (left + right) / 2 | 0;
  23305. if (indices[mid] < rawIndex) {
  23306. left = mid + 1;
  23307. }
  23308. else if (indices[mid] > rawIndex) {
  23309. right = mid - 1;
  23310. }
  23311. else {
  23312. return mid;
  23313. }
  23314. }
  23315. return -1;
  23316. };
  23317. /**
  23318. * Retreive the index of nearest value
  23319. * @param {string} dim
  23320. * @param {number} value
  23321. * @param {boolean} stack If given value is after stacked
  23322. * @param {number} [maxDistance=Infinity]
  23323. * @return {Array.<number>} Considere multiple points has the same value.
  23324. */
  23325. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  23326. var storage = this._storage;
  23327. var dimData = storage[dim];
  23328. var nearestIndices = [];
  23329. if (!dimData) {
  23330. return nearestIndices;
  23331. }
  23332. if (maxDistance == null) {
  23333. maxDistance = Infinity;
  23334. }
  23335. var minDist = Number.MAX_VALUE;
  23336. var minDiff = -1;
  23337. for (var i = 0, len = this.count(); i < len; i++) {
  23338. var diff = value - this.get(dim, i, stack);
  23339. var dist = Math.abs(diff);
  23340. if (diff <= maxDistance && dist <= minDist) {
  23341. // For the case of two data are same on xAxis, which has sequence data.
  23342. // Show the nearest index
  23343. // https://github.com/ecomfe/echarts/issues/2869
  23344. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23345. minDist = dist;
  23346. minDiff = diff;
  23347. nearestIndices.length = 0;
  23348. }
  23349. nearestIndices.push(i);
  23350. }
  23351. }
  23352. return nearestIndices;
  23353. };
  23354. /**
  23355. * Get raw data index
  23356. * @param {number} idx
  23357. * @return {number}
  23358. */
  23359. listProto.getRawIndex = getRawIndexWithoutIndices;
  23360. function getRawIndexWithoutIndices(idx) {
  23361. return idx;
  23362. }
  23363. function getRawIndexWithIndices(idx) {
  23364. if (idx < this._count && idx >= 0) {
  23365. return this._indices[idx];
  23366. }
  23367. return -1;
  23368. }
  23369. /**
  23370. * Get raw data item
  23371. * @param {number} idx
  23372. * @return {number}
  23373. */
  23374. listProto.getRawDataItem = function (idx) {
  23375. if (!this._rawData.persistent) {
  23376. var val = [];
  23377. for (var i = 0; i < this.dimensions.length; i++) {
  23378. var dim = this.dimensions[i];
  23379. val.push(this.get(dim, idx));
  23380. }
  23381. return val;
  23382. }
  23383. else {
  23384. return this._rawData.getItem(this.getRawIndex(idx));
  23385. }
  23386. };
  23387. /**
  23388. * @param {number} idx
  23389. * @param {boolean} [notDefaultIdx=false]
  23390. * @return {string}
  23391. */
  23392. listProto.getName = function (idx) {
  23393. var rawIndex = this.getRawIndex(idx);
  23394. return this._nameList[rawIndex]
  23395. || this._getNameFromStore(rawIndex)
  23396. || '';
  23397. };
  23398. /**
  23399. * @param {number} idx
  23400. * @param {boolean} [notDefaultIdx=false]
  23401. * @return {string}
  23402. */
  23403. listProto.getId = function (idx) {
  23404. return getId(this, this.getRawIndex(idx));
  23405. };
  23406. function getId(list, rawIndex) {
  23407. var id = list._idList[rawIndex];
  23408. if (id == null) {
  23409. id = list._getIdFromStore(rawIndex);
  23410. }
  23411. if (id == null) {
  23412. // FIXME Check the usage in graph, should not use prefix.
  23413. id = ID_PREFIX + rawIndex;
  23414. }
  23415. return id;
  23416. }
  23417. function normalizeDimensions(dimensions) {
  23418. if (!isArray(dimensions)) {
  23419. dimensions = [dimensions];
  23420. }
  23421. return dimensions;
  23422. }
  23423. function validateDimensions(list, dims) {
  23424. for (var i = 0; i < dims.length; i++) {
  23425. // stroage may be empty when no data, so use
  23426. // dimensionInfos to check.
  23427. if (!list._dimensionInfos[dims[i]]) {
  23428. console.error('Unkown dimension ' + dims[i]);
  23429. }
  23430. }
  23431. }
  23432. /**
  23433. * Data iteration
  23434. * @param {string|Array.<string>}
  23435. * @param {Function} cb
  23436. * @param {boolean} [stack=false]
  23437. * @param {*} [context=this]
  23438. *
  23439. * @example
  23440. * list.each('x', function (x, idx) {});
  23441. * list.each(['x', 'y'], function (x, y, idx) {});
  23442. * list.each(function (idx) {})
  23443. */
  23444. listProto.each = function (dims, cb, stack, context) {
  23445. 'use strict';
  23446. if (!this._count) {
  23447. return;
  23448. }
  23449. if (typeof dims === 'function') {
  23450. context = stack;
  23451. stack = cb;
  23452. cb = dims;
  23453. dims = [];
  23454. }
  23455. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23456. if (__DEV__) {
  23457. validateDimensions(this, dims);
  23458. }
  23459. var dimSize = dims.length;
  23460. context = context || this;
  23461. for (var i = 0; i < this.count(); i++) {
  23462. // Simple optimization
  23463. switch (dimSize) {
  23464. case 0:
  23465. cb.call(context, i);
  23466. break;
  23467. case 1:
  23468. cb.call(context, this.get(dims[0], i, stack), i);
  23469. break;
  23470. case 2:
  23471. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  23472. break;
  23473. default:
  23474. var k = 0;
  23475. var value = [];
  23476. for (; k < dimSize; k++) {
  23477. value[k] = this.get(dims[k], i, stack);
  23478. }
  23479. // Index
  23480. value[k] = i;
  23481. cb.apply(context, value);
  23482. }
  23483. }
  23484. };
  23485. /**
  23486. * Data filter
  23487. * @param {string|Array.<string>}
  23488. * @param {Function} cb
  23489. * @param {boolean} [stack=false]
  23490. * @param {*} [context=this]
  23491. */
  23492. listProto.filterSelf = function (dimensions, cb, stack, context) {
  23493. 'use strict';
  23494. if (!this._count) {
  23495. return;
  23496. }
  23497. if (typeof dimensions === 'function') {
  23498. context = stack;
  23499. stack = cb;
  23500. cb = dimensions;
  23501. dimensions = [];
  23502. }
  23503. stack = stack || false;
  23504. context = context || this;
  23505. dimensions = map(
  23506. normalizeDimensions(dimensions), this.getDimension, this
  23507. );
  23508. if (__DEV__) {
  23509. validateDimensions(this, dimensions);
  23510. }
  23511. var count = this.count();
  23512. var Ctor = getIndicesCtor(this);
  23513. var newIndices = new Ctor(count);
  23514. var value = [];
  23515. var dimSize = dimensions.length;
  23516. var offset = 0;
  23517. var dim0 = dimensions[0];
  23518. for (var i = 0; i < count; i++) {
  23519. var keep;
  23520. var rawIdx = this.getRawIndex(i);
  23521. // Simple optimization
  23522. if (dimSize === 0) {
  23523. keep = cb.call(context, i);
  23524. }
  23525. else if (dimSize === 1) {
  23526. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIdx);
  23527. keep = cb.call(context, val, i);
  23528. }
  23529. else {
  23530. for (var k = 0; k < dimSize; k++) {
  23531. value[k] = stack ? this.get(dimensions[k], i, true) : this._getFast(dim0, rawIdx);
  23532. }
  23533. value[k] = i;
  23534. keep = cb.apply(context, value);
  23535. }
  23536. if (keep) {
  23537. newIndices[offset++] = rawIdx;
  23538. }
  23539. }
  23540. // Set indices after filtered.
  23541. if (offset < count) {
  23542. this._indices = newIndices;
  23543. }
  23544. this._count = offset;
  23545. // Reset data extent
  23546. this._extent = {};
  23547. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23548. return this;
  23549. };
  23550. /**
  23551. * Select data in range. (For optimization of filter)
  23552. * (Manually inline code, support 5 million data filtering in data zoom.)
  23553. */
  23554. listProto.selectRange = function (range, stack) {
  23555. 'use strict';
  23556. if (!this._count) {
  23557. return;
  23558. }
  23559. stack = stack || false;
  23560. var dimensions = [];
  23561. for (var dim in range) {
  23562. if (range.hasOwnProperty(dim)) {
  23563. dimensions.push(dim);
  23564. }
  23565. }
  23566. if (__DEV__) {
  23567. validateDimensions(this, dimensions);
  23568. }
  23569. var dimSize = dimensions.length;
  23570. if (!dimSize) {
  23571. return;
  23572. }
  23573. var originalCount = this.count();
  23574. var Ctor = getIndicesCtor(this);
  23575. var newIndices = new Ctor(originalCount);
  23576. var offset = 0;
  23577. var dim0 = dimensions[0];
  23578. var min = range[dim0][0];
  23579. var max = range[dim0][1];
  23580. var quickFinished = false;
  23581. if (!this._indices && !stack) {
  23582. // Extreme optimization for common case. About 2x faster in chrome.
  23583. var idx = 0;
  23584. if (dimSize === 1) {
  23585. var dimStorage = this._storage[dimensions[0]];
  23586. for (var k = 0; k < this._chunkCount; k++) {
  23587. var chunkStorage = dimStorage[k];
  23588. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23589. for (var i = 0; i < len; i++) {
  23590. var val = chunkStorage[i];
  23591. if (val >= min && val <= max) {
  23592. newIndices[offset++] = idx;
  23593. }
  23594. idx++;
  23595. }
  23596. }
  23597. quickFinished = true;
  23598. }
  23599. else if (dimSize === 2) {
  23600. var dimStorage = this._storage[dim0];
  23601. var dimStorage2 = this._storage[dimensions[1]];
  23602. var min2 = range[dimensions[1]][0];
  23603. var max2 = range[dimensions[1]][1];
  23604. for (var k = 0; k < this._chunkCount; k++) {
  23605. var chunkStorage = dimStorage[k];
  23606. var chunkStorage2= dimStorage2[k];
  23607. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23608. for (var i = 0; i < len; i++) {
  23609. var val = chunkStorage[i];
  23610. var val2 = chunkStorage2[i];
  23611. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23612. newIndices[offset++] = idx;
  23613. }
  23614. idx++;
  23615. }
  23616. }
  23617. quickFinished = true;
  23618. }
  23619. }
  23620. if (!quickFinished) {
  23621. if (dimSize === 1) {
  23622. stack = stack || this.isStacked(dim0);
  23623. for (var i = 0; i < originalCount; i++) {
  23624. var rawIndex = this.getRawIndex(i);
  23625. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23626. if (val >= min && val <= max) {
  23627. newIndices[offset++] = rawIndex;
  23628. }
  23629. }
  23630. }
  23631. else {
  23632. for (var i = 0; i < originalCount; i++) {
  23633. var keep = true;
  23634. var rawIndex = this.getRawIndex(i);
  23635. for (var k = 0; k < dimSize; k++) {
  23636. var dimk = dimensions[k];
  23637. var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23638. if (val < range[dimk][0] || val > range[dimk][1]) {
  23639. keep = false;
  23640. }
  23641. }
  23642. if (keep) {
  23643. newIndices[offset++] = this.getRawIndex(i);
  23644. }
  23645. }
  23646. }
  23647. }
  23648. // Set indices after filtered.
  23649. if (offset < originalCount) {
  23650. this._indices = newIndices;
  23651. }
  23652. this._count = offset;
  23653. // Reset data extent
  23654. this._extent = {};
  23655. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23656. return this;
  23657. };
  23658. /**
  23659. * Data mapping to a plain array
  23660. * @param {string|Array.<string>} [dimensions]
  23661. * @param {Function} cb
  23662. * @param {boolean} [stack=false]
  23663. * @param {*} [context=this]
  23664. * @return {Array}
  23665. */
  23666. listProto.mapArray = function (dimensions, cb, stack, context) {
  23667. 'use strict';
  23668. if (typeof dimensions === 'function') {
  23669. context = stack;
  23670. stack = cb;
  23671. cb = dimensions;
  23672. dimensions = [];
  23673. }
  23674. var result = [];
  23675. this.each(dimensions, function () {
  23676. result.push(cb && cb.apply(this, arguments));
  23677. }, stack, context);
  23678. return result;
  23679. };
  23680. // Data in excludeDimensions is copied, otherwise transfered.
  23681. function cloneListForMapAndSample(original, excludeDimensions) {
  23682. var allDimensions = original.dimensions;
  23683. var list = new List(
  23684. map(allDimensions, original.getDimensionInfo, original),
  23685. original.hostModel
  23686. );
  23687. // FIXME If needs stackedOn, value may already been stacked
  23688. transferProperties(list, original);
  23689. var storage = list._storage = {};
  23690. var originalStorage = original._storage;
  23691. // Init storage
  23692. for (var i = 0; i < allDimensions.length; i++) {
  23693. var dim = allDimensions[i];
  23694. if (originalStorage[dim]) {
  23695. storage[dim] = indexOf(excludeDimensions, dim) >= 0
  23696. ? cloneDimStore(originalStorage[dim])
  23697. // Direct reference for other dimensions
  23698. : originalStorage[dim];
  23699. }
  23700. }
  23701. return list;
  23702. }
  23703. function cloneDimStore(originalDimStore) {
  23704. var newDimStore = new Array(originalDimStore.length);
  23705. for (var j = 0; j < originalDimStore.length; j++) {
  23706. newDimStore[j] = cloneChunk(originalDimStore[j]);
  23707. }
  23708. return newDimStore;
  23709. }
  23710. /**
  23711. * Data mapping to a new List with given dimensions
  23712. * @param {string|Array.<string>} dimensions
  23713. * @param {Function} cb
  23714. * @param {boolean} [stack=false]
  23715. * @param {*} [context=this]
  23716. * @return {Array}
  23717. */
  23718. listProto.map = function (dimensions, cb, stack, context) {
  23719. 'use strict';
  23720. dimensions = map(
  23721. normalizeDimensions(dimensions), this.getDimension, this
  23722. );
  23723. if (__DEV__) {
  23724. validateDimensions(this, dimensions);
  23725. }
  23726. var list = cloneListForMapAndSample(this, dimensions);
  23727. // Following properties are all immutable.
  23728. // So we can reference to the same value
  23729. list._indices = this._indices;
  23730. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23731. var storage = list._storage;
  23732. var tmpRetValue = [];
  23733. var chunkSize = this._chunkSize;
  23734. var dimSize = dimensions.length;
  23735. var dataCount = this.count();
  23736. var values = [];
  23737. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  23738. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  23739. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex, stack);
  23740. }
  23741. values[dimSize] = dataIndex;
  23742. var retValue = cb && cb.apply(context, values);
  23743. if (retValue != null) {
  23744. // a number or string (in oridinal dimension)?
  23745. if (typeof retValue !== 'object') {
  23746. tmpRetValue[0] = retValue;
  23747. retValue = tmpRetValue;
  23748. }
  23749. var rawIndex = this.getRawIndex(dataIndex);
  23750. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23751. var chunkOffset = rawIndex % chunkSize;
  23752. for (var i = 0; i < retValue.length; i++) {
  23753. var dim = dimensions[i];
  23754. var dimStore = storage[dim];
  23755. if (dimStore) {
  23756. dimStore[chunkIndex][chunkOffset] = retValue[i];
  23757. }
  23758. }
  23759. }
  23760. }
  23761. return list;
  23762. };
  23763. /**
  23764. * Large data down sampling on given dimension
  23765. * @param {string} dimension
  23766. * @param {number} rate
  23767. * @param {Function} sampleValue
  23768. * @param {Function} sampleIndex Sample index for name and id
  23769. */
  23770. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  23771. var list = cloneListForMapAndSample(this, [dimension]);
  23772. var targetStorage = list._storage;
  23773. var frameValues = [];
  23774. var frameSize = Math.floor(1 / rate);
  23775. var dimStore = targetStorage[dimension];
  23776. var len = this.count();
  23777. var chunkSize = this._chunkSize;
  23778. var newIndices = new (getIndicesCtor(this))(len);
  23779. var offset = 0;
  23780. for (var i = 0; i < len; i += frameSize) {
  23781. // Last frame
  23782. if (frameSize > len - i) {
  23783. frameSize = len - i;
  23784. frameValues.length = frameSize;
  23785. }
  23786. for (var k = 0; k < frameSize; k++) {
  23787. var dataIdx = this.getRawIndex(i + k);
  23788. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  23789. var originalChunkOffset = dataIdx % chunkSize;
  23790. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  23791. }
  23792. var value = sampleValue(frameValues);
  23793. var sampleFrameIdx = this.getRawIndex(
  23794. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  23795. );
  23796. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  23797. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  23798. // Only write value on the filtered data
  23799. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  23800. newIndices[offset++] = sampleFrameIdx;
  23801. }
  23802. list._count = offset;
  23803. list._indices = newIndices;
  23804. list.getRawIndex = getRawIndexWithIndices;
  23805. return list;
  23806. };
  23807. /**
  23808. * Get model of one data item.
  23809. *
  23810. * @param {number} idx
  23811. */
  23812. // FIXME Model proxy ?
  23813. listProto.getItemModel = function (idx) {
  23814. var hostModel = this.hostModel;
  23815. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  23816. };
  23817. /**
  23818. * Create a data differ
  23819. * @param {module:echarts/data/List} otherList
  23820. * @return {module:echarts/data/DataDiffer}
  23821. */
  23822. listProto.diff = function (otherList) {
  23823. var thisList = this;
  23824. return new DataDiffer(
  23825. otherList ? otherList.getIndices() : [],
  23826. this.getIndices(),
  23827. function (idx) {
  23828. return getId(otherList, idx);
  23829. },
  23830. function (idx) {
  23831. return getId(thisList, idx);
  23832. }
  23833. );
  23834. };
  23835. /**
  23836. * Get visual property.
  23837. * @param {string} key
  23838. */
  23839. listProto.getVisual = function (key) {
  23840. var visual = this._visual;
  23841. return visual && visual[key];
  23842. };
  23843. /**
  23844. * Set visual property
  23845. * @param {string|Object} key
  23846. * @param {*} [value]
  23847. *
  23848. * @example
  23849. * setVisual('color', color);
  23850. * setVisual({
  23851. * 'color': color
  23852. * });
  23853. */
  23854. listProto.setVisual = function (key, val) {
  23855. if (isObject$4(key)) {
  23856. for (var name in key) {
  23857. if (key.hasOwnProperty(name)) {
  23858. this.setVisual(name, key[name]);
  23859. }
  23860. }
  23861. return;
  23862. }
  23863. this._visual = this._visual || {};
  23864. this._visual[key] = val;
  23865. };
  23866. /**
  23867. * Set layout property.
  23868. * @param {string|Object} key
  23869. * @param {*} [val]
  23870. */
  23871. listProto.setLayout = function (key, val) {
  23872. if (isObject$4(key)) {
  23873. for (var name in key) {
  23874. if (key.hasOwnProperty(name)) {
  23875. this.setLayout(name, key[name]);
  23876. }
  23877. }
  23878. return;
  23879. }
  23880. this._layout[key] = val;
  23881. };
  23882. /**
  23883. * Get layout property.
  23884. * @param {string} key.
  23885. * @return {*}
  23886. */
  23887. listProto.getLayout = function (key) {
  23888. return this._layout[key];
  23889. };
  23890. /**
  23891. * Get layout of single data item
  23892. * @param {number} idx
  23893. */
  23894. listProto.getItemLayout = function (idx) {
  23895. return this._itemLayouts[idx];
  23896. };
  23897. /**
  23898. * Set layout of single data item
  23899. * @param {number} idx
  23900. * @param {Object} layout
  23901. * @param {boolean=} [merge=false]
  23902. */
  23903. listProto.setItemLayout = function (idx, layout, merge$$1) {
  23904. this._itemLayouts[idx] = merge$$1
  23905. ? extend(this._itemLayouts[idx] || {}, layout)
  23906. : layout;
  23907. };
  23908. /**
  23909. * Clear all layout of single data item
  23910. */
  23911. listProto.clearItemLayouts = function () {
  23912. this._itemLayouts.length = 0;
  23913. };
  23914. /**
  23915. * Get visual property of single data item
  23916. * @param {number} idx
  23917. * @param {string} key
  23918. * @param {boolean} [ignoreParent=false]
  23919. */
  23920. listProto.getItemVisual = function (idx, key, ignoreParent) {
  23921. var itemVisual = this._itemVisuals[idx];
  23922. var val = itemVisual && itemVisual[key];
  23923. if (val == null && !ignoreParent) {
  23924. // Use global visual property
  23925. return this.getVisual(key);
  23926. }
  23927. return val;
  23928. };
  23929. /**
  23930. * Set visual property of single data item
  23931. *
  23932. * @param {number} idx
  23933. * @param {string|Object} key
  23934. * @param {*} [value]
  23935. *
  23936. * @example
  23937. * setItemVisual(0, 'color', color);
  23938. * setItemVisual(0, {
  23939. * 'color': color
  23940. * });
  23941. */
  23942. listProto.setItemVisual = function (idx, key, value) {
  23943. var itemVisual = this._itemVisuals[idx] || {};
  23944. var hasItemVisual = this.hasItemVisual;
  23945. this._itemVisuals[idx] = itemVisual;
  23946. if (isObject$4(key)) {
  23947. for (var name in key) {
  23948. if (key.hasOwnProperty(name)) {
  23949. itemVisual[name] = key[name];
  23950. hasItemVisual[name] = true;
  23951. }
  23952. }
  23953. return;
  23954. }
  23955. itemVisual[key] = value;
  23956. hasItemVisual[key] = true;
  23957. };
  23958. /**
  23959. * Clear itemVisuals and list visual.
  23960. */
  23961. listProto.clearAllVisual = function () {
  23962. this._visual = {};
  23963. this._itemVisuals = [];
  23964. this.hasItemVisual = {};
  23965. };
  23966. var setItemDataAndSeriesIndex = function (child) {
  23967. child.seriesIndex = this.seriesIndex;
  23968. child.dataIndex = this.dataIndex;
  23969. child.dataType = this.dataType;
  23970. };
  23971. /**
  23972. * Set graphic element relative to data. It can be set as null
  23973. * @param {number} idx
  23974. * @param {module:zrender/Element} [el]
  23975. */
  23976. listProto.setItemGraphicEl = function (idx, el) {
  23977. var hostModel = this.hostModel;
  23978. if (el) {
  23979. // Add data index and series index for indexing the data by element
  23980. // Useful in tooltip
  23981. el.dataIndex = idx;
  23982. el.dataType = this.dataType;
  23983. el.seriesIndex = hostModel && hostModel.seriesIndex;
  23984. if (el.type === 'group') {
  23985. el.traverse(setItemDataAndSeriesIndex, el);
  23986. }
  23987. }
  23988. this._graphicEls[idx] = el;
  23989. };
  23990. /**
  23991. * @param {number} idx
  23992. * @return {module:zrender/Element}
  23993. */
  23994. listProto.getItemGraphicEl = function (idx) {
  23995. return this._graphicEls[idx];
  23996. };
  23997. /**
  23998. * @param {Function} cb
  23999. * @param {*} context
  24000. */
  24001. listProto.eachItemGraphicEl = function (cb, context) {
  24002. each$1(this._graphicEls, function (el, idx) {
  24003. if (el) {
  24004. cb && cb.call(context, el, idx);
  24005. }
  24006. });
  24007. };
  24008. /**
  24009. * Shallow clone a new list except visual and layout properties, and graph elements.
  24010. * New list only change the indices.
  24011. */
  24012. listProto.cloneShallow = function (list) {
  24013. if (!list) {
  24014. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24015. list = new List(dimensionInfoList, this.hostModel);
  24016. }
  24017. // FIXME
  24018. list._storage = this._storage;
  24019. transferProperties(list, this);
  24020. // Clone will not change the data extent and indices
  24021. if (this._indices) {
  24022. var Ctor = this._indices.constructor;
  24023. list._indices = new Ctor(this._indices);
  24024. }
  24025. else {
  24026. list._indices = null;
  24027. }
  24028. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24029. list._extent = clone(this._extent);
  24030. list._approximateExtent = clone(this._approximateExtent);
  24031. return list;
  24032. };
  24033. /**
  24034. * Wrap some method to add more feature
  24035. * @param {string} methodName
  24036. * @param {Function} injectFunction
  24037. */
  24038. listProto.wrapMethod = function (methodName, injectFunction) {
  24039. var originalMethod = this[methodName];
  24040. if (typeof originalMethod !== 'function') {
  24041. return;
  24042. }
  24043. this.__wrappedMethods = this.__wrappedMethods || [];
  24044. this.__wrappedMethods.push(methodName);
  24045. this[methodName] = function () {
  24046. var res = originalMethod.apply(this, arguments);
  24047. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24048. };
  24049. };
  24050. // Methods that create a new list based on this list should be listed here.
  24051. // Notice that those method should `RETURN` the new list.
  24052. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24053. // Methods that change indices of this list should be listed here.
  24054. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24055. /**
  24056. * @deprecated
  24057. * Use `echarts/data/helper/createDimensions` instead.
  24058. */
  24059. /**
  24060. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24061. *
  24062. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24063. * and guessing from the data structure.
  24064. * If no 'value' dimension specified, the first no-named dimension will be
  24065. * named as 'value'.
  24066. *
  24067. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24068. * provides not only dim template, but also default order.
  24069. * properties: 'name', 'type', 'displayName'.
  24070. * `name` of each item provides default coord name.
  24071. * [{dimsDef: [string...]}, ...] can be specified to give names.
  24072. * [{ordinalMeta}] can be specified.
  24073. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24074. * @param {Object} [opt]
  24075. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24076. * For example: ['asdf', {name, type}, ...].
  24077. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24078. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  24079. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  24080. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  24081. * If not specified, extra dim names will be:
  24082. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  24083. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24084. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24085. * @return {Array.<Object>} [{
  24086. * name: string mandatory,
  24087. * displayName: string, the origin name in dimsDef, see source helper.
  24088. * If displayName given, the tooltip will displayed vertically.
  24089. * coordDim: string mandatory,
  24090. * isSysCoord: boolean True if the coord is from sys dimension.
  24091. * coordDimIndex: number mandatory,
  24092. * type: string optional,
  24093. * otherDims: { never null/undefined
  24094. * tooltip: number optional,
  24095. * label: number optional,
  24096. * itemName: number optional,
  24097. * seriesName: number optional,
  24098. * },
  24099. * isExtraCoord: boolean true or undefined.
  24100. * other props ...
  24101. * }]
  24102. */
  24103. function completeDimensions(sysDims, source, opt) {
  24104. if (!Source.isInstance(source)) {
  24105. source = Source.seriesDataToSource(source);
  24106. }
  24107. opt = opt || {};
  24108. sysDims = (sysDims || []).slice();
  24109. var dimsDef = (opt.dimsDef || []).slice();
  24110. var encodeDef = createHashMap(opt.encodeDef);
  24111. var dataDimNameMap = createHashMap();
  24112. var coordDimNameMap = createHashMap();
  24113. // var valueCandidate;
  24114. var result = [];
  24115. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24116. // Apply user defined dims (`name` and `type`) and init result.
  24117. for (var i = 0; i < dimCount; i++) {
  24118. var dimDefItem = dimsDef[i] = extend(
  24119. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24120. );
  24121. var userDimName = dimDefItem.name;
  24122. var resultItem = result[i] = {otherDims: {}};
  24123. // Name will be applied later for avoiding duplication.
  24124. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24125. // Only if `series.dimensions` is defined in option
  24126. // displayName, will be set, and dimension will be diplayed vertically in
  24127. // tooltip by default.
  24128. resultItem.name = resultItem.displayName = userDimName;
  24129. dataDimNameMap.set(userDimName, i);
  24130. }
  24131. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24132. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24133. }
  24134. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24135. encodeDef.each(function (dataDims, coordDim) {
  24136. dataDims = normalizeToArray(dataDims).slice();
  24137. var validDataDims = encodeDef.set(coordDim, []);
  24138. each$1(dataDims, function (resultDimIdx, idx) {
  24139. // The input resultDimIdx can be dim name or index.
  24140. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24141. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24142. validDataDims[idx] = resultDimIdx;
  24143. applyDim(result[resultDimIdx], coordDim, idx);
  24144. }
  24145. });
  24146. });
  24147. // Apply templetes and default order from `sysDims`.
  24148. var availDimIdx = 0;
  24149. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24150. var coordDim;
  24151. var sysDimItem;
  24152. var sysDimItemDimsDef;
  24153. var sysDimItemOtherDims;
  24154. if (isString(sysDimItem)) {
  24155. coordDim = sysDimItem;
  24156. sysDimItem = {};
  24157. }
  24158. else {
  24159. coordDim = sysDimItem.name;
  24160. var ordinalMeta = sysDimItem.ordinalMeta;
  24161. sysDimItem.ordinalMeta = null;
  24162. sysDimItem = clone(sysDimItem);
  24163. sysDimItem.ordinalMeta = ordinalMeta;
  24164. // `coordDimIndex` should not be set directly.
  24165. sysDimItemDimsDef = sysDimItem.dimsDef;
  24166. sysDimItemOtherDims = sysDimItem.otherDims;
  24167. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24168. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24169. }
  24170. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24171. // dimensions provides default dim sequences.
  24172. if (!dataDims.length) {
  24173. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24174. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24175. availDimIdx++;
  24176. }
  24177. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24178. }
  24179. }
  24180. // Apply templates.
  24181. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24182. var resultItem = result[resultDimIdx];
  24183. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24184. if (resultItem.name == null && sysDimItemDimsDef) {
  24185. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24186. }
  24187. resultItem.isSysCoord = true;
  24188. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24189. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24190. });
  24191. });
  24192. function applyDim(resultItem, coordDim, coordDimIndex) {
  24193. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24194. resultItem.otherDims[coordDim] = coordDimIndex;
  24195. }
  24196. else {
  24197. resultItem.coordDim = coordDim;
  24198. resultItem.coordDimIndex = coordDimIndex;
  24199. coordDimNameMap.set(coordDim, true);
  24200. }
  24201. }
  24202. // Make sure the first extra dim is 'value'.
  24203. var extra = opt.extraPrefix || 'value';
  24204. // Set dim `name` and other `coordDim` and other props.
  24205. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24206. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24207. var coordDim = resultItem.coordDim;
  24208. coordDim == null && (
  24209. resultItem.coordDim = genName(
  24210. extra, coordDimNameMap, opt.extraFromZero
  24211. ),
  24212. resultItem.coordDimIndex = 0,
  24213. resultItem.isExtraCoord = true
  24214. );
  24215. resultItem.name == null && (resultItem.name = genName(
  24216. resultItem.coordDim,
  24217. dataDimNameMap
  24218. ));
  24219. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24220. resultItem.type = 'ordinal';
  24221. }
  24222. }
  24223. return result;
  24224. }
  24225. // ??? TODO
  24226. // Originally detect dimCount by data[0]. Should we
  24227. // optimize it to only by sysDims and dimensions and encode.
  24228. // So only necessary dims will be initialized.
  24229. // But
  24230. // (1) custom series should be considered. where other dims
  24231. // may be visited.
  24232. // (2) sometimes user need to calcualte bubble size or use visualMap
  24233. // on other dimensions besides coordSys needed.
  24234. function getDimCount(source, sysDims, dimsDef, dimCount) {
  24235. if (dimCount == null) {
  24236. dimCount = Math.max(
  24237. source.dimensionsDetectCount || 1,
  24238. sysDims.length,
  24239. dimsDef.length
  24240. );
  24241. each$1(sysDims, function (sysDimItem) {
  24242. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24243. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24244. });
  24245. }
  24246. return dimCount;
  24247. }
  24248. function genName(name, map$$1, fromZero) {
  24249. if (fromZero || map$$1.get(name) != null) {
  24250. var i = 0;
  24251. while (map$$1.get(name + i) != null) {
  24252. i++;
  24253. }
  24254. name += i;
  24255. }
  24256. map$$1.set(name, true);
  24257. return name;
  24258. }
  24259. /**
  24260. * Substitute `completeDimensions`.
  24261. * `completeDimensions` is to be deprecated.
  24262. */
  24263. /**
  24264. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24265. * @param {Object|Array} [opt]
  24266. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24267. * @param {number} [opt.dimensionsCount]
  24268. * @param {string} [opt.extraPrefix]
  24269. * @param {boolean} [opt.extraFromZero]
  24270. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24271. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24272. * @return {Array.<Object>} dimensionsInfo
  24273. */
  24274. var createDimensions = function (source, opt) {
  24275. opt = opt || {};
  24276. return completeDimensions(opt.coordDimensions || [], source, {
  24277. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24278. encodeDef: opt.encodeDefine || source.encodeDefine,
  24279. dimCount: opt.dimensionsCount,
  24280. extraPrefix: opt.extraPrefix,
  24281. extraFromZero: opt.extraFromZero
  24282. });
  24283. };
  24284. /**
  24285. * @param {module:echarts/data/Source|Array} source Or raw data.
  24286. * @param {module:echarts/model/Series} seriesModel
  24287. */
  24288. function createListFromArray(source, seriesModel) {
  24289. if (!Source.isInstance(source)) {
  24290. source = Source.seriesDataToSource(source);
  24291. }
  24292. var coordSysName = seriesModel.get('coordinateSystem');
  24293. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24294. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24295. var coordSysDimDefs;
  24296. if (coordSysDefine) {
  24297. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24298. var dimInfo = {name: dim};
  24299. var axisModel = coordSysDefine.axisMap.get(dim);
  24300. if (axisModel) {
  24301. var axisType = axisModel.get('type');
  24302. dimInfo.type = getDimensionTypeByAxis(axisType);
  24303. dimInfo.stackable = isStackable(axisType);
  24304. }
  24305. return dimInfo;
  24306. });
  24307. }
  24308. if (!coordSysDimDefs) {
  24309. // Get dimensions from registered coordinate system
  24310. coordSysDimDefs = (registeredCoordSys && (
  24311. registeredCoordSys.getDimensionsInfo
  24312. ? registeredCoordSys.getDimensionsInfo()
  24313. : registeredCoordSys.dimensions.slice()
  24314. )) || ['x', 'y'];
  24315. }
  24316. var dimInfoList = createDimensions(source, {
  24317. coordDimensions: coordSysDimDefs
  24318. });
  24319. var firstCategoryDimIndex;
  24320. var hasNameEncode;
  24321. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24322. var coordDim = dimInfo.coordDim;
  24323. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24324. if (categoryAxisModel) {
  24325. if (firstCategoryDimIndex == null) {
  24326. firstCategoryDimIndex = dimIndex;
  24327. }
  24328. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24329. }
  24330. if (dimInfo.otherDims.itemName != null) {
  24331. hasNameEncode = true;
  24332. }
  24333. });
  24334. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24335. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24336. }
  24337. var list = new List(dimInfoList, seriesModel);
  24338. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24339. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24340. // Use dataIndex as ordinal value in categoryAxis
  24341. return dimIndex === firstCategoryDimIndex
  24342. ? dataIndex
  24343. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24344. }
  24345. : null;
  24346. list.hasItemOption = false;
  24347. list.initData(source, null, dimValueGetter);
  24348. return list;
  24349. }
  24350. function isStackable(axisType) {
  24351. return axisType !== 'category' && axisType !== 'time';
  24352. }
  24353. function isNeedCompleteOrdinalData(source) {
  24354. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24355. var sampleItem = firstDataNotNull(source.data || []);
  24356. return sampleItem != null
  24357. && !isArray(getDataItemValue(sampleItem));
  24358. }
  24359. }
  24360. function firstDataNotNull(data) {
  24361. var i = 0;
  24362. while (i < data.length && data[i] == null) {
  24363. i++;
  24364. }
  24365. return data[i];
  24366. }
  24367. /**
  24368. * // Scale class management
  24369. * @module echarts/scale/Scale
  24370. */
  24371. /**
  24372. * @param {Object} [setting]
  24373. */
  24374. function Scale(setting) {
  24375. this._setting = setting || {};
  24376. /**
  24377. * Extent
  24378. * @type {Array.<number>}
  24379. * @protected
  24380. */
  24381. this._extent = [Infinity, -Infinity];
  24382. /**
  24383. * Step is calculated in adjustExtent
  24384. * @type {Array.<number>}
  24385. * @protected
  24386. */
  24387. this._interval = 0;
  24388. this.init && this.init.apply(this, arguments);
  24389. }
  24390. /**
  24391. * Parse input val to valid inner number.
  24392. * @param {*} val
  24393. * @return {number}
  24394. */
  24395. Scale.prototype.parse = function (val) {
  24396. // Notice: This would be a trap here, If the implementation
  24397. // of this method depends on extent, and this method is used
  24398. // before extent set (like in dataZoom), it would be wrong.
  24399. // Nevertheless, parse does not depend on extent generally.
  24400. return val;
  24401. };
  24402. Scale.prototype.getSetting = function (name) {
  24403. return this._setting[name];
  24404. };
  24405. Scale.prototype.contain = function (val) {
  24406. var extent = this._extent;
  24407. return val >= extent[0] && val <= extent[1];
  24408. };
  24409. /**
  24410. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24411. * @param {number} val
  24412. * @return {number}
  24413. */
  24414. Scale.prototype.normalize = function (val) {
  24415. var extent = this._extent;
  24416. if (extent[1] === extent[0]) {
  24417. return 0.5;
  24418. }
  24419. return (val - extent[0]) / (extent[1] - extent[0]);
  24420. };
  24421. /**
  24422. * Scale normalized value
  24423. * @param {number} val
  24424. * @return {number}
  24425. */
  24426. Scale.prototype.scale = function (val) {
  24427. var extent = this._extent;
  24428. return val * (extent[1] - extent[0]) + extent[0];
  24429. };
  24430. /**
  24431. * Set extent from data
  24432. * @param {Array.<number>} other
  24433. */
  24434. Scale.prototype.unionExtent = function (other) {
  24435. var extent = this._extent;
  24436. other[0] < extent[0] && (extent[0] = other[0]);
  24437. other[1] > extent[1] && (extent[1] = other[1]);
  24438. // not setExtent because in log axis it may transformed to power
  24439. // this.setExtent(extent[0], extent[1]);
  24440. };
  24441. /**
  24442. * Set extent from data
  24443. * @param {module:echarts/data/List} data
  24444. * @param {string} dim
  24445. */
  24446. Scale.prototype.unionExtentFromData = function (data, dim) {
  24447. this.unionExtent(data.getApproximateExtent(dim, true));
  24448. };
  24449. /**
  24450. * Get extent
  24451. * @return {Array.<number>}
  24452. */
  24453. Scale.prototype.getExtent = function () {
  24454. return this._extent.slice();
  24455. };
  24456. /**
  24457. * Set extent
  24458. * @param {number} start
  24459. * @param {number} end
  24460. */
  24461. Scale.prototype.setExtent = function (start, end) {
  24462. var thisExtent = this._extent;
  24463. if (!isNaN(start)) {
  24464. thisExtent[0] = start;
  24465. }
  24466. if (!isNaN(end)) {
  24467. thisExtent[1] = end;
  24468. }
  24469. };
  24470. /**
  24471. * @return {Array.<string>}
  24472. */
  24473. Scale.prototype.getTicksLabels = function () {
  24474. var labels = [];
  24475. var ticks = this.getTicks();
  24476. for (var i = 0; i < ticks.length; i++) {
  24477. labels.push(this.getLabel(ticks[i]));
  24478. }
  24479. return labels;
  24480. };
  24481. /**
  24482. * When axis extent depends on data and no data exists,
  24483. * axis ticks should not be drawn, which is named 'blank'.
  24484. */
  24485. Scale.prototype.isBlank = function () {
  24486. return this._isBlank;
  24487. },
  24488. /**
  24489. * When axis extent depends on data and no data exists,
  24490. * axis ticks should not be drawn, which is named 'blank'.
  24491. */
  24492. Scale.prototype.setBlank = function (isBlank) {
  24493. this._isBlank = isBlank;
  24494. };
  24495. enableClassExtend(Scale);
  24496. enableClassManagement(Scale, {
  24497. registerWhenExtend: true
  24498. });
  24499. /**
  24500. * @constructor
  24501. * @param {Object} [opt]
  24502. * @param {Object} [opt.categories=[]]
  24503. * @param {Object} [opt.needCollect=false]
  24504. * @param {Object} [opt.deduplication=false]
  24505. */
  24506. function OrdinalMeta(opt) {
  24507. /**
  24508. * @readOnly
  24509. * @type {Array.<string>}
  24510. */
  24511. this.categories = opt.categories || [];
  24512. /**
  24513. * @private
  24514. * @type {boolean}
  24515. */
  24516. this._needCollect = opt.needCollect;
  24517. /**
  24518. * @private
  24519. * @type {boolean}
  24520. */
  24521. this._deduplication = opt.deduplication;
  24522. /**
  24523. * @private
  24524. * @type {boolean}
  24525. */
  24526. this._map;
  24527. }
  24528. /**
  24529. * @param {module:echarts/model/Model} axisModel
  24530. * @return {module:echarts/data/OrdinalMeta}
  24531. */
  24532. OrdinalMeta.createByAxisModel = function (axisModel) {
  24533. var option = axisModel.option;
  24534. var data = option.data;
  24535. var categories = data && map(data, getName);
  24536. return new OrdinalMeta({
  24537. categories: categories,
  24538. needCollect: !categories,
  24539. // deduplication is default in axis.
  24540. deduplication: option.dedplication !== false
  24541. });
  24542. };
  24543. var proto$1 = OrdinalMeta.prototype;
  24544. /**
  24545. * @param {string} category
  24546. * @return {number} ordinal
  24547. */
  24548. proto$1.getOrdinal = function (category) {
  24549. return getOrCreateMap(this).get(category);
  24550. };
  24551. /**
  24552. * @param {*} category
  24553. * @return {number} The ordinal. If not found, return NaN.
  24554. */
  24555. proto$1.parseAndCollect = function (category) {
  24556. var index;
  24557. var needCollect = this._needCollect;
  24558. // The value of category dim can be the index of the given category set.
  24559. // This feature is only supported when !needCollect, because we should
  24560. // consider a common case: a value is 2017, which is a number but is
  24561. // expected to be tread as a category. This case usually happen in dataset,
  24562. // where it happent to be no need of the index feature.
  24563. if (typeof category !== 'string' && !needCollect) {
  24564. return category;
  24565. }
  24566. // Optimize for the scenario:
  24567. // category is ['2012-01-01', '2012-01-02', ...], where the input
  24568. // data has been ensured not duplicate and is large data.
  24569. // Notice, if a dataset dimension provide categroies, usually echarts
  24570. // should remove duplication except user tell echarts dont do that
  24571. // (set axis.deduplication = false), because echarts do not know whether
  24572. // the values in the category dimension has duplication (consider the
  24573. // parallel-aqi example)
  24574. if (needCollect && !this._deduplication) {
  24575. index = this.categories.length;
  24576. this.categories[index] = category;
  24577. return index;
  24578. }
  24579. var map$$1 = getOrCreateMap(this);
  24580. index = map$$1.get(category);
  24581. if (index == null) {
  24582. if (needCollect) {
  24583. index = this.categories.length;
  24584. this.categories[index] = category;
  24585. map$$1.set(category, index);
  24586. }
  24587. else {
  24588. index = NaN;
  24589. }
  24590. }
  24591. return index;
  24592. };
  24593. // Consider big data, do not create map until needed.
  24594. function getOrCreateMap(ordinalMeta) {
  24595. return ordinalMeta._map || (
  24596. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  24597. );
  24598. }
  24599. function getName(obj) {
  24600. if (isObject$1(obj) && obj.value != null) {
  24601. return obj.value;
  24602. }
  24603. else {
  24604. return obj + '';
  24605. }
  24606. }
  24607. /**
  24608. * Linear continuous scale
  24609. * @module echarts/coord/scale/Ordinal
  24610. *
  24611. * http://en.wikipedia.org/wiki/Level_of_measurement
  24612. */
  24613. // FIXME only one data
  24614. var scaleProto = Scale.prototype;
  24615. var OrdinalScale = Scale.extend({
  24616. type: 'ordinal',
  24617. /**
  24618. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  24619. */
  24620. init: function (ordinalMeta, extent) {
  24621. // Caution: Should not use instanceof, consider ec-extensions using
  24622. // import approach to get OrdinalMeta class.
  24623. if (!ordinalMeta || isArray(ordinalMeta)) {
  24624. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  24625. }
  24626. this._ordinalMeta = ordinalMeta;
  24627. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  24628. },
  24629. parse: function (val) {
  24630. return typeof val === 'string'
  24631. ? this._ordinalMeta.getOrdinal(val)
  24632. // val might be float.
  24633. : Math.round(val);
  24634. },
  24635. contain: function (rank) {
  24636. rank = this.parse(rank);
  24637. return scaleProto.contain.call(this, rank)
  24638. && this._ordinalMeta.categories[rank] != null;
  24639. },
  24640. /**
  24641. * Normalize given rank or name to linear [0, 1]
  24642. * @param {number|string} [val]
  24643. * @return {number}
  24644. */
  24645. normalize: function (val) {
  24646. return scaleProto.normalize.call(this, this.parse(val));
  24647. },
  24648. scale: function (val) {
  24649. return Math.round(scaleProto.scale.call(this, val));
  24650. },
  24651. /**
  24652. * @return {Array}
  24653. */
  24654. getTicks: function () {
  24655. var ticks = [];
  24656. var extent = this._extent;
  24657. var rank = extent[0];
  24658. while (rank <= extent[1]) {
  24659. ticks.push(rank);
  24660. rank++;
  24661. }
  24662. return ticks;
  24663. },
  24664. /**
  24665. * Get item on rank n
  24666. * @param {number} n
  24667. * @return {string}
  24668. */
  24669. getLabel: function (n) {
  24670. return this._ordinalMeta.categories[n];
  24671. },
  24672. /**
  24673. * @return {number}
  24674. */
  24675. count: function () {
  24676. return this._extent[1] - this._extent[0] + 1;
  24677. },
  24678. /**
  24679. * @override
  24680. */
  24681. unionExtentFromData: function (data, dim) {
  24682. this.unionExtent(data.getApproximateExtent(dim, false));
  24683. },
  24684. niceTicks: noop,
  24685. niceExtent: noop
  24686. });
  24687. /**
  24688. * @return {module:echarts/scale/Time}
  24689. */
  24690. OrdinalScale.create = function () {
  24691. return new OrdinalScale();
  24692. };
  24693. /**
  24694. * For testable.
  24695. */
  24696. var roundNumber$1 = round$1;
  24697. /**
  24698. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  24699. * Should be extent[0] < extent[1].
  24700. * @param {number} splitNumber splitNumber should be >= 1.
  24701. * @param {number} [minInterval]
  24702. * @param {number} [maxInterval]
  24703. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  24704. */
  24705. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  24706. var result = {};
  24707. var span = extent[1] - extent[0];
  24708. var interval = result.interval = nice(span / splitNumber, true);
  24709. if (minInterval != null && interval < minInterval) {
  24710. interval = result.interval = minInterval;
  24711. }
  24712. if (maxInterval != null && interval > maxInterval) {
  24713. interval = result.interval = maxInterval;
  24714. }
  24715. // Tow more digital for tick.
  24716. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  24717. // Niced extent inside original extent
  24718. var niceTickExtent = result.niceTickExtent = [
  24719. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  24720. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  24721. ];
  24722. fixExtent(niceTickExtent, extent);
  24723. return result;
  24724. }
  24725. /**
  24726. * @param {number} interval
  24727. * @return {number} interval precision
  24728. */
  24729. function getIntervalPrecision(interval) {
  24730. // Tow more digital for tick.
  24731. return getPrecisionSafe(interval) + 2;
  24732. }
  24733. function clamp(niceTickExtent, idx, extent) {
  24734. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  24735. }
  24736. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  24737. function fixExtent(niceTickExtent, extent) {
  24738. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  24739. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  24740. clamp(niceTickExtent, 0, extent);
  24741. clamp(niceTickExtent, 1, extent);
  24742. if (niceTickExtent[0] > niceTickExtent[1]) {
  24743. niceTickExtent[0] = niceTickExtent[1];
  24744. }
  24745. }
  24746. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  24747. var ticks = [];
  24748. // If interval is 0, return [];
  24749. if (!interval) {
  24750. return ticks;
  24751. }
  24752. // Consider this case: using dataZoom toolbox, zoom and zoom.
  24753. var safeLimit = 10000;
  24754. if (extent[0] < niceTickExtent[0]) {
  24755. ticks.push(extent[0]);
  24756. }
  24757. var tick = niceTickExtent[0];
  24758. while (tick <= niceTickExtent[1]) {
  24759. ticks.push(tick);
  24760. // Avoid rounding error
  24761. tick = roundNumber$1(tick + interval, intervalPrecision);
  24762. if (tick === ticks[ticks.length - 1]) {
  24763. // Consider out of safe float point, e.g.,
  24764. // -3711126.9907707 + 2e-10 === -3711126.9907707
  24765. break;
  24766. }
  24767. if (ticks.length > safeLimit) {
  24768. return [];
  24769. }
  24770. }
  24771. // Consider this case: the last item of ticks is smaller
  24772. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  24773. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  24774. ticks.push(extent[1]);
  24775. }
  24776. return ticks;
  24777. }
  24778. /**
  24779. * Interval scale
  24780. * @module echarts/scale/Interval
  24781. */
  24782. var roundNumber = round$1;
  24783. /**
  24784. * @alias module:echarts/coord/scale/Interval
  24785. * @constructor
  24786. */
  24787. var IntervalScale = Scale.extend({
  24788. type: 'interval',
  24789. _interval: 0,
  24790. _intervalPrecision: 2,
  24791. setExtent: function (start, end) {
  24792. var thisExtent = this._extent;
  24793. //start,end may be a Number like '25',so...
  24794. if (!isNaN(start)) {
  24795. thisExtent[0] = parseFloat(start);
  24796. }
  24797. if (!isNaN(end)) {
  24798. thisExtent[1] = parseFloat(end);
  24799. }
  24800. },
  24801. unionExtent: function (other) {
  24802. var extent = this._extent;
  24803. other[0] < extent[0] && (extent[0] = other[0]);
  24804. other[1] > extent[1] && (extent[1] = other[1]);
  24805. // unionExtent may called by it's sub classes
  24806. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  24807. },
  24808. /**
  24809. * Get interval
  24810. */
  24811. getInterval: function () {
  24812. return this._interval;
  24813. },
  24814. /**
  24815. * Set interval
  24816. */
  24817. setInterval: function (interval) {
  24818. this._interval = interval;
  24819. // Dropped auto calculated niceExtent and use user setted extent
  24820. // We assume user wan't to set both interval, min, max to get a better result
  24821. this._niceExtent = this._extent.slice();
  24822. this._intervalPrecision = getIntervalPrecision(interval);
  24823. },
  24824. /**
  24825. * @return {Array.<number>}
  24826. */
  24827. getTicks: function () {
  24828. return intervalScaleGetTicks(
  24829. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  24830. );
  24831. },
  24832. /**
  24833. * @return {Array.<string>}
  24834. */
  24835. getTicksLabels: function () {
  24836. var labels = [];
  24837. var ticks = this.getTicks();
  24838. for (var i = 0; i < ticks.length; i++) {
  24839. labels.push(this.getLabel(ticks[i]));
  24840. }
  24841. return labels;
  24842. },
  24843. /**
  24844. * @param {number} data
  24845. * @param {Object} [opt]
  24846. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  24847. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  24848. * @return {string}
  24849. */
  24850. getLabel: function (data, opt) {
  24851. if (data == null) {
  24852. return '';
  24853. }
  24854. var precision = opt && opt.precision;
  24855. if (precision == null) {
  24856. precision = getPrecisionSafe(data) || 0;
  24857. }
  24858. else if (precision === 'auto') {
  24859. // Should be more precise then tick.
  24860. precision = this._intervalPrecision;
  24861. }
  24862. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  24863. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  24864. data = roundNumber(data, precision, true);
  24865. return addCommas(data);
  24866. },
  24867. /**
  24868. * Update interval and extent of intervals for nice ticks
  24869. *
  24870. * @param {number} [splitNumber = 5] Desired number of ticks
  24871. * @param {number} [minInterval]
  24872. * @param {number} [maxInterval]
  24873. */
  24874. niceTicks: function (splitNumber, minInterval, maxInterval) {
  24875. splitNumber = splitNumber || 5;
  24876. var extent = this._extent;
  24877. var span = extent[1] - extent[0];
  24878. if (!isFinite(span)) {
  24879. return;
  24880. }
  24881. // User may set axis min 0 and data are all negative
  24882. // FIXME If it needs to reverse ?
  24883. if (span < 0) {
  24884. span = -span;
  24885. extent.reverse();
  24886. }
  24887. var result = intervalScaleNiceTicks(
  24888. extent, splitNumber, minInterval, maxInterval
  24889. );
  24890. this._intervalPrecision = result.intervalPrecision;
  24891. this._interval = result.interval;
  24892. this._niceExtent = result.niceTickExtent;
  24893. },
  24894. /**
  24895. * Nice extent.
  24896. * @param {Object} opt
  24897. * @param {number} [opt.splitNumber = 5] Given approx tick number
  24898. * @param {boolean} [opt.fixMin=false]
  24899. * @param {boolean} [opt.fixMax=false]
  24900. * @param {boolean} [opt.minInterval]
  24901. * @param {boolean} [opt.maxInterval]
  24902. */
  24903. niceExtent: function (opt) {
  24904. var extent = this._extent;
  24905. // If extent start and end are same, expand them
  24906. if (extent[0] === extent[1]) {
  24907. if (extent[0] !== 0) {
  24908. // Expand extent
  24909. var expandSize = extent[0];
  24910. // In the fowllowing case
  24911. // Axis has been fixed max 100
  24912. // Plus data are all 100 and axis extent are [100, 100].
  24913. // Extend to the both side will cause expanded max is larger than fixed max.
  24914. // So only expand to the smaller side.
  24915. if (!opt.fixMax) {
  24916. extent[1] += expandSize / 2;
  24917. extent[0] -= expandSize / 2;
  24918. }
  24919. else {
  24920. extent[0] -= expandSize / 2;
  24921. }
  24922. }
  24923. else {
  24924. extent[1] = 1;
  24925. }
  24926. }
  24927. var span = extent[1] - extent[0];
  24928. // If there are no data and extent are [Infinity, -Infinity]
  24929. if (!isFinite(span)) {
  24930. extent[0] = 0;
  24931. extent[1] = 1;
  24932. }
  24933. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  24934. // var extent = this._extent;
  24935. var interval = this._interval;
  24936. if (!opt.fixMin) {
  24937. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  24938. }
  24939. if (!opt.fixMax) {
  24940. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  24941. }
  24942. }
  24943. });
  24944. /**
  24945. * @return {module:echarts/scale/Time}
  24946. */
  24947. IntervalScale.create = function () {
  24948. return new IntervalScale();
  24949. };
  24950. var STACK_PREFIX = '__ec_stack_';
  24951. function getSeriesStackId(seriesModel) {
  24952. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  24953. }
  24954. function getAxisKey(axis) {
  24955. return axis.dim + axis.index;
  24956. }
  24957. /**
  24958. * @param {Object} opt
  24959. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  24960. * @param {number} opt.count Positive interger.
  24961. * @param {number} [opt.barWidth]
  24962. * @param {number} [opt.barMaxWidth]
  24963. * @param {number} [opt.barGap]
  24964. * @param {number} [opt.barCategoryGap]
  24965. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  24966. */
  24967. function getLayoutOnAxis(opt, api) {
  24968. var params = [];
  24969. var baseAxis = opt.axis;
  24970. var axisKey = 'axis0';
  24971. if (baseAxis.type !== 'category') {
  24972. return;
  24973. }
  24974. var bandWidth = baseAxis.getBandWidth();
  24975. for (var i = 0; i < opt.count || 0; i++) {
  24976. params.push(defaults({
  24977. bandWidth: bandWidth,
  24978. axisKey: axisKey,
  24979. stackId: STACK_PREFIX + i
  24980. }, opt));
  24981. }
  24982. var widthAndOffsets = doCalBarWidthAndOffset(params, api);
  24983. var result = [];
  24984. for (var i = 0; i < opt.count; i++) {
  24985. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  24986. item.offsetCenter = item.offset + item.width / 2;
  24987. result.push(item);
  24988. }
  24989. return result;
  24990. }
  24991. function calBarWidthAndOffset(barSeries, api) {
  24992. var seriesInfoList = map(barSeries, function (seriesModel) {
  24993. var data = seriesModel.getData();
  24994. var cartesian = seriesModel.coordinateSystem;
  24995. var baseAxis = cartesian.getBaseAxis();
  24996. var axisExtent = baseAxis.getExtent();
  24997. var bandWidth = baseAxis.type === 'category'
  24998. ? baseAxis.getBandWidth()
  24999. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  25000. var barWidth = parsePercent$1(
  25001. seriesModel.get('barWidth'), bandWidth
  25002. );
  25003. var barMaxWidth = parsePercent$1(
  25004. seriesModel.get('barMaxWidth'), bandWidth
  25005. );
  25006. var barGap = seriesModel.get('barGap');
  25007. var barCategoryGap = seriesModel.get('barCategoryGap');
  25008. return {
  25009. bandWidth: bandWidth,
  25010. barWidth: barWidth,
  25011. barMaxWidth: barMaxWidth,
  25012. barGap: barGap,
  25013. barCategoryGap: barCategoryGap,
  25014. axisKey: getAxisKey(baseAxis),
  25015. stackId: getSeriesStackId(seriesModel)
  25016. };
  25017. });
  25018. return doCalBarWidthAndOffset(seriesInfoList, api);
  25019. }
  25020. function doCalBarWidthAndOffset(seriesInfoList, api) {
  25021. // Columns info on each category axis. Key is cartesian name
  25022. var columnsMap = {};
  25023. each$1(seriesInfoList, function (seriesInfo, idx) {
  25024. var axisKey = seriesInfo.axisKey;
  25025. var bandWidth = seriesInfo.bandWidth;
  25026. var columnsOnAxis = columnsMap[axisKey] || {
  25027. bandWidth: bandWidth,
  25028. remainedWidth: bandWidth,
  25029. autoWidthCount: 0,
  25030. categoryGap: '20%',
  25031. gap: '30%',
  25032. stacks: {}
  25033. };
  25034. var stacks = columnsOnAxis.stacks;
  25035. columnsMap[axisKey] = columnsOnAxis;
  25036. var stackId = seriesInfo.stackId;
  25037. if (!stacks[stackId]) {
  25038. columnsOnAxis.autoWidthCount++;
  25039. }
  25040. stacks[stackId] = stacks[stackId] || {
  25041. width: 0,
  25042. maxWidth: 0
  25043. };
  25044. // Caution: In a single coordinate system, these barGrid attributes
  25045. // will be shared by series. Consider that they have default values,
  25046. // only the attributes set on the last series will work.
  25047. // Do not change this fact unless there will be a break change.
  25048. // TODO
  25049. var barWidth = seriesInfo.barWidth;
  25050. if (barWidth && !stacks[stackId].width) {
  25051. // See #6312, do not restrict width.
  25052. stacks[stackId].width = barWidth;
  25053. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25054. columnsOnAxis.remainedWidth -= barWidth;
  25055. }
  25056. var barMaxWidth = seriesInfo.barMaxWidth;
  25057. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25058. var barGap = seriesInfo.barGap;
  25059. (barGap != null) && (columnsOnAxis.gap = barGap);
  25060. var barCategoryGap = seriesInfo.barCategoryGap;
  25061. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25062. });
  25063. var result = {};
  25064. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25065. result[coordSysName] = {};
  25066. var stacks = columnsOnAxis.stacks;
  25067. var bandWidth = columnsOnAxis.bandWidth;
  25068. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25069. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25070. var remainedWidth = columnsOnAxis.remainedWidth;
  25071. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25072. var autoWidth = (remainedWidth - categoryGap)
  25073. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25074. autoWidth = Math.max(autoWidth, 0);
  25075. // Find if any auto calculated bar exceeded maxBarWidth
  25076. each$1(stacks, function (column, stack) {
  25077. var maxWidth = column.maxWidth;
  25078. if (maxWidth && maxWidth < autoWidth) {
  25079. maxWidth = Math.min(maxWidth, remainedWidth);
  25080. if (column.width) {
  25081. maxWidth = Math.min(maxWidth, column.width);
  25082. }
  25083. remainedWidth -= maxWidth;
  25084. column.width = maxWidth;
  25085. autoWidthCount--;
  25086. }
  25087. });
  25088. // Recalculate width again
  25089. autoWidth = (remainedWidth - categoryGap)
  25090. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25091. autoWidth = Math.max(autoWidth, 0);
  25092. var widthSum = 0;
  25093. var lastColumn;
  25094. each$1(stacks, function (column, idx) {
  25095. if (!column.width) {
  25096. column.width = autoWidth;
  25097. }
  25098. lastColumn = column;
  25099. widthSum += column.width * (1 + barGapPercent);
  25100. });
  25101. if (lastColumn) {
  25102. widthSum -= lastColumn.width * barGapPercent;
  25103. }
  25104. var offset = -widthSum / 2;
  25105. each$1(stacks, function (column, stackId) {
  25106. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25107. offset: offset,
  25108. width: column.width
  25109. };
  25110. offset += column.width * (1 + barGapPercent);
  25111. });
  25112. });
  25113. return result;
  25114. }
  25115. /**
  25116. * @param {string} seriesType
  25117. * @param {module:echarts/model/Global} ecModel
  25118. * @param {module:echarts/ExtensionAPI} api
  25119. */
  25120. function layout(seriesType, ecModel, api) {
  25121. var barWidthAndOffset = calBarWidthAndOffset(
  25122. filter(
  25123. ecModel.getSeriesByType(seriesType),
  25124. function (seriesModel) {
  25125. return !ecModel.isSeriesFiltered(seriesModel)
  25126. && seriesModel.coordinateSystem
  25127. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25128. }
  25129. )
  25130. );
  25131. var lastStackCoords = {};
  25132. var lastStackCoordsOrigin = {};
  25133. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25134. // Check series coordinate, do layout for cartesian2d only
  25135. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  25136. return;
  25137. }
  25138. var data = seriesModel.getData();
  25139. var cartesian = seriesModel.coordinateSystem;
  25140. var baseAxis = cartesian.getBaseAxis();
  25141. var stackId = getSeriesStackId(seriesModel);
  25142. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25143. var columnOffset = columnLayoutInfo.offset;
  25144. var columnWidth = columnLayoutInfo.width;
  25145. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25146. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25147. var valueAxisStart = baseAxis.onZero
  25148. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25149. : valueAxis.getGlobalExtent()[0];
  25150. var coordDims = [
  25151. data.mapDimension('x'),
  25152. data.mapDimension('y')
  25153. ];
  25154. var coords = data.mapArray(coordDims, function (x, y) {
  25155. return cartesian.dataToPoint([x, y]);
  25156. }, true);
  25157. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25158. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  25159. data.setLayout({
  25160. offset: columnOffset,
  25161. size: columnWidth
  25162. });
  25163. data.each(data.mapDimension(valueAxis.dim), function (value, idx) {
  25164. if (isNaN(value)) {
  25165. return;
  25166. }
  25167. if (!lastStackCoords[stackId][idx]) {
  25168. lastStackCoords[stackId][idx] = {
  25169. p: valueAxisStart, // Positive stack
  25170. n: valueAxisStart // Negative stack
  25171. };
  25172. lastStackCoordsOrigin[stackId][idx] = {
  25173. p: valueAxisStart, // Positive stack
  25174. n: valueAxisStart // Negative stack
  25175. };
  25176. }
  25177. var sign = value >= 0 ? 'p' : 'n';
  25178. var coord = coords[idx];
  25179. var lastCoord = lastStackCoords[stackId][idx][sign];
  25180. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  25181. var x;
  25182. var y;
  25183. var width;
  25184. var height;
  25185. if (valueAxis.isHorizontal()) {
  25186. x = lastCoord;
  25187. y = coord[1] + columnOffset;
  25188. width = coord[0] - lastCoordOrigin;
  25189. height = columnWidth;
  25190. lastStackCoordsOrigin[stackId][idx][sign] += width;
  25191. if (Math.abs(width) < barMinHeight) {
  25192. width = (width < 0 ? -1 : 1) * barMinHeight;
  25193. }
  25194. lastStackCoords[stackId][idx][sign] += width;
  25195. }
  25196. else {
  25197. x = coord[0] + columnOffset;
  25198. y = lastCoord;
  25199. width = columnWidth;
  25200. height = coord[1] - lastCoordOrigin;
  25201. lastStackCoordsOrigin[stackId][idx][sign] += height;
  25202. if (Math.abs(height) < barMinHeight) {
  25203. // Include zero to has a positive bar
  25204. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25205. }
  25206. lastStackCoords[stackId][idx][sign] += height;
  25207. }
  25208. data.setItemLayout(idx, {
  25209. x: x,
  25210. y: y,
  25211. width: width,
  25212. height: height
  25213. });
  25214. }, true);
  25215. }, this);
  25216. }
  25217. // [About UTC and local time zone]:
  25218. // In most cases, `number.parseDate` will treat input data string as local time
  25219. // (except time zone is specified in time string). And `format.formateTime` returns
  25220. // local time by default. option.useUTC is false by default. This design have
  25221. // concidered these common case:
  25222. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25223. // in local time by default.
  25224. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25225. // as its original time, without any time difference.
  25226. var intervalScaleProto = IntervalScale.prototype;
  25227. var mathCeil = Math.ceil;
  25228. var mathFloor = Math.floor;
  25229. var ONE_SECOND = 1000;
  25230. var ONE_MINUTE = ONE_SECOND * 60;
  25231. var ONE_HOUR = ONE_MINUTE * 60;
  25232. var ONE_DAY = ONE_HOUR * 24;
  25233. // FIXME 公用?
  25234. var bisect = function (a, x, lo, hi) {
  25235. while (lo < hi) {
  25236. var mid = lo + hi >>> 1;
  25237. if (a[mid][1] < x) {
  25238. lo = mid + 1;
  25239. }
  25240. else {
  25241. hi = mid;
  25242. }
  25243. }
  25244. return lo;
  25245. };
  25246. /**
  25247. * @alias module:echarts/coord/scale/Time
  25248. * @constructor
  25249. */
  25250. var TimeScale = IntervalScale.extend({
  25251. type: 'time',
  25252. /**
  25253. * @override
  25254. */
  25255. getLabel: function (val) {
  25256. var stepLvl = this._stepLvl;
  25257. var date = new Date(val);
  25258. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25259. },
  25260. /**
  25261. * @override
  25262. */
  25263. niceExtent: function (opt) {
  25264. var extent = this._extent;
  25265. // If extent start and end are same, expand them
  25266. if (extent[0] === extent[1]) {
  25267. // Expand extent
  25268. extent[0] -= ONE_DAY;
  25269. extent[1] += ONE_DAY;
  25270. }
  25271. // If there are no data and extent are [Infinity, -Infinity]
  25272. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25273. var d = new Date();
  25274. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25275. extent[0] = extent[1] - ONE_DAY;
  25276. }
  25277. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25278. // var extent = this._extent;
  25279. var interval = this._interval;
  25280. if (!opt.fixMin) {
  25281. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25282. }
  25283. if (!opt.fixMax) {
  25284. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25285. }
  25286. },
  25287. /**
  25288. * @override
  25289. */
  25290. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25291. approxTickNum = approxTickNum || 10;
  25292. var extent = this._extent;
  25293. var span = extent[1] - extent[0];
  25294. var approxInterval = span / approxTickNum;
  25295. if (minInterval != null && approxInterval < minInterval) {
  25296. approxInterval = minInterval;
  25297. }
  25298. if (maxInterval != null && approxInterval > maxInterval) {
  25299. approxInterval = maxInterval;
  25300. }
  25301. var scaleLevelsLen = scaleLevels.length;
  25302. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25303. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25304. var interval = level[1];
  25305. // Same with interval scale if span is much larger than 1 year
  25306. if (level[0] === 'year') {
  25307. var yearSpan = span / interval;
  25308. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25309. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25310. var yearStep = nice(yearSpan / approxTickNum, true);
  25311. interval *= yearStep;
  25312. }
  25313. var timezoneOffset = this.getSetting('useUTC')
  25314. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25315. var niceExtent = [
  25316. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25317. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25318. ];
  25319. fixExtent(niceExtent, extent);
  25320. this._stepLvl = level;
  25321. // Interval will be used in getTicks
  25322. this._interval = interval;
  25323. this._niceExtent = niceExtent;
  25324. },
  25325. parse: function (val) {
  25326. // val might be float.
  25327. return +parseDate(val);
  25328. }
  25329. });
  25330. each$1(['contain', 'normalize'], function (methodName) {
  25331. TimeScale.prototype[methodName] = function (val) {
  25332. return intervalScaleProto[methodName].call(this, this.parse(val));
  25333. };
  25334. });
  25335. // Steps from d3
  25336. var scaleLevels = [
  25337. // Format interval
  25338. ['hh:mm:ss', ONE_SECOND], // 1s
  25339. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25340. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25341. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25342. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25343. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25344. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25345. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25346. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25347. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25348. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25349. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25350. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25351. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25352. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25353. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25354. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25355. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25356. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25357. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25358. ['week', ONE_DAY * 7], // 7d
  25359. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25360. ['week', ONE_DAY * 14], // 2w
  25361. ['week', ONE_DAY * 21], // 3w
  25362. ['month', ONE_DAY * 31], // 1M
  25363. ['week', ONE_DAY * 42], // 6w
  25364. ['month', ONE_DAY * 62], // 2M
  25365. ['week', ONE_DAY * 42], // 10w
  25366. ['quarter', ONE_DAY * 380 / 4], // 3M
  25367. ['month', ONE_DAY * 31 * 4], // 4M
  25368. ['month', ONE_DAY * 31 * 5], // 5M
  25369. ['half-year', ONE_DAY * 380 / 2], // 6M
  25370. ['month', ONE_DAY * 31 * 8], // 8M
  25371. ['month', ONE_DAY * 31 * 10], // 10M
  25372. ['year', ONE_DAY * 380] // 1Y
  25373. ];
  25374. /**
  25375. * @param {module:echarts/model/Model}
  25376. * @return {module:echarts/scale/Time}
  25377. */
  25378. TimeScale.create = function (model) {
  25379. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25380. };
  25381. /**
  25382. * Log scale
  25383. * @module echarts/scale/Log
  25384. */
  25385. // Use some method of IntervalScale
  25386. var scaleProto$1 = Scale.prototype;
  25387. var intervalScaleProto$1 = IntervalScale.prototype;
  25388. var getPrecisionSafe$1 = getPrecisionSafe;
  25389. var roundingErrorFix = round$1;
  25390. var mathFloor$1 = Math.floor;
  25391. var mathCeil$1 = Math.ceil;
  25392. var mathPow$1 = Math.pow;
  25393. var mathLog = Math.log;
  25394. var LogScale = Scale.extend({
  25395. type: 'log',
  25396. base: 10,
  25397. $constructor: function () {
  25398. Scale.apply(this, arguments);
  25399. this._originalScale = new IntervalScale();
  25400. },
  25401. /**
  25402. * @return {Array.<number>}
  25403. */
  25404. getTicks: function () {
  25405. var originalScale = this._originalScale;
  25406. var extent = this._extent;
  25407. var originalExtent = originalScale.getExtent();
  25408. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25409. var powVal = round$1(mathPow$1(this.base, val));
  25410. // Fix #4158
  25411. powVal = (val === extent[0] && originalScale.__fixMin)
  25412. ? fixRoundingError(powVal, originalExtent[0])
  25413. : powVal;
  25414. powVal = (val === extent[1] && originalScale.__fixMax)
  25415. ? fixRoundingError(powVal, originalExtent[1])
  25416. : powVal;
  25417. return powVal;
  25418. }, this);
  25419. },
  25420. /**
  25421. * @param {number} val
  25422. * @return {string}
  25423. */
  25424. getLabel: intervalScaleProto$1.getLabel,
  25425. /**
  25426. * @param {number} val
  25427. * @return {number}
  25428. */
  25429. scale: function (val) {
  25430. val = scaleProto$1.scale.call(this, val);
  25431. return mathPow$1(this.base, val);
  25432. },
  25433. /**
  25434. * @param {number} start
  25435. * @param {number} end
  25436. */
  25437. setExtent: function (start, end) {
  25438. var base = this.base;
  25439. start = mathLog(start) / mathLog(base);
  25440. end = mathLog(end) / mathLog(base);
  25441. intervalScaleProto$1.setExtent.call(this, start, end);
  25442. },
  25443. /**
  25444. * @return {number} end
  25445. */
  25446. getExtent: function () {
  25447. var base = this.base;
  25448. var extent = scaleProto$1.getExtent.call(this);
  25449. extent[0] = mathPow$1(base, extent[0]);
  25450. extent[1] = mathPow$1(base, extent[1]);
  25451. // Fix #4158
  25452. var originalScale = this._originalScale;
  25453. var originalExtent = originalScale.getExtent();
  25454. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25455. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25456. return extent;
  25457. },
  25458. /**
  25459. * @param {Array.<number>} extent
  25460. */
  25461. unionExtent: function (extent) {
  25462. this._originalScale.unionExtent(extent);
  25463. var base = this.base;
  25464. extent[0] = mathLog(extent[0]) / mathLog(base);
  25465. extent[1] = mathLog(extent[1]) / mathLog(base);
  25466. scaleProto$1.unionExtent.call(this, extent);
  25467. },
  25468. /**
  25469. * @override
  25470. */
  25471. unionExtentFromData: function (data, dim) {
  25472. this.unionExtent(data.getApproximateExtent(dim, true, function (val) {
  25473. return val > 0;
  25474. }));
  25475. },
  25476. /**
  25477. * Update interval and extent of intervals for nice ticks
  25478. * @param {number} [approxTickNum = 10] Given approx tick number
  25479. */
  25480. niceTicks: function (approxTickNum) {
  25481. approxTickNum = approxTickNum || 10;
  25482. var extent = this._extent;
  25483. var span = extent[1] - extent[0];
  25484. if (span === Infinity || span <= 0) {
  25485. return;
  25486. }
  25487. var interval = quantity(span);
  25488. var err = approxTickNum / span * interval;
  25489. // Filter ticks to get closer to the desired count.
  25490. if (err <= 0.5) {
  25491. interval *= 10;
  25492. }
  25493. // Interval should be integer
  25494. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  25495. interval *= 10;
  25496. }
  25497. var niceExtent = [
  25498. round$1(mathCeil$1(extent[0] / interval) * interval),
  25499. round$1(mathFloor$1(extent[1] / interval) * interval)
  25500. ];
  25501. this._interval = interval;
  25502. this._niceExtent = niceExtent;
  25503. },
  25504. /**
  25505. * Nice extent.
  25506. * @override
  25507. */
  25508. niceExtent: function (opt) {
  25509. intervalScaleProto$1.niceExtent.call(this, opt);
  25510. var originalScale = this._originalScale;
  25511. originalScale.__fixMin = opt.fixMin;
  25512. originalScale.__fixMax = opt.fixMax;
  25513. }
  25514. });
  25515. each$1(['contain', 'normalize'], function (methodName) {
  25516. LogScale.prototype[methodName] = function (val) {
  25517. val = mathLog(val) / mathLog(this.base);
  25518. return scaleProto$1[methodName].call(this, val);
  25519. };
  25520. });
  25521. LogScale.create = function () {
  25522. return new LogScale();
  25523. };
  25524. function fixRoundingError(val, originalVal) {
  25525. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  25526. }
  25527. /**
  25528. * Get axis scale extent before niced.
  25529. * Item of returned array can only be number (including Infinity and NaN).
  25530. */
  25531. function getScaleExtent(scale, model) {
  25532. var scaleType = scale.type;
  25533. var min = model.getMin();
  25534. var max = model.getMax();
  25535. var fixMin = min != null;
  25536. var fixMax = max != null;
  25537. var originalExtent = scale.getExtent();
  25538. var axisDataLen;
  25539. var boundaryGap;
  25540. var span;
  25541. if (scaleType === 'ordinal') {
  25542. axisDataLen = model.getCategories().length;
  25543. }
  25544. else {
  25545. boundaryGap = model.get('boundaryGap');
  25546. if (!isArray(boundaryGap)) {
  25547. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  25548. }
  25549. if (typeof boundaryGap[0] === 'boolean') {
  25550. if (__DEV__) {
  25551. console.warn('Boolean type for boundaryGap is only '
  25552. + 'allowed for ordinal axis. Please use string in '
  25553. + 'percentage instead, e.g., "20%". Currently, '
  25554. + 'boundaryGap is set to be 0.');
  25555. }
  25556. boundaryGap = [0, 0];
  25557. }
  25558. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  25559. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  25560. span = (originalExtent[1] - originalExtent[0])
  25561. || Math.abs(originalExtent[0]);
  25562. }
  25563. // Notice: When min/max is not set (that is, when there are null/undefined,
  25564. // which is the most common case), these cases should be ensured:
  25565. // (1) For 'ordinal', show all axis.data.
  25566. // (2) For others:
  25567. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  25568. // disabled).
  25569. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  25570. // be the result that originalExtent enlarged by boundaryGap.
  25571. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  25572. // FIXME
  25573. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  25574. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  25575. // that the results processed by boundaryGap are positive/negative?
  25576. if (min == null) {
  25577. min = scaleType === 'ordinal'
  25578. ? (axisDataLen ? 0 : NaN)
  25579. : originalExtent[0] - boundaryGap[0] * span;
  25580. }
  25581. if (max == null) {
  25582. max = scaleType === 'ordinal'
  25583. ? (axisDataLen ? axisDataLen - 1 : NaN)
  25584. : originalExtent[1] + boundaryGap[1] * span;
  25585. }
  25586. if (min === 'dataMin') {
  25587. min = originalExtent[0];
  25588. }
  25589. else if (typeof min === 'function') {
  25590. min = min({
  25591. min: originalExtent[0],
  25592. max: originalExtent[1]
  25593. });
  25594. }
  25595. if (max === 'dataMax') {
  25596. max = originalExtent[1];
  25597. }
  25598. else if (typeof max === 'function') {
  25599. max = max({
  25600. min: originalExtent[0],
  25601. max: originalExtent[1]
  25602. });
  25603. }
  25604. (min == null || !isFinite(min)) && (min = NaN);
  25605. (max == null || !isFinite(max)) && (max = NaN);
  25606. scale.setBlank(eqNaN(min) || eqNaN(max));
  25607. // Evaluate if axis needs cross zero
  25608. if (model.getNeedCrossZero()) {
  25609. // Axis is over zero and min is not set
  25610. if (min > 0 && max > 0 && !fixMin) {
  25611. min = 0;
  25612. }
  25613. // Axis is under zero and max is not set
  25614. if (min < 0 && max < 0 && !fixMax) {
  25615. max = 0;
  25616. }
  25617. }
  25618. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  25619. // is base axis
  25620. var ecModel = model.ecModel;
  25621. if (ecModel) {
  25622. var isBaseAxisAndHasBarSeries = filter(ecModel.getSeriesByType('bar'), function (seriesModel) {
  25623. return seriesModel.getBaseAxis() === model.axis;
  25624. }).length > 0;
  25625. if ((scaleType === 'time' || scaleType === 'interval') && isBaseAxisAndHasBarSeries) {
  25626. // Adjust axis min and max to account for overflow
  25627. var adjustedScale = adjustScaleForOverflow(min, max, model);
  25628. min = adjustedScale.min;
  25629. max = adjustedScale.max;
  25630. }
  25631. }
  25632. return [min, max];
  25633. }
  25634. function adjustScaleForOverflow(min, max, model) {
  25635. var ecModel = model.ecModel;
  25636. // Get Axis Length
  25637. var axisExtent = model.axis.getExtent();
  25638. var axisLength = axisExtent[1] - axisExtent[0];
  25639. // Calculate placement of bars on axis
  25640. var barWidthAndOffset = calBarWidthAndOffset(filter(
  25641. ecModel.getSeriesByType('bar'),
  25642. function (seriesModel) {
  25643. return !ecModel.isSeriesFiltered(seriesModel)
  25644. && seriesModel.coordinateSystem
  25645. && seriesModel.coordinateSystem.type === 'cartesian2d';
  25646. }
  25647. ));
  25648. // Get bars on current base axis and calculate min and max overflow
  25649. var baseAxisKey = model.axis.dim + model.axis.index;
  25650. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  25651. if (barsOnCurrentAxis === undefined) {
  25652. return {min: min, max: max};
  25653. }
  25654. var minOverflow = Infinity;
  25655. each$1(barsOnCurrentAxis, function (item) {
  25656. minOverflow = Math.min(item.offset, minOverflow);
  25657. });
  25658. var maxOverflow = -Infinity;
  25659. each$1(barsOnCurrentAxis, function (item) {
  25660. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  25661. });
  25662. var totalOverFlow = Math.abs(minOverflow) + maxOverflow;
  25663. // Calulate required buffer based on old range and overflow
  25664. var oldRange = max - min;
  25665. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  25666. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  25667. max += overflowBuffer * (maxOverflow / totalOverFlow);
  25668. min -= overflowBuffer * (minOverflow / totalOverFlow);
  25669. return {min: min, max: max};
  25670. }
  25671. function niceScaleExtent(scale, model) {
  25672. var extent = getScaleExtent(scale, model);
  25673. var fixMin = model.getMin() != null;
  25674. var fixMax = model.getMax() != null;
  25675. var splitNumber = model.get('splitNumber');
  25676. if (scale.type === 'log') {
  25677. scale.base = model.get('logBase');
  25678. }
  25679. var scaleType = scale.type;
  25680. scale.setExtent(extent[0], extent[1]);
  25681. scale.niceExtent({
  25682. splitNumber: splitNumber,
  25683. fixMin: fixMin,
  25684. fixMax: fixMax,
  25685. minInterval: (scaleType === 'interval' || scaleType === 'time')
  25686. ? model.get('minInterval') : null,
  25687. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  25688. ? model.get('maxInterval') : null
  25689. });
  25690. // If some one specified the min, max. And the default calculated interval
  25691. // is not good enough. He can specify the interval. It is often appeared
  25692. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  25693. // to be 60.
  25694. // FIXME
  25695. var interval = model.get('interval');
  25696. if (interval != null) {
  25697. scale.setInterval && scale.setInterval(interval);
  25698. }
  25699. }
  25700. /**
  25701. * @param {module:echarts/model/Model} model
  25702. * @param {string} [axisType] Default retrieve from model.type
  25703. * @return {module:echarts/scale/*}
  25704. */
  25705. function createScaleByModel(model, axisType) {
  25706. axisType = axisType || model.get('type');
  25707. if (axisType) {
  25708. switch (axisType) {
  25709. // Buildin scale
  25710. case 'category':
  25711. return new OrdinalScale(
  25712. model.getOrdinalMeta
  25713. ? model.getOrdinalMeta()
  25714. : model.getCategories(),
  25715. [Infinity, -Infinity]
  25716. );
  25717. case 'value':
  25718. return new IntervalScale();
  25719. // Extended scale, like time and log
  25720. default:
  25721. return (Scale.getClass(axisType) || IntervalScale).create(model);
  25722. }
  25723. }
  25724. }
  25725. /**
  25726. * Check if the axis corss 0
  25727. */
  25728. function ifAxisCrossZero(axis) {
  25729. var dataExtent = axis.scale.getExtent();
  25730. var min = dataExtent[0];
  25731. var max = dataExtent[1];
  25732. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  25733. }
  25734. /**
  25735. * @param {Array.<number>} tickCoords In axis self coordinate.
  25736. * @param {Array.<string>} labels
  25737. * @param {string} font
  25738. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  25739. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  25740. * @return {number}
  25741. */
  25742. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  25743. var textSpaceTakenRect;
  25744. var autoLabelInterval = 0;
  25745. var accumulatedLabelInterval = 0;
  25746. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  25747. var step = 1;
  25748. if (labels.length > 40) {
  25749. // Simple optimization for large amount of labels
  25750. step = Math.floor(labels.length / 40);
  25751. }
  25752. for (var i = 0; i < tickCoords.length; i += step) {
  25753. var tickCoord = tickCoords[i];
  25754. // Not precise, do not consider align and vertical align
  25755. // and each distance from axis line yet.
  25756. var rect = getBoundingRect(
  25757. labels[i], font, 'center', 'top'
  25758. );
  25759. rect.x += tickCoord * Math.cos(rotation);
  25760. rect.y += tickCoord * Math.sin(rotation);
  25761. // Magic number
  25762. rect.width *= 1.3;
  25763. rect.height *= 1.3;
  25764. if (!textSpaceTakenRect) {
  25765. textSpaceTakenRect = rect.clone();
  25766. }
  25767. // There is no space for current label;
  25768. else if (textSpaceTakenRect.intersect(rect)) {
  25769. accumulatedLabelInterval++;
  25770. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  25771. }
  25772. else {
  25773. textSpaceTakenRect.union(rect);
  25774. // Reset
  25775. accumulatedLabelInterval = 0;
  25776. }
  25777. }
  25778. if (autoLabelInterval === 0 && step > 1) {
  25779. return step;
  25780. }
  25781. return (autoLabelInterval + 1) * step - 1;
  25782. }
  25783. /**
  25784. * @param {Object} axis
  25785. * @param {Function} labelFormatter
  25786. * @return {Array.<string>}
  25787. */
  25788. function getFormattedLabels(axis, labelFormatter) {
  25789. var scale = axis.scale;
  25790. var labels = scale.getTicksLabels();
  25791. var ticks = scale.getTicks();
  25792. if (typeof labelFormatter === 'string') {
  25793. labelFormatter = (function (tpl) {
  25794. return function (val) {
  25795. return tpl.replace('{value}', val != null ? val : '');
  25796. };
  25797. })(labelFormatter);
  25798. // Consider empty array
  25799. return map(labels, labelFormatter);
  25800. }
  25801. else if (typeof labelFormatter === 'function') {
  25802. return map(ticks, function (tick, idx) {
  25803. return labelFormatter(
  25804. getAxisRawValue(axis, tick),
  25805. idx
  25806. );
  25807. }, this);
  25808. }
  25809. else {
  25810. return labels;
  25811. }
  25812. }
  25813. function getAxisRawValue(axis, value) {
  25814. // In category axis with data zoom, tick is not the original
  25815. // index of axis.data. So tick should not be exposed to user
  25816. // in category axis.
  25817. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  25818. }
  25819. var axisModelCommonMixin = {
  25820. /**
  25821. * Format labels
  25822. * @return {Array.<string>}
  25823. */
  25824. getFormattedLabels: function () {
  25825. return getFormattedLabels(
  25826. this.axis,
  25827. this.get('axisLabel.formatter')
  25828. );
  25829. },
  25830. /**
  25831. * @param {boolean} origin
  25832. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  25833. */
  25834. getMin: function (origin) {
  25835. var option = this.option;
  25836. var min = (!origin && option.rangeStart != null)
  25837. ? option.rangeStart : option.min;
  25838. if (this.axis
  25839. && min != null
  25840. && min !== 'dataMin'
  25841. && typeof min !== 'function'
  25842. && !eqNaN(min)
  25843. ) {
  25844. min = this.axis.scale.parse(min);
  25845. }
  25846. return min;
  25847. },
  25848. /**
  25849. * @param {boolean} origin
  25850. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  25851. */
  25852. getMax: function (origin) {
  25853. var option = this.option;
  25854. var max = (!origin && option.rangeEnd != null)
  25855. ? option.rangeEnd : option.max;
  25856. if (this.axis
  25857. && max != null
  25858. && max !== 'dataMax'
  25859. && typeof max !== 'function'
  25860. && !eqNaN(max)
  25861. ) {
  25862. max = this.axis.scale.parse(max);
  25863. }
  25864. return max;
  25865. },
  25866. /**
  25867. * @return {boolean}
  25868. */
  25869. getNeedCrossZero: function () {
  25870. var option = this.option;
  25871. return (option.rangeStart != null || option.rangeEnd != null)
  25872. ? false : !option.scale;
  25873. },
  25874. /**
  25875. * Should be implemented by each axis model if necessary.
  25876. * @return {module:echarts/model/Component} coordinate system model
  25877. */
  25878. getCoordSysModel: noop,
  25879. /**
  25880. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  25881. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  25882. */
  25883. setRange: function (rangeStart, rangeEnd) {
  25884. this.option.rangeStart = rangeStart;
  25885. this.option.rangeEnd = rangeEnd;
  25886. },
  25887. /**
  25888. * Reset range
  25889. */
  25890. resetRange: function () {
  25891. // rangeStart and rangeEnd is readonly.
  25892. this.option.rangeStart = this.option.rangeEnd = null;
  25893. }
  25894. };
  25895. // Symbol factory
  25896. /**
  25897. * Triangle shape
  25898. * @inner
  25899. */
  25900. var Triangle = extendShape({
  25901. type: 'triangle',
  25902. shape: {
  25903. cx: 0,
  25904. cy: 0,
  25905. width: 0,
  25906. height: 0
  25907. },
  25908. buildPath: function (path, shape) {
  25909. var cx = shape.cx;
  25910. var cy = shape.cy;
  25911. var width = shape.width / 2;
  25912. var height = shape.height / 2;
  25913. path.moveTo(cx, cy - height);
  25914. path.lineTo(cx + width, cy + height);
  25915. path.lineTo(cx - width, cy + height);
  25916. path.closePath();
  25917. }
  25918. });
  25919. /**
  25920. * Diamond shape
  25921. * @inner
  25922. */
  25923. var Diamond = extendShape({
  25924. type: 'diamond',
  25925. shape: {
  25926. cx: 0,
  25927. cy: 0,
  25928. width: 0,
  25929. height: 0
  25930. },
  25931. buildPath: function (path, shape) {
  25932. var cx = shape.cx;
  25933. var cy = shape.cy;
  25934. var width = shape.width / 2;
  25935. var height = shape.height / 2;
  25936. path.moveTo(cx, cy - height);
  25937. path.lineTo(cx + width, cy);
  25938. path.lineTo(cx, cy + height);
  25939. path.lineTo(cx - width, cy);
  25940. path.closePath();
  25941. }
  25942. });
  25943. /**
  25944. * Pin shape
  25945. * @inner
  25946. */
  25947. var Pin = extendShape({
  25948. type: 'pin',
  25949. shape: {
  25950. // x, y on the cusp
  25951. x: 0,
  25952. y: 0,
  25953. width: 0,
  25954. height: 0
  25955. },
  25956. buildPath: function (path, shape) {
  25957. var x = shape.x;
  25958. var y = shape.y;
  25959. var w = shape.width / 5 * 3;
  25960. // Height must be larger than width
  25961. var h = Math.max(w, shape.height);
  25962. var r = w / 2;
  25963. // Dist on y with tangent point and circle center
  25964. var dy = r * r / (h - r);
  25965. var cy = y - h + r + dy;
  25966. var angle = Math.asin(dy / r);
  25967. // Dist on x with tangent point and circle center
  25968. var dx = Math.cos(angle) * r;
  25969. var tanX = Math.sin(angle);
  25970. var tanY = Math.cos(angle);
  25971. var cpLen = r * 0.6;
  25972. var cpLen2 = r * 0.7;
  25973. path.moveTo(x - dx, cy + dy);
  25974. path.arc(
  25975. x, cy, r,
  25976. Math.PI - angle,
  25977. Math.PI * 2 + angle
  25978. );
  25979. path.bezierCurveTo(
  25980. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  25981. x, y - cpLen2,
  25982. x, y
  25983. );
  25984. path.bezierCurveTo(
  25985. x, y - cpLen2,
  25986. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  25987. x - dx, cy + dy
  25988. );
  25989. path.closePath();
  25990. }
  25991. });
  25992. /**
  25993. * Arrow shape
  25994. * @inner
  25995. */
  25996. var Arrow = extendShape({
  25997. type: 'arrow',
  25998. shape: {
  25999. x: 0,
  26000. y: 0,
  26001. width: 0,
  26002. height: 0
  26003. },
  26004. buildPath: function (ctx, shape) {
  26005. var height = shape.height;
  26006. var width = shape.width;
  26007. var x = shape.x;
  26008. var y = shape.y;
  26009. var dx = width / 3 * 2;
  26010. ctx.moveTo(x, y);
  26011. ctx.lineTo(x + dx, y + height);
  26012. ctx.lineTo(x, y + height / 4 * 3);
  26013. ctx.lineTo(x - dx, y + height);
  26014. ctx.lineTo(x, y);
  26015. ctx.closePath();
  26016. }
  26017. });
  26018. /**
  26019. * Map of path contructors
  26020. * @type {Object.<string, module:zrender/graphic/Path>}
  26021. */
  26022. var symbolCtors = {
  26023. line: Line,
  26024. rect: Rect,
  26025. roundRect: Rect,
  26026. square: Rect,
  26027. circle: Circle,
  26028. diamond: Diamond,
  26029. pin: Pin,
  26030. arrow: Arrow,
  26031. triangle: Triangle
  26032. };
  26033. var symbolShapeMakers = {
  26034. line: function (x, y, w, h, shape) {
  26035. // FIXME
  26036. shape.x1 = x;
  26037. shape.y1 = y + h / 2;
  26038. shape.x2 = x + w;
  26039. shape.y2 = y + h / 2;
  26040. },
  26041. rect: function (x, y, w, h, shape) {
  26042. shape.x = x;
  26043. shape.y = y;
  26044. shape.width = w;
  26045. shape.height = h;
  26046. },
  26047. roundRect: function (x, y, w, h, shape) {
  26048. shape.x = x;
  26049. shape.y = y;
  26050. shape.width = w;
  26051. shape.height = h;
  26052. shape.r = Math.min(w, h) / 4;
  26053. },
  26054. square: function (x, y, w, h, shape) {
  26055. var size = Math.min(w, h);
  26056. shape.x = x;
  26057. shape.y = y;
  26058. shape.width = size;
  26059. shape.height = size;
  26060. },
  26061. circle: function (x, y, w, h, shape) {
  26062. // Put circle in the center of square
  26063. shape.cx = x + w / 2;
  26064. shape.cy = y + h / 2;
  26065. shape.r = Math.min(w, h) / 2;
  26066. },
  26067. diamond: function (x, y, w, h, shape) {
  26068. shape.cx = x + w / 2;
  26069. shape.cy = y + h / 2;
  26070. shape.width = w;
  26071. shape.height = h;
  26072. },
  26073. pin: function (x, y, w, h, shape) {
  26074. shape.x = x + w / 2;
  26075. shape.y = y + h / 2;
  26076. shape.width = w;
  26077. shape.height = h;
  26078. },
  26079. arrow: function (x, y, w, h, shape) {
  26080. shape.x = x + w / 2;
  26081. shape.y = y + h / 2;
  26082. shape.width = w;
  26083. shape.height = h;
  26084. },
  26085. triangle: function (x, y, w, h, shape) {
  26086. shape.cx = x + w / 2;
  26087. shape.cy = y + h / 2;
  26088. shape.width = w;
  26089. shape.height = h;
  26090. }
  26091. };
  26092. var symbolBuildProxies = {};
  26093. each$1(symbolCtors, function (Ctor, name) {
  26094. symbolBuildProxies[name] = new Ctor();
  26095. });
  26096. var SymbolClz = extendShape({
  26097. type: 'symbol',
  26098. shape: {
  26099. symbolType: '',
  26100. x: 0,
  26101. y: 0,
  26102. width: 0,
  26103. height: 0
  26104. },
  26105. beforeBrush: function () {
  26106. var style = this.style;
  26107. var shape = this.shape;
  26108. // FIXME
  26109. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26110. style.textPosition = ['50%', '40%'];
  26111. style.textAlign = 'center';
  26112. style.textVerticalAlign = 'middle';
  26113. }
  26114. },
  26115. buildPath: function (ctx, shape, inBundle) {
  26116. var symbolType = shape.symbolType;
  26117. var proxySymbol = symbolBuildProxies[symbolType];
  26118. if (shape.symbolType !== 'none') {
  26119. if (!proxySymbol) {
  26120. // Default rect
  26121. symbolType = 'rect';
  26122. proxySymbol = symbolBuildProxies[symbolType];
  26123. }
  26124. symbolShapeMakers[symbolType](
  26125. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26126. );
  26127. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26128. }
  26129. }
  26130. });
  26131. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26132. function symbolPathSetColor(color, innerColor) {
  26133. if (this.type !== 'image') {
  26134. var symbolStyle = this.style;
  26135. var symbolShape = this.shape;
  26136. if (symbolShape && symbolShape.symbolType === 'line') {
  26137. symbolStyle.stroke = color;
  26138. }
  26139. else if (this.__isEmptyBrush) {
  26140. symbolStyle.stroke = color;
  26141. symbolStyle.fill = innerColor || '#fff';
  26142. }
  26143. else {
  26144. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26145. symbolStyle.fill && (symbolStyle.fill = color);
  26146. symbolStyle.stroke && (symbolStyle.stroke = color);
  26147. }
  26148. this.dirty(false);
  26149. }
  26150. }
  26151. /**
  26152. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26153. * @param {string} symbolType
  26154. * @param {number} x
  26155. * @param {number} y
  26156. * @param {number} w
  26157. * @param {number} h
  26158. * @param {string} color
  26159. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26160. * for path and image only.
  26161. */
  26162. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26163. // TODO Support image object, DynamicImage.
  26164. var isEmpty = symbolType.indexOf('empty') === 0;
  26165. if (isEmpty) {
  26166. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26167. }
  26168. var symbolPath;
  26169. if (symbolType.indexOf('image://') === 0) {
  26170. symbolPath = makeImage(
  26171. symbolType.slice(8),
  26172. new BoundingRect(x, y, w, h),
  26173. keepAspect ? 'center' : 'cover'
  26174. );
  26175. }
  26176. else if (symbolType.indexOf('path://') === 0) {
  26177. symbolPath = makePath(
  26178. symbolType.slice(7),
  26179. {},
  26180. new BoundingRect(x, y, w, h),
  26181. keepAspect ? 'center' : 'cover'
  26182. );
  26183. }
  26184. else {
  26185. symbolPath = new SymbolClz({
  26186. shape: {
  26187. symbolType: symbolType,
  26188. x: x,
  26189. y: y,
  26190. width: w,
  26191. height: h
  26192. }
  26193. });
  26194. }
  26195. symbolPath.__isEmptyBrush = isEmpty;
  26196. symbolPath.setColor = symbolPathSetColor;
  26197. symbolPath.setColor(color);
  26198. return symbolPath;
  26199. }
  26200. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26201. /**
  26202. * Create a muti dimension List structure from seriesModel.
  26203. * @param {module:echarts/model/Model} seriesModel
  26204. * @return {module:echarts/data/List} list
  26205. */
  26206. function createList(seriesModel) {
  26207. return createListFromArray(seriesModel.getSource(), seriesModel);
  26208. }
  26209. /**
  26210. * Create scale
  26211. * @param {Array.<number>} dataExtent
  26212. * @param {Object|module:echarts/Model} option
  26213. */
  26214. function createScale(dataExtent, option) {
  26215. var axisModel = option;
  26216. if (!Model.isInstance(option)) {
  26217. axisModel = new Model(option);
  26218. mixin(axisModel, axisModelCommonMixin);
  26219. }
  26220. var scale = createScaleByModel(axisModel);
  26221. scale.setExtent(dataExtent[0], dataExtent[1]);
  26222. niceScaleExtent(scale, axisModel);
  26223. return scale;
  26224. }
  26225. /**
  26226. * Mixin common methods to axis model,
  26227. *
  26228. * Inlcude methods
  26229. * `getFormattedLabels() => Array.<string>`
  26230. * `getCategories() => Array.<string>`
  26231. * `getMin(origin: boolean) => number`
  26232. * `getMax(origin: boolean) => number`
  26233. * `getNeedCrossZero() => boolean`
  26234. * `setRange(start: number, end: number)`
  26235. * `resetRange()`
  26236. */
  26237. function mixinAxisModelCommonMethods(Model$$1) {
  26238. mixin(Model$$1, axisModelCommonMixin);
  26239. }
  26240. var helper = (Object.freeze || Object)({
  26241. createList: createList,
  26242. getLayoutRect: getLayoutRect,
  26243. createScale: createScale,
  26244. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26245. completeDimensions: completeDimensions,
  26246. createDimensions: createDimensions,
  26247. createSymbol: createSymbol
  26248. });
  26249. var EPSILON$3 = 1e-8;
  26250. function isAroundEqual$1(a, b) {
  26251. return Math.abs(a - b) < EPSILON$3;
  26252. }
  26253. function contain$1(points, x, y) {
  26254. var w = 0;
  26255. var p = points[0];
  26256. if (!p) {
  26257. return false;
  26258. }
  26259. for (var i = 1; i < points.length; i++) {
  26260. var p2 = points[i];
  26261. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26262. p = p2;
  26263. }
  26264. // Close polygon
  26265. var p0 = points[0];
  26266. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26267. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26268. }
  26269. return w !== 0;
  26270. }
  26271. /**
  26272. * @module echarts/coord/geo/Region
  26273. */
  26274. /**
  26275. * @param {string} name
  26276. * @param {Array} geometries
  26277. * @param {Array.<number>} cp
  26278. */
  26279. function Region(name, geometries, cp) {
  26280. /**
  26281. * @type {string}
  26282. * @readOnly
  26283. */
  26284. this.name = name;
  26285. /**
  26286. * @type {Array.<Array>}
  26287. * @readOnly
  26288. */
  26289. this.geometries = geometries;
  26290. if (!cp) {
  26291. var rect = this.getBoundingRect();
  26292. cp = [
  26293. rect.x + rect.width / 2,
  26294. rect.y + rect.height / 2
  26295. ];
  26296. }
  26297. else {
  26298. cp = [cp[0], cp[1]];
  26299. }
  26300. /**
  26301. * @type {Array.<number>}
  26302. */
  26303. this.center = cp;
  26304. }
  26305. Region.prototype = {
  26306. constructor: Region,
  26307. properties: null,
  26308. /**
  26309. * @return {module:zrender/core/BoundingRect}
  26310. */
  26311. getBoundingRect: function () {
  26312. var rect = this._rect;
  26313. if (rect) {
  26314. return rect;
  26315. }
  26316. var MAX_NUMBER = Number.MAX_VALUE;
  26317. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26318. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26319. var min2 = [];
  26320. var max2 = [];
  26321. var geometries = this.geometries;
  26322. for (var i = 0; i < geometries.length; i++) {
  26323. // Only support polygon
  26324. if (geometries[i].type !== 'polygon') {
  26325. continue;
  26326. }
  26327. // Doesn't consider hole
  26328. var exterior = geometries[i].exterior;
  26329. fromPoints(exterior, min2, max2);
  26330. min(min$$1, min$$1, min2);
  26331. max(max$$1, max$$1, max2);
  26332. }
  26333. // No data
  26334. if (i === 0) {
  26335. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26336. }
  26337. return (this._rect = new BoundingRect(
  26338. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26339. ));
  26340. },
  26341. /**
  26342. * @param {<Array.<number>} coord
  26343. * @return {boolean}
  26344. */
  26345. contain: function (coord) {
  26346. var rect = this.getBoundingRect();
  26347. var geometries = this.geometries;
  26348. if (!rect.contain(coord[0], coord[1])) {
  26349. return false;
  26350. }
  26351. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26352. // Only support polygon.
  26353. if (geometries[i].type !== 'polygon') {
  26354. continue;
  26355. }
  26356. var exterior = geometries[i].exterior;
  26357. var interiors = geometries[i].interiors;
  26358. if (contain$1(exterior, coord[0], coord[1])) {
  26359. // Not in the region if point is in the hole.
  26360. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26361. if (contain$1(interiors[k])) {
  26362. continue loopGeo;
  26363. }
  26364. }
  26365. return true;
  26366. }
  26367. }
  26368. return false;
  26369. },
  26370. transformTo: function (x, y, width, height) {
  26371. var rect = this.getBoundingRect();
  26372. var aspect = rect.width / rect.height;
  26373. if (!width) {
  26374. width = aspect * height;
  26375. }
  26376. else if (!height) {
  26377. height = width / aspect ;
  26378. }
  26379. var target = new BoundingRect(x, y, width, height);
  26380. var transform = rect.calculateTransform(target);
  26381. var geometries = this.geometries;
  26382. for (var i = 0; i < geometries.length; i++) {
  26383. // Only support polygon.
  26384. if (geometries[i].type !== 'polygon') {
  26385. continue;
  26386. }
  26387. var exterior = geometries[i].exterior;
  26388. var interiors = geometries[i].interiors;
  26389. for (var p = 0; p < exterior.length; p++) {
  26390. applyTransform(exterior[p], exterior[p], transform);
  26391. }
  26392. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26393. for (var p = 0; p < interiors[h].length; p++) {
  26394. applyTransform(interiors[h][p], interiors[h][p], transform);
  26395. }
  26396. }
  26397. }
  26398. rect = this._rect;
  26399. rect.copy(target);
  26400. // Update center
  26401. this.center = [
  26402. rect.x + rect.width / 2,
  26403. rect.y + rect.height / 2
  26404. ];
  26405. }
  26406. };
  26407. /**
  26408. * Parse and decode geo json
  26409. * @module echarts/coord/geo/parseGeoJson
  26410. */
  26411. function decode(json) {
  26412. if (!json.UTF8Encoding) {
  26413. return json;
  26414. }
  26415. var encodeScale = json.UTF8Scale;
  26416. if (encodeScale == null) {
  26417. encodeScale = 1024;
  26418. }
  26419. var features = json.features;
  26420. for (var f = 0; f < features.length; f++) {
  26421. var feature = features[f];
  26422. var geometry = feature.geometry;
  26423. var coordinates = geometry.coordinates;
  26424. var encodeOffsets = geometry.encodeOffsets;
  26425. for (var c = 0; c < coordinates.length; c++) {
  26426. var coordinate = coordinates[c];
  26427. if (geometry.type === 'Polygon') {
  26428. coordinates[c] = decodePolygon(
  26429. coordinate,
  26430. encodeOffsets[c],
  26431. encodeScale
  26432. );
  26433. }
  26434. else if (geometry.type === 'MultiPolygon') {
  26435. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26436. var polygon = coordinate[c2];
  26437. coordinate[c2] = decodePolygon(
  26438. polygon,
  26439. encodeOffsets[c][c2],
  26440. encodeScale
  26441. );
  26442. }
  26443. }
  26444. }
  26445. }
  26446. // Has been decoded
  26447. json.UTF8Encoding = false;
  26448. return json;
  26449. }
  26450. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26451. var result = [];
  26452. var prevX = encodeOffsets[0];
  26453. var prevY = encodeOffsets[1];
  26454. for (var i = 0; i < coordinate.length; i += 2) {
  26455. var x = coordinate.charCodeAt(i) - 64;
  26456. var y = coordinate.charCodeAt(i + 1) - 64;
  26457. // ZigZag decoding
  26458. x = (x >> 1) ^ (-(x & 1));
  26459. y = (y >> 1) ^ (-(y & 1));
  26460. // Delta deocding
  26461. x += prevX;
  26462. y += prevY;
  26463. prevX = x;
  26464. prevY = y;
  26465. // Dequantize
  26466. result.push([x / encodeScale, y / encodeScale]);
  26467. }
  26468. return result;
  26469. }
  26470. /**
  26471. * @alias module:echarts/coord/geo/parseGeoJson
  26472. * @param {Object} geoJson
  26473. * @return {module:zrender/container/Group}
  26474. */
  26475. var parseGeoJson$1 = function (geoJson) {
  26476. decode(geoJson);
  26477. return map(filter(geoJson.features, function (featureObj) {
  26478. // Output of mapshaper may have geometry null
  26479. return featureObj.geometry
  26480. && featureObj.properties
  26481. && featureObj.geometry.coordinates.length > 0;
  26482. }), function (featureObj) {
  26483. var properties = featureObj.properties;
  26484. var geo = featureObj.geometry;
  26485. var coordinates = geo.coordinates;
  26486. var geometries = [];
  26487. if (geo.type === 'Polygon') {
  26488. geometries.push({
  26489. type: 'polygon',
  26490. // According to the GeoJSON specification.
  26491. // First must be exterior, and the rest are all interior(holes).
  26492. exterior: coordinates[0],
  26493. interiors: coordinates.slice(1)
  26494. });
  26495. }
  26496. if (geo.type === 'MultiPolygon') {
  26497. each$1(coordinates, function (item) {
  26498. if (item[0]) {
  26499. geometries.push({
  26500. type: 'polygon',
  26501. exterior: item[0],
  26502. interiors: item.slice(1)
  26503. });
  26504. }
  26505. });
  26506. }
  26507. var region = new Region(
  26508. properties.name,
  26509. geometries,
  26510. properties.cp
  26511. );
  26512. region.properties = properties;
  26513. return region;
  26514. });
  26515. };
  26516. var linearMap$1 = linearMap;
  26517. function fixExtentWithBands(extent, nTick) {
  26518. var size = extent[1] - extent[0];
  26519. var len = nTick;
  26520. var margin = size / len / 2;
  26521. extent[0] += margin;
  26522. extent[1] -= margin;
  26523. }
  26524. var normalizedExtent = [0, 1];
  26525. /**
  26526. * @name module:echarts/coord/CartesianAxis
  26527. * @constructor
  26528. */
  26529. var Axis = function (dim, scale, extent) {
  26530. /**
  26531. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  26532. * @type {string}
  26533. */
  26534. this.dim = dim;
  26535. /**
  26536. * Axis scale
  26537. * @type {module:echarts/coord/scale/*}
  26538. */
  26539. this.scale = scale;
  26540. /**
  26541. * @type {Array.<number>}
  26542. * @private
  26543. */
  26544. this._extent = extent || [0, 0];
  26545. /**
  26546. * @type {boolean}
  26547. */
  26548. this.inverse = false;
  26549. /**
  26550. * Usually true when axis has a ordinal scale
  26551. * @type {boolean}
  26552. */
  26553. this.onBand = false;
  26554. /**
  26555. * @private
  26556. * @type {number}
  26557. */
  26558. this._labelInterval;
  26559. };
  26560. Axis.prototype = {
  26561. constructor: Axis,
  26562. /**
  26563. * If axis extent contain given coord
  26564. * @param {number} coord
  26565. * @return {boolean}
  26566. */
  26567. contain: function (coord) {
  26568. var extent = this._extent;
  26569. var min = Math.min(extent[0], extent[1]);
  26570. var max = Math.max(extent[0], extent[1]);
  26571. return coord >= min && coord <= max;
  26572. },
  26573. /**
  26574. * If axis extent contain given data
  26575. * @param {number} data
  26576. * @return {boolean}
  26577. */
  26578. containData: function (data) {
  26579. return this.contain(this.dataToCoord(data));
  26580. },
  26581. /**
  26582. * Get coord extent.
  26583. * @return {Array.<number>}
  26584. */
  26585. getExtent: function () {
  26586. return this._extent.slice();
  26587. },
  26588. /**
  26589. * Get precision used for formatting
  26590. * @param {Array.<number>} [dataExtent]
  26591. * @return {number}
  26592. */
  26593. getPixelPrecision: function (dataExtent) {
  26594. return getPixelPrecision(
  26595. dataExtent || this.scale.getExtent(),
  26596. this._extent
  26597. );
  26598. },
  26599. /**
  26600. * Set coord extent
  26601. * @param {number} start
  26602. * @param {number} end
  26603. */
  26604. setExtent: function (start, end) {
  26605. var extent = this._extent;
  26606. extent[0] = start;
  26607. extent[1] = end;
  26608. },
  26609. /**
  26610. * Convert data to coord. Data is the rank if it has a ordinal scale
  26611. * @param {number} data
  26612. * @param {boolean} clamp
  26613. * @return {number}
  26614. */
  26615. dataToCoord: function (data, clamp) {
  26616. var extent = this._extent;
  26617. var scale = this.scale;
  26618. data = scale.normalize(data);
  26619. if (this.onBand && scale.type === 'ordinal') {
  26620. extent = extent.slice();
  26621. fixExtentWithBands(extent, scale.count());
  26622. }
  26623. return linearMap$1(data, normalizedExtent, extent, clamp);
  26624. },
  26625. /**
  26626. * Convert coord to data. Data is the rank if it has a ordinal scale
  26627. * @param {number} coord
  26628. * @param {boolean} clamp
  26629. * @return {number}
  26630. */
  26631. coordToData: function (coord, clamp) {
  26632. var extent = this._extent;
  26633. var scale = this.scale;
  26634. if (this.onBand && scale.type === 'ordinal') {
  26635. extent = extent.slice();
  26636. fixExtentWithBands(extent, scale.count());
  26637. }
  26638. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  26639. return this.scale.scale(t);
  26640. },
  26641. /**
  26642. * Convert pixel point to data in axis
  26643. * @param {Array.<number>} point
  26644. * @param {boolean} clamp
  26645. * @return {number} data
  26646. */
  26647. pointToData: function (point, clamp) {
  26648. // Should be implemented in derived class if necessary.
  26649. },
  26650. /**
  26651. * @return {Array.<number>}
  26652. */
  26653. getTicksCoords: function (alignWithLabel) {
  26654. if (this.onBand && !alignWithLabel) {
  26655. var bands = this.getBands();
  26656. var coords = [];
  26657. for (var i = 0; i < bands.length; i++) {
  26658. coords.push(bands[i][0]);
  26659. }
  26660. if (bands[i - 1]) {
  26661. coords.push(bands[i - 1][1]);
  26662. }
  26663. return coords;
  26664. }
  26665. else {
  26666. return map(this.scale.getTicks(), this.dataToCoord, this);
  26667. }
  26668. },
  26669. /**
  26670. * Coords of labels are on the ticks or on the middle of bands
  26671. * @return {Array.<number>}
  26672. */
  26673. getLabelsCoords: function () {
  26674. return map(this.scale.getTicks(), this.dataToCoord, this);
  26675. },
  26676. /**
  26677. * Get bands.
  26678. *
  26679. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  26680. * |---1---|---2---|---3---|---4---|.
  26681. *
  26682. * @return {Array}
  26683. */
  26684. // FIXME Situation when labels is on ticks
  26685. getBands: function () {
  26686. var extent = this.getExtent();
  26687. var bands = [];
  26688. var len = this.scale.count();
  26689. var start = extent[0];
  26690. var end = extent[1];
  26691. var span = end - start;
  26692. for (var i = 0; i < len; i++) {
  26693. bands.push([
  26694. span * i / len + start,
  26695. span * (i + 1) / len + start
  26696. ]);
  26697. }
  26698. return bands;
  26699. },
  26700. /**
  26701. * Get width of band
  26702. * @return {number}
  26703. */
  26704. getBandWidth: function () {
  26705. var axisExtent = this._extent;
  26706. var dataExtent = this.scale.getExtent();
  26707. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  26708. // Fix #2728, avoid NaN when only one data.
  26709. len === 0 && (len = 1);
  26710. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  26711. return Math.abs(size) / len;
  26712. },
  26713. /**
  26714. * @abstract
  26715. * @return {boolean} Is horizontal
  26716. */
  26717. isHorizontal: null,
  26718. /**
  26719. * @abstract
  26720. * @return {number} Get axis rotate, by degree.
  26721. */
  26722. getRotate: null,
  26723. /**
  26724. * Get interval of the axis label.
  26725. * To get precise result, at least one of `getRotate` and `isHorizontal`
  26726. * should be implemented.
  26727. * @return {number}
  26728. */
  26729. getLabelInterval: function () {
  26730. var labelInterval = this._labelInterval;
  26731. if (!labelInterval) {
  26732. var axisModel = this.model;
  26733. var labelModel = axisModel.getModel('axisLabel');
  26734. labelInterval = labelModel.get('interval');
  26735. if (this.type === 'category'
  26736. && (labelInterval == null || labelInterval === 'auto')
  26737. ) {
  26738. labelInterval = getAxisLabelInterval(
  26739. map(this.scale.getTicks(), this.dataToCoord, this),
  26740. axisModel.getFormattedLabels(),
  26741. labelModel.getFont(),
  26742. this.getRotate
  26743. ? this.getRotate()
  26744. : (this.isHorizontal && !this.isHorizontal())
  26745. ? 90
  26746. : 0,
  26747. labelModel.get('rotate')
  26748. );
  26749. }
  26750. this._labelInterval = labelInterval;
  26751. }
  26752. return labelInterval;
  26753. }
  26754. };
  26755. /**
  26756. * Do not mount those modules on 'src/echarts' for better tree shaking.
  26757. */
  26758. var parseGeoJson = parseGeoJson$1;
  26759. var ecUtil = {};
  26760. each$1([
  26761. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  26762. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  26763. 'extend', 'defaults', 'clone', 'merge'
  26764. ],
  26765. function (name) {
  26766. ecUtil[name] = zrUtil[name];
  26767. }
  26768. );
  26769. var DatasetModel = extendComponentModel({
  26770. type: 'dataset',
  26771. /**
  26772. * @protected
  26773. */
  26774. defaultOption: {
  26775. // 'row', 'column'
  26776. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  26777. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  26778. sourceHeader: null,
  26779. dimensions: null,
  26780. source: null
  26781. },
  26782. optionUpdated: function () {
  26783. detectSourceFormat(this);
  26784. }
  26785. });
  26786. extendComponentView({type: 'dataset'});
  26787. SeriesModel.extend({
  26788. type: 'series.line',
  26789. dependencies: ['grid', 'polar'],
  26790. getInitialData: function (option, ecModel) {
  26791. if (__DEV__) {
  26792. var coordSys = option.coordinateSystem;
  26793. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  26794. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  26795. }
  26796. }
  26797. return createListFromArray(this.getSource(), this);
  26798. },
  26799. defaultOption: {
  26800. zlevel: 0, // 一级层叠
  26801. z: 2, // 二级层叠
  26802. coordinateSystem: 'cartesian2d',
  26803. legendHoverLink: true,
  26804. hoverAnimation: true,
  26805. // stack: null
  26806. // xAxisIndex: 0,
  26807. // yAxisIndex: 0,
  26808. // polarIndex: 0,
  26809. // If clip the overflow value
  26810. clipOverflow: true,
  26811. // cursor: null,
  26812. label: {
  26813. position: 'top'
  26814. },
  26815. // itemStyle: {
  26816. // },
  26817. lineStyle: {
  26818. width: 2,
  26819. type: 'solid'
  26820. },
  26821. // areaStyle: {origin: 'auto'},
  26822. // false, 'start', 'end', 'middle'
  26823. step: false,
  26824. // Disabled if step is true
  26825. smooth: false,
  26826. smoothMonotone: null,
  26827. // 拐点图形类型
  26828. symbol: 'emptyCircle',
  26829. // 拐点图形大小
  26830. symbolSize: 4,
  26831. // 拐点图形旋转控制
  26832. symbolRotate: null,
  26833. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  26834. showSymbol: true,
  26835. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  26836. showAllSymbol: false,
  26837. // 是否连接断点
  26838. connectNulls: false,
  26839. // 数据过滤,'average', 'max', 'min', 'sum'
  26840. sampling: 'none',
  26841. animationEasing: 'linear',
  26842. // Disable progressive
  26843. progressive: 0,
  26844. hoverLayerThreshold: Infinity
  26845. }
  26846. });
  26847. /**
  26848. * @param {module:echarts/data/List} data
  26849. * @param {number} dataIndex
  26850. * @return {string} label string. Not null/undefined
  26851. */
  26852. function getDefaultLabel(data, dataIndex) {
  26853. var labelDims = data.mapDimension('defaultedLabel', true);
  26854. var len = labelDims.length;
  26855. // Simple optimization (in lots of cases, label dims length is 1)
  26856. if (len === 1) {
  26857. return retrieveRawValue(data, dataIndex, labelDims[0]);
  26858. }
  26859. else if (len) {
  26860. var vals = [];
  26861. for (var i = 0; i < labelDims.length; i++) {
  26862. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  26863. vals.push(val);
  26864. }
  26865. return vals.join(' ');
  26866. }
  26867. }
  26868. /**
  26869. * @module echarts/chart/helper/Symbol
  26870. */
  26871. function getSymbolSize(data, idx) {
  26872. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  26873. return symbolSize instanceof Array
  26874. ? symbolSize.slice()
  26875. : [+symbolSize, +symbolSize];
  26876. }
  26877. function getScale(symbolSize) {
  26878. return [symbolSize[0] / 2, symbolSize[1] / 2];
  26879. }
  26880. /**
  26881. * @constructor
  26882. * @alias {module:echarts/chart/helper/Symbol}
  26883. * @param {module:echarts/data/List} data
  26884. * @param {number} idx
  26885. * @extends {module:zrender/graphic/Group}
  26886. */
  26887. function SymbolClz$1(data, idx, seriesScope) {
  26888. Group.call(this);
  26889. this.updateData(data, idx, seriesScope);
  26890. }
  26891. var symbolProto = SymbolClz$1.prototype;
  26892. function driftSymbol(dx, dy) {
  26893. this.parent.drift(dx, dy);
  26894. }
  26895. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  26896. // Remove paths created before
  26897. this.removeAll();
  26898. var color = data.getItemVisual(idx, 'color');
  26899. // var symbolPath = createSymbol(
  26900. // symbolType, -0.5, -0.5, 1, 1, color
  26901. // );
  26902. // If width/height are set too small (e.g., set to 1) on ios10
  26903. // and macOS Sierra, a circle stroke become a rect, no matter what
  26904. // the scale is set. So we set width/height as 2. See #4150.
  26905. var symbolPath = createSymbol(
  26906. symbolType, -1, -1, 2, 2, color
  26907. );
  26908. symbolPath.attr({
  26909. z2: 100,
  26910. culling: true,
  26911. scale: getScale(symbolSize)
  26912. });
  26913. // Rewrite drift method
  26914. symbolPath.drift = driftSymbol;
  26915. this._symbolType = symbolType;
  26916. this.add(symbolPath);
  26917. };
  26918. /**
  26919. * Stop animation
  26920. * @param {boolean} toLastFrame
  26921. */
  26922. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  26923. this.childAt(0).stopAnimation(toLastFrame);
  26924. };
  26925. /**
  26926. * FIXME:
  26927. * Caution: This method breaks the encapsulation of this module,
  26928. * but it indeed brings convenience. So do not use the method
  26929. * unless you detailedly know all the implements of `Symbol`,
  26930. * especially animation.
  26931. *
  26932. * Get symbol path element.
  26933. */
  26934. symbolProto.getSymbolPath = function () {
  26935. return this.childAt(0);
  26936. };
  26937. /**
  26938. * Get scale(aka, current symbol size).
  26939. * Including the change caused by animation
  26940. */
  26941. symbolProto.getScale = function () {
  26942. return this.childAt(0).scale;
  26943. };
  26944. /**
  26945. * Highlight symbol
  26946. */
  26947. symbolProto.highlight = function () {
  26948. this.childAt(0).trigger('emphasis');
  26949. };
  26950. /**
  26951. * Downplay symbol
  26952. */
  26953. symbolProto.downplay = function () {
  26954. this.childAt(0).trigger('normal');
  26955. };
  26956. /**
  26957. * @param {number} zlevel
  26958. * @param {number} z
  26959. */
  26960. symbolProto.setZ = function (zlevel, z) {
  26961. var symbolPath = this.childAt(0);
  26962. symbolPath.zlevel = zlevel;
  26963. symbolPath.z = z;
  26964. };
  26965. symbolProto.setDraggable = function (draggable) {
  26966. var symbolPath = this.childAt(0);
  26967. symbolPath.draggable = draggable;
  26968. symbolPath.cursor = draggable ? 'move' : 'pointer';
  26969. };
  26970. /**
  26971. * Update symbol properties
  26972. * @param {module:echarts/data/List} data
  26973. * @param {number} idx
  26974. * @param {Object} [seriesScope]
  26975. * @param {Object} [seriesScope.itemStyle]
  26976. * @param {Object} [seriesScope.hoverItemStyle]
  26977. * @param {Object} [seriesScope.symbolRotate]
  26978. * @param {Object} [seriesScope.symbolOffset]
  26979. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  26980. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  26981. * @param {boolean} [seriesScope.hoverAnimation]
  26982. * @param {Object} [seriesScope.cursorStyle]
  26983. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  26984. * @param {string} [seriesScope.symbolInnerColor]
  26985. * @param {Object} [seriesScope.fadeIn=false]
  26986. */
  26987. symbolProto.updateData = function (data, idx, seriesScope) {
  26988. this.silent = false;
  26989. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  26990. var seriesModel = data.hostModel;
  26991. var symbolSize = getSymbolSize(data, idx);
  26992. var isInit = symbolType !== this._symbolType;
  26993. if (isInit) {
  26994. this._createSymbol(symbolType, data, idx, symbolSize);
  26995. }
  26996. else {
  26997. var symbolPath = this.childAt(0);
  26998. symbolPath.silent = false;
  26999. updateProps(symbolPath, {
  27000. scale: getScale(symbolSize)
  27001. }, seriesModel, idx);
  27002. }
  27003. this._updateCommon(data, idx, symbolSize, seriesScope);
  27004. if (isInit) {
  27005. var symbolPath = this.childAt(0);
  27006. var fadeIn = seriesScope && seriesScope.fadeIn;
  27007. var target = {scale: symbolPath.scale.slice()};
  27008. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27009. symbolPath.scale = [0, 0];
  27010. fadeIn && (symbolPath.style.opacity = 0);
  27011. initProps(symbolPath, target, seriesModel, idx);
  27012. }
  27013. this._seriesModel = seriesModel;
  27014. };
  27015. // Update common properties
  27016. var normalStyleAccessPath = ['itemStyle'];
  27017. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27018. var normalLabelAccessPath = ['label'];
  27019. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27020. /**
  27021. * @param {module:echarts/data/List} data
  27022. * @param {number} idx
  27023. * @param {Array.<number>} symbolSize
  27024. * @param {Object} [seriesScope]
  27025. */
  27026. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27027. var symbolPath = this.childAt(0);
  27028. var seriesModel = data.hostModel;
  27029. var color = data.getItemVisual(idx, 'color');
  27030. // Reset style
  27031. if (symbolPath.type !== 'image') {
  27032. symbolPath.useStyle({
  27033. strokeNoScale: true
  27034. });
  27035. }
  27036. var itemStyle = seriesScope && seriesScope.itemStyle;
  27037. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27038. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27039. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27040. var labelModel = seriesScope && seriesScope.labelModel;
  27041. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27042. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27043. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27044. if (!seriesScope || data.hasItemOption) {
  27045. var itemModel = (seriesScope && seriesScope.itemModel)
  27046. ? seriesScope.itemModel : data.getItemModel(idx);
  27047. // Color must be excluded.
  27048. // Because symbol provide setColor individually to set fill and stroke
  27049. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27050. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27051. symbolRotate = itemModel.getShallow('symbolRotate');
  27052. symbolOffset = itemModel.getShallow('symbolOffset');
  27053. labelModel = itemModel.getModel(normalLabelAccessPath);
  27054. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27055. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27056. cursorStyle = itemModel.getShallow('cursor');
  27057. }
  27058. else {
  27059. hoverItemStyle = extend({}, hoverItemStyle);
  27060. }
  27061. var elStyle = symbolPath.style;
  27062. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27063. if (symbolOffset) {
  27064. symbolPath.attr('position', [
  27065. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27066. parsePercent$1(symbolOffset[1], symbolSize[1])
  27067. ]);
  27068. }
  27069. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27070. // PENDING setColor before setStyle!!!
  27071. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27072. symbolPath.setStyle(itemStyle);
  27073. var opacity = data.getItemVisual(idx, 'opacity');
  27074. if (opacity != null) {
  27075. elStyle.opacity = opacity;
  27076. }
  27077. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27078. setLabelStyle(
  27079. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27080. {
  27081. labelFetcher: seriesModel,
  27082. labelDataIndex: idx,
  27083. defaultText: getLabelDefaultText,
  27084. isRectText: true,
  27085. autoColor: color
  27086. }
  27087. );
  27088. // Do not execute util needed.
  27089. function getLabelDefaultText(idx, opt) {
  27090. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27091. }
  27092. symbolPath.off('mouseover')
  27093. .off('mouseout')
  27094. .off('emphasis')
  27095. .off('normal');
  27096. symbolPath.hoverStyle = hoverItemStyle;
  27097. // FIXME
  27098. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27099. setHoverStyle(symbolPath);
  27100. var scale = getScale(symbolSize);
  27101. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27102. var onEmphasis = function() {
  27103. var ratio = scale[1] / scale[0];
  27104. this.animateTo({
  27105. scale: [
  27106. Math.max(scale[0] * 1.1, scale[0] + 3),
  27107. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27108. ]
  27109. }, 400, 'elasticOut');
  27110. };
  27111. var onNormal = function() {
  27112. this.animateTo({
  27113. scale: scale
  27114. }, 400, 'elasticOut');
  27115. };
  27116. symbolPath.on('mouseover', onEmphasis)
  27117. .on('mouseout', onNormal)
  27118. .on('emphasis', onEmphasis)
  27119. .on('normal', onNormal);
  27120. }
  27121. };
  27122. /**
  27123. * @param {Function} cb
  27124. * @param {Object} [opt]
  27125. * @param {Object} [opt.keepLabel=true]
  27126. */
  27127. symbolProto.fadeOut = function (cb, opt) {
  27128. var symbolPath = this.childAt(0);
  27129. // Avoid mistaken hover when fading out
  27130. this.silent = symbolPath.silent = true;
  27131. // Not show text when animating
  27132. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27133. updateProps(
  27134. symbolPath,
  27135. {
  27136. style: {opacity: 0},
  27137. scale: [0, 0]
  27138. },
  27139. this._seriesModel,
  27140. this.dataIndex,
  27141. cb
  27142. );
  27143. };
  27144. inherits(SymbolClz$1, Group);
  27145. /**
  27146. * @module echarts/chart/helper/SymbolDraw
  27147. */
  27148. /**
  27149. * @constructor
  27150. * @alias module:echarts/chart/helper/SymbolDraw
  27151. * @param {module:zrender/graphic/Group} [symbolCtor]
  27152. */
  27153. function SymbolDraw(symbolCtor) {
  27154. this.group = new Group();
  27155. this._symbolCtor = symbolCtor || SymbolClz$1;
  27156. }
  27157. var symbolDrawProto = SymbolDraw.prototype;
  27158. function symbolNeedsDraw(data, point, idx, isIgnore) {
  27159. return point && !isNaN(point[0]) && !isNaN(point[1])
  27160. && !(isIgnore && isIgnore(idx))
  27161. && data.getItemVisual(idx, 'symbol') !== 'none';
  27162. }
  27163. /**
  27164. * Update symbols draw by new data
  27165. * @param {module:echarts/data/List} data
  27166. * @param {Array.<boolean>} [isIgnore]
  27167. */
  27168. symbolDrawProto.updateData = function (data, isIgnore) {
  27169. var group = this.group;
  27170. var seriesModel = data.hostModel;
  27171. var oldData = this._data;
  27172. var SymbolCtor = this._symbolCtor;
  27173. var seriesScope = makeSeriesScope(data);
  27174. // There is no oldLineData only when first rendering or switching from
  27175. // stream mode to normal mode, where previous elements should be removed.
  27176. if (!oldData) {
  27177. group.removeAll();
  27178. }
  27179. data.diff(oldData)
  27180. .add(function (newIdx) {
  27181. var point = data.getItemLayout(newIdx);
  27182. if (symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27183. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27184. symbolEl.attr('position', point);
  27185. data.setItemGraphicEl(newIdx, symbolEl);
  27186. group.add(symbolEl);
  27187. }
  27188. })
  27189. .update(function (newIdx, oldIdx) {
  27190. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27191. var point = data.getItemLayout(newIdx);
  27192. if (!symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  27193. group.remove(symbolEl);
  27194. return;
  27195. }
  27196. if (!symbolEl) {
  27197. symbolEl = new SymbolCtor(data, newIdx);
  27198. symbolEl.attr('position', point);
  27199. }
  27200. else {
  27201. symbolEl.updateData(data, newIdx, seriesScope);
  27202. updateProps(symbolEl, {
  27203. position: point
  27204. }, seriesModel);
  27205. }
  27206. // Add back
  27207. group.add(symbolEl);
  27208. data.setItemGraphicEl(newIdx, symbolEl);
  27209. })
  27210. .remove(function (oldIdx) {
  27211. var el = oldData.getItemGraphicEl(oldIdx);
  27212. el && el.fadeOut(function () {
  27213. group.remove(el);
  27214. });
  27215. })
  27216. .execute();
  27217. this._data = data;
  27218. };
  27219. symbolDrawProto.isPersistent = function () {
  27220. return true;
  27221. };
  27222. symbolDrawProto.updateLayout = function () {
  27223. var data = this._data;
  27224. if (data) {
  27225. // Not use animation
  27226. data.eachItemGraphicEl(function (el, idx) {
  27227. var point = data.getItemLayout(idx);
  27228. el.attr('position', point);
  27229. });
  27230. }
  27231. };
  27232. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27233. this._seriesScope = makeSeriesScope(data);
  27234. this._data = null;
  27235. this.group.removeAll();
  27236. };
  27237. symbolDrawProto.incrementalUpdate = function (taskParams, data, isIgnore) {
  27238. function updateIncrementalAndHover(el) {
  27239. if (!el.isGroup) {
  27240. el.incremental = el.useHoverLayer = true;
  27241. }
  27242. }
  27243. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27244. var point = data.getItemLayout(idx);
  27245. if (symbolNeedsDraw(data, point, idx, isIgnore)) {
  27246. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27247. el.traverse(updateIncrementalAndHover);
  27248. el.attr('position', point);
  27249. this.group.add(el);
  27250. data.setItemGraphicEl(idx, el);
  27251. }
  27252. }
  27253. };
  27254. symbolDrawProto.remove = function (enableAnimation) {
  27255. var group = this.group;
  27256. var data = this._data;
  27257. if (data) {
  27258. if (enableAnimation) {
  27259. data.eachItemGraphicEl(function (el) {
  27260. el.fadeOut(function () {
  27261. group.remove(el);
  27262. });
  27263. });
  27264. }
  27265. else {
  27266. group.removeAll();
  27267. }
  27268. }
  27269. };
  27270. function makeSeriesScope(data) {
  27271. var seriesModel = data.hostModel;
  27272. return {
  27273. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27274. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27275. symbolRotate: seriesModel.get('symbolRotate'),
  27276. symbolOffset: seriesModel.get('symbolOffset'),
  27277. hoverAnimation: seriesModel.get('hoverAnimation'),
  27278. labelModel: seriesModel.getModel('label'),
  27279. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27280. cursorStyle: seriesModel.get('cursor')
  27281. };
  27282. }
  27283. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27284. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27285. // not do well in performance when roam with fixed dataZoom window.
  27286. function sign$1(val) {
  27287. return val >= 0 ? 1 : -1;
  27288. }
  27289. function getStackedOnPoint(coordSys, data, idx) {
  27290. var baseAxis = coordSys.getBaseAxis();
  27291. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27292. var valueStart = baseAxis.onZero
  27293. ? 0 : valueAxis.scale.getExtent()[0];
  27294. var valueDim = valueAxis.dim;
  27295. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  27296. var stackedOnSameSign;
  27297. var stackedOn = data.stackedOn;
  27298. var val = data.get(valueDim, idx);
  27299. // Find first stacked value with same sign
  27300. while (stackedOn &&
  27301. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  27302. ) {
  27303. stackedOnSameSign = stackedOn;
  27304. break;
  27305. }
  27306. var stackedData = [];
  27307. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27308. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27309. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27310. return coordSys.dataToPoint(stackedData);
  27311. }
  27312. // function convertToIntId(newIdList, oldIdList) {
  27313. // // Generate int id instead of string id.
  27314. // // Compare string maybe slow in score function of arrDiff
  27315. // // Assume id in idList are all unique
  27316. // var idIndicesMap = {};
  27317. // var idx = 0;
  27318. // for (var i = 0; i < newIdList.length; i++) {
  27319. // idIndicesMap[newIdList[i]] = idx;
  27320. // newIdList[i] = idx++;
  27321. // }
  27322. // for (var i = 0; i < oldIdList.length; i++) {
  27323. // var oldId = oldIdList[i];
  27324. // // Same with newIdList
  27325. // if (idIndicesMap[oldId]) {
  27326. // oldIdList[i] = idIndicesMap[oldId];
  27327. // }
  27328. // else {
  27329. // oldIdList[i] = idx++;
  27330. // }
  27331. // }
  27332. // }
  27333. function diffData(oldData, newData) {
  27334. var diffResult = [];
  27335. newData.diff(oldData)
  27336. .add(function (idx) {
  27337. diffResult.push({cmd: '+', idx: idx});
  27338. })
  27339. .update(function (newIdx, oldIdx) {
  27340. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27341. })
  27342. .remove(function (idx) {
  27343. diffResult.push({cmd: '-', idx: idx});
  27344. })
  27345. .execute();
  27346. return diffResult;
  27347. }
  27348. var lineAnimationDiff = function (
  27349. oldData, newData,
  27350. oldStackedOnPoints, newStackedOnPoints,
  27351. oldCoordSys, newCoordSys
  27352. ) {
  27353. var diff = diffData(oldData, newData);
  27354. // var newIdList = newData.mapArray(newData.getId);
  27355. // var oldIdList = oldData.mapArray(oldData.getId);
  27356. // convertToIntId(newIdList, oldIdList);
  27357. // // FIXME One data ?
  27358. // diff = arrayDiff(oldIdList, newIdList);
  27359. var currPoints = [];
  27360. var nextPoints = [];
  27361. // Points for stacking base line
  27362. var currStackedPoints = [];
  27363. var nextStackedPoints = [];
  27364. var status = [];
  27365. var sortedIndices = [];
  27366. var rawIndices = [];
  27367. var dims = newCoordSys.dimensions;
  27368. for (var i = 0; i < diff.length; i++) {
  27369. var diffItem = diff[i];
  27370. var pointAdded = true;
  27371. // FIXME, animation is not so perfect when dataZoom window moves fast
  27372. // Which is in case remvoing or add more than one data in the tail or head
  27373. switch (diffItem.cmd) {
  27374. case '=':
  27375. var currentPt = oldData.getItemLayout(diffItem.idx);
  27376. var nextPt = newData.getItemLayout(diffItem.idx1);
  27377. // If previous data is NaN, use next point directly
  27378. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27379. currentPt = nextPt.slice();
  27380. }
  27381. currPoints.push(currentPt);
  27382. nextPoints.push(nextPt);
  27383. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27384. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27385. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27386. break;
  27387. case '+':
  27388. var idx = diffItem.idx;
  27389. currPoints.push(
  27390. oldCoordSys.dataToPoint([
  27391. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  27392. ])
  27393. );
  27394. nextPoints.push(newData.getItemLayout(idx).slice());
  27395. currStackedPoints.push(
  27396. getStackedOnPoint(oldCoordSys, newData, idx)
  27397. );
  27398. nextStackedPoints.push(newStackedOnPoints[idx]);
  27399. rawIndices.push(newData.getRawIndex(idx));
  27400. break;
  27401. case '-':
  27402. var idx = diffItem.idx;
  27403. var rawIndex = oldData.getRawIndex(idx);
  27404. // Data is replaced. In the case of dynamic data queue
  27405. // FIXME FIXME FIXME
  27406. if (rawIndex !== idx) {
  27407. currPoints.push(oldData.getItemLayout(idx));
  27408. nextPoints.push(newCoordSys.dataToPoint([
  27409. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  27410. ]));
  27411. currStackedPoints.push(oldStackedOnPoints[idx]);
  27412. nextStackedPoints.push(
  27413. getStackedOnPoint(
  27414. newCoordSys, oldData, idx
  27415. )
  27416. );
  27417. rawIndices.push(rawIndex);
  27418. }
  27419. else {
  27420. pointAdded = false;
  27421. }
  27422. }
  27423. // Original indices
  27424. if (pointAdded) {
  27425. status.push(diffItem);
  27426. sortedIndices.push(sortedIndices.length);
  27427. }
  27428. }
  27429. // Diff result may be crossed if all items are changed
  27430. // Sort by data index
  27431. sortedIndices.sort(function (a, b) {
  27432. return rawIndices[a] - rawIndices[b];
  27433. });
  27434. var sortedCurrPoints = [];
  27435. var sortedNextPoints = [];
  27436. var sortedCurrStackedPoints = [];
  27437. var sortedNextStackedPoints = [];
  27438. var sortedStatus = [];
  27439. for (var i = 0; i < sortedIndices.length; i++) {
  27440. var idx = sortedIndices[i];
  27441. sortedCurrPoints[i] = currPoints[idx];
  27442. sortedNextPoints[i] = nextPoints[idx];
  27443. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  27444. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  27445. sortedStatus[i] = status[idx];
  27446. }
  27447. return {
  27448. current: sortedCurrPoints,
  27449. next: sortedNextPoints,
  27450. stackedOnCurrent: sortedCurrStackedPoints,
  27451. stackedOnNext: sortedNextStackedPoints,
  27452. status: sortedStatus
  27453. };
  27454. };
  27455. // Poly path support NaN point
  27456. var vec2Min = min;
  27457. var vec2Max = max;
  27458. var scaleAndAdd$1 = scaleAndAdd;
  27459. var v2Copy = copy;
  27460. // Temporary variable
  27461. var v = [];
  27462. var cp0 = [];
  27463. var cp1 = [];
  27464. function isPointNull(p) {
  27465. return isNaN(p[0]) || isNaN(p[1]);
  27466. }
  27467. function drawSegment(
  27468. ctx, points, start, segLen, allLen,
  27469. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  27470. ) {
  27471. var prevIdx = 0;
  27472. var idx = start;
  27473. for (var k = 0; k < segLen; k++) {
  27474. var p = points[idx];
  27475. if (idx >= allLen || idx < 0) {
  27476. break;
  27477. }
  27478. if (isPointNull(p)) {
  27479. if (connectNulls) {
  27480. idx += dir;
  27481. continue;
  27482. }
  27483. break;
  27484. }
  27485. if (idx === start) {
  27486. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  27487. v2Copy(cp0, p);
  27488. }
  27489. else {
  27490. if (smooth > 0) {
  27491. var nextIdx = idx + dir;
  27492. var nextP = points[nextIdx];
  27493. if (connectNulls) {
  27494. // Find next point not null
  27495. while (nextP && isPointNull(points[nextIdx])) {
  27496. nextIdx += dir;
  27497. nextP = points[nextIdx];
  27498. }
  27499. }
  27500. var ratioNextSeg = 0.5;
  27501. var prevP = points[prevIdx];
  27502. var nextP = points[nextIdx];
  27503. // Last point
  27504. if (!nextP || isPointNull(nextP)) {
  27505. v2Copy(cp1, p);
  27506. }
  27507. else {
  27508. // If next data is null in not connect case
  27509. if (isPointNull(nextP) && !connectNulls) {
  27510. nextP = p;
  27511. }
  27512. sub(v, nextP, prevP);
  27513. var lenPrevSeg;
  27514. var lenNextSeg;
  27515. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  27516. var dim = smoothMonotone === 'x' ? 0 : 1;
  27517. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  27518. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  27519. }
  27520. else {
  27521. lenPrevSeg = dist(p, prevP);
  27522. lenNextSeg = dist(p, nextP);
  27523. }
  27524. // Use ratio of seg length
  27525. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  27526. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  27527. }
  27528. // Smooth constraint
  27529. vec2Min(cp0, cp0, smoothMax);
  27530. vec2Max(cp0, cp0, smoothMin);
  27531. vec2Min(cp1, cp1, smoothMax);
  27532. vec2Max(cp1, cp1, smoothMin);
  27533. ctx.bezierCurveTo(
  27534. cp0[0], cp0[1],
  27535. cp1[0], cp1[1],
  27536. p[0], p[1]
  27537. );
  27538. // cp0 of next segment
  27539. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  27540. }
  27541. else {
  27542. ctx.lineTo(p[0], p[1]);
  27543. }
  27544. }
  27545. prevIdx = idx;
  27546. idx += dir;
  27547. }
  27548. return k;
  27549. }
  27550. function getBoundingBox(points, smoothConstraint) {
  27551. var ptMin = [Infinity, Infinity];
  27552. var ptMax = [-Infinity, -Infinity];
  27553. if (smoothConstraint) {
  27554. for (var i = 0; i < points.length; i++) {
  27555. var pt = points[i];
  27556. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  27557. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  27558. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  27559. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  27560. }
  27561. }
  27562. return {
  27563. min: smoothConstraint ? ptMin : ptMax,
  27564. max: smoothConstraint ? ptMax : ptMin
  27565. };
  27566. }
  27567. var Polyline$1 = Path.extend({
  27568. type: 'ec-polyline',
  27569. shape: {
  27570. points: [],
  27571. smooth: 0,
  27572. smoothConstraint: true,
  27573. smoothMonotone: null,
  27574. connectNulls: false
  27575. },
  27576. style: {
  27577. fill: null,
  27578. stroke: '#000'
  27579. },
  27580. brush: fixClipWithShadow(Path.prototype.brush),
  27581. buildPath: function (ctx, shape) {
  27582. var points = shape.points;
  27583. var i = 0;
  27584. var len$$1 = points.length;
  27585. var result = getBoundingBox(points, shape.smoothConstraint);
  27586. if (shape.connectNulls) {
  27587. // Must remove first and last null values avoid draw error in polygon
  27588. for (; len$$1 > 0; len$$1--) {
  27589. if (!isPointNull(points[len$$1 - 1])) {
  27590. break;
  27591. }
  27592. }
  27593. for (; i < len$$1; i++) {
  27594. if (!isPointNull(points[i])) {
  27595. break;
  27596. }
  27597. }
  27598. }
  27599. while (i < len$$1) {
  27600. i += drawSegment(
  27601. ctx, points, i, len$$1, len$$1,
  27602. 1, result.min, result.max, shape.smooth,
  27603. shape.smoothMonotone, shape.connectNulls
  27604. ) + 1;
  27605. }
  27606. }
  27607. });
  27608. var Polygon$1 = Path.extend({
  27609. type: 'ec-polygon',
  27610. shape: {
  27611. points: [],
  27612. // Offset between stacked base points and points
  27613. stackedOnPoints: [],
  27614. smooth: 0,
  27615. stackedOnSmooth: 0,
  27616. smoothConstraint: true,
  27617. smoothMonotone: null,
  27618. connectNulls: false
  27619. },
  27620. brush: fixClipWithShadow(Path.prototype.brush),
  27621. buildPath: function (ctx, shape) {
  27622. var points = shape.points;
  27623. var stackedOnPoints = shape.stackedOnPoints;
  27624. var i = 0;
  27625. var len$$1 = points.length;
  27626. var smoothMonotone = shape.smoothMonotone;
  27627. var bbox = getBoundingBox(points, shape.smoothConstraint);
  27628. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  27629. if (shape.connectNulls) {
  27630. // Must remove first and last null values avoid draw error in polygon
  27631. for (; len$$1 > 0; len$$1--) {
  27632. if (!isPointNull(points[len$$1 - 1])) {
  27633. break;
  27634. }
  27635. }
  27636. for (; i < len$$1; i++) {
  27637. if (!isPointNull(points[i])) {
  27638. break;
  27639. }
  27640. }
  27641. }
  27642. while (i < len$$1) {
  27643. var k = drawSegment(
  27644. ctx, points, i, len$$1, len$$1,
  27645. 1, bbox.min, bbox.max, shape.smooth,
  27646. smoothMonotone, shape.connectNulls
  27647. );
  27648. drawSegment(
  27649. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  27650. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  27651. smoothMonotone, shape.connectNulls
  27652. );
  27653. i += k + 1;
  27654. ctx.closePath();
  27655. }
  27656. }
  27657. });
  27658. // FIXME step not support polar
  27659. function isPointsSame(points1, points2) {
  27660. if (points1.length !== points2.length) {
  27661. return;
  27662. }
  27663. for (var i = 0; i < points1.length; i++) {
  27664. var p1 = points1[i];
  27665. var p2 = points2[i];
  27666. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  27667. return;
  27668. }
  27669. }
  27670. return true;
  27671. }
  27672. function getSmooth(smooth) {
  27673. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  27674. }
  27675. function getAxisExtentWithGap(axis) {
  27676. var extent = axis.getGlobalExtent();
  27677. if (axis.onBand) {
  27678. // Remove extra 1px to avoid line miter in clipped edge
  27679. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  27680. var dir = extent[1] > extent[0] ? 1 : -1;
  27681. extent[0] += dir * halfBandWidth;
  27682. extent[1] -= dir * halfBandWidth;
  27683. }
  27684. return extent;
  27685. }
  27686. function sign(val) {
  27687. return val >= 0 ? 1 : -1;
  27688. }
  27689. /**
  27690. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  27691. * @param {module:echarts/data/List} data
  27692. * @param {Array.<Array.<number>>} points
  27693. * @param {string} origin origin of areaStyle. Valid values: 'auto', 'start',
  27694. * 'end'.
  27695. * auto: from axisLine to data
  27696. * start: from min to data
  27697. * end: from data to max
  27698. * @private
  27699. */
  27700. function getStackedOnPoints(seriesModel, coordSys, data, origin) {
  27701. var baseAxis = coordSys.getBaseAxis();
  27702. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27703. var valueStart = 0;
  27704. var extent = valueAxis.scale.getExtent();
  27705. if (origin === 'start') {
  27706. valueStart = extent[0];
  27707. }
  27708. else if (origin === 'end') {
  27709. valueStart = extent[1];
  27710. }
  27711. else {
  27712. // auto
  27713. var extent = valueAxis.scale.getExtent();
  27714. if (extent[0] > 0) {
  27715. // Both positive
  27716. valueStart = extent[0];
  27717. }
  27718. else if (extent[1] < 0) {
  27719. // Both negative
  27720. valueStart = extent[1];
  27721. }
  27722. // If is one positive, and one negative, onZero shall be true
  27723. }
  27724. var valueCoordDim = valueAxis.dim;
  27725. var baseDataOffset = valueCoordDim === 'x' || valueCoordDim === 'radius' ? 1 : 0;
  27726. var valueDim = data.mapDimension(valueCoordDim);
  27727. return data.mapArray(valueDim ? [valueDim] : [], function (val, idx) {
  27728. var stackedOnSameSign;
  27729. var stackedOn = data.stackedOn;
  27730. // Find first stacked value with same sign
  27731. while (stackedOn &&
  27732. sign(stackedOn.get(valueDim, idx)) === sign(val)
  27733. ) {
  27734. stackedOnSameSign = stackedOn;
  27735. break;
  27736. }
  27737. var stackedData = [];
  27738. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  27739. stackedData[1 - baseDataOffset] = stackedOnSameSign
  27740. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  27741. return coordSys.dataToPoint(stackedData);
  27742. }, true);
  27743. }
  27744. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  27745. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  27746. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  27747. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  27748. var x = Math.min(xExtent[0], xExtent[1]);
  27749. var y = Math.min(yExtent[0], yExtent[1]);
  27750. var width = Math.max(xExtent[0], xExtent[1]) - x;
  27751. var height = Math.max(yExtent[0], yExtent[1]) - y;
  27752. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  27753. // Expand clip shape to avoid clipping when line value exceeds axis
  27754. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  27755. if (isHorizontal) {
  27756. y -= expandSize;
  27757. height += expandSize * 2;
  27758. }
  27759. else {
  27760. x -= expandSize;
  27761. width += expandSize * 2;
  27762. }
  27763. var clipPath = new Rect({
  27764. shape: {
  27765. x: x,
  27766. y: y,
  27767. width: width,
  27768. height: height
  27769. }
  27770. });
  27771. if (hasAnimation) {
  27772. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  27773. initProps(clipPath, {
  27774. shape: {
  27775. width: width,
  27776. height: height
  27777. }
  27778. }, seriesModel);
  27779. }
  27780. return clipPath;
  27781. }
  27782. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  27783. var angleAxis = polar.getAngleAxis();
  27784. var radiusAxis = polar.getRadiusAxis();
  27785. var radiusExtent = radiusAxis.getExtent();
  27786. var angleExtent = angleAxis.getExtent();
  27787. var RADIAN = Math.PI / 180;
  27788. var clipPath = new Sector({
  27789. shape: {
  27790. cx: polar.cx,
  27791. cy: polar.cy,
  27792. r0: radiusExtent[0],
  27793. r: radiusExtent[1],
  27794. startAngle: -angleExtent[0] * RADIAN,
  27795. endAngle: -angleExtent[1] * RADIAN,
  27796. clockwise: angleAxis.inverse
  27797. }
  27798. });
  27799. if (hasAnimation) {
  27800. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  27801. initProps(clipPath, {
  27802. shape: {
  27803. endAngle: -angleExtent[1] * RADIAN
  27804. }
  27805. }, seriesModel);
  27806. }
  27807. return clipPath;
  27808. }
  27809. function createClipShape(coordSys, hasAnimation, seriesModel) {
  27810. return coordSys.type === 'polar'
  27811. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  27812. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  27813. }
  27814. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  27815. var baseAxis = coordSys.getBaseAxis();
  27816. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  27817. var stepPoints = [];
  27818. for (var i = 0; i < points.length - 1; i++) {
  27819. var nextPt = points[i + 1];
  27820. var pt = points[i];
  27821. stepPoints.push(pt);
  27822. var stepPt = [];
  27823. switch (stepTurnAt) {
  27824. case 'end':
  27825. stepPt[baseIndex] = nextPt[baseIndex];
  27826. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27827. // default is start
  27828. stepPoints.push(stepPt);
  27829. break;
  27830. case 'middle':
  27831. // default is start
  27832. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  27833. var stepPt2 = [];
  27834. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  27835. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  27836. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  27837. stepPoints.push(stepPt);
  27838. stepPoints.push(stepPt2);
  27839. break;
  27840. default:
  27841. stepPt[baseIndex] = pt[baseIndex];
  27842. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  27843. // default is start
  27844. stepPoints.push(stepPt);
  27845. }
  27846. }
  27847. // Last points
  27848. points[i] && stepPoints.push(points[i]);
  27849. return stepPoints;
  27850. }
  27851. function getVisualGradient(data, coordSys) {
  27852. var visualMetaList = data.getVisual('visualMeta');
  27853. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  27854. // When data.count() is 0, gradient range can not be calculated.
  27855. return;
  27856. }
  27857. var visualMeta;
  27858. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  27859. // Can only be x or y
  27860. if (visualMetaList[i].dimension < 2) {
  27861. visualMeta = visualMetaList[i];
  27862. break;
  27863. }
  27864. }
  27865. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  27866. if (__DEV__) {
  27867. console.warn('Visual map on line style only support x or y dimension.');
  27868. }
  27869. return;
  27870. }
  27871. // If the area to be rendered is bigger than area defined by LinearGradient,
  27872. // the canvas spec prescribes that the color of the first stop and the last
  27873. // stop should be used. But if two stops are added at offset 0, in effect
  27874. // browsers use the color of the second stop to render area outside
  27875. // LinearGradient. So we can only infinitesimally extend area defined in
  27876. // LinearGradient to render `outerColors`.
  27877. var dimension = visualMeta.dimension;
  27878. var dimName = data.dimensions[dimension];
  27879. var axis = coordSys.getAxis(dimName);
  27880. // dataToCoor mapping may not be linear, but must be monotonic.
  27881. var colorStops = map(visualMeta.stops, function (stop) {
  27882. return {
  27883. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  27884. color: stop.color
  27885. };
  27886. });
  27887. var stopLen = colorStops.length;
  27888. var outerColors = visualMeta.outerColors.slice();
  27889. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  27890. colorStops.reverse();
  27891. outerColors.reverse();
  27892. }
  27893. var tinyExtent = 10; // Arbitrary value: 10px
  27894. var minCoord = colorStops[0].coord - tinyExtent;
  27895. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  27896. var coordSpan = maxCoord - minCoord;
  27897. if (coordSpan < 1e-3) {
  27898. return 'transparent';
  27899. }
  27900. each$1(colorStops, function (stop) {
  27901. stop.offset = (stop.coord - minCoord) / coordSpan;
  27902. });
  27903. colorStops.push({
  27904. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  27905. color: outerColors[1] || 'transparent'
  27906. });
  27907. colorStops.unshift({ // notice colorStops.length have been changed.
  27908. offset: stopLen ? colorStops[0].offset : 0.5,
  27909. color: outerColors[0] || 'transparent'
  27910. });
  27911. // zrUtil.each(colorStops, function (colorStop) {
  27912. // // Make sure each offset has rounded px to avoid not sharp edge
  27913. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  27914. // });
  27915. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  27916. gradient[dimName] = minCoord;
  27917. gradient[dimName + '2'] = maxCoord;
  27918. return gradient;
  27919. }
  27920. Chart.extend({
  27921. type: 'line',
  27922. init: function () {
  27923. var lineGroup = new Group();
  27924. var symbolDraw = new SymbolDraw();
  27925. this.group.add(symbolDraw.group);
  27926. this._symbolDraw = symbolDraw;
  27927. this._lineGroup = lineGroup;
  27928. },
  27929. render: function (seriesModel, ecModel, api) {
  27930. var coordSys = seriesModel.coordinateSystem;
  27931. var group = this.group;
  27932. var data = seriesModel.getData();
  27933. var lineStyleModel = seriesModel.getModel('lineStyle');
  27934. var areaStyleModel = seriesModel.getModel('areaStyle');
  27935. var points = data.mapArray(data.getItemLayout, true);
  27936. var isCoordSysPolar = coordSys.type === 'polar';
  27937. var prevCoordSys = this._coordSys;
  27938. var symbolDraw = this._symbolDraw;
  27939. var polyline = this._polyline;
  27940. var polygon = this._polygon;
  27941. var lineGroup = this._lineGroup;
  27942. var hasAnimation = seriesModel.get('animation');
  27943. var isAreaChart = !areaStyleModel.isEmpty();
  27944. var origin = areaStyleModel.get('origin');
  27945. var stackedOnPoints = getStackedOnPoints(seriesModel, coordSys, data, origin);
  27946. var showSymbol = seriesModel.get('showSymbol');
  27947. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  27948. && this._getSymbolIgnoreFunc(data, coordSys);
  27949. // Remove temporary symbols
  27950. var oldData = this._data;
  27951. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  27952. if (el.__temp) {
  27953. group.remove(el);
  27954. oldData.setItemGraphicEl(idx, null);
  27955. }
  27956. });
  27957. // Remove previous created symbols if showSymbol changed to false
  27958. if (!showSymbol) {
  27959. symbolDraw.remove();
  27960. }
  27961. group.add(lineGroup);
  27962. // FIXME step not support polar
  27963. var step = !isCoordSysPolar && seriesModel.get('step');
  27964. // Initialization animation or coordinate system changed
  27965. if (
  27966. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  27967. ) {
  27968. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  27969. if (step) {
  27970. // TODO If stacked series is not step
  27971. points = turnPointsIntoStep(points, coordSys, step);
  27972. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  27973. }
  27974. polyline = this._newPolyline(points, coordSys, hasAnimation);
  27975. if (isAreaChart) {
  27976. polygon = this._newPolygon(
  27977. points, stackedOnPoints,
  27978. coordSys, hasAnimation
  27979. );
  27980. }
  27981. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  27982. }
  27983. else {
  27984. if (isAreaChart && !polygon) {
  27985. // If areaStyle is added
  27986. polygon = this._newPolygon(
  27987. points, stackedOnPoints,
  27988. coordSys, hasAnimation
  27989. );
  27990. }
  27991. else if (polygon && !isAreaChart) {
  27992. // If areaStyle is removed
  27993. lineGroup.remove(polygon);
  27994. polygon = this._polygon = null;
  27995. }
  27996. // Update clipPath
  27997. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  27998. // Always update, or it is wrong in the case turning on legend
  27999. // because points are not changed
  28000. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  28001. // Stop symbol animation and sync with line points
  28002. // FIXME performance?
  28003. data.eachItemGraphicEl(function (el) {
  28004. el.stopAnimation(true);
  28005. });
  28006. // In the case data zoom triggerred refreshing frequently
  28007. // Data may not change if line has a category axis. So it should animate nothing
  28008. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  28009. || !isPointsSame(this._points, points)
  28010. ) {
  28011. if (hasAnimation) {
  28012. this._updateAnimation(
  28013. data, stackedOnPoints, coordSys, api, step
  28014. );
  28015. }
  28016. else {
  28017. // Not do it in update with animation
  28018. if (step) {
  28019. // TODO If stacked series is not step
  28020. points = turnPointsIntoStep(points, coordSys, step);
  28021. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28022. }
  28023. polyline.setShape({
  28024. points: points
  28025. });
  28026. polygon && polygon.setShape({
  28027. points: points,
  28028. stackedOnPoints: stackedOnPoints
  28029. });
  28030. }
  28031. }
  28032. }
  28033. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28034. polyline.useStyle(defaults(
  28035. // Use color in lineStyle first
  28036. lineStyleModel.getLineStyle(),
  28037. {
  28038. fill: 'none',
  28039. stroke: visualColor,
  28040. lineJoin: 'bevel'
  28041. }
  28042. ));
  28043. var smooth = seriesModel.get('smooth');
  28044. smooth = getSmooth(seriesModel.get('smooth'));
  28045. polyline.setShape({
  28046. smooth: smooth,
  28047. smoothMonotone: seriesModel.get('smoothMonotone'),
  28048. connectNulls: seriesModel.get('connectNulls')
  28049. });
  28050. if (polygon) {
  28051. var stackedOn = data.stackedOn;
  28052. var stackedOnSmooth = 0;
  28053. polygon.useStyle(defaults(
  28054. areaStyleModel.getAreaStyle(),
  28055. {
  28056. fill: visualColor,
  28057. opacity: 0.7,
  28058. lineJoin: 'bevel'
  28059. }
  28060. ));
  28061. if (stackedOn) {
  28062. var stackedOnSeries = stackedOn.hostModel;
  28063. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28064. }
  28065. polygon.setShape({
  28066. smooth: smooth,
  28067. stackedOnSmooth: stackedOnSmooth,
  28068. smoothMonotone: seriesModel.get('smoothMonotone'),
  28069. connectNulls: seriesModel.get('connectNulls')
  28070. });
  28071. }
  28072. this._data = data;
  28073. // Save the coordinate system for transition animation when data changed
  28074. this._coordSys = coordSys;
  28075. this._stackedOnPoints = stackedOnPoints;
  28076. this._points = points;
  28077. this._step = step;
  28078. },
  28079. dispose: function () {},
  28080. highlight: function (seriesModel, ecModel, api, payload) {
  28081. var data = seriesModel.getData();
  28082. var dataIndex = queryDataIndex(data, payload);
  28083. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28084. var symbol = data.getItemGraphicEl(dataIndex);
  28085. if (!symbol) {
  28086. // Create a temporary symbol if it is not exists
  28087. var pt = data.getItemLayout(dataIndex);
  28088. if (!pt) {
  28089. // Null data
  28090. return;
  28091. }
  28092. symbol = new SymbolClz$1(data, dataIndex);
  28093. symbol.position = pt;
  28094. symbol.setZ(
  28095. seriesModel.get('zlevel'),
  28096. seriesModel.get('z')
  28097. );
  28098. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28099. symbol.__temp = true;
  28100. data.setItemGraphicEl(dataIndex, symbol);
  28101. // Stop scale animation
  28102. symbol.stopSymbolAnimation(true);
  28103. this.group.add(symbol);
  28104. }
  28105. symbol.highlight();
  28106. }
  28107. else {
  28108. // Highlight whole series
  28109. Chart.prototype.highlight.call(
  28110. this, seriesModel, ecModel, api, payload
  28111. );
  28112. }
  28113. },
  28114. downplay: function (seriesModel, ecModel, api, payload) {
  28115. var data = seriesModel.getData();
  28116. var dataIndex = queryDataIndex(data, payload);
  28117. if (dataIndex != null && dataIndex >= 0) {
  28118. var symbol = data.getItemGraphicEl(dataIndex);
  28119. if (symbol) {
  28120. if (symbol.__temp) {
  28121. data.setItemGraphicEl(dataIndex, null);
  28122. this.group.remove(symbol);
  28123. }
  28124. else {
  28125. symbol.downplay();
  28126. }
  28127. }
  28128. }
  28129. else {
  28130. // FIXME
  28131. // can not downplay completely.
  28132. // Downplay whole series
  28133. Chart.prototype.downplay.call(
  28134. this, seriesModel, ecModel, api, payload
  28135. );
  28136. }
  28137. },
  28138. /**
  28139. * @param {module:zrender/container/Group} group
  28140. * @param {Array.<Array.<number>>} points
  28141. * @private
  28142. */
  28143. _newPolyline: function (points) {
  28144. var polyline = this._polyline;
  28145. // Remove previous created polyline
  28146. if (polyline) {
  28147. this._lineGroup.remove(polyline);
  28148. }
  28149. polyline = new Polyline$1({
  28150. shape: {
  28151. points: points
  28152. },
  28153. silent: true,
  28154. z2: 10
  28155. });
  28156. this._lineGroup.add(polyline);
  28157. this._polyline = polyline;
  28158. return polyline;
  28159. },
  28160. /**
  28161. * @param {module:zrender/container/Group} group
  28162. * @param {Array.<Array.<number>>} stackedOnPoints
  28163. * @param {Array.<Array.<number>>} points
  28164. * @private
  28165. */
  28166. _newPolygon: function (points, stackedOnPoints) {
  28167. var polygon = this._polygon;
  28168. // Remove previous created polygon
  28169. if (polygon) {
  28170. this._lineGroup.remove(polygon);
  28171. }
  28172. polygon = new Polygon$1({
  28173. shape: {
  28174. points: points,
  28175. stackedOnPoints: stackedOnPoints
  28176. },
  28177. silent: true
  28178. });
  28179. this._lineGroup.add(polygon);
  28180. this._polygon = polygon;
  28181. return polygon;
  28182. },
  28183. /**
  28184. * @private
  28185. */
  28186. _getSymbolIgnoreFunc: function (data, coordSys) {
  28187. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28188. // `getLabelInterval` is provided by echarts/component/axis
  28189. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28190. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28191. }
  28192. },
  28193. /**
  28194. * @private
  28195. */
  28196. // FIXME Two value axis
  28197. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  28198. var polyline = this._polyline;
  28199. var polygon = this._polygon;
  28200. var seriesModel = data.hostModel;
  28201. var diff = lineAnimationDiff(
  28202. this._data, data,
  28203. this._stackedOnPoints, stackedOnPoints,
  28204. this._coordSys, coordSys
  28205. );
  28206. var current = diff.current;
  28207. var stackedOnCurrent = diff.stackedOnCurrent;
  28208. var next = diff.next;
  28209. var stackedOnNext = diff.stackedOnNext;
  28210. if (step) {
  28211. // TODO If stacked series is not step
  28212. current = turnPointsIntoStep(diff.current, coordSys, step);
  28213. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28214. next = turnPointsIntoStep(diff.next, coordSys, step);
  28215. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28216. }
  28217. // `diff.current` is subset of `current` (which should be ensured by
  28218. // turnPointsIntoStep), so points in `__points` can be updated when
  28219. // points in `current` are update during animation.
  28220. polyline.shape.__points = diff.current;
  28221. polyline.shape.points = current;
  28222. updateProps(polyline, {
  28223. shape: {
  28224. points: next
  28225. }
  28226. }, seriesModel);
  28227. if (polygon) {
  28228. polygon.setShape({
  28229. points: current,
  28230. stackedOnPoints: stackedOnCurrent
  28231. });
  28232. updateProps(polygon, {
  28233. shape: {
  28234. points: next,
  28235. stackedOnPoints: stackedOnNext
  28236. }
  28237. }, seriesModel);
  28238. }
  28239. var updatedDataInfo = [];
  28240. var diffStatus = diff.status;
  28241. for (var i = 0; i < diffStatus.length; i++) {
  28242. var cmd = diffStatus[i].cmd;
  28243. if (cmd === '=') {
  28244. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28245. if (el) {
  28246. updatedDataInfo.push({
  28247. el: el,
  28248. ptIdx: i // Index of points
  28249. });
  28250. }
  28251. }
  28252. }
  28253. if (polyline.animators && polyline.animators.length) {
  28254. polyline.animators[0].during(function () {
  28255. for (var i = 0; i < updatedDataInfo.length; i++) {
  28256. var el = updatedDataInfo[i].el;
  28257. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28258. }
  28259. });
  28260. }
  28261. },
  28262. remove: function (ecModel) {
  28263. var group = this.group;
  28264. var oldData = this._data;
  28265. this._lineGroup.removeAll();
  28266. this._symbolDraw.remove(true);
  28267. // Remove temporary created elements when highlighting
  28268. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28269. if (el.__temp) {
  28270. group.remove(el);
  28271. oldData.setItemGraphicEl(idx, null);
  28272. }
  28273. });
  28274. this._polyline =
  28275. this._polygon =
  28276. this._coordSys =
  28277. this._points =
  28278. this._stackedOnPoints =
  28279. this._data = null;
  28280. }
  28281. });
  28282. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28283. // Encoding visual for all series include which is filtered for legend drawing
  28284. return {
  28285. seriesType: seriesType,
  28286. performRawSeries: true,
  28287. reset: function (seriesModel, ecModel, api) {
  28288. var data = seriesModel.getData();
  28289. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28290. var symbolSize = seriesModel.get('symbolSize');
  28291. data.setVisual({
  28292. legendSymbol: legendSymbol || symbolType,
  28293. symbol: symbolType,
  28294. symbolSize: symbolSize
  28295. });
  28296. // Only visible series has each data be visual encoded
  28297. if (ecModel.isSeriesFiltered(seriesModel)) {
  28298. return;
  28299. }
  28300. var hasCallback = typeof symbolSize === 'function';
  28301. function dataEach(data, idx) {
  28302. if (typeof symbolSize === 'function') {
  28303. var rawValue = seriesModel.getRawValue(idx);
  28304. // FIXME
  28305. var params = seriesModel.getDataParams(idx);
  28306. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28307. }
  28308. if (data.hasItemOption) {
  28309. var itemModel = data.getItemModel(idx);
  28310. var itemSymbolType = itemModel.getShallow('symbol', true);
  28311. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28312. // If has item symbol
  28313. if (itemSymbolType != null) {
  28314. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28315. }
  28316. if (itemSymbolSize != null) {
  28317. // PENDING Transform symbolSize ?
  28318. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  28319. }
  28320. }
  28321. }
  28322. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  28323. }
  28324. };
  28325. };
  28326. var pointsLayout = function (seriesType) {
  28327. return {
  28328. seriesType: seriesType,
  28329. plan: createRenderPlanner(),
  28330. reset: function (seriesModel) {
  28331. var data = seriesModel.getData();
  28332. var coordSys = seriesModel.coordinateSystem;
  28333. var pipelineContext = seriesModel.pipelineContext;
  28334. var isLargeRender = pipelineContext.large;
  28335. if (!coordSys) {
  28336. return;
  28337. }
  28338. var dims = map(coordSys.dimensions, function (dim) {
  28339. return data.getDimension(data.mapDimension(dim));
  28340. }).slice(0, 2);
  28341. var dimLen = dims.length;
  28342. function progress(params, data) {
  28343. var segCount = params.end - params.start;
  28344. var points = isLargeRender && new Float32Array(segCount * dimLen);
  28345. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  28346. var point;
  28347. if (dimLen === 1) {
  28348. var x = data.get(dims[0], i, true);
  28349. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  28350. }
  28351. else {
  28352. var x = tmpIn[0] = data.get(dims[0], i, true);
  28353. var y = tmpIn[1] = data.get(dims[1], i, true);
  28354. // Also {Array.<number>}, not undefined to avoid if...else... statement
  28355. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  28356. }
  28357. if (isLargeRender) {
  28358. points[offset++] = point ? point[0] : NaN;
  28359. points[offset++] = point ? point[1] : NaN;
  28360. }
  28361. else {
  28362. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  28363. }
  28364. }
  28365. isLargeRender && data.setLayout('symbolPoints', points);
  28366. }
  28367. return dimLen && {progress: progress};
  28368. }
  28369. };
  28370. };
  28371. var samplers = {
  28372. average: function (frame) {
  28373. var sum = 0;
  28374. var count = 0;
  28375. for (var i = 0; i < frame.length; i++) {
  28376. if (!isNaN(frame[i])) {
  28377. sum += frame[i];
  28378. count++;
  28379. }
  28380. }
  28381. // Return NaN if count is 0
  28382. return count === 0 ? NaN : sum / count;
  28383. },
  28384. sum: function (frame) {
  28385. var sum = 0;
  28386. for (var i = 0; i < frame.length; i++) {
  28387. // Ignore NaN
  28388. sum += frame[i] || 0;
  28389. }
  28390. return sum;
  28391. },
  28392. max: function (frame) {
  28393. var max = -Infinity;
  28394. for (var i = 0; i < frame.length; i++) {
  28395. frame[i] > max && (max = frame[i]);
  28396. }
  28397. return max;
  28398. },
  28399. min: function (frame) {
  28400. var min = Infinity;
  28401. for (var i = 0; i < frame.length; i++) {
  28402. frame[i] < min && (min = frame[i]);
  28403. }
  28404. return min;
  28405. },
  28406. // TODO
  28407. // Median
  28408. nearest: function (frame) {
  28409. return frame[0];
  28410. }
  28411. };
  28412. var indexSampler = function (frame, value) {
  28413. return Math.round(frame.length / 2);
  28414. };
  28415. var dataSample = function (seriesType) {
  28416. return {
  28417. seriesType: seriesType,
  28418. reset: function (seriesModel, ecModel, api) {
  28419. var data = seriesModel.getData();
  28420. var sampling = seriesModel.get('sampling');
  28421. var coordSys = seriesModel.coordinateSystem;
  28422. // Only cartesian2d support down sampling
  28423. if (coordSys.type === 'cartesian2d' && sampling) {
  28424. var baseAxis = coordSys.getBaseAxis();
  28425. var valueAxis = coordSys.getOtherAxis(baseAxis);
  28426. var extent = baseAxis.getExtent();
  28427. // Coordinste system has been resized
  28428. var size = extent[1] - extent[0];
  28429. var rate = Math.round(data.count() / size);
  28430. if (rate > 1) {
  28431. var sampler;
  28432. if (typeof sampling === 'string') {
  28433. sampler = samplers[sampling];
  28434. }
  28435. else if (typeof sampling === 'function') {
  28436. sampler = sampling;
  28437. }
  28438. if (sampler) {
  28439. seriesModel.setData(data.downSample(
  28440. valueAxis.dim, 1 / rate, sampler, indexSampler
  28441. ));
  28442. }
  28443. }
  28444. }
  28445. }
  28446. };
  28447. };
  28448. /**
  28449. * Cartesian coordinate system
  28450. * @module echarts/coord/Cartesian
  28451. *
  28452. */
  28453. function dimAxisMapper(dim) {
  28454. return this._axes[dim];
  28455. }
  28456. /**
  28457. * @alias module:echarts/coord/Cartesian
  28458. * @constructor
  28459. */
  28460. var Cartesian = function (name) {
  28461. this._axes = {};
  28462. this._dimList = [];
  28463. /**
  28464. * @type {string}
  28465. */
  28466. this.name = name || '';
  28467. };
  28468. Cartesian.prototype = {
  28469. constructor: Cartesian,
  28470. type: 'cartesian',
  28471. /**
  28472. * Get axis
  28473. * @param {number|string} dim
  28474. * @return {module:echarts/coord/Cartesian~Axis}
  28475. */
  28476. getAxis: function (dim) {
  28477. return this._axes[dim];
  28478. },
  28479. /**
  28480. * Get axes list
  28481. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  28482. */
  28483. getAxes: function () {
  28484. return map(this._dimList, dimAxisMapper, this);
  28485. },
  28486. /**
  28487. * Get axes list by given scale type
  28488. */
  28489. getAxesByScale: function (scaleType) {
  28490. scaleType = scaleType.toLowerCase();
  28491. return filter(
  28492. this.getAxes(),
  28493. function (axis) {
  28494. return axis.scale.type === scaleType;
  28495. }
  28496. );
  28497. },
  28498. /**
  28499. * Add axis
  28500. * @param {module:echarts/coord/Cartesian.Axis}
  28501. */
  28502. addAxis: function (axis) {
  28503. var dim = axis.dim;
  28504. this._axes[dim] = axis;
  28505. this._dimList.push(dim);
  28506. },
  28507. /**
  28508. * Convert data to coord in nd space
  28509. * @param {Array.<number>|Object.<string, number>} val
  28510. * @return {Array.<number>|Object.<string, number>}
  28511. */
  28512. dataToCoord: function (val) {
  28513. return this._dataCoordConvert(val, 'dataToCoord');
  28514. },
  28515. /**
  28516. * Convert coord in nd space to data
  28517. * @param {Array.<number>|Object.<string, number>} val
  28518. * @return {Array.<number>|Object.<string, number>}
  28519. */
  28520. coordToData: function (val) {
  28521. return this._dataCoordConvert(val, 'coordToData');
  28522. },
  28523. _dataCoordConvert: function (input, method) {
  28524. var dimList = this._dimList;
  28525. var output = input instanceof Array ? [] : {};
  28526. for (var i = 0; i < dimList.length; i++) {
  28527. var dim = dimList[i];
  28528. var axis = this._axes[dim];
  28529. output[dim] = axis[method](input[dim]);
  28530. }
  28531. return output;
  28532. }
  28533. };
  28534. function Cartesian2D(name) {
  28535. Cartesian.call(this, name);
  28536. }
  28537. Cartesian2D.prototype = {
  28538. constructor: Cartesian2D,
  28539. type: 'cartesian2d',
  28540. /**
  28541. * @type {Array.<string>}
  28542. * @readOnly
  28543. */
  28544. dimensions: ['x', 'y'],
  28545. /**
  28546. * Base axis will be used on stacking.
  28547. *
  28548. * @return {module:echarts/coord/cartesian/Axis2D}
  28549. */
  28550. getBaseAxis: function () {
  28551. return this.getAxesByScale('ordinal')[0]
  28552. || this.getAxesByScale('time')[0]
  28553. || this.getAxis('x');
  28554. },
  28555. /**
  28556. * If contain point
  28557. * @param {Array.<number>} point
  28558. * @return {boolean}
  28559. */
  28560. containPoint: function (point) {
  28561. var axisX = this.getAxis('x');
  28562. var axisY = this.getAxis('y');
  28563. return axisX.contain(axisX.toLocalCoord(point[0]))
  28564. && axisY.contain(axisY.toLocalCoord(point[1]));
  28565. },
  28566. /**
  28567. * If contain data
  28568. * @param {Array.<number>} data
  28569. * @return {boolean}
  28570. */
  28571. containData: function (data) {
  28572. return this.getAxis('x').containData(data[0])
  28573. && this.getAxis('y').containData(data[1]);
  28574. },
  28575. /**
  28576. * @param {Array.<number>} data
  28577. * @param {Array.<number>} out
  28578. * @return {Array.<number>}
  28579. */
  28580. dataToPoint: function (data, reserved, out) {
  28581. var xAxis = this.getAxis('x');
  28582. var yAxis = this.getAxis('y');
  28583. out = out || [];
  28584. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  28585. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  28586. return out;
  28587. },
  28588. /**
  28589. * @param {Array.<number>} data
  28590. * @param {Array.<number>} out
  28591. * @return {Array.<number>}
  28592. */
  28593. clampData: function (data, out) {
  28594. var xAxisExtent = this.getAxis('x').scale.getExtent();
  28595. var yAxisExtent = this.getAxis('y').scale.getExtent();
  28596. out = out || [];
  28597. out[0] = Math.min(
  28598. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  28599. Math.max(xAxisExtent[0], xAxisExtent[1])
  28600. );
  28601. out[1] = Math.min(
  28602. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  28603. Math.max(yAxisExtent[0], yAxisExtent[1])
  28604. );
  28605. return out;
  28606. },
  28607. /**
  28608. * @param {Array.<number>} point
  28609. * @param {Array.<number>} out
  28610. * @return {Array.<number>}
  28611. */
  28612. pointToData: function (point, out) {
  28613. var xAxis = this.getAxis('x');
  28614. var yAxis = this.getAxis('y');
  28615. out = out || [];
  28616. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  28617. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  28618. return out;
  28619. },
  28620. /**
  28621. * Get other axis
  28622. * @param {module:echarts/coord/cartesian/Axis2D} axis
  28623. */
  28624. getOtherAxis: function (axis) {
  28625. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  28626. }
  28627. };
  28628. inherits(Cartesian2D, Cartesian);
  28629. /**
  28630. * Extend axis 2d
  28631. * @constructor module:echarts/coord/cartesian/Axis2D
  28632. * @extends {module:echarts/coord/cartesian/Axis}
  28633. * @param {string} dim
  28634. * @param {*} scale
  28635. * @param {Array.<number>} coordExtent
  28636. * @param {string} axisType
  28637. * @param {string} position
  28638. */
  28639. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  28640. Axis.call(this, dim, scale, coordExtent);
  28641. /**
  28642. * Axis type
  28643. * - 'category'
  28644. * - 'value'
  28645. * - 'time'
  28646. * - 'log'
  28647. * @type {string}
  28648. */
  28649. this.type = axisType || 'value';
  28650. /**
  28651. * Axis position
  28652. * - 'top'
  28653. * - 'bottom'
  28654. * - 'left'
  28655. * - 'right'
  28656. */
  28657. this.position = position || 'bottom';
  28658. };
  28659. Axis2D.prototype = {
  28660. constructor: Axis2D,
  28661. /**
  28662. * Index of axis, can be used as key
  28663. */
  28664. index: 0,
  28665. /**
  28666. * If axis is on the zero position of the other axis
  28667. * @type {boolean}
  28668. */
  28669. onZero: false,
  28670. /**
  28671. * Axis model
  28672. * @param {module:echarts/coord/cartesian/AxisModel}
  28673. */
  28674. model: null,
  28675. isHorizontal: function () {
  28676. var position = this.position;
  28677. return position === 'top' || position === 'bottom';
  28678. },
  28679. /**
  28680. * Each item cooresponds to this.getExtent(), which
  28681. * means globalExtent[0] may greater than globalExtent[1],
  28682. * unless `asc` is input.
  28683. *
  28684. * @param {boolean} [asc]
  28685. * @return {Array.<number>}
  28686. */
  28687. getGlobalExtent: function (asc) {
  28688. var ret = this.getExtent();
  28689. ret[0] = this.toGlobalCoord(ret[0]);
  28690. ret[1] = this.toGlobalCoord(ret[1]);
  28691. asc && ret[0] > ret[1] && ret.reverse();
  28692. return ret;
  28693. },
  28694. getOtherAxis: function () {
  28695. this.grid.getOtherAxis();
  28696. },
  28697. /**
  28698. * If label is ignored.
  28699. * Automatically used when axis is category and label can not be all shown
  28700. * @param {number} idx
  28701. * @return {boolean}
  28702. */
  28703. isLabelIgnored: function (idx) {
  28704. if (this.type === 'category') {
  28705. var labelInterval = this.getLabelInterval();
  28706. return ((typeof labelInterval === 'function')
  28707. && !labelInterval(idx, this.scale.getLabel(idx)))
  28708. || idx % (labelInterval + 1);
  28709. }
  28710. },
  28711. /**
  28712. * @override
  28713. */
  28714. pointToData: function (point, clamp) {
  28715. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  28716. },
  28717. /**
  28718. * Transform global coord to local coord,
  28719. * i.e. var localCoord = axis.toLocalCoord(80);
  28720. * designate by module:echarts/coord/cartesian/Grid.
  28721. * @type {Function}
  28722. */
  28723. toLocalCoord: null,
  28724. /**
  28725. * Transform global coord to local coord,
  28726. * i.e. var globalCoord = axis.toLocalCoord(40);
  28727. * designate by module:echarts/coord/cartesian/Grid.
  28728. * @type {Function}
  28729. */
  28730. toGlobalCoord: null
  28731. };
  28732. inherits(Axis2D, Axis);
  28733. var defaultOption = {
  28734. show: true,
  28735. zlevel: 0, // 一级层叠
  28736. z: 0, // 二级层叠
  28737. // 反向坐标轴
  28738. inverse: false,
  28739. // 坐标轴名字,默认为空
  28740. name: '',
  28741. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  28742. nameLocation: 'end',
  28743. // 坐标轴名字旋转,degree。
  28744. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  28745. nameTruncate: {
  28746. maxWidth: null,
  28747. ellipsis: '...',
  28748. placeholder: '.'
  28749. },
  28750. // 坐标轴文字样式,默认取全局样式
  28751. nameTextStyle: {},
  28752. // 文字与轴线距离
  28753. nameGap: 15,
  28754. silent: false, // Default false to support tooltip.
  28755. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  28756. tooltip: {
  28757. show: false
  28758. },
  28759. axisPointer: {},
  28760. // 坐标轴线
  28761. axisLine: {
  28762. // 默认显示,属性show控制显示与否
  28763. show: true,
  28764. onZero: true,
  28765. onZeroAxisIndex: null,
  28766. // 属性lineStyle控制线条样式
  28767. lineStyle: {
  28768. color: '#333',
  28769. width: 1,
  28770. type: 'solid'
  28771. },
  28772. // 坐标轴两端的箭头
  28773. symbol: ['none', 'none'],
  28774. symbolSize: [10, 15]
  28775. },
  28776. // 坐标轴小标记
  28777. axisTick: {
  28778. // 属性show控制显示与否,默认显示
  28779. show: true,
  28780. // 控制小标记是否在grid里
  28781. inside: false,
  28782. // 属性length控制线长
  28783. length: 5,
  28784. // 属性lineStyle控制线条样式
  28785. lineStyle: {
  28786. width: 1
  28787. }
  28788. },
  28789. // 坐标轴文本标签,详见axis.axisLabel
  28790. axisLabel: {
  28791. show: true,
  28792. // 控制文本标签是否在grid里
  28793. inside: false,
  28794. rotate: 0,
  28795. showMinLabel: null, // true | false | null (auto)
  28796. showMaxLabel: null, // true | false | null (auto)
  28797. margin: 8,
  28798. // formatter: null,
  28799. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  28800. fontSize: 12
  28801. },
  28802. // 分隔线
  28803. splitLine: {
  28804. // 默认显示,属性show控制显示与否
  28805. show: true,
  28806. // 属性lineStyle(详见lineStyle)控制线条样式
  28807. lineStyle: {
  28808. color: ['#ccc'],
  28809. width: 1,
  28810. type: 'solid'
  28811. }
  28812. },
  28813. // 分隔区域
  28814. splitArea: {
  28815. // 默认不显示,属性show控制显示与否
  28816. show: false,
  28817. // 属性areaStyle(详见areaStyle)控制区域样式
  28818. areaStyle: {
  28819. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  28820. }
  28821. }
  28822. };
  28823. var axisDefault = {};
  28824. axisDefault.categoryAxis = merge({
  28825. // 类目起始和结束两端空白策略
  28826. boundaryGap: true,
  28827. // Set false to faster category collection.
  28828. // Only usefull in the case like: category is
  28829. // ['2012-01-01', '2012-01-02', ...], where the input
  28830. // data has been ensured not duplicate and is large data.
  28831. // null means "auto":
  28832. // if axis.data provided, do not deduplication,
  28833. // else do deduplication.
  28834. deduplication: null,
  28835. // splitArea: {
  28836. // show: false
  28837. // },
  28838. splitLine: {
  28839. show: false
  28840. },
  28841. // 坐标轴小标记
  28842. axisTick: {
  28843. // If tick is align with label when boundaryGap is true
  28844. alignWithLabel: false,
  28845. interval: 'auto'
  28846. },
  28847. // 坐标轴文本标签,详见axis.axisLabel
  28848. axisLabel: {
  28849. interval: 'auto'
  28850. }
  28851. }, defaultOption);
  28852. axisDefault.valueAxis = merge({
  28853. // 数值起始和结束两端空白策略
  28854. boundaryGap: [0, 0],
  28855. // TODO
  28856. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  28857. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  28858. // min: null,
  28859. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  28860. // max: null,
  28861. // Readonly prop, specifies start value of the range when using data zoom.
  28862. // rangeStart: null
  28863. // Readonly prop, specifies end value of the range when using data zoom.
  28864. // rangeEnd: null
  28865. // 脱离0值比例,放大聚焦到最终_min,_max区间
  28866. // scale: false,
  28867. // 分割段数,默认为5
  28868. splitNumber: 5
  28869. // Minimum interval
  28870. // minInterval: null
  28871. // maxInterval: null
  28872. }, defaultOption);
  28873. // FIXME
  28874. axisDefault.timeAxis = defaults({
  28875. scale: true,
  28876. min: 'dataMin',
  28877. max: 'dataMax'
  28878. }, axisDefault.valueAxis);
  28879. axisDefault.logAxis = defaults({
  28880. scale: true,
  28881. logBase: 10
  28882. }, axisDefault.valueAxis);
  28883. // FIXME axisType is fixed ?
  28884. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  28885. /**
  28886. * Generate sub axis model class
  28887. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  28888. * @param {module:echarts/model/Component} BaseAxisModelClass
  28889. * @param {Function} axisTypeDefaulter
  28890. * @param {Object} [extraDefaultOption]
  28891. */
  28892. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  28893. each$1(AXIS_TYPES, function (axisType) {
  28894. BaseAxisModelClass.extend({
  28895. /**
  28896. * @readOnly
  28897. */
  28898. type: axisName + 'Axis.' + axisType,
  28899. mergeDefaultAndTheme: function (option, ecModel) {
  28900. var layoutMode = this.layoutMode;
  28901. var inputPositionParams = layoutMode
  28902. ? getLayoutParams(option) : {};
  28903. var themeModel = ecModel.getTheme();
  28904. merge(option, themeModel.get(axisType + 'Axis'));
  28905. merge(option, this.getDefaultOption());
  28906. option.type = axisTypeDefaulter(axisName, option);
  28907. if (layoutMode) {
  28908. mergeLayoutParam(option, inputPositionParams, layoutMode);
  28909. }
  28910. },
  28911. /**
  28912. * @override
  28913. */
  28914. optionUpdated: function () {
  28915. var thisOption = this.option;
  28916. if (thisOption.type === 'category') {
  28917. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  28918. }
  28919. },
  28920. /**
  28921. * Should not be called before all of 'getInitailData' finished.
  28922. * Because categories are collected during initializing data.
  28923. */
  28924. getCategories: function () {
  28925. // FIXME
  28926. // warning if called before all of 'getInitailData' finished.
  28927. if (this.option.type === 'category') {
  28928. return this.__ordinalMeta.categories;
  28929. }
  28930. },
  28931. getOrdinalMeta: function () {
  28932. return this.__ordinalMeta;
  28933. },
  28934. defaultOption: mergeAll(
  28935. [
  28936. {},
  28937. axisDefault[axisType + 'Axis'],
  28938. extraDefaultOption
  28939. ],
  28940. true
  28941. )
  28942. });
  28943. });
  28944. ComponentModel.registerSubTypeDefaulter(
  28945. axisName + 'Axis',
  28946. curry(axisTypeDefaulter, axisName)
  28947. );
  28948. };
  28949. var AxisModel = ComponentModel.extend({
  28950. type: 'cartesian2dAxis',
  28951. /**
  28952. * @type {module:echarts/coord/cartesian/Axis2D}
  28953. */
  28954. axis: null,
  28955. /**
  28956. * @override
  28957. */
  28958. init: function () {
  28959. AxisModel.superApply(this, 'init', arguments);
  28960. this.resetRange();
  28961. },
  28962. /**
  28963. * @override
  28964. */
  28965. mergeOption: function () {
  28966. AxisModel.superApply(this, 'mergeOption', arguments);
  28967. this.resetRange();
  28968. },
  28969. /**
  28970. * @override
  28971. */
  28972. restoreData: function () {
  28973. AxisModel.superApply(this, 'restoreData', arguments);
  28974. this.resetRange();
  28975. },
  28976. /**
  28977. * @override
  28978. * @return {module:echarts/model/Component}
  28979. */
  28980. getCoordSysModel: function () {
  28981. return this.ecModel.queryComponents({
  28982. mainType: 'grid',
  28983. index: this.option.gridIndex,
  28984. id: this.option.gridId
  28985. })[0];
  28986. }
  28987. });
  28988. function getAxisType(axisDim, option) {
  28989. // Default axis with data is category axis
  28990. return option.type || (option.data ? 'category' : 'value');
  28991. }
  28992. merge(AxisModel.prototype, axisModelCommonMixin);
  28993. var extraOption = {
  28994. // gridIndex: 0,
  28995. // gridId: '',
  28996. // Offset is for multiple axis on the same position
  28997. offset: 0
  28998. };
  28999. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  29000. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  29001. // Grid 是在有直角坐标系的时候必须要存在的
  29002. // 所以这里也要被 Cartesian2D 依赖
  29003. ComponentModel.extend({
  29004. type: 'grid',
  29005. dependencies: ['xAxis', 'yAxis'],
  29006. layoutMode: 'box',
  29007. /**
  29008. * @type {module:echarts/coord/cartesian/Grid}
  29009. */
  29010. coordinateSystem: null,
  29011. defaultOption: {
  29012. show: false,
  29013. zlevel: 0,
  29014. z: 0,
  29015. left: '10%',
  29016. top: 60,
  29017. right: '10%',
  29018. bottom: 60,
  29019. // If grid size contain label
  29020. containLabel: false,
  29021. // width: {totalWidth} - left - right,
  29022. // height: {totalHeight} - top - bottom,
  29023. backgroundColor: 'rgba(0,0,0,0)',
  29024. borderWidth: 1,
  29025. borderColor: '#ccc'
  29026. }
  29027. });
  29028. /**
  29029. * Grid is a region which contains at most 4 cartesian systems
  29030. *
  29031. * TODO Default cartesian
  29032. */
  29033. // Depends on GridModel, AxisModel, which performs preprocess.
  29034. var each$6 = each$1;
  29035. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29036. var niceScaleExtent$1 = niceScaleExtent;
  29037. /**
  29038. * Check if the axis is used in the specified grid
  29039. * @inner
  29040. */
  29041. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29042. return axisModel.getCoordSysModel() === gridModel;
  29043. }
  29044. function rotateTextRect(textRect, rotate) {
  29045. var rotateRadians = rotate * Math.PI / 180;
  29046. var boundingBox = textRect.plain();
  29047. var beforeWidth = boundingBox.width;
  29048. var beforeHeight = boundingBox.height;
  29049. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29050. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29051. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29052. return rotatedRect;
  29053. }
  29054. function getLabelUnionRect(axis) {
  29055. var axisModel = axis.model;
  29056. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29057. var axisLabelModel = axisModel.getModel('axisLabel');
  29058. var rect;
  29059. var step = 1;
  29060. var labelCount = labels.length;
  29061. if (labelCount > 40) {
  29062. // Simple optimization for large amount of labels
  29063. step = Math.ceil(labelCount / 40);
  29064. }
  29065. for (var i = 0; i < labelCount; i += step) {
  29066. if (!axis.isLabelIgnored(i)) {
  29067. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29068. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29069. rect ? rect.union(singleRect) : (rect = singleRect);
  29070. }
  29071. }
  29072. return rect;
  29073. }
  29074. function Grid(gridModel, ecModel, api) {
  29075. /**
  29076. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29077. * @private
  29078. */
  29079. this._coordsMap = {};
  29080. /**
  29081. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29082. * @private
  29083. */
  29084. this._coordsList = [];
  29085. /**
  29086. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29087. * @private
  29088. */
  29089. this._axesMap = {};
  29090. /**
  29091. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29092. * @private
  29093. */
  29094. this._axesList = [];
  29095. this._initCartesian(gridModel, ecModel, api);
  29096. this.model = gridModel;
  29097. }
  29098. var gridProto = Grid.prototype;
  29099. gridProto.type = 'grid';
  29100. gridProto.axisPointerEnabled = true;
  29101. gridProto.getRect = function () {
  29102. return this._rect;
  29103. };
  29104. gridProto.update = function (ecModel, api) {
  29105. var axesMap = this._axesMap;
  29106. this._updateScale(ecModel, this.model);
  29107. each$6(axesMap.x, function (xAxis) {
  29108. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29109. });
  29110. each$6(axesMap.y, function (yAxis) {
  29111. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29112. });
  29113. each$6(axesMap.x, function (xAxis) {
  29114. fixAxisOnZero(axesMap, 'y', xAxis);
  29115. });
  29116. each$6(axesMap.y, function (yAxis) {
  29117. fixAxisOnZero(axesMap, 'x', yAxis);
  29118. });
  29119. // Resize again if containLabel is enabled
  29120. // FIXME It may cause getting wrong grid size in data processing stage
  29121. this.resize(this.model, api);
  29122. };
  29123. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29124. // onZero can not be enabled in these two situations:
  29125. // 1. When any other axis is a category axis.
  29126. // 2. When no axis is cross 0 point.
  29127. var axes = axesMap[otherAxisDim];
  29128. if (!axis.onZero) {
  29129. return;
  29130. }
  29131. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29132. // If target axis is specified.
  29133. if (onZeroAxisIndex != null) {
  29134. var otherAxis = axes[onZeroAxisIndex];
  29135. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29136. axis.onZero = false;
  29137. }
  29138. return;
  29139. }
  29140. for (var idx in axes) {
  29141. if (axes.hasOwnProperty(idx)) {
  29142. var otherAxis = axes[idx];
  29143. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29144. onZeroAxisIndex = +idx;
  29145. break;
  29146. }
  29147. }
  29148. }
  29149. if (onZeroAxisIndex == null) {
  29150. axis.onZero = false;
  29151. }
  29152. axis.onZeroAxisIndex = onZeroAxisIndex;
  29153. }
  29154. function canNotOnZeroToAxis(axis) {
  29155. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29156. }
  29157. /**
  29158. * Resize the grid
  29159. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29160. * @param {module:echarts/ExtensionAPI} api
  29161. */
  29162. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29163. var gridRect = getLayoutRect(
  29164. gridModel.getBoxLayoutParams(), {
  29165. width: api.getWidth(),
  29166. height: api.getHeight()
  29167. });
  29168. this._rect = gridRect;
  29169. var axesList = this._axesList;
  29170. adjustAxes();
  29171. // Minus label size
  29172. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29173. each$6(axesList, function (axis) {
  29174. if (!axis.model.get('axisLabel.inside')) {
  29175. var labelUnionRect = getLabelUnionRect(axis);
  29176. if (labelUnionRect) {
  29177. var dim = axis.isHorizontal() ? 'height' : 'width';
  29178. var margin = axis.model.get('axisLabel.margin');
  29179. gridRect[dim] -= labelUnionRect[dim] + margin;
  29180. if (axis.position === 'top') {
  29181. gridRect.y += labelUnionRect.height + margin;
  29182. }
  29183. else if (axis.position === 'left') {
  29184. gridRect.x += labelUnionRect.width + margin;
  29185. }
  29186. }
  29187. }
  29188. });
  29189. adjustAxes();
  29190. }
  29191. function adjustAxes() {
  29192. each$6(axesList, function (axis) {
  29193. var isHorizontal = axis.isHorizontal();
  29194. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29195. var idx = axis.inverse ? 1 : 0;
  29196. axis.setExtent(extent[idx], extent[1 - idx]);
  29197. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29198. });
  29199. }
  29200. };
  29201. /**
  29202. * @param {string} axisType
  29203. * @param {number} [axisIndex]
  29204. */
  29205. gridProto.getAxis = function (axisType, axisIndex) {
  29206. var axesMapOnDim = this._axesMap[axisType];
  29207. if (axesMapOnDim != null) {
  29208. if (axisIndex == null) {
  29209. // Find first axis
  29210. for (var name in axesMapOnDim) {
  29211. if (axesMapOnDim.hasOwnProperty(name)) {
  29212. return axesMapOnDim[name];
  29213. }
  29214. }
  29215. }
  29216. return axesMapOnDim[axisIndex];
  29217. }
  29218. };
  29219. /**
  29220. * @return {Array.<module:echarts/coord/Axis>}
  29221. */
  29222. gridProto.getAxes = function () {
  29223. return this._axesList.slice();
  29224. };
  29225. /**
  29226. * Usage:
  29227. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29228. * grid.getCartesian(xAxisIndex);
  29229. * grid.getCartesian(null, yAxisIndex);
  29230. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29231. *
  29232. * @param {number|Object} [xAxisIndex]
  29233. * @param {number} [yAxisIndex]
  29234. */
  29235. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29236. if (xAxisIndex != null && yAxisIndex != null) {
  29237. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29238. return this._coordsMap[key];
  29239. }
  29240. if (isObject$1(xAxisIndex)) {
  29241. yAxisIndex = xAxisIndex.yAxisIndex;
  29242. xAxisIndex = xAxisIndex.xAxisIndex;
  29243. }
  29244. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29245. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29246. if (coordList[i].getAxis('x').index === xAxisIndex
  29247. || coordList[i].getAxis('y').index === yAxisIndex
  29248. ) {
  29249. return coordList[i];
  29250. }
  29251. }
  29252. };
  29253. gridProto.getCartesians = function () {
  29254. return this._coordsList.slice();
  29255. };
  29256. /**
  29257. * @implements
  29258. * see {module:echarts/CoodinateSystem}
  29259. */
  29260. gridProto.convertToPixel = function (ecModel, finder, value) {
  29261. var target = this._findConvertTarget(ecModel, finder);
  29262. return target.cartesian
  29263. ? target.cartesian.dataToPoint(value)
  29264. : target.axis
  29265. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29266. : null;
  29267. };
  29268. /**
  29269. * @implements
  29270. * see {module:echarts/CoodinateSystem}
  29271. */
  29272. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29273. var target = this._findConvertTarget(ecModel, finder);
  29274. return target.cartesian
  29275. ? target.cartesian.pointToData(value)
  29276. : target.axis
  29277. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29278. : null;
  29279. };
  29280. /**
  29281. * @inner
  29282. */
  29283. gridProto._findConvertTarget = function (ecModel, finder) {
  29284. var seriesModel = finder.seriesModel;
  29285. var xAxisModel = finder.xAxisModel
  29286. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29287. var yAxisModel = finder.yAxisModel
  29288. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29289. var gridModel = finder.gridModel;
  29290. var coordsList = this._coordsList;
  29291. var cartesian;
  29292. var axis;
  29293. if (seriesModel) {
  29294. cartesian = seriesModel.coordinateSystem;
  29295. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29296. }
  29297. else if (xAxisModel && yAxisModel) {
  29298. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29299. }
  29300. else if (xAxisModel) {
  29301. axis = this.getAxis('x', xAxisModel.componentIndex);
  29302. }
  29303. else if (yAxisModel) {
  29304. axis = this.getAxis('y', yAxisModel.componentIndex);
  29305. }
  29306. // Lowest priority.
  29307. else if (gridModel) {
  29308. var grid = gridModel.coordinateSystem;
  29309. if (grid === this) {
  29310. cartesian = this._coordsList[0];
  29311. }
  29312. }
  29313. return {cartesian: cartesian, axis: axis};
  29314. };
  29315. /**
  29316. * @implements
  29317. * see {module:echarts/CoodinateSystem}
  29318. */
  29319. gridProto.containPoint = function (point) {
  29320. var coord = this._coordsList[0];
  29321. if (coord) {
  29322. return coord.containPoint(point);
  29323. }
  29324. };
  29325. /**
  29326. * Initialize cartesian coordinate systems
  29327. * @private
  29328. */
  29329. gridProto._initCartesian = function (gridModel, ecModel, api) {
  29330. var axisPositionUsed = {
  29331. left: false,
  29332. right: false,
  29333. top: false,
  29334. bottom: false
  29335. };
  29336. var axesMap = {
  29337. x: {},
  29338. y: {}
  29339. };
  29340. var axesCount = {
  29341. x: 0,
  29342. y: 0
  29343. };
  29344. /// Create axis
  29345. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  29346. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  29347. if (!axesCount.x || !axesCount.y) {
  29348. // Roll back when there no either x or y axis
  29349. this._axesMap = {};
  29350. this._axesList = [];
  29351. return;
  29352. }
  29353. this._axesMap = axesMap;
  29354. /// Create cartesian2d
  29355. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  29356. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  29357. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29358. var cartesian = new Cartesian2D(key);
  29359. cartesian.grid = this;
  29360. cartesian.model = gridModel;
  29361. this._coordsMap[key] = cartesian;
  29362. this._coordsList.push(cartesian);
  29363. cartesian.addAxis(xAxis);
  29364. cartesian.addAxis(yAxis);
  29365. }, this);
  29366. }, this);
  29367. function createAxisCreator(axisType) {
  29368. return function (axisModel, idx) {
  29369. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  29370. return;
  29371. }
  29372. var axisPosition = axisModel.get('position');
  29373. if (axisType === 'x') {
  29374. // Fix position
  29375. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  29376. // Default bottom of X
  29377. axisPosition = 'bottom';
  29378. if (axisPositionUsed[axisPosition]) {
  29379. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  29380. }
  29381. }
  29382. }
  29383. else {
  29384. // Fix position
  29385. if (axisPosition !== 'left' && axisPosition !== 'right') {
  29386. // Default left of Y
  29387. axisPosition = 'left';
  29388. if (axisPositionUsed[axisPosition]) {
  29389. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  29390. }
  29391. }
  29392. }
  29393. axisPositionUsed[axisPosition] = true;
  29394. var axis = new Axis2D(
  29395. axisType, createScaleByModel(axisModel),
  29396. [0, 0],
  29397. axisModel.get('type'),
  29398. axisPosition
  29399. );
  29400. var isCategory = axis.type === 'category';
  29401. axis.onBand = isCategory && axisModel.get('boundaryGap');
  29402. axis.inverse = axisModel.get('inverse');
  29403. axis.onZero = axisModel.get('axisLine.onZero');
  29404. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  29405. // Inject axis into axisModel
  29406. axisModel.axis = axis;
  29407. // Inject axisModel into axis
  29408. axis.model = axisModel;
  29409. // Inject grid info axis
  29410. axis.grid = this;
  29411. // Index of axis, can be used as key
  29412. axis.index = idx;
  29413. this._axesList.push(axis);
  29414. axesMap[axisType][idx] = axis;
  29415. axesCount[axisType]++;
  29416. };
  29417. }
  29418. };
  29419. /**
  29420. * Update cartesian properties from series
  29421. * @param {module:echarts/model/Option} option
  29422. * @private
  29423. */
  29424. gridProto._updateScale = function (ecModel, gridModel) {
  29425. // Reset scale
  29426. each$1(this._axesList, function (axis) {
  29427. axis.scale.setExtent(Infinity, -Infinity);
  29428. });
  29429. ecModel.eachSeries(function (seriesModel) {
  29430. if (isCartesian2D(seriesModel)) {
  29431. var axesModels = findAxesModels(seriesModel, ecModel);
  29432. var xAxisModel = axesModels[0];
  29433. var yAxisModel = axesModels[1];
  29434. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  29435. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  29436. ) {
  29437. return;
  29438. }
  29439. var cartesian = this.getCartesian(
  29440. xAxisModel.componentIndex, yAxisModel.componentIndex
  29441. );
  29442. var data = seriesModel.getData();
  29443. var xAxis = cartesian.getAxis('x');
  29444. var yAxis = cartesian.getAxis('y');
  29445. if (data.type === 'list') {
  29446. unionExtent(data, xAxis, seriesModel);
  29447. unionExtent(data, yAxis, seriesModel);
  29448. }
  29449. }
  29450. }, this);
  29451. function unionExtent(data, axis, seriesModel) {
  29452. each$6(data.mapDimension(axis.dim, true), function (dim) {
  29453. axis.scale.unionExtentFromData(data, dim);
  29454. });
  29455. }
  29456. };
  29457. /**
  29458. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  29459. * @return {Object} {baseAxes: [], otherAxes: []}
  29460. */
  29461. gridProto.getTooltipAxes = function (dim) {
  29462. var baseAxes = [];
  29463. var otherAxes = [];
  29464. each$6(this.getCartesians(), function (cartesian) {
  29465. var baseAxis = (dim != null && dim !== 'auto')
  29466. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  29467. var otherAxis = cartesian.getOtherAxis(baseAxis);
  29468. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  29469. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  29470. });
  29471. return {baseAxes: baseAxes, otherAxes: otherAxes};
  29472. };
  29473. /**
  29474. * @inner
  29475. */
  29476. function updateAxisTransform(axis, coordBase) {
  29477. var axisExtent = axis.getExtent();
  29478. var axisExtentSum = axisExtent[0] + axisExtent[1];
  29479. // Fast transform
  29480. axis.toGlobalCoord = axis.dim === 'x'
  29481. ? function (coord) {
  29482. return coord + coordBase;
  29483. }
  29484. : function (coord) {
  29485. return axisExtentSum - coord + coordBase;
  29486. };
  29487. axis.toLocalCoord = axis.dim === 'x'
  29488. ? function (coord) {
  29489. return coord - coordBase;
  29490. }
  29491. : function (coord) {
  29492. return axisExtentSum - coord + coordBase;
  29493. };
  29494. }
  29495. var axesTypes = ['xAxis', 'yAxis'];
  29496. /**
  29497. * @inner
  29498. */
  29499. function findAxesModels(seriesModel, ecModel) {
  29500. return map(axesTypes, function (axisType) {
  29501. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  29502. if (__DEV__) {
  29503. if (!axisModel) {
  29504. throw new Error(axisType + ' "' + retrieve(
  29505. seriesModel.get(axisType + 'Index'),
  29506. seriesModel.get(axisType + 'Id'),
  29507. 0
  29508. ) + '" not found');
  29509. }
  29510. }
  29511. return axisModel;
  29512. });
  29513. }
  29514. /**
  29515. * @inner
  29516. */
  29517. function isCartesian2D(seriesModel) {
  29518. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  29519. }
  29520. Grid.create = function (ecModel, api) {
  29521. var grids = [];
  29522. ecModel.eachComponent('grid', function (gridModel, idx) {
  29523. var grid = new Grid(gridModel, ecModel, api);
  29524. grid.name = 'grid_' + idx;
  29525. // dataSampling requires axis extent, so resize
  29526. // should be performed in create stage.
  29527. grid.resize(gridModel, api, true);
  29528. gridModel.coordinateSystem = grid;
  29529. grids.push(grid);
  29530. });
  29531. // Inject the coordinateSystems into seriesModel
  29532. ecModel.eachSeries(function (seriesModel) {
  29533. if (!isCartesian2D(seriesModel)) {
  29534. return;
  29535. }
  29536. var axesModels = findAxesModels(seriesModel, ecModel);
  29537. var xAxisModel = axesModels[0];
  29538. var yAxisModel = axesModels[1];
  29539. var gridModel = xAxisModel.getCoordSysModel();
  29540. if (__DEV__) {
  29541. if (!gridModel) {
  29542. throw new Error(
  29543. 'Grid "' + retrieve(
  29544. xAxisModel.get('gridIndex'),
  29545. xAxisModel.get('gridId'),
  29546. 0
  29547. ) + '" not found'
  29548. );
  29549. }
  29550. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  29551. throw new Error('xAxis and yAxis must use the same grid');
  29552. }
  29553. }
  29554. var grid = gridModel.coordinateSystem;
  29555. seriesModel.coordinateSystem = grid.getCartesian(
  29556. xAxisModel.componentIndex, yAxisModel.componentIndex
  29557. );
  29558. });
  29559. return grids;
  29560. };
  29561. // For deciding which dimensions to use when creating list data
  29562. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  29563. CoordinateSystemManager.register('cartesian2d', Grid);
  29564. var PI$2 = Math.PI;
  29565. function makeAxisEventDataBase(axisModel) {
  29566. var eventData = {
  29567. componentType: axisModel.mainType
  29568. };
  29569. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  29570. return eventData;
  29571. }
  29572. /**
  29573. * A final axis is translated and rotated from a "standard axis".
  29574. * So opt.position and opt.rotation is required.
  29575. *
  29576. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  29577. * for example: (0, 0) ------------> (0, 50)
  29578. *
  29579. * nameDirection or tickDirection or labelDirection is 1 means tick
  29580. * or label is below the standard axis, whereas is -1 means above
  29581. * the standard axis. labelOffset means offset between label and axis,
  29582. * which is useful when 'onZero', where axisLabel is in the grid and
  29583. * label in outside grid.
  29584. *
  29585. * Tips: like always,
  29586. * positive rotation represents anticlockwise, and negative rotation
  29587. * represents clockwise.
  29588. * The direction of position coordinate is the same as the direction
  29589. * of screen coordinate.
  29590. *
  29591. * Do not need to consider axis 'inverse', which is auto processed by
  29592. * axis extent.
  29593. *
  29594. * @param {module:zrender/container/Group} group
  29595. * @param {Object} axisModel
  29596. * @param {Object} opt Standard axis parameters.
  29597. * @param {Array.<number>} opt.position [x, y]
  29598. * @param {number} opt.rotation by radian
  29599. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  29600. * @param {number} [opt.tickDirection=1] 1 or -1
  29601. * @param {number} [opt.labelDirection=1] 1 or -1
  29602. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  29603. * @param {string} [opt.axisLabelShow] default get from axisModel.
  29604. * @param {string} [opt.axisName] default get from axisModel.
  29605. * @param {number} [opt.axisNameAvailableWidth]
  29606. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  29607. * @param {number} [opt.labelInterval] Default label interval when label
  29608. * interval from model is null or 'auto'.
  29609. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  29610. * @param {number} [opt.nameTruncateMaxWidth]
  29611. */
  29612. var AxisBuilder = function (axisModel, opt) {
  29613. /**
  29614. * @readOnly
  29615. */
  29616. this.opt = opt;
  29617. /**
  29618. * @readOnly
  29619. */
  29620. this.axisModel = axisModel;
  29621. // Default value
  29622. defaults(
  29623. opt,
  29624. {
  29625. labelOffset: 0,
  29626. nameDirection: 1,
  29627. tickDirection: 1,
  29628. labelDirection: 1,
  29629. silent: true
  29630. }
  29631. );
  29632. /**
  29633. * @readOnly
  29634. */
  29635. this.group = new Group();
  29636. // FIXME Not use a seperate text group?
  29637. var dumbGroup = new Group({
  29638. position: opt.position.slice(),
  29639. rotation: opt.rotation
  29640. });
  29641. // this.group.add(dumbGroup);
  29642. // this._dumbGroup = dumbGroup;
  29643. dumbGroup.updateTransform();
  29644. this._transform = dumbGroup.transform;
  29645. this._dumbGroup = dumbGroup;
  29646. };
  29647. AxisBuilder.prototype = {
  29648. constructor: AxisBuilder,
  29649. hasBuilder: function (name) {
  29650. return !!builders[name];
  29651. },
  29652. add: function (name) {
  29653. builders[name].call(this);
  29654. },
  29655. getGroup: function () {
  29656. return this.group;
  29657. }
  29658. };
  29659. var builders = {
  29660. /**
  29661. * @private
  29662. */
  29663. axisLine: function () {
  29664. var opt = this.opt;
  29665. var axisModel = this.axisModel;
  29666. if (!axisModel.get('axisLine.show')) {
  29667. return;
  29668. }
  29669. var extent = this.axisModel.axis.getExtent();
  29670. var matrix = this._transform;
  29671. var pt1 = [extent[0], 0];
  29672. var pt2 = [extent[1], 0];
  29673. if (matrix) {
  29674. applyTransform(pt1, pt1, matrix);
  29675. applyTransform(pt2, pt2, matrix);
  29676. }
  29677. var lineStyle = extend(
  29678. {
  29679. lineCap: 'round'
  29680. },
  29681. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  29682. );
  29683. this.group.add(new Line(subPixelOptimizeLine({
  29684. // Id for animation
  29685. anid: 'line',
  29686. shape: {
  29687. x1: pt1[0],
  29688. y1: pt1[1],
  29689. x2: pt2[0],
  29690. y2: pt2[1]
  29691. },
  29692. style: lineStyle,
  29693. strokeContainThreshold: opt.strokeContainThreshold || 5,
  29694. silent: true,
  29695. z2: 1
  29696. })));
  29697. var arrows = axisModel.get('axisLine.symbol');
  29698. var arrowSize = axisModel.get('axisLine.symbolSize');
  29699. if (arrows != null) {
  29700. if (typeof arrows === 'string') {
  29701. // Use the same arrow for start and end point
  29702. arrows = [arrows, arrows];
  29703. }
  29704. if (typeof arrowSize === 'string'
  29705. || typeof arrowSize === 'number'
  29706. ) {
  29707. // Use the same size for width and height
  29708. arrowSize = [arrowSize, arrowSize];
  29709. }
  29710. var symbolWidth = arrowSize[0];
  29711. var symbolHeight = arrowSize[1];
  29712. each$1([
  29713. [opt.rotation + Math.PI / 2, pt1],
  29714. [opt.rotation - Math.PI / 2, pt2]
  29715. ], function (item, index) {
  29716. if (arrows[index] !== 'none' && arrows[index] != null) {
  29717. var symbol = createSymbol(
  29718. arrows[index],
  29719. -symbolWidth / 2,
  29720. -symbolHeight / 2,
  29721. symbolWidth,
  29722. symbolHeight,
  29723. lineStyle.stroke,
  29724. true
  29725. );
  29726. symbol.attr({
  29727. rotation: item[0],
  29728. position: item[1],
  29729. silent: true
  29730. });
  29731. this.group.add(symbol);
  29732. }
  29733. }, this);
  29734. }
  29735. },
  29736. /**
  29737. * @private
  29738. */
  29739. axisTickLabel: function () {
  29740. var axisModel = this.axisModel;
  29741. var opt = this.opt;
  29742. var tickEls = buildAxisTick(this, axisModel, opt);
  29743. var labelEls = buildAxisLabel(this, axisModel, opt);
  29744. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  29745. },
  29746. /**
  29747. * @private
  29748. */
  29749. axisName: function () {
  29750. var opt = this.opt;
  29751. var axisModel = this.axisModel;
  29752. var name = retrieve(opt.axisName, axisModel.get('name'));
  29753. if (!name) {
  29754. return;
  29755. }
  29756. var nameLocation = axisModel.get('nameLocation');
  29757. var nameDirection = opt.nameDirection;
  29758. var textStyleModel = axisModel.getModel('nameTextStyle');
  29759. var gap = axisModel.get('nameGap') || 0;
  29760. var extent = this.axisModel.axis.getExtent();
  29761. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  29762. var pos = [
  29763. nameLocation === 'start'
  29764. ? extent[0] - gapSignal * gap
  29765. : nameLocation === 'end'
  29766. ? extent[1] + gapSignal * gap
  29767. : (extent[0] + extent[1]) / 2, // 'middle'
  29768. // Reuse labelOffset.
  29769. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  29770. ];
  29771. var labelLayout;
  29772. var nameRotation = axisModel.get('nameRotate');
  29773. if (nameRotation != null) {
  29774. nameRotation = nameRotation * PI$2 / 180; // To radian.
  29775. }
  29776. var axisNameAvailableWidth;
  29777. if (isNameLocationCenter(nameLocation)) {
  29778. labelLayout = innerTextLayout(
  29779. opt.rotation,
  29780. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  29781. nameDirection
  29782. );
  29783. }
  29784. else {
  29785. labelLayout = endTextLayout(
  29786. opt, nameLocation, nameRotation || 0, extent
  29787. );
  29788. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  29789. if (axisNameAvailableWidth != null) {
  29790. axisNameAvailableWidth = Math.abs(
  29791. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  29792. );
  29793. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  29794. }
  29795. }
  29796. var textFont = textStyleModel.getFont();
  29797. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  29798. var ellipsis = truncateOpt.ellipsis;
  29799. var maxWidth = retrieve(
  29800. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  29801. );
  29802. // FIXME
  29803. // truncate rich text? (consider performance)
  29804. var truncatedText = (ellipsis != null && maxWidth != null)
  29805. ? truncateText$1(
  29806. name, maxWidth, textFont, ellipsis,
  29807. {minChar: 2, placeholder: truncateOpt.placeholder}
  29808. )
  29809. : name;
  29810. var tooltipOpt = axisModel.get('tooltip', true);
  29811. var mainType = axisModel.mainType;
  29812. var formatterParams = {
  29813. componentType: mainType,
  29814. name: name,
  29815. $vars: ['name']
  29816. };
  29817. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  29818. var textEl = new Text({
  29819. // Id for animation
  29820. anid: 'name',
  29821. __fullText: name,
  29822. __truncatedText: truncatedText,
  29823. position: pos,
  29824. rotation: labelLayout.rotation,
  29825. silent: isSilent(axisModel),
  29826. z2: 1,
  29827. tooltip: (tooltipOpt && tooltipOpt.show)
  29828. ? extend({
  29829. content: name,
  29830. formatter: function () {
  29831. return name;
  29832. },
  29833. formatterParams: formatterParams
  29834. }, tooltipOpt)
  29835. : null
  29836. });
  29837. setTextStyle(textEl.style, textStyleModel, {
  29838. text: truncatedText,
  29839. textFont: textFont,
  29840. textFill: textStyleModel.getTextColor()
  29841. || axisModel.get('axisLine.lineStyle.color'),
  29842. textAlign: labelLayout.textAlign,
  29843. textVerticalAlign: labelLayout.textVerticalAlign
  29844. });
  29845. if (axisModel.get('triggerEvent')) {
  29846. textEl.eventData = makeAxisEventDataBase(axisModel);
  29847. textEl.eventData.targetType = 'axisName';
  29848. textEl.eventData.name = name;
  29849. }
  29850. // FIXME
  29851. this._dumbGroup.add(textEl);
  29852. textEl.updateTransform();
  29853. this.group.add(textEl);
  29854. textEl.decomposeTransform();
  29855. }
  29856. };
  29857. /**
  29858. * @public
  29859. * @static
  29860. * @param {Object} opt
  29861. * @param {number} axisRotation in radian
  29862. * @param {number} textRotation in radian
  29863. * @param {number} direction
  29864. * @return {Object} {
  29865. * rotation, // according to axis
  29866. * textAlign,
  29867. * textVerticalAlign
  29868. * }
  29869. */
  29870. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  29871. var rotationDiff = remRadian(textRotation - axisRotation);
  29872. var textAlign;
  29873. var textVerticalAlign;
  29874. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  29875. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  29876. textAlign = 'center';
  29877. }
  29878. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  29879. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  29880. textAlign = 'center';
  29881. }
  29882. else {
  29883. textVerticalAlign = 'middle';
  29884. if (rotationDiff > 0 && rotationDiff < PI$2) {
  29885. textAlign = direction > 0 ? 'right' : 'left';
  29886. }
  29887. else {
  29888. textAlign = direction > 0 ? 'left' : 'right';
  29889. }
  29890. }
  29891. return {
  29892. rotation: rotationDiff,
  29893. textAlign: textAlign,
  29894. textVerticalAlign: textVerticalAlign
  29895. };
  29896. };
  29897. function endTextLayout(opt, textPosition, textRotate, extent) {
  29898. var rotationDiff = remRadian(textRotate - opt.rotation);
  29899. var textAlign;
  29900. var textVerticalAlign;
  29901. var inverse = extent[0] > extent[1];
  29902. var onLeft = (textPosition === 'start' && !inverse)
  29903. || (textPosition !== 'start' && inverse);
  29904. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  29905. textVerticalAlign = onLeft ? 'bottom' : 'top';
  29906. textAlign = 'center';
  29907. }
  29908. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  29909. textVerticalAlign = onLeft ? 'top' : 'bottom';
  29910. textAlign = 'center';
  29911. }
  29912. else {
  29913. textVerticalAlign = 'middle';
  29914. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  29915. textAlign = onLeft ? 'left' : 'right';
  29916. }
  29917. else {
  29918. textAlign = onLeft ? 'right' : 'left';
  29919. }
  29920. }
  29921. return {
  29922. rotation: rotationDiff,
  29923. textAlign: textAlign,
  29924. textVerticalAlign: textVerticalAlign
  29925. };
  29926. }
  29927. function isSilent(axisModel) {
  29928. var tooltipOpt = axisModel.get('tooltip');
  29929. return axisModel.get('silent')
  29930. // Consider mouse cursor, add these restrictions.
  29931. || !(
  29932. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  29933. );
  29934. }
  29935. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  29936. // If min or max are user set, we need to check
  29937. // If the tick on min(max) are overlap on their neighbour tick
  29938. // If they are overlapped, we need to hide the min(max) tick label
  29939. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29940. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29941. // FIXME
  29942. // Have not consider onBand yet, where tick els is more than label els.
  29943. labelEls = labelEls || [];
  29944. tickEls = tickEls || [];
  29945. var firstLabel = labelEls[0];
  29946. var nextLabel = labelEls[1];
  29947. var lastLabel = labelEls[labelEls.length - 1];
  29948. var prevLabel = labelEls[labelEls.length - 2];
  29949. var firstTick = tickEls[0];
  29950. var nextTick = tickEls[1];
  29951. var lastTick = tickEls[tickEls.length - 1];
  29952. var prevTick = tickEls[tickEls.length - 2];
  29953. if (showMinLabel === false) {
  29954. ignoreEl(firstLabel);
  29955. ignoreEl(firstTick);
  29956. }
  29957. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  29958. if (showMinLabel) {
  29959. ignoreEl(nextLabel);
  29960. ignoreEl(nextTick);
  29961. }
  29962. else {
  29963. ignoreEl(firstLabel);
  29964. ignoreEl(firstTick);
  29965. }
  29966. }
  29967. if (showMaxLabel === false) {
  29968. ignoreEl(lastLabel);
  29969. ignoreEl(lastTick);
  29970. }
  29971. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  29972. if (showMaxLabel) {
  29973. ignoreEl(prevLabel);
  29974. ignoreEl(prevTick);
  29975. }
  29976. else {
  29977. ignoreEl(lastLabel);
  29978. ignoreEl(lastTick);
  29979. }
  29980. }
  29981. }
  29982. function ignoreEl(el) {
  29983. el && (el.ignore = true);
  29984. }
  29985. function isTwoLabelOverlapped(current, next, labelLayout) {
  29986. // current and next has the same rotation.
  29987. var firstRect = current && current.getBoundingRect().clone();
  29988. var nextRect = next && next.getBoundingRect().clone();
  29989. if (!firstRect || !nextRect) {
  29990. return;
  29991. }
  29992. // When checking intersect of two rotated labels, we use mRotationBack
  29993. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  29994. var mRotationBack = identity([]);
  29995. rotate(mRotationBack, mRotationBack, -current.rotation);
  29996. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  29997. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  29998. return firstRect.intersect(nextRect);
  29999. }
  30000. function isNameLocationCenter(nameLocation) {
  30001. return nameLocation === 'middle' || nameLocation === 'center';
  30002. }
  30003. /**
  30004. * @static
  30005. */
  30006. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  30007. axis,
  30008. i,
  30009. interval,
  30010. ticksCnt,
  30011. showMinLabel,
  30012. showMaxLabel
  30013. ) {
  30014. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  30015. return false;
  30016. }
  30017. // FIXME
  30018. // Have not consider label overlap (if label is too long) yet.
  30019. var rawTick;
  30020. var scale$$1 = axis.scale;
  30021. return scale$$1.type === 'ordinal'
  30022. && (
  30023. typeof interval === 'function'
  30024. ? (
  30025. rawTick = scale$$1.getTicks()[i],
  30026. !interval(rawTick, scale$$1.getLabel(rawTick))
  30027. )
  30028. : i % (interval + 1)
  30029. );
  30030. };
  30031. /**
  30032. * @static
  30033. */
  30034. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30035. var interval = model.get('interval');
  30036. if (interval == null || interval == 'auto') {
  30037. interval = labelInterval;
  30038. }
  30039. return interval;
  30040. };
  30041. function buildAxisTick(axisBuilder, axisModel, opt) {
  30042. var axis = axisModel.axis;
  30043. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30044. return;
  30045. }
  30046. var tickModel = axisModel.getModel('axisTick');
  30047. var lineStyleModel = tickModel.getModel('lineStyle');
  30048. var tickLen = tickModel.get('length');
  30049. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30050. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30051. // FIXME
  30052. // Corresponds to ticksCoords ?
  30053. var ticks = axis.scale.getTicks();
  30054. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30055. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30056. var pt1 = [];
  30057. var pt2 = [];
  30058. var matrix = axisBuilder._transform;
  30059. var tickEls = [];
  30060. var ticksCnt = ticksCoords.length;
  30061. for (var i = 0; i < ticksCnt; i++) {
  30062. // Only ordinal scale support tick interval
  30063. if (ifIgnoreOnTick$1(
  30064. axis, i, tickInterval, ticksCnt,
  30065. showMinLabel, showMaxLabel
  30066. )) {
  30067. continue;
  30068. }
  30069. var tickCoord = ticksCoords[i];
  30070. pt1[0] = tickCoord;
  30071. pt1[1] = 0;
  30072. pt2[0] = tickCoord;
  30073. pt2[1] = opt.tickDirection * tickLen;
  30074. if (matrix) {
  30075. applyTransform(pt1, pt1, matrix);
  30076. applyTransform(pt2, pt2, matrix);
  30077. }
  30078. // Tick line, Not use group transform to have better line draw
  30079. var tickEl = new Line(subPixelOptimizeLine({
  30080. // Id for animation
  30081. anid: 'tick_' + ticks[i],
  30082. shape: {
  30083. x1: pt1[0],
  30084. y1: pt1[1],
  30085. x2: pt2[0],
  30086. y2: pt2[1]
  30087. },
  30088. style: defaults(
  30089. lineStyleModel.getLineStyle(),
  30090. {
  30091. stroke: axisModel.get('axisLine.lineStyle.color')
  30092. }
  30093. ),
  30094. z2: 2,
  30095. silent: true
  30096. }));
  30097. axisBuilder.group.add(tickEl);
  30098. tickEls.push(tickEl);
  30099. }
  30100. return tickEls;
  30101. }
  30102. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30103. var axis = axisModel.axis;
  30104. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30105. if (!show || axis.scale.isBlank()) {
  30106. return;
  30107. }
  30108. var labelModel = axisModel.getModel('axisLabel');
  30109. var labelMargin = labelModel.get('margin');
  30110. var ticks = axis.scale.getTicks();
  30111. var labels = axisModel.getFormattedLabels();
  30112. // Special label rotate.
  30113. var labelRotation = (
  30114. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30115. ) * PI$2 / 180;
  30116. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30117. var categoryData = axisModel.getCategories();
  30118. var labelEls = [];
  30119. var silent = isSilent(axisModel);
  30120. var triggerEvent = axisModel.get('triggerEvent');
  30121. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30122. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30123. each$1(ticks, function (tickVal, index) {
  30124. if (ifIgnoreOnTick$1(
  30125. axis, index, opt.labelInterval, ticks.length,
  30126. showMinLabel, showMaxLabel
  30127. )) {
  30128. return;
  30129. }
  30130. var itemLabelModel = labelModel;
  30131. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30132. itemLabelModel = new Model(
  30133. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30134. );
  30135. }
  30136. var textColor = itemLabelModel.getTextColor()
  30137. || axisModel.get('axisLine.lineStyle.color');
  30138. var tickCoord = axis.dataToCoord(tickVal);
  30139. var pos = [
  30140. tickCoord,
  30141. opt.labelOffset + opt.labelDirection * labelMargin
  30142. ];
  30143. var labelStr = axis.scale.getLabel(tickVal);
  30144. var textEl = new Text({
  30145. // Id for animation
  30146. anid: 'label_' + tickVal,
  30147. position: pos,
  30148. rotation: labelLayout.rotation,
  30149. silent: silent,
  30150. z2: 10
  30151. });
  30152. setTextStyle(textEl.style, itemLabelModel, {
  30153. text: labels[index],
  30154. textAlign: itemLabelModel.getShallow('align', true)
  30155. || labelLayout.textAlign,
  30156. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30157. || itemLabelModel.getShallow('baseline', true)
  30158. || labelLayout.textVerticalAlign,
  30159. textFill: typeof textColor === 'function'
  30160. ? textColor(
  30161. // (1) In category axis with data zoom, tick is not the original
  30162. // index of axis.data. So tick should not be exposed to user
  30163. // in category axis.
  30164. // (2) Compatible with previous version, which always returns labelStr.
  30165. // But in interval scale labelStr is like '223,445', which maked
  30166. // user repalce ','. So we modify it to return original val but remain
  30167. // it as 'string' to avoid error in replacing.
  30168. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30169. index
  30170. )
  30171. : textColor
  30172. });
  30173. // Pack data for mouse event
  30174. if (triggerEvent) {
  30175. textEl.eventData = makeAxisEventDataBase(axisModel);
  30176. textEl.eventData.targetType = 'axisLabel';
  30177. textEl.eventData.value = labelStr;
  30178. }
  30179. // FIXME
  30180. axisBuilder._dumbGroup.add(textEl);
  30181. textEl.updateTransform();
  30182. labelEls.push(textEl);
  30183. axisBuilder.group.add(textEl);
  30184. textEl.decomposeTransform();
  30185. });
  30186. return labelEls;
  30187. }
  30188. var each$7 = each$1;
  30189. var curry$1 = curry;
  30190. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30191. // allAxesInfo should be updated when setOption performed.
  30192. function collect(ecModel, api) {
  30193. var result = {
  30194. /**
  30195. * key: makeKey(axis.model)
  30196. * value: {
  30197. * axis,
  30198. * coordSys,
  30199. * axisPointerModel,
  30200. * triggerTooltip,
  30201. * involveSeries,
  30202. * snap,
  30203. * seriesModels,
  30204. * seriesDataCount
  30205. * }
  30206. */
  30207. axesInfo: {},
  30208. seriesInvolved: false,
  30209. /**
  30210. * key: makeKey(coordSys.model)
  30211. * value: Object: key makeKey(axis.model), value: axisInfo
  30212. */
  30213. coordSysAxesInfo: {},
  30214. coordSysMap: {}
  30215. };
  30216. collectAxesInfo(result, ecModel, api);
  30217. // Check seriesInvolved for performance, in case too many series in some chart.
  30218. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30219. return result;
  30220. }
  30221. function collectAxesInfo(result, ecModel, api) {
  30222. var globalTooltipModel = ecModel.getComponent('tooltip');
  30223. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30224. // links can only be set on global.
  30225. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30226. var linkGroups = [];
  30227. // Collect axes info.
  30228. each$7(api.getCoordinateSystems(), function (coordSys) {
  30229. // Some coordinate system do not support axes, like geo.
  30230. if (!coordSys.axisPointerEnabled) {
  30231. return;
  30232. }
  30233. var coordSysKey = makeKey(coordSys.model);
  30234. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30235. result.coordSysMap[coordSysKey] = coordSys;
  30236. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30237. // for user. So we enable seting tooltip on coordSys model.
  30238. var coordSysModel = coordSys.model;
  30239. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30240. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30241. // If axis tooltip used, choose tooltip axis for each coordSys.
  30242. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30243. if (coordSys.getTooltipAxes
  30244. && globalTooltipModel
  30245. // If tooltip.showContent is set as false, tooltip will not
  30246. // show but axisPointer will show as normal.
  30247. && baseTooltipModel.get('show')
  30248. ) {
  30249. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30250. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30251. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30252. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30253. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30254. if (triggerAxis || cross) {
  30255. each$7(tooltipAxes.baseAxes, curry$1(
  30256. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30257. ));
  30258. }
  30259. if (cross) {
  30260. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30261. }
  30262. }
  30263. // fromTooltip: true | false | 'cross'
  30264. // triggerTooltip: true | false | null
  30265. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30266. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30267. var axisPointerShow = axisPointerModel.get('show');
  30268. if (!axisPointerShow || (
  30269. axisPointerShow === 'auto'
  30270. && !fromTooltip
  30271. && !isHandleTrigger(axisPointerModel)
  30272. )) {
  30273. return;
  30274. }
  30275. if (triggerTooltip == null) {
  30276. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30277. }
  30278. axisPointerModel = fromTooltip
  30279. ? makeAxisPointerModel(
  30280. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30281. fromTooltip, triggerTooltip
  30282. )
  30283. : axisPointerModel;
  30284. var snap = axisPointerModel.get('snap');
  30285. var key = makeKey(axis.model);
  30286. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30287. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30288. var axisInfo = result.axesInfo[key] = {
  30289. key: key,
  30290. axis: axis,
  30291. coordSys: coordSys,
  30292. axisPointerModel: axisPointerModel,
  30293. triggerTooltip: triggerTooltip,
  30294. involveSeries: involveSeries,
  30295. snap: snap,
  30296. useHandle: isHandleTrigger(axisPointerModel),
  30297. seriesModels: []
  30298. };
  30299. axesInfoInCoordSys[key] = axisInfo;
  30300. result.seriesInvolved |= involveSeries;
  30301. var groupIndex = getLinkGroupIndex(linksOption, axis);
  30302. if (groupIndex != null) {
  30303. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  30304. linkGroup.axesInfo[key] = axisInfo;
  30305. linkGroup.mapper = linksOption[groupIndex].mapper;
  30306. axisInfo.linkGroup = linkGroup;
  30307. }
  30308. }
  30309. });
  30310. }
  30311. function makeAxisPointerModel(
  30312. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  30313. ) {
  30314. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  30315. var volatileOption = {};
  30316. each$7(
  30317. [
  30318. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  30319. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  30320. ],
  30321. function (field) {
  30322. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  30323. }
  30324. );
  30325. // category axis do not auto snap, otherwise some tick that do not
  30326. // has value can not be hovered. value/time/log axis default snap if
  30327. // triggered from tooltip and trigger tooltip.
  30328. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  30329. // Compatibel with previous behavior, tooltip axis do not show label by default.
  30330. // Only these properties can be overrided from tooltip to axisPointer.
  30331. if (tooltipAxisPointerModel.get('type') === 'cross') {
  30332. volatileOption.type = 'line';
  30333. }
  30334. var labelOption = volatileOption.label || (volatileOption.label = {});
  30335. // Follow the convention, do not show label when triggered by tooltip by default.
  30336. labelOption.show == null && (labelOption.show = false);
  30337. if (fromTooltip === 'cross') {
  30338. // When 'cross', both axes show labels.
  30339. labelOption.show = true;
  30340. // If triggerTooltip, this is a base axis, which should better not use cross style
  30341. // (cross style is dashed by default)
  30342. if (!triggerTooltip) {
  30343. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  30344. crossStyle && defaults(labelOption, crossStyle.textStyle);
  30345. }
  30346. }
  30347. return axis.model.getModel(
  30348. 'axisPointer',
  30349. new Model(volatileOption, globalAxisPointerModel, ecModel)
  30350. );
  30351. }
  30352. function collectSeriesInfo(result, ecModel) {
  30353. // Prepare data for axis trigger
  30354. ecModel.eachSeries(function (seriesModel) {
  30355. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  30356. var coordSys = seriesModel.coordinateSystem;
  30357. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  30358. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  30359. if (!coordSys
  30360. || seriesTooltipTrigger === 'none'
  30361. || seriesTooltipTrigger === false
  30362. || seriesTooltipTrigger === 'item'
  30363. || seriesTooltipShow === false
  30364. || seriesModel.get('axisPointer.show', true) === false
  30365. ) {
  30366. return;
  30367. }
  30368. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  30369. var axis = axisInfo.axis;
  30370. if (coordSys.getAxis(axis.dim) === axis) {
  30371. axisInfo.seriesModels.push(seriesModel);
  30372. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  30373. axisInfo.seriesDataCount += seriesModel.getData().count();
  30374. }
  30375. });
  30376. }, this);
  30377. }
  30378. /**
  30379. * For example:
  30380. * {
  30381. * axisPointer: {
  30382. * links: [{
  30383. * xAxisIndex: [2, 4],
  30384. * yAxisIndex: 'all'
  30385. * }, {
  30386. * xAxisId: ['a5', 'a7'],
  30387. * xAxisName: 'xxx'
  30388. * }]
  30389. * }
  30390. * }
  30391. */
  30392. function getLinkGroupIndex(linksOption, axis) {
  30393. var axisModel = axis.model;
  30394. var dim = axis.dim;
  30395. for (var i = 0; i < linksOption.length; i++) {
  30396. var linkOption = linksOption[i] || {};
  30397. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  30398. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  30399. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  30400. ) {
  30401. return i;
  30402. }
  30403. }
  30404. }
  30405. function checkPropInLink(linkPropValue, axisPropValue) {
  30406. return linkPropValue === 'all'
  30407. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  30408. || linkPropValue === axisPropValue;
  30409. }
  30410. function fixValue(axisModel) {
  30411. var axisInfo = getAxisInfo(axisModel);
  30412. if (!axisInfo) {
  30413. return;
  30414. }
  30415. var axisPointerModel = axisInfo.axisPointerModel;
  30416. var scale = axisInfo.axis.scale;
  30417. var option = axisPointerModel.option;
  30418. var status = axisPointerModel.get('status');
  30419. var value = axisPointerModel.get('value');
  30420. // Parse init value for category and time axis.
  30421. if (value != null) {
  30422. value = scale.parse(value);
  30423. }
  30424. var useHandle = isHandleTrigger(axisPointerModel);
  30425. // If `handle` used, `axisPointer` will always be displayed, so value
  30426. // and status should be initialized.
  30427. if (status == null) {
  30428. option.status = useHandle ? 'show' : 'hide';
  30429. }
  30430. var extent = scale.getExtent().slice();
  30431. extent[0] > extent[1] && extent.reverse();
  30432. if (// Pick a value on axis when initializing.
  30433. value == null
  30434. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  30435. // where we should re-pick a value to keep `handle` displaying normally.
  30436. || value > extent[1]
  30437. ) {
  30438. // Make handle displayed on the end of the axis when init, which looks better.
  30439. value = extent[1];
  30440. }
  30441. if (value < extent[0]) {
  30442. value = extent[0];
  30443. }
  30444. option.value = value;
  30445. if (useHandle) {
  30446. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  30447. }
  30448. }
  30449. function getAxisInfo(axisModel) {
  30450. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  30451. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  30452. }
  30453. function getAxisPointerModel(axisModel) {
  30454. var axisInfo = getAxisInfo(axisModel);
  30455. return axisInfo && axisInfo.axisPointerModel;
  30456. }
  30457. function isHandleTrigger(axisPointerModel) {
  30458. return !!axisPointerModel.get('handle.show');
  30459. }
  30460. /**
  30461. * @param {module:echarts/model/Model} model
  30462. * @return {string} unique key
  30463. */
  30464. function makeKey(model) {
  30465. return model.type + '||' + model.id;
  30466. }
  30467. /**
  30468. * Base class of AxisView.
  30469. */
  30470. var AxisView = extendComponentView({
  30471. type: 'axis',
  30472. /**
  30473. * @private
  30474. */
  30475. _axisPointer: null,
  30476. /**
  30477. * @protected
  30478. * @type {string}
  30479. */
  30480. axisPointerClass: null,
  30481. /**
  30482. * @override
  30483. */
  30484. render: function (axisModel, ecModel, api, payload) {
  30485. // FIXME
  30486. // This process should proformed after coordinate systems updated
  30487. // (axis scale updated), and should be performed each time update.
  30488. // So put it here temporarily, although it is not appropriate to
  30489. // put a model-writing procedure in `view`.
  30490. this.axisPointerClass && fixValue(axisModel);
  30491. AxisView.superApply(this, 'render', arguments);
  30492. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  30493. },
  30494. /**
  30495. * Action handler.
  30496. * @public
  30497. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30498. * @param {module:echarts/model/Global} ecModel
  30499. * @param {module:echarts/ExtensionAPI} api
  30500. * @param {Object} payload
  30501. */
  30502. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  30503. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  30504. },
  30505. /**
  30506. * @override
  30507. */
  30508. remove: function (ecModel, api) {
  30509. var axisPointer = this._axisPointer;
  30510. axisPointer && axisPointer.remove(api);
  30511. AxisView.superApply(this, 'remove', arguments);
  30512. },
  30513. /**
  30514. * @override
  30515. */
  30516. dispose: function (ecModel, api) {
  30517. disposeAxisPointer(this, api);
  30518. AxisView.superApply(this, 'dispose', arguments);
  30519. }
  30520. });
  30521. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  30522. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  30523. if (!Clazz) {
  30524. return;
  30525. }
  30526. var axisPointerModel = getAxisPointerModel(axisModel);
  30527. axisPointerModel
  30528. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  30529. .render(axisModel, axisPointerModel, api, forceRender)
  30530. : disposeAxisPointer(axisView, api);
  30531. }
  30532. function disposeAxisPointer(axisView, ecModel, api) {
  30533. var axisPointer = axisView._axisPointer;
  30534. axisPointer && axisPointer.dispose(ecModel, api);
  30535. axisView._axisPointer = null;
  30536. }
  30537. var axisPointerClazz = [];
  30538. AxisView.registerAxisPointerClass = function (type, clazz) {
  30539. if (__DEV__) {
  30540. if (axisPointerClazz[type]) {
  30541. throw new Error('axisPointer ' + type + ' exists');
  30542. }
  30543. }
  30544. axisPointerClazz[type] = clazz;
  30545. };
  30546. AxisView.getAxisPointerClass = function (type) {
  30547. return type && axisPointerClazz[type];
  30548. };
  30549. /**
  30550. * @param {Object} opt {labelInside}
  30551. * @return {Object} {
  30552. * position, rotation, labelDirection, labelOffset,
  30553. * tickDirection, labelRotate, labelInterval, z2
  30554. * }
  30555. */
  30556. function layout$1(gridModel, axisModel, opt) {
  30557. opt = opt || {};
  30558. var grid = gridModel.coordinateSystem;
  30559. var axis = axisModel.axis;
  30560. var layout = {};
  30561. var rawAxisPosition = axis.position;
  30562. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  30563. var axisDim = axis.dim;
  30564. var rect = grid.getRect();
  30565. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  30566. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  30567. var axisOffset = axisModel.get('offset') || 0;
  30568. var posBound = axisDim === 'x'
  30569. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  30570. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  30571. if (axis.onZero) {
  30572. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  30573. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  30574. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  30575. }
  30576. // Axis position
  30577. layout.position = [
  30578. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  30579. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  30580. ];
  30581. // Axis rotation
  30582. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  30583. // Tick and label direction, x y is axisDim
  30584. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  30585. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  30586. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  30587. if (axisModel.get('axisTick.inside')) {
  30588. layout.tickDirection = -layout.tickDirection;
  30589. }
  30590. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  30591. layout.labelDirection = -layout.labelDirection;
  30592. }
  30593. // Special label rotation
  30594. var labelRotate = axisModel.get('axisLabel.rotate');
  30595. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  30596. // label interval when auto mode.
  30597. layout.labelInterval = axis.getLabelInterval();
  30598. // Over splitLine and splitArea
  30599. layout.z2 = 1;
  30600. return layout;
  30601. }
  30602. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  30603. var getInterval = AxisBuilder.getInterval;
  30604. var axisBuilderAttrs = [
  30605. 'axisLine', 'axisTickLabel', 'axisName'
  30606. ];
  30607. var selfBuilderAttrs = [
  30608. 'splitArea', 'splitLine'
  30609. ];
  30610. // function getAlignWithLabel(model, axisModel) {
  30611. // var alignWithLabel = model.get('alignWithLabel');
  30612. // if (alignWithLabel === 'auto') {
  30613. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  30614. // }
  30615. // return alignWithLabel;
  30616. // }
  30617. var CartesianAxisView = AxisView.extend({
  30618. type: 'cartesianAxis',
  30619. axisPointerClass: 'CartesianAxisPointer',
  30620. /**
  30621. * @override
  30622. */
  30623. render: function (axisModel, ecModel, api, payload) {
  30624. this.group.removeAll();
  30625. var oldAxisGroup = this._axisGroup;
  30626. this._axisGroup = new Group();
  30627. this.group.add(this._axisGroup);
  30628. if (!axisModel.get('show')) {
  30629. return;
  30630. }
  30631. var gridModel = axisModel.getCoordSysModel();
  30632. var layout = layout$1(gridModel, axisModel);
  30633. var axisBuilder = new AxisBuilder(axisModel, layout);
  30634. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  30635. this._axisGroup.add(axisBuilder.getGroup());
  30636. each$1(selfBuilderAttrs, function (name) {
  30637. if (axisModel.get(name + '.show')) {
  30638. this['_' + name](axisModel, gridModel, layout.labelInterval);
  30639. }
  30640. }, this);
  30641. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  30642. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  30643. },
  30644. /**
  30645. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30646. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30647. * @param {number|Function} labelInterval
  30648. * @private
  30649. */
  30650. _splitLine: function (axisModel, gridModel, labelInterval) {
  30651. var axis = axisModel.axis;
  30652. if (axis.scale.isBlank()) {
  30653. return;
  30654. }
  30655. var splitLineModel = axisModel.getModel('splitLine');
  30656. var lineStyleModel = splitLineModel.getModel('lineStyle');
  30657. var lineColors = lineStyleModel.get('color');
  30658. var lineInterval = getInterval(splitLineModel, labelInterval);
  30659. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  30660. var gridRect = gridModel.coordinateSystem.getRect();
  30661. var isHorizontal = axis.isHorizontal();
  30662. var lineCount = 0;
  30663. var ticksCoords = axis.getTicksCoords(
  30664. // splitLineModel.get('alignWithLabel')
  30665. );
  30666. var ticks = axis.scale.getTicks();
  30667. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30668. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30669. var p1 = [];
  30670. var p2 = [];
  30671. // Simple optimization
  30672. // Batching the lines if color are the same
  30673. var lineStyle = lineStyleModel.getLineStyle();
  30674. for (var i = 0; i < ticksCoords.length; i++) {
  30675. if (ifIgnoreOnTick(
  30676. axis, i, lineInterval, ticksCoords.length,
  30677. showMinLabel, showMaxLabel
  30678. )) {
  30679. continue;
  30680. }
  30681. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30682. if (isHorizontal) {
  30683. p1[0] = tickCoord;
  30684. p1[1] = gridRect.y;
  30685. p2[0] = tickCoord;
  30686. p2[1] = gridRect.y + gridRect.height;
  30687. }
  30688. else {
  30689. p1[0] = gridRect.x;
  30690. p1[1] = tickCoord;
  30691. p2[0] = gridRect.x + gridRect.width;
  30692. p2[1] = tickCoord;
  30693. }
  30694. var colorIndex = (lineCount++) % lineColors.length;
  30695. this._axisGroup.add(new Line(subPixelOptimizeLine({
  30696. anid: 'line_' + ticks[i],
  30697. shape: {
  30698. x1: p1[0],
  30699. y1: p1[1],
  30700. x2: p2[0],
  30701. y2: p2[1]
  30702. },
  30703. style: defaults({
  30704. stroke: lineColors[colorIndex]
  30705. }, lineStyle),
  30706. silent: true
  30707. })));
  30708. }
  30709. },
  30710. /**
  30711. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  30712. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30713. * @param {number|Function} labelInterval
  30714. * @private
  30715. */
  30716. _splitArea: function (axisModel, gridModel, labelInterval) {
  30717. var axis = axisModel.axis;
  30718. if (axis.scale.isBlank()) {
  30719. return;
  30720. }
  30721. var splitAreaModel = axisModel.getModel('splitArea');
  30722. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  30723. var areaColors = areaStyleModel.get('color');
  30724. var gridRect = gridModel.coordinateSystem.getRect();
  30725. var ticksCoords = axis.getTicksCoords(
  30726. // splitAreaModel.get('alignWithLabel')
  30727. );
  30728. var ticks = axis.scale.getTicks();
  30729. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  30730. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  30731. var count = 0;
  30732. var areaInterval = getInterval(splitAreaModel, labelInterval);
  30733. var areaStyle = areaStyleModel.getAreaStyle();
  30734. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  30735. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30736. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30737. for (var i = 1; i < ticksCoords.length; i++) {
  30738. if (ifIgnoreOnTick(
  30739. axis, i, areaInterval, ticksCoords.length,
  30740. showMinLabel, showMaxLabel
  30741. )) {
  30742. continue;
  30743. }
  30744. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  30745. var x;
  30746. var y;
  30747. var width;
  30748. var height;
  30749. if (axis.isHorizontal()) {
  30750. x = prevX;
  30751. y = gridRect.y;
  30752. width = tickCoord - x;
  30753. height = gridRect.height;
  30754. }
  30755. else {
  30756. x = gridRect.x;
  30757. y = prevY;
  30758. width = gridRect.width;
  30759. height = tickCoord - y;
  30760. }
  30761. var colorIndex = (count++) % areaColors.length;
  30762. this._axisGroup.add(new Rect({
  30763. anid: 'area_' + ticks[i],
  30764. shape: {
  30765. x: x,
  30766. y: y,
  30767. width: width,
  30768. height: height
  30769. },
  30770. style: defaults({
  30771. fill: areaColors[colorIndex]
  30772. }, areaStyle),
  30773. silent: true
  30774. }));
  30775. prevX = x + width;
  30776. prevY = y + height;
  30777. }
  30778. }
  30779. });
  30780. CartesianAxisView.extend({
  30781. type: 'xAxis'
  30782. });
  30783. CartesianAxisView.extend({
  30784. type: 'yAxis'
  30785. });
  30786. // Grid view
  30787. extendComponentView({
  30788. type: 'grid',
  30789. render: function (gridModel, ecModel) {
  30790. this.group.removeAll();
  30791. if (gridModel.get('show')) {
  30792. this.group.add(new Rect({
  30793. shape: gridModel.coordinateSystem.getRect(),
  30794. style: defaults({
  30795. fill: gridModel.get('backgroundColor')
  30796. }, gridModel.getItemStyle()),
  30797. silent: true,
  30798. z2: -1
  30799. }));
  30800. }
  30801. }
  30802. });
  30803. registerPreprocessor(function (option) {
  30804. // Only create grid when need
  30805. if (option.xAxis && option.yAxis && !option.grid) {
  30806. option.grid = {};
  30807. }
  30808. });
  30809. // In case developer forget to include grid component
  30810. registerVisual(visualSymbol('line', 'circle', 'line'));
  30811. registerLayout(pointsLayout('line'));
  30812. // Down sample after filter
  30813. registerProcessor(
  30814. PRIORITY.PROCESSOR.STATISTIC,
  30815. dataSample('line')
  30816. );
  30817. var BaseBarSeries = SeriesModel.extend({
  30818. type: 'series.__base_bar__',
  30819. getInitialData: function (option, ecModel) {
  30820. return createListFromArray(this.getSource(), this);
  30821. },
  30822. getMarkerPosition: function (value) {
  30823. var coordSys = this.coordinateSystem;
  30824. if (coordSys) {
  30825. // PENDING if clamp ?
  30826. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  30827. var data = this.getData();
  30828. var offset = data.getLayout('offset');
  30829. var size = data.getLayout('size');
  30830. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  30831. pt[offsetIndex] += offset + size / 2;
  30832. return pt;
  30833. }
  30834. return [NaN, NaN];
  30835. },
  30836. defaultOption: {
  30837. zlevel: 0, // 一级层叠
  30838. z: 2, // 二级层叠
  30839. coordinateSystem: 'cartesian2d',
  30840. legendHoverLink: true,
  30841. // stack: null
  30842. // Cartesian coordinate system
  30843. // xAxisIndex: 0,
  30844. // yAxisIndex: 0,
  30845. // 最小高度改为0
  30846. barMinHeight: 0,
  30847. // 最小角度为0,仅对极坐标系下的柱状图有效
  30848. barMinAngle: 0,
  30849. // cursor: null,
  30850. // barMaxWidth: null,
  30851. // 默认自适应
  30852. // barWidth: null,
  30853. // 柱间距离,默认为柱形宽度的30%,可设固定值
  30854. // barGap: '30%',
  30855. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  30856. // barCategoryGap: '20%',
  30857. // label: {
  30858. // show: false
  30859. // },
  30860. itemStyle: {},
  30861. emphasis: {}
  30862. }
  30863. });
  30864. BaseBarSeries.extend({
  30865. type: 'series.bar',
  30866. dependencies: ['grid', 'polar'],
  30867. brushSelector: 'rect'
  30868. });
  30869. function setLabel(
  30870. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  30871. ) {
  30872. var labelModel = itemModel.getModel('label');
  30873. var hoverLabelModel = itemModel.getModel('emphasis.label');
  30874. setLabelStyle(
  30875. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  30876. {
  30877. labelFetcher: seriesModel,
  30878. labelDataIndex: dataIndex,
  30879. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  30880. isRectText: true,
  30881. autoColor: color
  30882. }
  30883. );
  30884. fixPosition(normalStyle);
  30885. fixPosition(hoverStyle);
  30886. }
  30887. function fixPosition(style, labelPositionOutside) {
  30888. if (style.textPosition === 'outside') {
  30889. style.textPosition = labelPositionOutside;
  30890. }
  30891. }
  30892. var getBarItemStyle = makeStyleMapper(
  30893. [
  30894. ['fill', 'color'],
  30895. ['stroke', 'borderColor'],
  30896. ['lineWidth', 'borderWidth'],
  30897. // Compatitable with 2
  30898. ['stroke', 'barBorderColor'],
  30899. ['lineWidth', 'barBorderWidth'],
  30900. ['opacity'],
  30901. ['shadowBlur'],
  30902. ['shadowOffsetX'],
  30903. ['shadowOffsetY'],
  30904. ['shadowColor']
  30905. ]
  30906. );
  30907. var barItemStyle = {
  30908. getBarItemStyle: function (excludes) {
  30909. var style = getBarItemStyle(this, excludes);
  30910. if (this.getBorderLineDash) {
  30911. var lineDash = this.getBorderLineDash();
  30912. lineDash && (style.lineDash = lineDash);
  30913. }
  30914. return style;
  30915. }
  30916. };
  30917. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  30918. // FIXME
  30919. // Just for compatible with ec2.
  30920. extend(Model.prototype, barItemStyle);
  30921. extendChartView({
  30922. type: 'bar',
  30923. render: function (seriesModel, ecModel, api) {
  30924. var coordinateSystemType = seriesModel.get('coordinateSystem');
  30925. if (coordinateSystemType === 'cartesian2d'
  30926. || coordinateSystemType === 'polar'
  30927. ) {
  30928. this._render(seriesModel, ecModel, api);
  30929. }
  30930. else if (__DEV__) {
  30931. console.warn('Only cartesian2d and polar supported for bar.');
  30932. }
  30933. return this.group;
  30934. },
  30935. dispose: noop,
  30936. _render: function (seriesModel, ecModel, api) {
  30937. var group = this.group;
  30938. var data = seriesModel.getData();
  30939. var oldData = this._data;
  30940. var coord = seriesModel.coordinateSystem;
  30941. var baseAxis = coord.getBaseAxis();
  30942. var isHorizontalOrRadial;
  30943. if (coord.type === 'cartesian2d') {
  30944. isHorizontalOrRadial = baseAxis.isHorizontal();
  30945. }
  30946. else if (coord.type === 'polar') {
  30947. isHorizontalOrRadial = baseAxis.dim === 'angle';
  30948. }
  30949. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  30950. data.diff(oldData)
  30951. .add(function (dataIndex) {
  30952. if (!data.hasValue(dataIndex)) {
  30953. return;
  30954. }
  30955. var itemModel = data.getItemModel(dataIndex);
  30956. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  30957. var el = elementCreator[coord.type](
  30958. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  30959. );
  30960. data.setItemGraphicEl(dataIndex, el);
  30961. group.add(el);
  30962. updateStyle(
  30963. el, data, dataIndex, itemModel, layout,
  30964. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30965. );
  30966. })
  30967. .update(function (newIndex, oldIndex) {
  30968. var el = oldData.getItemGraphicEl(oldIndex);
  30969. if (!data.hasValue(newIndex)) {
  30970. group.remove(el);
  30971. return;
  30972. }
  30973. var itemModel = data.getItemModel(newIndex);
  30974. var layout = getLayout[coord.type](data, newIndex, itemModel);
  30975. if (el) {
  30976. updateProps(el, {shape: layout}, animationModel, newIndex);
  30977. }
  30978. else {
  30979. el = elementCreator[coord.type](
  30980. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  30981. );
  30982. }
  30983. data.setItemGraphicEl(newIndex, el);
  30984. // Add back
  30985. group.add(el);
  30986. updateStyle(
  30987. el, data, newIndex, itemModel, layout,
  30988. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  30989. );
  30990. })
  30991. .remove(function (dataIndex) {
  30992. var el = oldData.getItemGraphicEl(dataIndex);
  30993. if (coord.type === 'cartesian2d') {
  30994. el && removeRect(dataIndex, animationModel, el);
  30995. }
  30996. else {
  30997. el && removeSector(dataIndex, animationModel, el);
  30998. }
  30999. })
  31000. .execute();
  31001. this._data = data;
  31002. },
  31003. remove: function (ecModel, api) {
  31004. var group = this.group;
  31005. var data = this._data;
  31006. if (ecModel.get('animation')) {
  31007. if (data) {
  31008. data.eachItemGraphicEl(function (el) {
  31009. if (el.type === 'sector') {
  31010. removeSector(el.dataIndex, ecModel, el);
  31011. }
  31012. else {
  31013. removeRect(el.dataIndex, ecModel, el);
  31014. }
  31015. });
  31016. }
  31017. }
  31018. else {
  31019. group.removeAll();
  31020. }
  31021. }
  31022. });
  31023. var elementCreator = {
  31024. cartesian2d: function (
  31025. data, dataIndex, itemModel, layout, isHorizontal,
  31026. animationModel, isUpdate
  31027. ) {
  31028. var rect = new Rect({shape: extend({}, layout)});
  31029. // Animation
  31030. if (animationModel) {
  31031. var rectShape = rect.shape;
  31032. var animateProperty = isHorizontal ? 'height' : 'width';
  31033. var animateTarget = {};
  31034. rectShape[animateProperty] = 0;
  31035. animateTarget[animateProperty] = layout[animateProperty];
  31036. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31037. shape: animateTarget
  31038. }, animationModel, dataIndex);
  31039. }
  31040. return rect;
  31041. },
  31042. polar: function (
  31043. data, dataIndex, itemModel, layout, isRadial,
  31044. animationModel, isUpdate
  31045. ) {
  31046. var sector = new Sector({shape: extend({}, layout)});
  31047. // Animation
  31048. if (animationModel) {
  31049. var sectorShape = sector.shape;
  31050. var animateProperty = isRadial ? 'r' : 'endAngle';
  31051. var animateTarget = {};
  31052. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31053. animateTarget[animateProperty] = layout[animateProperty];
  31054. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31055. shape: animateTarget
  31056. }, animationModel, dataIndex);
  31057. }
  31058. return sector;
  31059. }
  31060. };
  31061. function removeRect(dataIndex, animationModel, el) {
  31062. // Not show text when animating
  31063. el.style.text = null;
  31064. updateProps(el, {
  31065. shape: {
  31066. width: 0
  31067. }
  31068. }, animationModel, dataIndex, function () {
  31069. el.parent && el.parent.remove(el);
  31070. });
  31071. }
  31072. function removeSector(dataIndex, animationModel, el) {
  31073. // Not show text when animating
  31074. el.style.text = null;
  31075. updateProps(el, {
  31076. shape: {
  31077. r: el.shape.r0
  31078. }
  31079. }, animationModel, dataIndex, function () {
  31080. el.parent && el.parent.remove(el);
  31081. });
  31082. }
  31083. var getLayout = {
  31084. cartesian2d: function (data, dataIndex, itemModel) {
  31085. var layout = data.getItemLayout(dataIndex);
  31086. var fixedLineWidth = getLineWidth(itemModel, layout);
  31087. // fix layout with lineWidth
  31088. var signX = layout.width > 0 ? 1 : -1;
  31089. var signY = layout.height > 0 ? 1 : -1;
  31090. return {
  31091. x: layout.x + signX * fixedLineWidth / 2,
  31092. y: layout.y + signY * fixedLineWidth / 2,
  31093. width: layout.width - signX * fixedLineWidth,
  31094. height: layout.height - signY * fixedLineWidth
  31095. };
  31096. },
  31097. polar: function (data, dataIndex, itemModel) {
  31098. var layout = data.getItemLayout(dataIndex);
  31099. return {
  31100. cx: layout.cx,
  31101. cy: layout.cy,
  31102. r0: layout.r0,
  31103. r: layout.r,
  31104. startAngle: layout.startAngle,
  31105. endAngle: layout.endAngle
  31106. };
  31107. }
  31108. };
  31109. function updateStyle(
  31110. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31111. ) {
  31112. var color = data.getItemVisual(dataIndex, 'color');
  31113. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31114. var itemStyleModel = itemModel.getModel('itemStyle');
  31115. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31116. if (!isPolar) {
  31117. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31118. }
  31119. el.useStyle(defaults(
  31120. {
  31121. fill: color,
  31122. opacity: opacity
  31123. },
  31124. itemStyleModel.getBarItemStyle()
  31125. ));
  31126. var cursorStyle = itemModel.getShallow('cursor');
  31127. cursorStyle && el.attr('cursor', cursorStyle);
  31128. var labelPositionOutside = isHorizontal
  31129. ? (layout.height > 0 ? 'bottom' : 'top')
  31130. : (layout.width > 0 ? 'left' : 'right');
  31131. if (!isPolar) {
  31132. setLabel(
  31133. el.style, hoverStyle, itemModel, color,
  31134. seriesModel, dataIndex, labelPositionOutside
  31135. );
  31136. }
  31137. setHoverStyle(el, hoverStyle);
  31138. }
  31139. // In case width or height are too small.
  31140. function getLineWidth(itemModel, rawLayout) {
  31141. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31142. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31143. }
  31144. // In case developer forget to include grid component
  31145. registerLayout(curry(layout, 'bar'));
  31146. // Visual coding for legend
  31147. registerVisual(function (ecModel) {
  31148. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31149. var data = seriesModel.getData();
  31150. data.setVisual('legendSymbol', 'roundRect');
  31151. });
  31152. });
  31153. /**
  31154. * [Usage]:
  31155. * (1)
  31156. * createListSimply(seriesModel, ['value']);
  31157. * (2)
  31158. * createListSimply(seriesModel, {
  31159. * coordDimensions: ['value'],
  31160. * dimensionsCount: 5
  31161. * });
  31162. *
  31163. * @param {module:echarts/model/Series} seriesModel
  31164. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31165. * The options in opt, see `echarts/data/helper/createDimensions`
  31166. * @param {Array.<string>} [nameList]
  31167. * @return {module:echarts/data/List}
  31168. */
  31169. var createListSimply = function (seriesModel, opt, nameList) {
  31170. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31171. var source = seriesModel.getSource();
  31172. var dimensionsInfo = createDimensions(source, opt);
  31173. var list = new List(dimensionsInfo, seriesModel);
  31174. list.initData(source, nameList);
  31175. return list;
  31176. };
  31177. /**
  31178. * Data selectable mixin for chart series.
  31179. * To eanble data select, option of series must have `selectedMode`.
  31180. * And each data item will use `selected` to toggle itself selected status
  31181. */
  31182. var selectableMixin = {
  31183. /**
  31184. * @param {Array.<Object>|module:echars/data/List} targetList
  31185. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31186. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31187. */
  31188. updateSelectedMap: function (targetList) {
  31189. if (isArray(targetList)) {
  31190. this._targetList = targetList.slice();
  31191. }
  31192. else {
  31193. var ecList = targetList;
  31194. var valueDim = ecList.mapDimension('value');
  31195. var targetList = this._targetList = [];
  31196. for (var i = 0, len = ecList.count(); i < len; i++) {
  31197. targetList.push({
  31198. name: ecList.getName(i),
  31199. value: ecList.get(valueDim, i),
  31200. selected: retrieveRawAttr(ecList, i, 'selected')
  31201. });
  31202. }
  31203. }
  31204. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31205. targetMap.set(target.name, target);
  31206. return targetMap;
  31207. }, createHashMap());
  31208. },
  31209. /**
  31210. * Either name or id should be passed as input here.
  31211. * If both of them are defined, id is used.
  31212. *
  31213. * @param {string|undefined} name name of data
  31214. * @param {number|undefined} id dataIndex of data
  31215. */
  31216. // PENGING If selectedMode is null ?
  31217. select: function (name, id) {
  31218. var target = id != null
  31219. ? this._targetList[id]
  31220. : this._selectTargetMap.get(name);
  31221. var selectedMode = this.get('selectedMode');
  31222. if (selectedMode === 'single') {
  31223. this._selectTargetMap.each(function (target) {
  31224. target.selected = false;
  31225. });
  31226. }
  31227. target && (target.selected = true);
  31228. },
  31229. /**
  31230. * Either name or id should be passed as input here.
  31231. * If both of them are defined, id is used.
  31232. *
  31233. * @param {string|undefined} name name of data
  31234. * @param {number|undefined} id dataIndex of data
  31235. */
  31236. unSelect: function (name, id) {
  31237. var target = id != null
  31238. ? this._targetList[id]
  31239. : this._selectTargetMap.get(name);
  31240. // var selectedMode = this.get('selectedMode');
  31241. // selectedMode !== 'single' && target && (target.selected = false);
  31242. target && (target.selected = false);
  31243. },
  31244. /**
  31245. * Either name or id should be passed as input here.
  31246. * If both of them are defined, id is used.
  31247. *
  31248. * @param {string|undefined} name name of data
  31249. * @param {number|undefined} id dataIndex of data
  31250. */
  31251. toggleSelected: function (name, id) {
  31252. var target = id != null
  31253. ? this._targetList[id]
  31254. : this._selectTargetMap.get(name);
  31255. if (target != null) {
  31256. this[target.selected ? 'unSelect' : 'select'](name, id);
  31257. return target.selected;
  31258. }
  31259. },
  31260. /**
  31261. * Either name or id should be passed as input here.
  31262. * If both of them are defined, id is used.
  31263. *
  31264. * @param {string|undefined} name name of data
  31265. * @param {number|undefined} id dataIndex of data
  31266. */
  31267. isSelected: function (name, id) {
  31268. var target = id != null
  31269. ? this._targetList[id]
  31270. : this._selectTargetMap.get(name);
  31271. return target && target.selected;
  31272. }
  31273. };
  31274. var PieSeries = extendSeriesModel({
  31275. type: 'series.pie',
  31276. // Overwrite
  31277. init: function (option) {
  31278. PieSeries.superApply(this, 'init', arguments);
  31279. // Enable legend selection for each data item
  31280. // Use a function instead of direct access because data reference may changed
  31281. this.legendDataProvider = function () {
  31282. return this.getRawData();
  31283. };
  31284. this.updateSelectedMap(this.getRawData());
  31285. this._defaultLabelLine(option);
  31286. },
  31287. // Overwrite
  31288. mergeOption: function (newOption) {
  31289. PieSeries.superCall(this, 'mergeOption', newOption);
  31290. this.updateSelectedMap(this.getRawData());
  31291. },
  31292. getInitialData: function (option, ecModel) {
  31293. return createListSimply(this, ['value']);
  31294. },
  31295. // Overwrite
  31296. getDataParams: function (dataIndex) {
  31297. var data = this.getData();
  31298. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  31299. // FIXME toFixed?
  31300. var valueList = [];
  31301. data.each(data.mapDimension('value'), function (value) {
  31302. valueList.push(value);
  31303. });
  31304. params.percent = getPercentWithPrecision(
  31305. valueList,
  31306. dataIndex,
  31307. data.hostModel.get('percentPrecision')
  31308. );
  31309. params.$vars.push('percent');
  31310. return params;
  31311. },
  31312. _defaultLabelLine: function (option) {
  31313. // Extend labelLine emphasis
  31314. defaultEmphasis(option, 'labelLine', ['show']);
  31315. var labelLineNormalOpt = option.labelLine;
  31316. var labelLineEmphasisOpt = option.emphasis.labelLine;
  31317. // Not show label line if `label.normal.show = false`
  31318. labelLineNormalOpt.show = labelLineNormalOpt.show
  31319. && option.label.show;
  31320. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  31321. && option.emphasis.label.show;
  31322. },
  31323. defaultOption: {
  31324. zlevel: 0,
  31325. z: 2,
  31326. legendHoverLink: true,
  31327. hoverAnimation: true,
  31328. // 默认全局居中
  31329. center: ['50%', '50%'],
  31330. radius: [0, '75%'],
  31331. // 默认顺时针
  31332. clockwise: true,
  31333. startAngle: 90,
  31334. // 最小角度改为0
  31335. minAngle: 0,
  31336. // 选中时扇区偏移量
  31337. selectedOffset: 10,
  31338. // 高亮扇区偏移量
  31339. hoverOffset: 10,
  31340. // If use strategy to avoid label overlapping
  31341. avoidLabelOverlap: true,
  31342. // 选择模式,默认关闭,可选single,multiple
  31343. // selectedMode: false,
  31344. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  31345. // roseType: null,
  31346. percentPrecision: 2,
  31347. // If still show when all data zero.
  31348. stillShowZeroSum: true,
  31349. // cursor: null,
  31350. label: {
  31351. // If rotate around circle
  31352. rotate: false,
  31353. show: true,
  31354. // 'outer', 'inside', 'center'
  31355. position: 'outer'
  31356. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  31357. // 默认使用全局文本样式,详见TEXTSTYLE
  31358. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  31359. },
  31360. // Enabled when label.normal.position is 'outer'
  31361. labelLine: {
  31362. show: true,
  31363. // 引导线两段中的第一段长度
  31364. length: 15,
  31365. // 引导线两段中的第二段长度
  31366. length2: 15,
  31367. smooth: false,
  31368. lineStyle: {
  31369. // color: 各异,
  31370. width: 1,
  31371. type: 'solid'
  31372. }
  31373. },
  31374. itemStyle: {
  31375. borderWidth: 1
  31376. },
  31377. // Animation type canbe expansion, scale
  31378. animationType: 'expansion',
  31379. animationEasing: 'cubicOut'
  31380. }
  31381. });
  31382. mixin(PieSeries, selectableMixin);
  31383. /**
  31384. * @param {module:echarts/model/Series} seriesModel
  31385. * @param {boolean} hasAnimation
  31386. * @inner
  31387. */
  31388. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  31389. var data = seriesModel.getData();
  31390. var dataIndex = this.dataIndex;
  31391. var name = data.getName(dataIndex);
  31392. var selectedOffset = seriesModel.get('selectedOffset');
  31393. api.dispatchAction({
  31394. type: 'pieToggleSelect',
  31395. from: uid,
  31396. name: name,
  31397. seriesId: seriesModel.id
  31398. });
  31399. data.each(function (idx) {
  31400. toggleItemSelected(
  31401. data.getItemGraphicEl(idx),
  31402. data.getItemLayout(idx),
  31403. seriesModel.isSelected(data.getName(idx)),
  31404. selectedOffset,
  31405. hasAnimation
  31406. );
  31407. });
  31408. }
  31409. /**
  31410. * @param {module:zrender/graphic/Sector} el
  31411. * @param {Object} layout
  31412. * @param {boolean} isSelected
  31413. * @param {number} selectedOffset
  31414. * @param {boolean} hasAnimation
  31415. * @inner
  31416. */
  31417. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  31418. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31419. var dx = Math.cos(midAngle);
  31420. var dy = Math.sin(midAngle);
  31421. var offset = isSelected ? selectedOffset : 0;
  31422. var position = [dx * offset, dy * offset];
  31423. hasAnimation
  31424. // animateTo will stop revious animation like update transition
  31425. ? el.animate()
  31426. .when(200, {
  31427. position: position
  31428. })
  31429. .start('bounceOut')
  31430. : el.attr('position', position);
  31431. }
  31432. /**
  31433. * Piece of pie including Sector, Label, LabelLine
  31434. * @constructor
  31435. * @extends {module:zrender/graphic/Group}
  31436. */
  31437. function PiePiece(data, idx) {
  31438. Group.call(this);
  31439. var sector = new Sector({
  31440. z2: 2
  31441. });
  31442. var polyline = new Polyline();
  31443. var text = new Text();
  31444. this.add(sector);
  31445. this.add(polyline);
  31446. this.add(text);
  31447. this.updateData(data, idx, true);
  31448. // Hover to change label and labelLine
  31449. function onEmphasis() {
  31450. polyline.ignore = polyline.hoverIgnore;
  31451. text.ignore = text.hoverIgnore;
  31452. }
  31453. function onNormal() {
  31454. polyline.ignore = polyline.normalIgnore;
  31455. text.ignore = text.normalIgnore;
  31456. }
  31457. this.on('emphasis', onEmphasis)
  31458. .on('normal', onNormal)
  31459. .on('mouseover', onEmphasis)
  31460. .on('mouseout', onNormal);
  31461. }
  31462. var piePieceProto = PiePiece.prototype;
  31463. piePieceProto.updateData = function (data, idx, firstCreate) {
  31464. var sector = this.childAt(0);
  31465. var seriesModel = data.hostModel;
  31466. var itemModel = data.getItemModel(idx);
  31467. var layout = data.getItemLayout(idx);
  31468. var sectorShape = extend({}, layout);
  31469. sectorShape.label = null;
  31470. if (firstCreate) {
  31471. sector.setShape(sectorShape);
  31472. var animationType = seriesModel.getShallow('animationType');
  31473. if (animationType === 'scale') {
  31474. sector.shape.r = layout.r0;
  31475. initProps(sector, {
  31476. shape: {
  31477. r: layout.r
  31478. }
  31479. }, seriesModel, idx);
  31480. }
  31481. // Expansion
  31482. else {
  31483. sector.shape.endAngle = layout.startAngle;
  31484. updateProps(sector, {
  31485. shape: {
  31486. endAngle: layout.endAngle
  31487. }
  31488. }, seriesModel, idx);
  31489. }
  31490. }
  31491. else {
  31492. updateProps(sector, {
  31493. shape: sectorShape
  31494. }, seriesModel, idx);
  31495. }
  31496. // Update common style
  31497. var visualColor = data.getItemVisual(idx, 'color');
  31498. sector.useStyle(
  31499. defaults(
  31500. {
  31501. lineJoin: 'bevel',
  31502. fill: visualColor
  31503. },
  31504. itemModel.getModel('itemStyle').getItemStyle()
  31505. )
  31506. );
  31507. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  31508. var cursorStyle = itemModel.getShallow('cursor');
  31509. cursorStyle && sector.attr('cursor', cursorStyle);
  31510. // Toggle selected
  31511. toggleItemSelected(
  31512. this,
  31513. data.getItemLayout(idx),
  31514. seriesModel.isSelected(null, idx),
  31515. seriesModel.get('selectedOffset'),
  31516. seriesModel.get('animation')
  31517. );
  31518. function onEmphasis() {
  31519. // Sector may has animation of updating data. Force to move to the last frame
  31520. // Or it may stopped on the wrong shape
  31521. sector.stopAnimation(true);
  31522. sector.animateTo({
  31523. shape: {
  31524. r: layout.r + seriesModel.get('hoverOffset')
  31525. }
  31526. }, 300, 'elasticOut');
  31527. }
  31528. function onNormal() {
  31529. sector.stopAnimation(true);
  31530. sector.animateTo({
  31531. shape: {
  31532. r: layout.r
  31533. }
  31534. }, 300, 'elasticOut');
  31535. }
  31536. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  31537. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  31538. sector
  31539. .on('mouseover', onEmphasis)
  31540. .on('mouseout', onNormal)
  31541. .on('emphasis', onEmphasis)
  31542. .on('normal', onNormal);
  31543. }
  31544. this._updateLabel(data, idx);
  31545. setHoverStyle(this);
  31546. };
  31547. piePieceProto._updateLabel = function (data, idx) {
  31548. var labelLine = this.childAt(1);
  31549. var labelText = this.childAt(2);
  31550. var seriesModel = data.hostModel;
  31551. var itemModel = data.getItemModel(idx);
  31552. var layout = data.getItemLayout(idx);
  31553. var labelLayout = layout.label;
  31554. var visualColor = data.getItemVisual(idx, 'color');
  31555. updateProps(labelLine, {
  31556. shape: {
  31557. points: labelLayout.linePoints || [
  31558. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  31559. ]
  31560. }
  31561. }, seriesModel, idx);
  31562. updateProps(labelText, {
  31563. style: {
  31564. x: labelLayout.x,
  31565. y: labelLayout.y
  31566. }
  31567. }, seriesModel, idx);
  31568. labelText.attr({
  31569. rotation: labelLayout.rotation,
  31570. origin: [labelLayout.x, labelLayout.y],
  31571. z2: 10
  31572. });
  31573. var labelModel = itemModel.getModel('label');
  31574. var labelHoverModel = itemModel.getModel('emphasis.label');
  31575. var labelLineModel = itemModel.getModel('labelLine');
  31576. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  31577. var visualColor = data.getItemVisual(idx, 'color');
  31578. setLabelStyle(
  31579. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  31580. {
  31581. labelFetcher: data.hostModel,
  31582. labelDataIndex: idx,
  31583. defaultText: data.getName(idx),
  31584. autoColor: visualColor,
  31585. useInsideStyle: !!labelLayout.inside
  31586. },
  31587. {
  31588. textAlign: labelLayout.textAlign,
  31589. textVerticalAlign: labelLayout.verticalAlign,
  31590. opacity: data.getItemVisual(idx, 'opacity')
  31591. }
  31592. );
  31593. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  31594. labelText.hoverIgnore = !labelHoverModel.get('show');
  31595. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  31596. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  31597. // Default use item visual color
  31598. labelLine.setStyle({
  31599. stroke: visualColor,
  31600. opacity: data.getItemVisual(idx, 'opacity')
  31601. });
  31602. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  31603. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  31604. var smooth = labelLineModel.get('smooth');
  31605. if (smooth && smooth === true) {
  31606. smooth = 0.4;
  31607. }
  31608. labelLine.setShape({
  31609. smooth: smooth
  31610. });
  31611. };
  31612. inherits(PiePiece, Group);
  31613. // Pie view
  31614. var PieView = Chart.extend({
  31615. type: 'pie',
  31616. init: function () {
  31617. var sectorGroup = new Group();
  31618. this._sectorGroup = sectorGroup;
  31619. },
  31620. render: function (seriesModel, ecModel, api, payload) {
  31621. if (payload && (payload.from === this.uid)) {
  31622. return;
  31623. }
  31624. var data = seriesModel.getData();
  31625. var oldData = this._data;
  31626. var group = this.group;
  31627. var hasAnimation = ecModel.get('animation');
  31628. var isFirstRender = !oldData;
  31629. var animationType = seriesModel.get('animationType');
  31630. var onSectorClick = curry(
  31631. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  31632. );
  31633. var selectedMode = seriesModel.get('selectedMode');
  31634. data.diff(oldData)
  31635. .add(function (idx) {
  31636. var piePiece = new PiePiece(data, idx);
  31637. // Default expansion animation
  31638. if (isFirstRender && animationType !== 'scale') {
  31639. piePiece.eachChild(function (child) {
  31640. child.stopAnimation(true);
  31641. });
  31642. }
  31643. selectedMode && piePiece.on('click', onSectorClick);
  31644. data.setItemGraphicEl(idx, piePiece);
  31645. group.add(piePiece);
  31646. })
  31647. .update(function (newIdx, oldIdx) {
  31648. var piePiece = oldData.getItemGraphicEl(oldIdx);
  31649. piePiece.updateData(data, newIdx);
  31650. piePiece.off('click');
  31651. selectedMode && piePiece.on('click', onSectorClick);
  31652. group.add(piePiece);
  31653. data.setItemGraphicEl(newIdx, piePiece);
  31654. })
  31655. .remove(function (idx) {
  31656. var piePiece = oldData.getItemGraphicEl(idx);
  31657. group.remove(piePiece);
  31658. })
  31659. .execute();
  31660. if (
  31661. hasAnimation && isFirstRender && data.count() > 0
  31662. // Default expansion animation
  31663. && animationType !== 'scale'
  31664. ) {
  31665. var shape = data.getItemLayout(0);
  31666. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  31667. var removeClipPath = bind(group.removeClipPath, group);
  31668. group.setClipPath(this._createClipPath(
  31669. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  31670. ));
  31671. }
  31672. this._data = data;
  31673. },
  31674. dispose: function () {},
  31675. _createClipPath: function (
  31676. cx, cy, r, startAngle, clockwise, cb, seriesModel
  31677. ) {
  31678. var clipPath = new Sector({
  31679. shape: {
  31680. cx: cx,
  31681. cy: cy,
  31682. r0: 0,
  31683. r: r,
  31684. startAngle: startAngle,
  31685. endAngle: startAngle,
  31686. clockwise: clockwise
  31687. }
  31688. });
  31689. initProps(clipPath, {
  31690. shape: {
  31691. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  31692. }
  31693. }, seriesModel, cb);
  31694. return clipPath;
  31695. },
  31696. /**
  31697. * @implement
  31698. */
  31699. containPoint: function (point, seriesModel) {
  31700. var data = seriesModel.getData();
  31701. var itemLayout = data.getItemLayout(0);
  31702. if (itemLayout) {
  31703. var dx = point[0] - itemLayout.cx;
  31704. var dy = point[1] - itemLayout.cy;
  31705. var radius = Math.sqrt(dx * dx + dy * dy);
  31706. return radius <= itemLayout.r && radius >= itemLayout.r0;
  31707. }
  31708. }
  31709. });
  31710. var createDataSelectAction = function (seriesType, actionInfos) {
  31711. each$1(actionInfos, function (actionInfo) {
  31712. actionInfo.update = 'updateView';
  31713. /**
  31714. * @payload
  31715. * @property {string} seriesName
  31716. * @property {string} name
  31717. */
  31718. registerAction(actionInfo, function (payload, ecModel) {
  31719. var selected = {};
  31720. ecModel.eachComponent(
  31721. {mainType: 'series', subType: seriesType, query: payload},
  31722. function (seriesModel) {
  31723. if (seriesModel[actionInfo.method]) {
  31724. seriesModel[actionInfo.method](
  31725. payload.name,
  31726. payload.dataIndex
  31727. );
  31728. }
  31729. var data = seriesModel.getData();
  31730. // Create selected map
  31731. data.each(function (idx) {
  31732. var name = data.getName(idx);
  31733. selected[name] = seriesModel.isSelected(name)
  31734. || false;
  31735. });
  31736. }
  31737. );
  31738. return {
  31739. name: payload.name,
  31740. selected: selected
  31741. };
  31742. });
  31743. });
  31744. };
  31745. // Pick color from palette for each data item.
  31746. // Applicable for charts that require applying color palette
  31747. // in data level (like pie, funnel, chord).
  31748. var dataColor = function (seriesType) {
  31749. return {
  31750. getTargetSeries: function (ecModel) {
  31751. // Pie and funnel may use diferrent scope
  31752. var paletteScope = {};
  31753. var seiresModelMap = createHashMap();
  31754. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31755. seriesModel.__paletteScope = paletteScope;
  31756. seiresModelMap.set(seriesModel.uid, seriesModel);
  31757. });
  31758. return seiresModelMap;
  31759. },
  31760. reset: function (seriesModel, ecModel) {
  31761. var dataAll = seriesModel.getRawData();
  31762. var idxMap = {};
  31763. var data = seriesModel.getData();
  31764. data.each(function (idx) {
  31765. var rawIdx = data.getRawIndex(idx);
  31766. idxMap[rawIdx] = idx;
  31767. });
  31768. dataAll.each(function (rawIdx) {
  31769. var filteredIdx = idxMap[rawIdx];
  31770. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  31771. var singleDataColor = filteredIdx != null
  31772. && data.getItemVisual(filteredIdx, 'color', true);
  31773. if (!singleDataColor) {
  31774. // FIXME Performance
  31775. var itemModel = dataAll.getItemModel(rawIdx);
  31776. var color = itemModel.get('itemStyle.color')
  31777. || seriesModel.getColorFromPalette(
  31778. dataAll.getName(rawIdx), seriesModel.__paletteScope,
  31779. dataAll.count()
  31780. );
  31781. // Legend may use the visual info in data before processed
  31782. dataAll.setItemVisual(rawIdx, 'color', color);
  31783. // Data is not filtered
  31784. if (filteredIdx != null) {
  31785. data.setItemVisual(filteredIdx, 'color', color);
  31786. }
  31787. }
  31788. else {
  31789. // Set data all color for legend
  31790. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  31791. }
  31792. });
  31793. }
  31794. };
  31795. };
  31796. // FIXME emphasis label position is not same with normal label position
  31797. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  31798. list.sort(function (a, b) {
  31799. return a.y - b.y;
  31800. });
  31801. // 压
  31802. function shiftDown(start, end, delta, dir) {
  31803. for (var j = start; j < end; j++) {
  31804. list[j].y += delta;
  31805. if (j > start
  31806. && j + 1 < end
  31807. && list[j + 1].y > list[j].y + list[j].height
  31808. ) {
  31809. shiftUp(j, delta / 2);
  31810. return;
  31811. }
  31812. }
  31813. shiftUp(end - 1, delta / 2);
  31814. }
  31815. // 弹
  31816. function shiftUp(end, delta) {
  31817. for (var j = end; j >= 0; j--) {
  31818. list[j].y -= delta;
  31819. if (j > 0
  31820. && list[j].y > list[j - 1].y + list[j - 1].height
  31821. ) {
  31822. break;
  31823. }
  31824. }
  31825. }
  31826. function changeX(list, isDownList, cx, cy, r, dir) {
  31827. var lastDeltaX = dir > 0
  31828. ? isDownList // 右侧
  31829. ? Number.MAX_VALUE // 下
  31830. : 0 // 上
  31831. : isDownList // 左侧
  31832. ? Number.MAX_VALUE // 下
  31833. : 0; // 上
  31834. for (var i = 0, l = list.length; i < l; i++) {
  31835. // Not change x for center label
  31836. if (list[i].position === 'center') {
  31837. continue;
  31838. }
  31839. var deltaY = Math.abs(list[i].y - cy);
  31840. var length = list[i].len;
  31841. var length2 = list[i].len2;
  31842. var deltaX = (deltaY < r + length)
  31843. ? Math.sqrt(
  31844. (r + length + length2) * (r + length + length2)
  31845. - deltaY * deltaY
  31846. )
  31847. : Math.abs(list[i].x - cx);
  31848. if (isDownList && deltaX >= lastDeltaX) {
  31849. // 右下,左下
  31850. deltaX = lastDeltaX - 10;
  31851. }
  31852. if (!isDownList && deltaX <= lastDeltaX) {
  31853. // 右上,左上
  31854. deltaX = lastDeltaX + 10;
  31855. }
  31856. list[i].x = cx + deltaX * dir;
  31857. lastDeltaX = deltaX;
  31858. }
  31859. }
  31860. var lastY = 0;
  31861. var delta;
  31862. var len = list.length;
  31863. var upList = [];
  31864. var downList = [];
  31865. for (var i = 0; i < len; i++) {
  31866. delta = list[i].y - lastY;
  31867. if (delta < 0) {
  31868. shiftDown(i, len, -delta, dir);
  31869. }
  31870. lastY = list[i].y + list[i].height;
  31871. }
  31872. if (viewHeight - lastY < 0) {
  31873. shiftUp(len - 1, lastY - viewHeight);
  31874. }
  31875. for (var i = 0; i < len; i++) {
  31876. if (list[i].y >= cy) {
  31877. downList.push(list[i]);
  31878. }
  31879. else {
  31880. upList.push(list[i]);
  31881. }
  31882. }
  31883. changeX(upList, false, cx, cy, r, dir);
  31884. changeX(downList, true, cx, cy, r, dir);
  31885. }
  31886. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  31887. var leftList = [];
  31888. var rightList = [];
  31889. for (var i = 0; i < labelLayoutList.length; i++) {
  31890. if (labelLayoutList[i].x < cx) {
  31891. leftList.push(labelLayoutList[i]);
  31892. }
  31893. else {
  31894. rightList.push(labelLayoutList[i]);
  31895. }
  31896. }
  31897. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  31898. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  31899. for (var i = 0; i < labelLayoutList.length; i++) {
  31900. var linePoints = labelLayoutList[i].linePoints;
  31901. if (linePoints) {
  31902. var dist = linePoints[1][0] - linePoints[2][0];
  31903. if (labelLayoutList[i].x < cx) {
  31904. linePoints[2][0] = labelLayoutList[i].x + 3;
  31905. }
  31906. else {
  31907. linePoints[2][0] = labelLayoutList[i].x - 3;
  31908. }
  31909. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  31910. linePoints[1][0] = linePoints[2][0] + dist;
  31911. }
  31912. }
  31913. }
  31914. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  31915. var data = seriesModel.getData();
  31916. var labelLayoutList = [];
  31917. var cx;
  31918. var cy;
  31919. var hasLabelRotate = false;
  31920. data.each(function (idx) {
  31921. var layout = data.getItemLayout(idx);
  31922. var itemModel = data.getItemModel(idx);
  31923. var labelModel = itemModel.getModel('label');
  31924. // Use position in normal or emphasis
  31925. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  31926. var labelLineModel = itemModel.getModel('labelLine');
  31927. var labelLineLen = labelLineModel.get('length');
  31928. var labelLineLen2 = labelLineModel.get('length2');
  31929. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  31930. var dx = Math.cos(midAngle);
  31931. var dy = Math.sin(midAngle);
  31932. var textX;
  31933. var textY;
  31934. var linePoints;
  31935. var textAlign;
  31936. cx = layout.cx;
  31937. cy = layout.cy;
  31938. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  31939. if (labelPosition === 'center') {
  31940. textX = layout.cx;
  31941. textY = layout.cy;
  31942. textAlign = 'center';
  31943. }
  31944. else {
  31945. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  31946. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  31947. textX = x1 + dx * 3;
  31948. textY = y1 + dy * 3;
  31949. if (!isLabelInside) {
  31950. // For roseType
  31951. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  31952. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  31953. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  31954. var y3 = y2;
  31955. textX = x3 + (dx < 0 ? -5 : 5);
  31956. textY = y3;
  31957. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  31958. }
  31959. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  31960. }
  31961. var font = labelModel.getFont();
  31962. var labelRotate = labelModel.get('rotate')
  31963. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  31964. var text = seriesModel.getFormattedLabel(idx, 'normal')
  31965. || data.getName(idx);
  31966. var textRect = getBoundingRect(
  31967. text, font, textAlign, 'top'
  31968. );
  31969. hasLabelRotate = !!labelRotate;
  31970. layout.label = {
  31971. x: textX,
  31972. y: textY,
  31973. position: labelPosition,
  31974. height: textRect.height,
  31975. len: labelLineLen,
  31976. len2: labelLineLen2,
  31977. linePoints: linePoints,
  31978. textAlign: textAlign,
  31979. verticalAlign: 'middle',
  31980. rotation: labelRotate,
  31981. inside: isLabelInside
  31982. };
  31983. // Not layout the inside label
  31984. if (!isLabelInside) {
  31985. labelLayoutList.push(layout.label);
  31986. }
  31987. });
  31988. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  31989. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  31990. }
  31991. };
  31992. var PI2$4 = Math.PI * 2;
  31993. var RADIAN = Math.PI / 180;
  31994. var pieLayout = function (seriesType, ecModel, api, payload) {
  31995. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31996. var data = seriesModel.getData();
  31997. var valueDim = data.mapDimension('value');
  31998. var center = seriesModel.get('center');
  31999. var radius = seriesModel.get('radius');
  32000. if (!isArray(radius)) {
  32001. radius = [0, radius];
  32002. }
  32003. if (!isArray(center)) {
  32004. center = [center, center];
  32005. }
  32006. var width = api.getWidth();
  32007. var height = api.getHeight();
  32008. var size = Math.min(width, height);
  32009. var cx = parsePercent$1(center[0], width);
  32010. var cy = parsePercent$1(center[1], height);
  32011. var r0 = parsePercent$1(radius[0], size / 2);
  32012. var r = parsePercent$1(radius[1], size / 2);
  32013. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  32014. var minAngle = seriesModel.get('minAngle') * RADIAN;
  32015. var validDataCount = 0;
  32016. data.each(valueDim, function (value) {
  32017. !isNaN(value) && validDataCount++;
  32018. });
  32019. var sum = data.getSum(valueDim);
  32020. // Sum may be 0
  32021. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  32022. var clockwise = seriesModel.get('clockwise');
  32023. var roseType = seriesModel.get('roseType');
  32024. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32025. // [0...max]
  32026. var extent = data.getDataExtent(valueDim);
  32027. extent[0] = 0;
  32028. // In the case some sector angle is smaller than minAngle
  32029. var restAngle = PI2$4;
  32030. var valueSumLargerThanMinAngle = 0;
  32031. var currentAngle = startAngle;
  32032. var dir = clockwise ? 1 : -1;
  32033. data.each(valueDim, function (value, idx) {
  32034. var angle;
  32035. if (isNaN(value)) {
  32036. data.setItemLayout(idx, {
  32037. angle: NaN,
  32038. startAngle: NaN,
  32039. endAngle: NaN,
  32040. clockwise: clockwise,
  32041. cx: cx,
  32042. cy: cy,
  32043. r0: r0,
  32044. r: roseType
  32045. ? NaN
  32046. : r
  32047. });
  32048. return;
  32049. }
  32050. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32051. if (roseType !== 'area') {
  32052. angle = (sum === 0 && stillShowZeroSum)
  32053. ? unitRadian : (value * unitRadian);
  32054. }
  32055. else {
  32056. angle = PI2$4 / validDataCount;
  32057. }
  32058. if (angle < minAngle) {
  32059. angle = minAngle;
  32060. restAngle -= minAngle;
  32061. }
  32062. else {
  32063. valueSumLargerThanMinAngle += value;
  32064. }
  32065. var endAngle = currentAngle + dir * angle;
  32066. data.setItemLayout(idx, {
  32067. angle: angle,
  32068. startAngle: currentAngle,
  32069. endAngle: endAngle,
  32070. clockwise: clockwise,
  32071. cx: cx,
  32072. cy: cy,
  32073. r0: r0,
  32074. r: roseType
  32075. ? linearMap(value, extent, [r0, r])
  32076. : r
  32077. });
  32078. currentAngle = endAngle;
  32079. }, true);
  32080. // Some sector is constrained by minAngle
  32081. // Rest sectors needs recalculate angle
  32082. if (restAngle < PI2$4 && validDataCount) {
  32083. // Average the angle if rest angle is not enough after all angles is
  32084. // Constrained by minAngle
  32085. if (restAngle <= 1e-3) {
  32086. var angle = PI2$4 / validDataCount;
  32087. data.each(valueDim, function (value, idx) {
  32088. if (!isNaN(value)) {
  32089. var layout = data.getItemLayout(idx);
  32090. layout.angle = angle;
  32091. layout.startAngle = startAngle + dir * idx * angle;
  32092. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32093. }
  32094. });
  32095. }
  32096. else {
  32097. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32098. currentAngle = startAngle;
  32099. data.each(valueDim, function (value, idx) {
  32100. if (!isNaN(value)) {
  32101. var layout = data.getItemLayout(idx);
  32102. var angle = layout.angle === minAngle
  32103. ? minAngle : value * unitRadian;
  32104. layout.startAngle = currentAngle;
  32105. layout.endAngle = currentAngle + dir * angle;
  32106. currentAngle += dir * angle;
  32107. }
  32108. });
  32109. }
  32110. }
  32111. labelLayout(seriesModel, r, width, height);
  32112. });
  32113. };
  32114. var dataFilter = function (seriesType) {
  32115. return {
  32116. seriesType: seriesType,
  32117. reset: function (seriesModel, ecModel) {
  32118. var legendModels = ecModel.findComponents({
  32119. mainType: 'legend'
  32120. });
  32121. if (!legendModels || !legendModels.length) {
  32122. return;
  32123. }
  32124. var data = seriesModel.getData();
  32125. data.filterSelf(function (idx) {
  32126. var name = data.getName(idx);
  32127. // If in any legend component the status is not selected.
  32128. for (var i = 0; i < legendModels.length; i++) {
  32129. if (!legendModels[i].isSelected(name)) {
  32130. return false;
  32131. }
  32132. }
  32133. return true;
  32134. }, this);
  32135. }
  32136. };
  32137. };
  32138. createDataSelectAction('pie', [{
  32139. type: 'pieToggleSelect',
  32140. event: 'pieselectchanged',
  32141. method: 'toggleSelected'
  32142. }, {
  32143. type: 'pieSelect',
  32144. event: 'pieselected',
  32145. method: 'select'
  32146. }, {
  32147. type: 'pieUnSelect',
  32148. event: 'pieunselected',
  32149. method: 'unSelect'
  32150. }]);
  32151. registerVisual(dataColor('pie'));
  32152. registerLayout(curry(pieLayout, 'pie'));
  32153. registerProcessor(dataFilter('pie'));
  32154. SeriesModel.extend({
  32155. type: 'series.scatter',
  32156. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32157. getInitialData: function (option, ecModel) {
  32158. return createListFromArray(this.getSource(), this);
  32159. },
  32160. brushSelector: 'point',
  32161. getProgressive: function () {
  32162. var progressive = this.option.progressive;
  32163. if (progressive == null) {
  32164. // PENDING
  32165. return this.option.large ? 5e3 : this.get('progressive');
  32166. }
  32167. return progressive;
  32168. },
  32169. getProgressiveThreshold: function () {
  32170. var progressiveThreshold = this.option.progressiveThreshold;
  32171. if (progressiveThreshold == null) {
  32172. // PENDING
  32173. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32174. }
  32175. return progressiveThreshold;
  32176. },
  32177. defaultOption: {
  32178. coordinateSystem: 'cartesian2d',
  32179. zlevel: 0,
  32180. z: 2,
  32181. legendHoverLink: true,
  32182. hoverAnimation: true,
  32183. // Cartesian coordinate system
  32184. // xAxisIndex: 0,
  32185. // yAxisIndex: 0,
  32186. // Polar coordinate system
  32187. // polarIndex: 0,
  32188. // Geo coordinate system
  32189. // geoIndex: 0,
  32190. // symbol: null, // 图形类型
  32191. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32192. // symbolRotate: null, // 图形旋转控制
  32193. large: false,
  32194. // Available when large is true
  32195. largeThreshold: 2000,
  32196. // cursor: null,
  32197. // label: {
  32198. // show: false
  32199. // distance: 5,
  32200. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32201. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32202. // 'inside'|'left'|'right'|'top'|'bottom'
  32203. // 默认使用全局文本样式,详见TEXTSTYLE
  32204. // },
  32205. itemStyle: {
  32206. opacity: 0.8
  32207. // color: 各异
  32208. },
  32209. progressive: null
  32210. }
  32211. });
  32212. // TODO Batch by color
  32213. var BOOST_SIZE_THRESHOLD = 4;
  32214. var LargeSymbolPath = extendShape({
  32215. shape: {
  32216. points: null
  32217. },
  32218. symbolProxy: null,
  32219. buildPath: function (path, shape) {
  32220. var points = shape.points;
  32221. var size = shape.size;
  32222. var symbolProxy = this.symbolProxy;
  32223. var symbolProxyShape = symbolProxy.shape;
  32224. var ctx = path.getContext ? path.getContext() : path;
  32225. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32226. // Do draw in afterBrush.
  32227. if (canBoost) {
  32228. return;
  32229. }
  32230. for (var i = 0; i < points.length;) {
  32231. var x = points[i++];
  32232. var y = points[i++];
  32233. if (isNaN(x) || isNaN(y)) {
  32234. continue;
  32235. }
  32236. symbolProxyShape.x = x - size[0] / 2;
  32237. symbolProxyShape.y = y - size[1] / 2;
  32238. symbolProxyShape.width = size[0];
  32239. symbolProxyShape.height = size[1];
  32240. symbolProxy.buildPath(path, symbolProxyShape, true);
  32241. }
  32242. },
  32243. afterBrush: function (ctx) {
  32244. var shape = this.shape;
  32245. var points = shape.points;
  32246. var size = shape.size;
  32247. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32248. if (!canBoost) {
  32249. return;
  32250. }
  32251. this.setTransform(ctx);
  32252. // PENDING If style or other canvas status changed?
  32253. for (var i = 0; i < points.length;) {
  32254. var x = points[i++];
  32255. var y = points[i++];
  32256. if (isNaN(x) || isNaN(y)) {
  32257. continue;
  32258. }
  32259. // fillRect is faster than building a rect path and draw.
  32260. // And it support light globalCompositeOperation.
  32261. ctx.fillRect(
  32262. x - size[0] / 2, y - size[1] / 2,
  32263. size[0], size[1]
  32264. );
  32265. }
  32266. this.restoreTransform(ctx);
  32267. },
  32268. findDataIndex: function (x, y) {
  32269. // TODO ???
  32270. // Consider transform
  32271. var shape = this.shape;
  32272. var points = shape.points;
  32273. var size = shape.size;
  32274. var w = Math.max(size[0], 4);
  32275. var h = Math.max(size[1], 4);
  32276. // Not consider transform
  32277. // Treat each element as a rect
  32278. // top down traverse
  32279. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32280. var i = idx * 2;
  32281. var x0 = points[i] - w / 2;
  32282. var y0 = points[i + 1] - h / 2;
  32283. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32284. return idx;
  32285. }
  32286. }
  32287. return -1;
  32288. }
  32289. });
  32290. function LargeSymbolDraw() {
  32291. this.group = new Group();
  32292. }
  32293. var largeSymbolProto = LargeSymbolDraw.prototype;
  32294. largeSymbolProto.isPersistent = function () {
  32295. return !this._incremental;
  32296. };
  32297. /**
  32298. * Update symbols draw by new data
  32299. * @param {module:echarts/data/List} data
  32300. */
  32301. largeSymbolProto.updateData = function (data) {
  32302. this.group.removeAll();
  32303. var symbolEl = new LargeSymbolPath({
  32304. rectHover: true,
  32305. cursor: 'default'
  32306. });
  32307. symbolEl.setShape({
  32308. points: data.getLayout('symbolPoints')
  32309. });
  32310. this._setCommon(symbolEl, data);
  32311. this.group.add(symbolEl);
  32312. this._incremental = null;
  32313. };
  32314. largeSymbolProto.updateLayout = function (data) {
  32315. if (this._incremental) {
  32316. return;
  32317. }
  32318. var points = data.getLayout('symbolPoints');
  32319. this.group.eachChild(function (child) {
  32320. if (child.startIndex != null) {
  32321. var len = (child.endIndex - child.startIndex) * 2;
  32322. var byteOffset = child.startIndex * 4 * 2;
  32323. points = new Float32Array(points.buffer, byteOffset, len);
  32324. }
  32325. child.setShape('points', points);
  32326. });
  32327. };
  32328. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  32329. this.group.removeAll();
  32330. this._clearIncremental();
  32331. // Only use incremental displayables when data amount is larger than 2 million.
  32332. // PENDING Incremental data?
  32333. if (data.count() > 2e6) {
  32334. if (!this._incremental) {
  32335. this._incremental = new IncrementalDisplayble({
  32336. silent: true
  32337. });
  32338. }
  32339. this.group.add(this._incremental);
  32340. }
  32341. else {
  32342. this._incremental = null;
  32343. }
  32344. };
  32345. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  32346. var symbolEl;
  32347. if (this._incremental) {
  32348. symbolEl = new LargeSymbolPath();
  32349. this._incremental.addDisplayable(symbolEl, true);
  32350. }
  32351. else {
  32352. symbolEl = new LargeSymbolPath({
  32353. rectHover: true,
  32354. cursor: 'default',
  32355. startIndex: taskParams.start,
  32356. endIndex: taskParams.end
  32357. });
  32358. symbolEl.incremental = true;
  32359. this.group.add(symbolEl);
  32360. }
  32361. symbolEl.setShape({
  32362. points: data.getLayout('symbolPoints')
  32363. });
  32364. this._setCommon(symbolEl, data, !!this._incremental);
  32365. };
  32366. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  32367. var hostModel = data.hostModel;
  32368. // TODO
  32369. // if (data.hasItemVisual.symbolSize) {
  32370. // // TODO typed array?
  32371. // symbolEl.setShape('sizes', data.mapArray(
  32372. // function (idx) {
  32373. // var size = data.getItemVisual(idx, 'symbolSize');
  32374. // return (size instanceof Array) ? size : [size, size];
  32375. // }
  32376. // ));
  32377. // }
  32378. // else {
  32379. var size = data.getVisual('symbolSize');
  32380. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  32381. // }
  32382. // Create symbolProxy to build path for each data
  32383. symbolEl.symbolProxy = createSymbol(
  32384. data.getVisual('symbol'), 0, 0, 0, 0
  32385. );
  32386. // Use symbolProxy setColor method
  32387. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  32388. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  32389. symbolEl.useStyle(
  32390. // Draw shadow when doing fillRect is extremely slow.
  32391. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  32392. );
  32393. var visualColor = data.getVisual('color');
  32394. if (visualColor) {
  32395. symbolEl.setColor(visualColor);
  32396. }
  32397. if (!isIncremental) {
  32398. // Enable tooltip
  32399. // PENDING May have performance issue when path is extremely large
  32400. symbolEl.seriesIndex = hostModel.seriesIndex;
  32401. symbolEl.on('mousemove', function (e) {
  32402. symbolEl.dataIndex = null;
  32403. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  32404. if (dataIndex >= 0) {
  32405. // Provide dataIndex for tooltip
  32406. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  32407. }
  32408. });
  32409. }
  32410. };
  32411. largeSymbolProto.remove = function () {
  32412. this._clearIncremental();
  32413. this._incremental = null;
  32414. this.group.removeAll();
  32415. };
  32416. largeSymbolProto._clearIncremental = function () {
  32417. var incremental = this._incremental;
  32418. if (incremental) {
  32419. incremental.clearDisplaybles();
  32420. }
  32421. };
  32422. extendChartView({
  32423. type: 'scatter',
  32424. render: function (seriesModel, ecModel, api) {
  32425. var data = seriesModel.getData();
  32426. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32427. symbolDraw.updateData(data);
  32428. this._finished = true;
  32429. },
  32430. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  32431. var data = seriesModel.getData();
  32432. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  32433. symbolDraw.incrementalPrepareUpdate(data);
  32434. this._finished = false;
  32435. },
  32436. incrementalRender: function (taskParams, seriesModel, ecModel) {
  32437. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  32438. this._finished = taskParams.end === seriesModel.getData().count();
  32439. },
  32440. updateTransform: function (seriesModel, ecModel, api) {
  32441. var data = seriesModel.getData();
  32442. // Must mark group dirty and make sure the incremental layer will be cleared
  32443. // PENDING
  32444. this.group.dirty();
  32445. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  32446. return {
  32447. update: true
  32448. };
  32449. }
  32450. else {
  32451. var res = pointsLayout().reset(seriesModel);
  32452. if (res.progress) {
  32453. res.progress({ start: 0, end: data.count() }, data);
  32454. }
  32455. this._symbolDraw.updateLayout(data);
  32456. }
  32457. },
  32458. _updateSymbolDraw: function (data, seriesModel) {
  32459. var symbolDraw = this._symbolDraw;
  32460. var pipelineContext = seriesModel.pipelineContext;
  32461. var isLargeDraw = pipelineContext.large;
  32462. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  32463. symbolDraw && symbolDraw.remove();
  32464. symbolDraw = this._symbolDraw = isLargeDraw
  32465. ? new LargeSymbolDraw()
  32466. : new SymbolDraw();
  32467. this._isLargeDraw = isLargeDraw;
  32468. this.group.removeAll();
  32469. }
  32470. this.group.add(symbolDraw.group);
  32471. return symbolDraw;
  32472. },
  32473. remove: function (ecModel, api) {
  32474. this._symbolDraw && this._symbolDraw.remove(true);
  32475. this._symbolDraw = null;
  32476. },
  32477. dispose: function () {}
  32478. });
  32479. // import * as zrUtil from 'zrender/src/core/util';
  32480. // In case developer forget to include grid component
  32481. registerVisual(visualSymbol('scatter', 'circle'));
  32482. registerLayout(pointsLayout('scatter'));
  32483. // echarts.registerProcessor(function (ecModel, api) {
  32484. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  32485. // var data = seriesModel.getData();
  32486. // var coordSys = seriesModel.coordinateSystem;
  32487. // if (coordSys.type !== 'geo') {
  32488. // return;
  32489. // }
  32490. // var startPt = coordSys.pointToData([0, 0]);
  32491. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  32492. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  32493. // return data.mapDimension(dim);
  32494. // });
  32495. // var range = {};
  32496. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  32497. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  32498. // data.selectRange(range);
  32499. // });
  32500. // });
  32501. function IndicatorAxis(dim, scale, radiusExtent) {
  32502. Axis.call(this, dim, scale, radiusExtent);
  32503. /**
  32504. * Axis type
  32505. * - 'category'
  32506. * - 'value'
  32507. * - 'time'
  32508. * - 'log'
  32509. * @type {string}
  32510. */
  32511. this.type = 'value';
  32512. this.angle = 0;
  32513. /**
  32514. * Indicator name
  32515. * @type {string}
  32516. */
  32517. this.name = '';
  32518. /**
  32519. * @type {module:echarts/model/Model}
  32520. */
  32521. this.model;
  32522. }
  32523. inherits(IndicatorAxis, Axis);
  32524. // TODO clockwise
  32525. function Radar(radarModel, ecModel, api) {
  32526. this._model = radarModel;
  32527. /**
  32528. * Radar dimensions
  32529. * @type {Array.<string>}
  32530. */
  32531. this.dimensions = [];
  32532. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  32533. var dim = 'indicator_' + idx;
  32534. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  32535. indicatorAxis.name = indicatorModel.get('name');
  32536. // Inject model and axis
  32537. indicatorAxis.model = indicatorModel;
  32538. indicatorModel.axis = indicatorAxis;
  32539. this.dimensions.push(dim);
  32540. return indicatorAxis;
  32541. }, this);
  32542. this.resize(radarModel, api);
  32543. /**
  32544. * @type {number}
  32545. * @readOnly
  32546. */
  32547. this.cx;
  32548. /**
  32549. * @type {number}
  32550. * @readOnly
  32551. */
  32552. this.cy;
  32553. /**
  32554. * @type {number}
  32555. * @readOnly
  32556. */
  32557. this.r;
  32558. /**
  32559. * @type {number}
  32560. * @readOnly
  32561. */
  32562. this.startAngle;
  32563. }
  32564. Radar.prototype.getIndicatorAxes = function () {
  32565. return this._indicatorAxes;
  32566. };
  32567. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  32568. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  32569. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  32570. };
  32571. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  32572. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  32573. var angle = indicatorAxis.angle;
  32574. var x = this.cx + coord * Math.cos(angle);
  32575. var y = this.cy - coord * Math.sin(angle);
  32576. return [x, y];
  32577. };
  32578. Radar.prototype.pointToData = function (pt) {
  32579. var dx = pt[0] - this.cx;
  32580. var dy = pt[1] - this.cy;
  32581. var radius = Math.sqrt(dx * dx + dy * dy);
  32582. dx /= radius;
  32583. dy /= radius;
  32584. var radian = Math.atan2(-dy, dx);
  32585. // Find the closest angle
  32586. // FIXME index can calculated directly
  32587. var minRadianDiff = Infinity;
  32588. var closestAxis;
  32589. var closestAxisIdx = -1;
  32590. for (var i = 0; i < this._indicatorAxes.length; i++) {
  32591. var indicatorAxis = this._indicatorAxes[i];
  32592. var diff = Math.abs(radian - indicatorAxis.angle);
  32593. if (diff < minRadianDiff) {
  32594. closestAxis = indicatorAxis;
  32595. closestAxisIdx = i;
  32596. minRadianDiff = diff;
  32597. }
  32598. }
  32599. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  32600. };
  32601. Radar.prototype.resize = function (radarModel, api) {
  32602. var center = radarModel.get('center');
  32603. var viewWidth = api.getWidth();
  32604. var viewHeight = api.getHeight();
  32605. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  32606. this.cx = parsePercent$1(center[0], viewWidth);
  32607. this.cy = parsePercent$1(center[1], viewHeight);
  32608. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  32609. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  32610. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  32611. indicatorAxis.setExtent(0, this.r);
  32612. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  32613. // Normalize to [-PI, PI]
  32614. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  32615. indicatorAxis.angle = angle;
  32616. }, this);
  32617. };
  32618. Radar.prototype.update = function (ecModel, api) {
  32619. var indicatorAxes = this._indicatorAxes;
  32620. var radarModel = this._model;
  32621. each$1(indicatorAxes, function (indicatorAxis) {
  32622. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  32623. });
  32624. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  32625. if (radarSeries.get('coordinateSystem') !== 'radar'
  32626. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  32627. ) {
  32628. return;
  32629. }
  32630. var data = radarSeries.getData();
  32631. each$1(indicatorAxes, function (indicatorAxis) {
  32632. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  32633. });
  32634. }, this);
  32635. var splitNumber = radarModel.get('splitNumber');
  32636. function increaseInterval(interval) {
  32637. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  32638. // Increase interval
  32639. var f = interval / exp10;
  32640. if (f === 2) {
  32641. f = 5;
  32642. }
  32643. else { // f is 2 or 5
  32644. f *= 2;
  32645. }
  32646. return f * exp10;
  32647. }
  32648. // Force all the axis fixing the maxSplitNumber.
  32649. each$1(indicatorAxes, function (indicatorAxis, idx) {
  32650. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  32651. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  32652. var axisModel = indicatorAxis.model;
  32653. var scale = indicatorAxis.scale;
  32654. var fixedMin = axisModel.getMin();
  32655. var fixedMax = axisModel.getMax();
  32656. var interval = scale.getInterval();
  32657. if (fixedMin != null && fixedMax != null) {
  32658. // User set min, max, divide to get new interval
  32659. scale.setExtent(+fixedMin, +fixedMax);
  32660. scale.setInterval(
  32661. (fixedMax - fixedMin) / splitNumber
  32662. );
  32663. }
  32664. else if (fixedMin != null) {
  32665. var max;
  32666. // User set min, expand extent on the other side
  32667. do {
  32668. max = fixedMin + interval * splitNumber;
  32669. scale.setExtent(+fixedMin, max);
  32670. // Interval must been set after extent
  32671. // FIXME
  32672. scale.setInterval(interval);
  32673. interval = increaseInterval(interval);
  32674. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  32675. }
  32676. else if (fixedMax != null) {
  32677. var min;
  32678. // User set min, expand extent on the other side
  32679. do {
  32680. min = fixedMax - interval * splitNumber;
  32681. scale.setExtent(min, +fixedMax);
  32682. scale.setInterval(interval);
  32683. interval = increaseInterval(interval);
  32684. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  32685. }
  32686. else {
  32687. var nicedSplitNumber = scale.getTicks().length - 1;
  32688. if (nicedSplitNumber > splitNumber) {
  32689. interval = increaseInterval(interval);
  32690. }
  32691. // PENDING
  32692. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  32693. var halfSplitNumber = Math.round(splitNumber / 2);
  32694. scale.setExtent(
  32695. round$1(center - halfSplitNumber * interval),
  32696. round$1(center + (splitNumber - halfSplitNumber) * interval)
  32697. );
  32698. scale.setInterval(interval);
  32699. }
  32700. });
  32701. };
  32702. /**
  32703. * Radar dimensions is based on the data
  32704. * @type {Array}
  32705. */
  32706. Radar.dimensions = [];
  32707. Radar.create = function (ecModel, api) {
  32708. var radarList = [];
  32709. ecModel.eachComponent('radar', function (radarModel) {
  32710. var radar = new Radar(radarModel, ecModel, api);
  32711. radarList.push(radar);
  32712. radarModel.coordinateSystem = radar;
  32713. });
  32714. ecModel.eachSeriesByType('radar', function (radarSeries) {
  32715. if (radarSeries.get('coordinateSystem') === 'radar') {
  32716. // Inject coordinate system
  32717. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  32718. }
  32719. });
  32720. return radarList;
  32721. };
  32722. CoordinateSystemManager.register('radar', Radar);
  32723. var valueAxisDefault = axisDefault.valueAxis;
  32724. function defaultsShow(opt, show) {
  32725. return defaults({
  32726. show: show
  32727. }, opt);
  32728. }
  32729. var RadarModel = extendComponentModel({
  32730. type: 'radar',
  32731. optionUpdated: function () {
  32732. var boundaryGap = this.get('boundaryGap');
  32733. var splitNumber = this.get('splitNumber');
  32734. var scale = this.get('scale');
  32735. var axisLine = this.get('axisLine');
  32736. var axisTick = this.get('axisTick');
  32737. var axisLabel = this.get('axisLabel');
  32738. var nameTextStyle = this.get('name');
  32739. var showName = this.get('name.show');
  32740. var nameFormatter = this.get('name.formatter');
  32741. var nameGap = this.get('nameGap');
  32742. var triggerEvent = this.get('triggerEvent');
  32743. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  32744. // PENDING
  32745. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  32746. indicatorOpt.min = 0;
  32747. }
  32748. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  32749. indicatorOpt.max = 0;
  32750. }
  32751. var iNameTextStyle = nameTextStyle;
  32752. if(indicatorOpt.color != null) {
  32753. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  32754. }
  32755. // Use same configuration
  32756. indicatorOpt = merge(clone(indicatorOpt), {
  32757. boundaryGap: boundaryGap,
  32758. splitNumber: splitNumber,
  32759. scale: scale,
  32760. axisLine: axisLine,
  32761. axisTick: axisTick,
  32762. axisLabel: axisLabel,
  32763. // Competitable with 2 and use text
  32764. name: indicatorOpt.text,
  32765. nameLocation: 'end',
  32766. nameGap: nameGap,
  32767. // min: 0,
  32768. nameTextStyle: iNameTextStyle,
  32769. triggerEvent: triggerEvent
  32770. }, false);
  32771. if (!showName) {
  32772. indicatorOpt.name = '';
  32773. }
  32774. if (typeof nameFormatter === 'string') {
  32775. var indName = indicatorOpt.name;
  32776. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  32777. }
  32778. else if (typeof nameFormatter === 'function') {
  32779. indicatorOpt.name = nameFormatter(
  32780. indicatorOpt.name, indicatorOpt
  32781. );
  32782. }
  32783. var model = extend(
  32784. new Model(indicatorOpt, null, this.ecModel),
  32785. axisModelCommonMixin
  32786. );
  32787. // For triggerEvent.
  32788. model.mainType = 'radar';
  32789. model.componentIndex = this.componentIndex;
  32790. return model;
  32791. }, this);
  32792. this.getIndicatorModels = function () {
  32793. return indicatorModels;
  32794. };
  32795. },
  32796. defaultOption: {
  32797. zlevel: 0,
  32798. z: 0,
  32799. center: ['50%', '50%'],
  32800. radius: '75%',
  32801. startAngle: 90,
  32802. name: {
  32803. show: true
  32804. // formatter: null
  32805. // textStyle: {}
  32806. },
  32807. boundaryGap: [0, 0],
  32808. splitNumber: 5,
  32809. nameGap: 15,
  32810. scale: false,
  32811. // Polygon or circle
  32812. shape: 'polygon',
  32813. axisLine: merge(
  32814. {
  32815. lineStyle: {
  32816. color: '#bbb'
  32817. }
  32818. },
  32819. valueAxisDefault.axisLine
  32820. ),
  32821. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  32822. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  32823. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  32824. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  32825. // {text, min, max}
  32826. indicator: []
  32827. }
  32828. });
  32829. var axisBuilderAttrs$1 = [
  32830. 'axisLine', 'axisTickLabel', 'axisName'
  32831. ];
  32832. extendComponentView({
  32833. type: 'radar',
  32834. render: function (radarModel, ecModel, api) {
  32835. var group = this.group;
  32836. group.removeAll();
  32837. this._buildAxes(radarModel);
  32838. this._buildSplitLineAndArea(radarModel);
  32839. },
  32840. _buildAxes: function (radarModel) {
  32841. var radar = radarModel.coordinateSystem;
  32842. var indicatorAxes = radar.getIndicatorAxes();
  32843. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  32844. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  32845. position: [radar.cx, radar.cy],
  32846. rotation: indicatorAxis.angle,
  32847. labelDirection: -1,
  32848. tickDirection: -1,
  32849. nameDirection: 1
  32850. });
  32851. return axisBuilder;
  32852. });
  32853. each$1(axisBuilders, function (axisBuilder) {
  32854. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  32855. this.group.add(axisBuilder.getGroup());
  32856. }, this);
  32857. },
  32858. _buildSplitLineAndArea: function (radarModel) {
  32859. var radar = radarModel.coordinateSystem;
  32860. var indicatorAxes = radar.getIndicatorAxes();
  32861. if (!indicatorAxes.length) {
  32862. return;
  32863. }
  32864. var shape = radarModel.get('shape');
  32865. var splitLineModel = radarModel.getModel('splitLine');
  32866. var splitAreaModel = radarModel.getModel('splitArea');
  32867. var lineStyleModel = splitLineModel.getModel('lineStyle');
  32868. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  32869. var showSplitLine = splitLineModel.get('show');
  32870. var showSplitArea = splitAreaModel.get('show');
  32871. var splitLineColors = lineStyleModel.get('color');
  32872. var splitAreaColors = areaStyleModel.get('color');
  32873. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  32874. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  32875. var splitLines = [];
  32876. var splitAreas = [];
  32877. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  32878. var colorIndex = idx % areaOrLineColorList.length;
  32879. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  32880. return colorIndex;
  32881. }
  32882. if (shape === 'circle') {
  32883. var ticksRadius = indicatorAxes[0].getTicksCoords();
  32884. var cx = radar.cx;
  32885. var cy = radar.cy;
  32886. for (var i = 0; i < ticksRadius.length; i++) {
  32887. if (showSplitLine) {
  32888. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  32889. splitLines[colorIndex].push(new Circle({
  32890. shape: {
  32891. cx: cx,
  32892. cy: cy,
  32893. r: ticksRadius[i]
  32894. }
  32895. }));
  32896. }
  32897. if (showSplitArea && i < ticksRadius.length - 1) {
  32898. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  32899. splitAreas[colorIndex].push(new Ring({
  32900. shape: {
  32901. cx: cx,
  32902. cy: cy,
  32903. r0: ticksRadius[i],
  32904. r: ticksRadius[i + 1]
  32905. }
  32906. }));
  32907. }
  32908. }
  32909. }
  32910. // Polyyon
  32911. else {
  32912. var realSplitNumber;
  32913. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  32914. var ticksCoords = indicatorAxis.getTicksCoords();
  32915. realSplitNumber = realSplitNumber == null
  32916. ? ticksCoords.length - 1
  32917. : Math.min(ticksCoords.length - 1, realSplitNumber);
  32918. return map(ticksCoords, function (tickCoord) {
  32919. return radar.coordToPoint(tickCoord, idx);
  32920. });
  32921. });
  32922. var prevPoints = [];
  32923. for (var i = 0; i <= realSplitNumber; i++) {
  32924. var points = [];
  32925. for (var j = 0; j < indicatorAxes.length; j++) {
  32926. points.push(axesTicksPoints[j][i]);
  32927. }
  32928. // Close
  32929. if (points[0]) {
  32930. points.push(points[0].slice());
  32931. }
  32932. else {
  32933. if (__DEV__) {
  32934. console.error('Can\'t draw value axis ' + i);
  32935. }
  32936. }
  32937. if (showSplitLine) {
  32938. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  32939. splitLines[colorIndex].push(new Polyline({
  32940. shape: {
  32941. points: points
  32942. }
  32943. }));
  32944. }
  32945. if (showSplitArea && prevPoints) {
  32946. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  32947. splitAreas[colorIndex].push(new Polygon({
  32948. shape: {
  32949. points: points.concat(prevPoints)
  32950. }
  32951. }));
  32952. }
  32953. prevPoints = points.slice().reverse();
  32954. }
  32955. }
  32956. var lineStyle = lineStyleModel.getLineStyle();
  32957. var areaStyle = areaStyleModel.getAreaStyle();
  32958. // Add splitArea before splitLine
  32959. each$1(splitAreas, function (splitAreas, idx) {
  32960. this.group.add(mergePath(
  32961. splitAreas, {
  32962. style: defaults({
  32963. stroke: 'none',
  32964. fill: splitAreaColors[idx % splitAreaColors.length]
  32965. }, areaStyle),
  32966. silent: true
  32967. }
  32968. ));
  32969. }, this);
  32970. each$1(splitLines, function (splitLines, idx) {
  32971. this.group.add(mergePath(
  32972. splitLines, {
  32973. style: defaults({
  32974. fill: 'none',
  32975. stroke: splitLineColors[idx % splitLineColors.length]
  32976. }, lineStyle),
  32977. silent: true
  32978. }
  32979. ));
  32980. }, this);
  32981. }
  32982. });
  32983. var RadarSeries = SeriesModel.extend({
  32984. type: 'series.radar',
  32985. dependencies: ['radar'],
  32986. // Overwrite
  32987. init: function (option) {
  32988. RadarSeries.superApply(this, 'init', arguments);
  32989. // Enable legend selection for each data item
  32990. // Use a function instead of direct access because data reference may changed
  32991. this.legendDataProvider = function () {
  32992. return this.getRawData();
  32993. };
  32994. },
  32995. getInitialData: function (option, ecModel) {
  32996. return createListSimply(this, {
  32997. extraPrefix: 'indicator_',
  32998. extraFromZero: true
  32999. });
  33000. },
  33001. formatTooltip: function (dataIndex) {
  33002. var data = this.getData();
  33003. var coordSys = this.coordinateSystem;
  33004. var indicatorAxes = coordSys.getIndicatorAxes();
  33005. var name = this.getData().getName(dataIndex);
  33006. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  33007. + map(indicatorAxes, function (axis, idx) {
  33008. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  33009. return encodeHTML(axis.name + ' : ' + val);
  33010. }).join('<br />');
  33011. },
  33012. defaultOption: {
  33013. zlevel: 0,
  33014. z: 2,
  33015. coordinateSystem: 'radar',
  33016. legendHoverLink: true,
  33017. radarIndex: 0,
  33018. lineStyle: {
  33019. width: 2,
  33020. type: 'solid'
  33021. },
  33022. label: {
  33023. position: 'top'
  33024. },
  33025. // areaStyle: {
  33026. // },
  33027. // itemStyle: {}
  33028. symbol: 'emptyCircle',
  33029. symbolSize: 4
  33030. // symbolRotate: null
  33031. }
  33032. });
  33033. function normalizeSymbolSize(symbolSize) {
  33034. if (!isArray(symbolSize)) {
  33035. symbolSize = [+symbolSize, +symbolSize];
  33036. }
  33037. return symbolSize;
  33038. }
  33039. extendChartView({
  33040. type: 'radar',
  33041. render: function (seriesModel, ecModel, api) {
  33042. var polar = seriesModel.coordinateSystem;
  33043. var group = this.group;
  33044. var data = seriesModel.getData();
  33045. var oldData = this._data;
  33046. function createSymbol$$1(data, idx) {
  33047. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33048. var color = data.getItemVisual(idx, 'color');
  33049. if (symbolType === 'none') {
  33050. return;
  33051. }
  33052. var symbolSize = normalizeSymbolSize(
  33053. data.getItemVisual(idx, 'symbolSize')
  33054. );
  33055. var symbolPath = createSymbol(
  33056. symbolType, -1, -1, 2, 2, color
  33057. );
  33058. symbolPath.attr({
  33059. style: {
  33060. strokeNoScale: true
  33061. },
  33062. z2: 100,
  33063. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  33064. });
  33065. return symbolPath;
  33066. }
  33067. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  33068. // Simply rerender all
  33069. symbolGroup.removeAll();
  33070. for (var i = 0; i < newPoints.length - 1; i++) {
  33071. var symbolPath = createSymbol$$1(data, idx);
  33072. if (symbolPath) {
  33073. symbolPath.__dimIdx = i;
  33074. if (oldPoints[i]) {
  33075. symbolPath.attr('position', oldPoints[i]);
  33076. graphic[isInit ? 'initProps' : 'updateProps'](
  33077. symbolPath, {
  33078. position: newPoints[i]
  33079. }, seriesModel, idx
  33080. );
  33081. }
  33082. else {
  33083. symbolPath.attr('position', newPoints[i]);
  33084. }
  33085. symbolGroup.add(symbolPath);
  33086. }
  33087. }
  33088. }
  33089. function getInitialPoints(points) {
  33090. return map(points, function (pt) {
  33091. return [polar.cx, polar.cy];
  33092. });
  33093. }
  33094. data.diff(oldData)
  33095. .add(function (idx) {
  33096. var points = data.getItemLayout(idx);
  33097. if (!points) {
  33098. return;
  33099. }
  33100. var polygon = new Polygon();
  33101. var polyline = new Polyline();
  33102. var target = {
  33103. shape: {
  33104. points: points
  33105. }
  33106. };
  33107. polygon.shape.points = getInitialPoints(points);
  33108. polyline.shape.points = getInitialPoints(points);
  33109. initProps(polygon, target, seriesModel, idx);
  33110. initProps(polyline, target, seriesModel, idx);
  33111. var itemGroup = new Group();
  33112. var symbolGroup = new Group();
  33113. itemGroup.add(polyline);
  33114. itemGroup.add(polygon);
  33115. itemGroup.add(symbolGroup);
  33116. updateSymbols(
  33117. polyline.shape.points, points, symbolGroup, data, idx, true
  33118. );
  33119. data.setItemGraphicEl(idx, itemGroup);
  33120. })
  33121. .update(function (newIdx, oldIdx) {
  33122. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  33123. var polyline = itemGroup.childAt(0);
  33124. var polygon = itemGroup.childAt(1);
  33125. var symbolGroup = itemGroup.childAt(2);
  33126. var target = {
  33127. shape: {
  33128. points: data.getItemLayout(newIdx)
  33129. }
  33130. };
  33131. if (!target.shape.points) {
  33132. return;
  33133. }
  33134. updateSymbols(
  33135. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  33136. );
  33137. updateProps(polyline, target, seriesModel);
  33138. updateProps(polygon, target, seriesModel);
  33139. data.setItemGraphicEl(newIdx, itemGroup);
  33140. })
  33141. .remove(function (idx) {
  33142. group.remove(oldData.getItemGraphicEl(idx));
  33143. })
  33144. .execute();
  33145. data.eachItemGraphicEl(function (itemGroup, idx) {
  33146. var itemModel = data.getItemModel(idx);
  33147. var polyline = itemGroup.childAt(0);
  33148. var polygon = itemGroup.childAt(1);
  33149. var symbolGroup = itemGroup.childAt(2);
  33150. var color = data.getItemVisual(idx, 'color');
  33151. group.add(itemGroup);
  33152. polyline.useStyle(
  33153. defaults(
  33154. itemModel.getModel('lineStyle').getLineStyle(),
  33155. {
  33156. fill: 'none',
  33157. stroke: color
  33158. }
  33159. )
  33160. );
  33161. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  33162. var areaStyleModel = itemModel.getModel('areaStyle');
  33163. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  33164. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  33165. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  33166. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  33167. polygon.ignore = polygonIgnore;
  33168. polygon.useStyle(
  33169. defaults(
  33170. areaStyleModel.getAreaStyle(),
  33171. {
  33172. fill: color,
  33173. opacity: 0.7
  33174. }
  33175. )
  33176. );
  33177. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  33178. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  33179. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  33180. var labelModel = itemModel.getModel('label');
  33181. var labelHoverModel = itemModel.getModel('emphasis.label');
  33182. symbolGroup.eachChild(function (symbolPath) {
  33183. symbolPath.setStyle(itemStyle);
  33184. symbolPath.hoverStyle = clone(itemHoverStyle);
  33185. setLabelStyle(
  33186. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  33187. {
  33188. labelFetcher: data.hostModel,
  33189. labelDataIndex: idx,
  33190. labelDimIndex: symbolPath.__dimIdx,
  33191. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  33192. autoColor: color,
  33193. isRectText: true
  33194. }
  33195. );
  33196. });
  33197. function onEmphasis() {
  33198. polygon.attr('ignore', hoverPolygonIgnore);
  33199. }
  33200. function onNormal() {
  33201. polygon.attr('ignore', polygonIgnore);
  33202. }
  33203. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  33204. itemGroup.on('emphasis', onEmphasis)
  33205. .on('mouseover', onEmphasis)
  33206. .on('normal', onNormal)
  33207. .on('mouseout', onNormal);
  33208. setHoverStyle(itemGroup);
  33209. });
  33210. this._data = data;
  33211. },
  33212. remove: function () {
  33213. this.group.removeAll();
  33214. this._data = null;
  33215. },
  33216. dispose: function () {}
  33217. });
  33218. var radarLayout = function (ecModel) {
  33219. ecModel.eachSeriesByType('radar', function (seriesModel) {
  33220. var data = seriesModel.getData();
  33221. var points = [];
  33222. var coordSys = seriesModel.coordinateSystem;
  33223. if (!coordSys) {
  33224. return;
  33225. }
  33226. function pointsConverter(val, idx) {
  33227. points[idx] = points[idx] || [];
  33228. points[idx][i] = coordSys.dataToPoint(val, i);
  33229. }
  33230. var axes = coordSys.getIndicatorAxes();
  33231. for (var i = 0; i < coordSys.getIndicatorAxes().length; i++) {
  33232. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  33233. }
  33234. data.each(function (idx) {
  33235. // Close polygon
  33236. points[idx][0] && points[idx].push(points[idx][0].slice());
  33237. data.setItemLayout(idx, points[idx]);
  33238. });
  33239. });
  33240. };
  33241. // Backward compat for radar chart in 2
  33242. var backwardCompat$1 = function (option) {
  33243. var polarOptArr = option.polar;
  33244. if (polarOptArr) {
  33245. if (!isArray(polarOptArr)) {
  33246. polarOptArr = [polarOptArr];
  33247. }
  33248. var polarNotRadar = [];
  33249. each$1(polarOptArr, function (polarOpt, idx) {
  33250. if (polarOpt.indicator) {
  33251. if (polarOpt.type && !polarOpt.shape) {
  33252. polarOpt.shape = polarOpt.type;
  33253. }
  33254. option.radar = option.radar || [];
  33255. if (!isArray(option.radar)) {
  33256. option.radar = [option.radar];
  33257. }
  33258. option.radar.push(polarOpt);
  33259. }
  33260. else {
  33261. polarNotRadar.push(polarOpt);
  33262. }
  33263. });
  33264. option.polar = polarNotRadar;
  33265. }
  33266. each$1(option.series, function (seriesOpt) {
  33267. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  33268. seriesOpt.radarIndex = seriesOpt.polarIndex;
  33269. }
  33270. });
  33271. };
  33272. // Must use radar component
  33273. registerVisual(dataColor('radar'));
  33274. registerVisual(visualSymbol('radar', 'circle'));
  33275. registerLayout(radarLayout);
  33276. registerProcessor(dataFilter('radar'));
  33277. registerPreprocessor(backwardCompat$1);
  33278. // import geoCreator from '../../coord/geo/geoCreator';
  33279. var MapSeries = SeriesModel.extend({
  33280. type: 'series.map',
  33281. dependencies: ['geo'],
  33282. layoutMode: 'box',
  33283. /**
  33284. * Only first map series of same mapType will drawMap
  33285. * @type {boolean}
  33286. */
  33287. needsDrawMap: false,
  33288. /**
  33289. * Group of all map series with same mapType
  33290. * @type {boolean}
  33291. */
  33292. seriesGroup: [],
  33293. init: function (option) {
  33294. this._fillOption(option, this.getMapType());
  33295. // this.option = option;
  33296. MapSeries.superApply(this, 'init', arguments);
  33297. this.updateSelectedMap(this.getRawData());
  33298. },
  33299. getInitialData: function (option) {
  33300. return createListSimply(this, ['value']);
  33301. },
  33302. mergeOption: function (newOption) {
  33303. this._fillOption(newOption, this.getMapType());
  33304. MapSeries.superApply(this, 'mergeOption', arguments);
  33305. this.updateSelectedMap(this.getRawData());
  33306. },
  33307. /**
  33308. * If no host geo model, return null, which means using a
  33309. * inner exclusive geo model.
  33310. */
  33311. getHostGeoModel: function () {
  33312. var geoIndex = this.option.geoIndex;
  33313. return geoIndex != null
  33314. ? this.dependentModels.geo[geoIndex]
  33315. : null;
  33316. },
  33317. getMapType: function () {
  33318. return (this.getHostGeoModel() || this).option.map;
  33319. },
  33320. _fillOption: function (option, mapName) {
  33321. // Shallow clone
  33322. // option = zrUtil.extend({}, option);
  33323. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  33324. // return option;
  33325. },
  33326. getRawValue: function (dataIndex) {
  33327. // Use value stored in data instead because it is calculated from multiple series
  33328. // FIXME Provide all value of multiple series ?
  33329. var data = this.getData();
  33330. return data.get(data.mapDimension('value'), dataIndex);
  33331. },
  33332. /**
  33333. * Get model of region
  33334. * @param {string} name
  33335. * @return {module:echarts/model/Model}
  33336. */
  33337. getRegionModel: function (regionName) {
  33338. var data = this.getData();
  33339. return data.getItemModel(data.indexOfName(regionName));
  33340. },
  33341. /**
  33342. * Map tooltip formatter
  33343. *
  33344. * @param {number} dataIndex
  33345. */
  33346. formatTooltip: function (dataIndex) {
  33347. // FIXME orignalData and data is a bit confusing
  33348. var data = this.getData();
  33349. var formattedValue = addCommas(this.getRawValue(dataIndex));
  33350. var name = data.getName(dataIndex);
  33351. var seriesGroup = this.seriesGroup;
  33352. var seriesNames = [];
  33353. for (var i = 0; i < seriesGroup.length; i++) {
  33354. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  33355. var valueDim = data.mapDimension('value');
  33356. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  33357. seriesNames.push(
  33358. encodeHTML(seriesGroup[i].name)
  33359. );
  33360. }
  33361. }
  33362. return seriesNames.join(', ') + '<br />'
  33363. + encodeHTML(name + ' : ' + formattedValue);
  33364. },
  33365. /**
  33366. * @implement
  33367. */
  33368. getTooltipPosition: function (dataIndex) {
  33369. if (dataIndex != null) {
  33370. var name = this.getData().getName(dataIndex);
  33371. var geo = this.coordinateSystem;
  33372. var region = geo.getRegion(name);
  33373. return region && geo.dataToPoint(region.center);
  33374. }
  33375. },
  33376. setZoom: function (zoom) {
  33377. this.option.zoom = zoom;
  33378. },
  33379. setCenter: function (center) {
  33380. this.option.center = center;
  33381. },
  33382. defaultOption: {
  33383. // 一级层叠
  33384. zlevel: 0,
  33385. // 二级层叠
  33386. z: 2,
  33387. coordinateSystem: 'geo',
  33388. // map should be explicitly specified since ec3.
  33389. map: '',
  33390. // If `geoIndex` is not specified, a exclusive geo will be
  33391. // created. Otherwise use the specified geo component, and
  33392. // `map` and `mapType` are ignored.
  33393. // geoIndex: 0,
  33394. // 'center' | 'left' | 'right' | 'x%' | {number}
  33395. left: 'center',
  33396. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  33397. top: 'center',
  33398. // right
  33399. // bottom
  33400. // width:
  33401. // height
  33402. // Aspect is width / height. Inited to be geoJson bbox aspect
  33403. // This parameter is used for scale this aspect
  33404. aspectScale: 0.75,
  33405. ///// Layout with center and size
  33406. // If you wan't to put map in a fixed size box with right aspect ratio
  33407. // This two properties may more conveninet
  33408. // layoutCenter: [50%, 50%]
  33409. // layoutSize: 100
  33410. // 数值合并方式,默认加和,可选为:
  33411. // 'sum' | 'average' | 'max' | 'min'
  33412. // mapValueCalculation: 'sum',
  33413. // 地图数值计算结果小数精度
  33414. // mapValuePrecision: 0,
  33415. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  33416. showLegendSymbol: true,
  33417. // 选择模式,默认关闭,可选single,multiple
  33418. // selectedMode: false,
  33419. dataRangeHoverLink: true,
  33420. // 是否开启缩放及漫游模式
  33421. // roam: false,
  33422. // Define left-top, right-bottom coords to control view
  33423. // For example, [ [180, 90], [-180, -90] ],
  33424. // higher priority than center and zoom
  33425. boundingCoords: null,
  33426. // Default on center of map
  33427. center: null,
  33428. zoom: 1,
  33429. scaleLimit: null,
  33430. label: {
  33431. show: false,
  33432. color: '#000'
  33433. },
  33434. // scaleLimit: null,
  33435. itemStyle: {
  33436. borderWidth: 0.5,
  33437. borderColor: '#444',
  33438. areaColor: '#eee'
  33439. },
  33440. emphasis: {
  33441. label: {
  33442. show: true,
  33443. color: 'rgb(100,0,0)'
  33444. },
  33445. itemStyle: {
  33446. areaColor: 'rgba(255,215,0,0.8)'
  33447. }
  33448. }
  33449. }
  33450. });
  33451. mixin(MapSeries, selectableMixin);
  33452. var ATTR = '\0_ec_interaction_mutex';
  33453. function take(zr, resourceKey, userKey) {
  33454. var store = getStore(zr);
  33455. store[resourceKey] = userKey;
  33456. }
  33457. function release(zr, resourceKey, userKey) {
  33458. var store = getStore(zr);
  33459. var uKey = store[resourceKey];
  33460. if (uKey === userKey) {
  33461. store[resourceKey] = null;
  33462. }
  33463. }
  33464. function isTaken(zr, resourceKey) {
  33465. return !!getStore(zr)[resourceKey];
  33466. }
  33467. function getStore(zr) {
  33468. return zr[ATTR] || (zr[ATTR] = {});
  33469. }
  33470. /**
  33471. * payload: {
  33472. * type: 'takeGlobalCursor',
  33473. * key: 'dataZoomSelect', or 'brush', or ...,
  33474. * If no userKey, release global cursor.
  33475. * }
  33476. */
  33477. registerAction(
  33478. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  33479. function () {}
  33480. );
  33481. /**
  33482. * @alias module:echarts/component/helper/RoamController
  33483. * @constructor
  33484. * @mixin {module:zrender/mixin/Eventful}
  33485. *
  33486. * @param {module:zrender/zrender~ZRender} zr
  33487. */
  33488. function RoamController(zr) {
  33489. /**
  33490. * @type {Function}
  33491. */
  33492. this.pointerChecker;
  33493. /**
  33494. * @type {module:zrender}
  33495. */
  33496. this._zr = zr;
  33497. /**
  33498. * @type {Object}
  33499. */
  33500. this._opt = {};
  33501. // Avoid two roamController bind the same handler
  33502. var bind$$1 = bind;
  33503. var mousedownHandler = bind$$1(mousedown, this);
  33504. var mousemoveHandler = bind$$1(mousemove, this);
  33505. var mouseupHandler = bind$$1(mouseup, this);
  33506. var mousewheelHandler = bind$$1(mousewheel, this);
  33507. var pinchHandler = bind$$1(pinch, this);
  33508. Eventful.call(this);
  33509. /**
  33510. * @param {Function} pointerChecker
  33511. * input: x, y
  33512. * output: boolean
  33513. */
  33514. this.setPointerChecker = function (pointerChecker) {
  33515. this.pointerChecker = pointerChecker;
  33516. };
  33517. /**
  33518. * Notice: only enable needed types. For example, if 'zoom'
  33519. * is not needed, 'zoom' should not be enabled, otherwise
  33520. * default mousewheel behaviour (scroll page) will be disabled.
  33521. *
  33522. * @param {boolean|string} [controlType=true] Specify the control type,
  33523. * which can be null/undefined or true/false
  33524. * or 'pan/move' or 'zoom'/'scale'
  33525. * @param {Object} [opt]
  33526. * @param {Object} [opt.zoomOnMouseWheel=true]
  33527. * @param {Object} [opt.moveOnMouseMove=true]
  33528. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  33529. */
  33530. this.enable = function (controlType, opt) {
  33531. // Disable previous first
  33532. this.disable();
  33533. this._opt = defaults(clone(opt) || {}, {
  33534. zoomOnMouseWheel: true,
  33535. moveOnMouseMove: true,
  33536. preventDefaultMouseMove: true
  33537. });
  33538. if (controlType == null) {
  33539. controlType = true;
  33540. }
  33541. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  33542. zr.on('mousedown', mousedownHandler);
  33543. zr.on('mousemove', mousemoveHandler);
  33544. zr.on('mouseup', mouseupHandler);
  33545. }
  33546. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  33547. zr.on('mousewheel', mousewheelHandler);
  33548. zr.on('pinch', pinchHandler);
  33549. }
  33550. };
  33551. this.disable = function () {
  33552. zr.off('mousedown', mousedownHandler);
  33553. zr.off('mousemove', mousemoveHandler);
  33554. zr.off('mouseup', mouseupHandler);
  33555. zr.off('mousewheel', mousewheelHandler);
  33556. zr.off('pinch', pinchHandler);
  33557. };
  33558. this.dispose = this.disable;
  33559. this.isDragging = function () {
  33560. return this._dragging;
  33561. };
  33562. this.isPinching = function () {
  33563. return this._pinching;
  33564. };
  33565. }
  33566. mixin(RoamController, Eventful);
  33567. function mousedown(e) {
  33568. if (notLeftMouse(e)
  33569. || (e.target && e.target.draggable)
  33570. ) {
  33571. return;
  33572. }
  33573. var x = e.offsetX;
  33574. var y = e.offsetY;
  33575. // Only check on mosedown, but not mousemove.
  33576. // Mouse can be out of target when mouse moving.
  33577. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  33578. this._x = x;
  33579. this._y = y;
  33580. this._dragging = true;
  33581. }
  33582. }
  33583. function mousemove(e) {
  33584. if (notLeftMouse(e)
  33585. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  33586. || !this._dragging
  33587. || e.gestureEvent === 'pinch'
  33588. || isTaken(this._zr, 'globalPan')
  33589. ) {
  33590. return;
  33591. }
  33592. var x = e.offsetX;
  33593. var y = e.offsetY;
  33594. var oldX = this._x;
  33595. var oldY = this._y;
  33596. var dx = x - oldX;
  33597. var dy = y - oldY;
  33598. this._x = x;
  33599. this._y = y;
  33600. this._opt.preventDefaultMouseMove && stop(e.event);
  33601. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  33602. }
  33603. function mouseup(e) {
  33604. if (!notLeftMouse(e)) {
  33605. this._dragging = false;
  33606. }
  33607. }
  33608. function mousewheel(e) {
  33609. // wheelDelta maybe -0 in chrome mac.
  33610. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  33611. return;
  33612. }
  33613. // Convenience:
  33614. // Mac and VM Windows on Mac: scroll up: zoom out.
  33615. // Windows: scroll up: zoom in.
  33616. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  33617. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  33618. }
  33619. function pinch(e) {
  33620. if (isTaken(this._zr, 'globalPan')) {
  33621. return;
  33622. }
  33623. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  33624. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  33625. }
  33626. function zoom(e, zoomDelta, zoomX, zoomY) {
  33627. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  33628. // When mouse is out of roamController rect,
  33629. // default befavoius should not be be disabled, otherwise
  33630. // page sliding is disabled, contrary to expectation.
  33631. stop(e.event);
  33632. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  33633. }
  33634. }
  33635. function checkKeyBinding(roamController, prop, e) {
  33636. var setting = roamController._opt[prop];
  33637. return setting
  33638. && (!isString(setting) || e.event[setting + 'Key']);
  33639. }
  33640. /**
  33641. * For geo and graph.
  33642. *
  33643. * @param {Object} controllerHost
  33644. * @param {module:zrender/Element} controllerHost.target
  33645. */
  33646. function updateViewOnPan(controllerHost, dx, dy) {
  33647. var target = controllerHost.target;
  33648. var pos = target.position;
  33649. pos[0] += dx;
  33650. pos[1] += dy;
  33651. target.dirty();
  33652. }
  33653. /**
  33654. * For geo and graph.
  33655. *
  33656. * @param {Object} controllerHost
  33657. * @param {module:zrender/Element} controllerHost.target
  33658. * @param {number} controllerHost.zoom
  33659. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  33660. */
  33661. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  33662. var target = controllerHost.target;
  33663. var zoomLimit = controllerHost.zoomLimit;
  33664. var pos = target.position;
  33665. var scale = target.scale;
  33666. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  33667. newZoom *= zoomDelta;
  33668. if (zoomLimit) {
  33669. var zoomMin = zoomLimit.min || 0;
  33670. var zoomMax = zoomLimit.max || Infinity;
  33671. newZoom = Math.max(
  33672. Math.min(zoomMax, newZoom),
  33673. zoomMin
  33674. );
  33675. }
  33676. var zoomScale = newZoom / controllerHost.zoom;
  33677. controllerHost.zoom = newZoom;
  33678. // Keep the mouse center when scaling
  33679. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  33680. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  33681. scale[0] *= zoomScale;
  33682. scale[1] *= zoomScale;
  33683. target.dirty();
  33684. }
  33685. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  33686. /**
  33687. * Avoid that: mouse click on a elements that is over geo or graph,
  33688. * but roam is triggered.
  33689. */
  33690. function onIrrelevantElement(e, api, targetCoordSysModel) {
  33691. var model = api.getComponentByElement(e.topTarget);
  33692. // If model is axisModel, it works only if it is injected with coordinateSystem.
  33693. var coordSys = model && model.coordinateSystem;
  33694. return model
  33695. && model !== targetCoordSysModel
  33696. && !IRRELEVANT_EXCLUDES[model.mainType]
  33697. && (coordSys && coordSys.model !== targetCoordSysModel);
  33698. }
  33699. function getFixedItemStyle(model, scale) {
  33700. var itemStyle = model.getItemStyle();
  33701. var areaColor = model.get('areaColor');
  33702. // If user want the color not to be changed when hover,
  33703. // they should both set areaColor and color to be null.
  33704. if (areaColor != null) {
  33705. itemStyle.fill = areaColor;
  33706. }
  33707. return itemStyle;
  33708. }
  33709. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  33710. group.off('click');
  33711. group.off('mousedown');
  33712. if (mapOrGeoModel.get('selectedMode')) {
  33713. group.on('mousedown', function () {
  33714. mapDraw._mouseDownFlag = true;
  33715. });
  33716. group.on('click', function (e) {
  33717. if (!mapDraw._mouseDownFlag) {
  33718. return;
  33719. }
  33720. mapDraw._mouseDownFlag = false;
  33721. var el = e.target;
  33722. while (!el.__regions) {
  33723. el = el.parent;
  33724. }
  33725. if (!el) {
  33726. return;
  33727. }
  33728. var action = {
  33729. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  33730. batch: map(el.__regions, function (region) {
  33731. return {
  33732. name: region.name,
  33733. from: fromView.uid
  33734. };
  33735. })
  33736. };
  33737. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  33738. api.dispatchAction(action);
  33739. updateMapSelected(mapOrGeoModel, group);
  33740. });
  33741. }
  33742. }
  33743. function updateMapSelected(mapOrGeoModel, group) {
  33744. // FIXME
  33745. group.eachChild(function (otherRegionEl) {
  33746. each$1(otherRegionEl.__regions, function (region) {
  33747. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  33748. });
  33749. });
  33750. }
  33751. /**
  33752. * @alias module:echarts/component/helper/MapDraw
  33753. * @param {module:echarts/ExtensionAPI} api
  33754. * @param {boolean} updateGroup
  33755. */
  33756. function MapDraw(api, updateGroup) {
  33757. var group = new Group();
  33758. /**
  33759. * @type {module:echarts/component/helper/RoamController}
  33760. * @private
  33761. */
  33762. this._controller = new RoamController(api.getZr());
  33763. /**
  33764. * @type {Object} {target, zoom, zoomLimit}
  33765. * @private
  33766. */
  33767. this._controllerHost = {target: updateGroup ? group : null};
  33768. /**
  33769. * @type {module:zrender/container/Group}
  33770. * @readOnly
  33771. */
  33772. this.group = group;
  33773. /**
  33774. * @type {boolean}
  33775. * @private
  33776. */
  33777. this._updateGroup = updateGroup;
  33778. /**
  33779. * This flag is used to make sure that only one among
  33780. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  33781. * action may be triggered when `pan`, which is unexpected.
  33782. * @type {booelan}
  33783. */
  33784. this._mouseDownFlag;
  33785. }
  33786. MapDraw.prototype = {
  33787. constructor: MapDraw,
  33788. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  33789. var isGeo = mapOrGeoModel.mainType === 'geo';
  33790. // Map series has data. GEO model that controlled by map series
  33791. // will be assigned with map data. Other GEO model has no data.
  33792. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  33793. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  33794. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  33795. data = mapSeries.getData();
  33796. }
  33797. });
  33798. var geo = mapOrGeoModel.coordinateSystem;
  33799. var group = this.group;
  33800. var scale = geo.scale;
  33801. var groupNewProp = {
  33802. position: geo.position,
  33803. scale: scale
  33804. };
  33805. // No animation when first draw or in action
  33806. if (!group.childAt(0) || payload) {
  33807. group.attr(groupNewProp);
  33808. }
  33809. else {
  33810. updateProps(group, groupNewProp, mapOrGeoModel);
  33811. }
  33812. group.removeAll();
  33813. var itemStyleAccessPath = ['itemStyle'];
  33814. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  33815. var labelAccessPath = ['label'];
  33816. var hoverLabelAccessPath = ['emphasis', 'label'];
  33817. var nameMap = createHashMap();
  33818. each$1(geo.regions, function (region) {
  33819. // Consider in GeoJson properties.name may be duplicated, for example,
  33820. // there is multiple region named "United Kindom" or "France" (so many
  33821. // colonies). And it is not appropriate to merge them in geo, which
  33822. // will make them share the same label and bring trouble in label
  33823. // location calculation.
  33824. var regionGroup = nameMap.get(region.name)
  33825. || nameMap.set(region.name, new Group());
  33826. var compoundPath = new CompoundPath({
  33827. shape: {
  33828. paths: []
  33829. }
  33830. });
  33831. regionGroup.add(compoundPath);
  33832. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  33833. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  33834. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  33835. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  33836. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  33837. var labelModel = regionModel.getModel(labelAccessPath);
  33838. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  33839. var dataIdx;
  33840. // Use the itemStyle in data if has data
  33841. if (data) {
  33842. dataIdx = data.indexOfName(region.name);
  33843. // Only visual color of each item will be used. It can be encoded by dataRange
  33844. // But visual color of series is used in symbol drawing
  33845. //
  33846. // Visual color for each series is for the symbol draw
  33847. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  33848. if (visualColor) {
  33849. itemStyle.fill = visualColor;
  33850. }
  33851. }
  33852. each$1(region.geometries, function (geometry) {
  33853. if (geometry.type !== 'polygon') {
  33854. return;
  33855. }
  33856. compoundPath.shape.paths.push(new Polygon({
  33857. shape: {
  33858. points: geometry.exterior
  33859. }
  33860. }));
  33861. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  33862. compoundPath.shape.paths.push(new Polygon({
  33863. shape: {
  33864. points: geometry.interiors[i]
  33865. }
  33866. }));
  33867. }
  33868. });
  33869. compoundPath.setStyle(itemStyle);
  33870. compoundPath.style.strokeNoScale = true;
  33871. compoundPath.culling = true;
  33872. // Label
  33873. var showLabel = labelModel.get('show');
  33874. var hoverShowLabel = hoverLabelModel.get('show');
  33875. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  33876. var itemLayout = data && data.getItemLayout(dataIdx);
  33877. // In the following cases label will be drawn
  33878. // 1. In map series and data value is NaN
  33879. // 2. In geo component
  33880. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  33881. if (
  33882. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  33883. || (itemLayout && itemLayout.showLabel)
  33884. ) {
  33885. var query = !isGeo ? dataIdx : region.name;
  33886. var labelFetcher;
  33887. // Consider dataIdx not found.
  33888. if (!data || dataIdx >= 0) {
  33889. labelFetcher = mapOrGeoModel;
  33890. }
  33891. var textEl = new Text({
  33892. position: region.center.slice(),
  33893. scale: [1 / scale[0], 1 / scale[1]],
  33894. z2: 10,
  33895. silent: true
  33896. });
  33897. setLabelStyle(
  33898. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  33899. {
  33900. labelFetcher: labelFetcher,
  33901. labelDataIndex: query,
  33902. defaultText: region.name,
  33903. useInsideStyle: false
  33904. },
  33905. {
  33906. textAlign: 'center',
  33907. textVerticalAlign: 'middle'
  33908. }
  33909. );
  33910. regionGroup.add(textEl);
  33911. }
  33912. // setItemGraphicEl, setHoverStyle after all polygons and labels
  33913. // are added to the rigionGroup
  33914. if (data) {
  33915. data.setItemGraphicEl(dataIdx, regionGroup);
  33916. }
  33917. else {
  33918. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  33919. // Package custom mouse event for geo component
  33920. compoundPath.eventData = {
  33921. componentType: 'geo',
  33922. geoIndex: mapOrGeoModel.componentIndex,
  33923. name: region.name,
  33924. region: (regionModel && regionModel.option) || {}
  33925. };
  33926. }
  33927. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  33928. groupRegions.push(region);
  33929. setHoverStyle(
  33930. regionGroup,
  33931. hoverItemStyle,
  33932. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  33933. );
  33934. group.add(regionGroup);
  33935. });
  33936. this._updateController(mapOrGeoModel, ecModel, api);
  33937. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  33938. updateMapSelected(mapOrGeoModel, group);
  33939. },
  33940. remove: function () {
  33941. this.group.removeAll();
  33942. this._controller.dispose();
  33943. this._controllerHost = {};
  33944. },
  33945. _updateController: function (mapOrGeoModel, ecModel, api) {
  33946. var geo = mapOrGeoModel.coordinateSystem;
  33947. var controller = this._controller;
  33948. var controllerHost = this._controllerHost;
  33949. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  33950. controllerHost.zoom = geo.getZoom();
  33951. // roamType is will be set default true if it is null
  33952. controller.enable(mapOrGeoModel.get('roam') || false);
  33953. var mainType = mapOrGeoModel.mainType;
  33954. function makeActionBase() {
  33955. var action = {
  33956. type: 'geoRoam',
  33957. componentType: mainType
  33958. };
  33959. action[mainType + 'Id'] = mapOrGeoModel.id;
  33960. return action;
  33961. }
  33962. controller.off('pan').on('pan', function (dx, dy) {
  33963. this._mouseDownFlag = false;
  33964. updateViewOnPan(controllerHost, dx, dy);
  33965. api.dispatchAction(extend(makeActionBase(), {
  33966. dx: dx,
  33967. dy: dy
  33968. }));
  33969. }, this);
  33970. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  33971. this._mouseDownFlag = false;
  33972. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  33973. api.dispatchAction(extend(makeActionBase(), {
  33974. zoom: zoom,
  33975. originX: mouseX,
  33976. originY: mouseY
  33977. }));
  33978. if (this._updateGroup) {
  33979. var group = this.group;
  33980. var scale = group.scale;
  33981. group.traverse(function (el) {
  33982. if (el.type === 'text') {
  33983. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  33984. }
  33985. });
  33986. }
  33987. }, this);
  33988. controller.setPointerChecker(function (e, x, y) {
  33989. return geo.getViewRectAfterRoam().contain(x, y)
  33990. && !onIrrelevantElement(e, api, mapOrGeoModel);
  33991. });
  33992. }
  33993. };
  33994. extendChartView({
  33995. type: 'map',
  33996. render: function (mapModel, ecModel, api, payload) {
  33997. // Not render if it is an toggleSelect action from self
  33998. if (payload && payload.type === 'mapToggleSelect'
  33999. && payload.from === this.uid
  34000. ) {
  34001. return;
  34002. }
  34003. var group = this.group;
  34004. group.removeAll();
  34005. if (mapModel.getHostGeoModel()) {
  34006. return;
  34007. }
  34008. // Not update map if it is an roam action from self
  34009. if (!(payload && payload.type === 'geoRoam'
  34010. && payload.componentType === 'series'
  34011. && payload.seriesId === mapModel.id
  34012. )
  34013. ) {
  34014. if (mapModel.needsDrawMap) {
  34015. var mapDraw = this._mapDraw || new MapDraw(api, true);
  34016. group.add(mapDraw.group);
  34017. mapDraw.draw(mapModel, ecModel, api, this, payload);
  34018. this._mapDraw = mapDraw;
  34019. }
  34020. else {
  34021. // Remove drawed map
  34022. this._mapDraw && this._mapDraw.remove();
  34023. this._mapDraw = null;
  34024. }
  34025. }
  34026. else {
  34027. var mapDraw = this._mapDraw;
  34028. mapDraw && group.add(mapDraw.group);
  34029. }
  34030. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  34031. && this._renderSymbols(mapModel, ecModel, api);
  34032. },
  34033. remove: function () {
  34034. this._mapDraw && this._mapDraw.remove();
  34035. this._mapDraw = null;
  34036. this.group.removeAll();
  34037. },
  34038. dispose: function () {
  34039. this._mapDraw && this._mapDraw.remove();
  34040. this._mapDraw = null;
  34041. },
  34042. _renderSymbols: function (mapModel, ecModel, api) {
  34043. var originalData = mapModel.originalData;
  34044. var group = this.group;
  34045. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  34046. if (isNaN(value)) {
  34047. return;
  34048. }
  34049. var layout = originalData.getItemLayout(idx);
  34050. if (!layout || !layout.point) {
  34051. // Not exists in map
  34052. return;
  34053. }
  34054. var point = layout.point;
  34055. var offset = layout.offset;
  34056. var circle = new Circle({
  34057. style: {
  34058. // Because the special of map draw.
  34059. // Which needs statistic of multiple series and draw on one map.
  34060. // And each series also need a symbol with legend color
  34061. //
  34062. // Layout and visual are put one the different data
  34063. fill: mapModel.getData().getVisual('color')
  34064. },
  34065. shape: {
  34066. cx: point[0] + offset * 9,
  34067. cy: point[1],
  34068. r: 3
  34069. },
  34070. silent: true,
  34071. // Do not overlap the first series, on which labels are displayed.
  34072. z2: !offset ? 10 : 8
  34073. });
  34074. // First data on the same region
  34075. if (!offset) {
  34076. var fullData = mapModel.mainSeries.getData();
  34077. var name = originalData.getName(idx);
  34078. var fullIndex = fullData.indexOfName(name);
  34079. var itemModel = originalData.getItemModel(idx);
  34080. var labelModel = itemModel.getModel('label');
  34081. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34082. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  34083. var normalText = retrieve2(
  34084. mapModel.getFormattedLabel(idx, 'normal'),
  34085. name
  34086. );
  34087. var emphasisText = retrieve2(
  34088. mapModel.getFormattedLabel(idx, 'emphasis'),
  34089. normalText
  34090. );
  34091. var onEmphasis = function () {
  34092. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  34093. text: hoverLabelModel.get('show') ? emphasisText : null
  34094. }, {isRectText: true, useInsideStyle: false}, true);
  34095. circle.style.extendFrom(hoverStyle);
  34096. // Make label upper than others if overlaps.
  34097. circle.__mapOriginalZ2 = circle.z2;
  34098. circle.z2 += 1;
  34099. };
  34100. var onNormal = function () {
  34101. setTextStyle(circle.style, labelModel, {
  34102. text: labelModel.get('show') ? normalText : null,
  34103. textPosition: labelModel.getShallow('position') || 'bottom'
  34104. }, {isRectText: true, useInsideStyle: false});
  34105. if (circle.__mapOriginalZ2 != null) {
  34106. circle.z2 = circle.__mapOriginalZ2;
  34107. circle.__mapOriginalZ2 = null;
  34108. }
  34109. };
  34110. polygonGroups.on('mouseover', onEmphasis)
  34111. .on('mouseout', onNormal)
  34112. .on('emphasis', onEmphasis)
  34113. .on('normal', onNormal);
  34114. onNormal();
  34115. }
  34116. group.add(circle);
  34117. });
  34118. }
  34119. });
  34120. /**
  34121. * @param {module:echarts/coord/View} view
  34122. * @param {Object} payload
  34123. * @param {Object} [zoomLimit]
  34124. */
  34125. function updateCenterAndZoom(
  34126. view, payload, zoomLimit
  34127. ) {
  34128. var previousZoom = view.getZoom();
  34129. var center = view.getCenter();
  34130. var zoom = payload.zoom;
  34131. var point = view.dataToPoint(center);
  34132. if (payload.dx != null && payload.dy != null) {
  34133. point[0] -= payload.dx;
  34134. point[1] -= payload.dy;
  34135. var center = view.pointToData(point);
  34136. view.setCenter(center);
  34137. }
  34138. if (zoom != null) {
  34139. if (zoomLimit) {
  34140. var zoomMin = zoomLimit.min || 0;
  34141. var zoomMax = zoomLimit.max || Infinity;
  34142. zoom = Math.max(
  34143. Math.min(previousZoom * zoom, zoomMax),
  34144. zoomMin
  34145. ) / previousZoom;
  34146. }
  34147. // Zoom on given point(originX, originY)
  34148. view.scale[0] *= zoom;
  34149. view.scale[1] *= zoom;
  34150. var position = view.position;
  34151. var fixX = (payload.originX - position[0]) * (zoom - 1);
  34152. var fixY = (payload.originY - position[1]) * (zoom - 1);
  34153. position[0] -= fixX;
  34154. position[1] -= fixY;
  34155. view.updateTransform();
  34156. // Get the new center
  34157. var center = view.pointToData(point);
  34158. view.setCenter(center);
  34159. view.setZoom(zoom * previousZoom);
  34160. }
  34161. return {
  34162. center: view.getCenter(),
  34163. zoom: view.getZoom()
  34164. };
  34165. }
  34166. /**
  34167. * @payload
  34168. * @property {string} [componentType=series]
  34169. * @property {number} [dx]
  34170. * @property {number} [dy]
  34171. * @property {number} [zoom]
  34172. * @property {number} [originX]
  34173. * @property {number} [originY]
  34174. */
  34175. registerAction({
  34176. type: 'geoRoam',
  34177. event: 'geoRoam',
  34178. update: 'updateTransform'
  34179. }, function (payload, ecModel) {
  34180. var componentType = payload.componentType || 'series';
  34181. ecModel.eachComponent(
  34182. { mainType: componentType, query: payload },
  34183. function (componentModel) {
  34184. var geo = componentModel.coordinateSystem;
  34185. if (geo.type !== 'geo') {
  34186. return;
  34187. }
  34188. var res = updateCenterAndZoom(
  34189. geo, payload, componentModel.get('scaleLimit')
  34190. );
  34191. componentModel.setCenter
  34192. && componentModel.setCenter(res.center);
  34193. componentModel.setZoom
  34194. && componentModel.setZoom(res.zoom);
  34195. // All map series with same `map` use the same geo coordinate system
  34196. // So the center and zoom must be in sync. Include the series not selected by legend
  34197. if (componentType === 'series') {
  34198. each$1(componentModel.seriesGroup, function (seriesModel) {
  34199. seriesModel.setCenter(res.center);
  34200. seriesModel.setZoom(res.zoom);
  34201. });
  34202. }
  34203. }
  34204. );
  34205. });
  34206. /**
  34207. * Simple view coordinate system
  34208. * Mapping given x, y to transformd view x, y
  34209. */
  34210. var v2ApplyTransform$1 = applyTransform;
  34211. // Dummy transform node
  34212. function TransformDummy() {
  34213. Transformable.call(this);
  34214. }
  34215. mixin(TransformDummy, Transformable);
  34216. function View(name) {
  34217. /**
  34218. * @type {string}
  34219. */
  34220. this.name = name;
  34221. /**
  34222. * @type {Object}
  34223. */
  34224. this.zoomLimit;
  34225. Transformable.call(this);
  34226. this._roamTransformable = new TransformDummy();
  34227. this._rawTransformable = new TransformDummy();
  34228. this._center;
  34229. this._zoom;
  34230. }
  34231. View.prototype = {
  34232. constructor: View,
  34233. type: 'view',
  34234. /**
  34235. * @param {Array.<string>}
  34236. * @readOnly
  34237. */
  34238. dimensions: ['x', 'y'],
  34239. /**
  34240. * Set bounding rect
  34241. * @param {number} x
  34242. * @param {number} y
  34243. * @param {number} width
  34244. * @param {number} height
  34245. */
  34246. // PENDING to getRect
  34247. setBoundingRect: function (x, y, width, height) {
  34248. this._rect = new BoundingRect(x, y, width, height);
  34249. return this._rect;
  34250. },
  34251. /**
  34252. * @return {module:zrender/core/BoundingRect}
  34253. */
  34254. // PENDING to getRect
  34255. getBoundingRect: function () {
  34256. return this._rect;
  34257. },
  34258. /**
  34259. * @param {number} x
  34260. * @param {number} y
  34261. * @param {number} width
  34262. * @param {number} height
  34263. */
  34264. setViewRect: function (x, y, width, height) {
  34265. this.transformTo(x, y, width, height);
  34266. this._viewRect = new BoundingRect(x, y, width, height);
  34267. },
  34268. /**
  34269. * Transformed to particular position and size
  34270. * @param {number} x
  34271. * @param {number} y
  34272. * @param {number} width
  34273. * @param {number} height
  34274. */
  34275. transformTo: function (x, y, width, height) {
  34276. var rect = this.getBoundingRect();
  34277. var rawTransform = this._rawTransformable;
  34278. rawTransform.transform = rect.calculateTransform(
  34279. new BoundingRect(x, y, width, height)
  34280. );
  34281. rawTransform.decomposeTransform();
  34282. this._updateTransform();
  34283. },
  34284. /**
  34285. * Set center of view
  34286. * @param {Array.<number>} [centerCoord]
  34287. */
  34288. setCenter: function (centerCoord) {
  34289. if (!centerCoord) {
  34290. return;
  34291. }
  34292. this._center = centerCoord;
  34293. this._updateCenterAndZoom();
  34294. },
  34295. /**
  34296. * @param {number} zoom
  34297. */
  34298. setZoom: function (zoom) {
  34299. zoom = zoom || 1;
  34300. var zoomLimit = this.zoomLimit;
  34301. if (zoomLimit) {
  34302. if (zoomLimit.max != null) {
  34303. zoom = Math.min(zoomLimit.max, zoom);
  34304. }
  34305. if (zoomLimit.min != null) {
  34306. zoom = Math.max(zoomLimit.min, zoom);
  34307. }
  34308. }
  34309. this._zoom = zoom;
  34310. this._updateCenterAndZoom();
  34311. },
  34312. /**
  34313. * Get default center without roam
  34314. */
  34315. getDefaultCenter: function () {
  34316. // Rect before any transform
  34317. var rawRect = this.getBoundingRect();
  34318. var cx = rawRect.x + rawRect.width / 2;
  34319. var cy = rawRect.y + rawRect.height / 2;
  34320. return [cx, cy];
  34321. },
  34322. getCenter: function () {
  34323. return this._center || this.getDefaultCenter();
  34324. },
  34325. getZoom: function () {
  34326. return this._zoom || 1;
  34327. },
  34328. /**
  34329. * @return {Array.<number}
  34330. */
  34331. getRoamTransform: function () {
  34332. return this._roamTransformable.getLocalTransform();
  34333. },
  34334. /**
  34335. * Remove roam
  34336. */
  34337. _updateCenterAndZoom: function () {
  34338. // Must update after view transform updated
  34339. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  34340. var roamTransform = this._roamTransformable;
  34341. var defaultCenter = this.getDefaultCenter();
  34342. var center = this.getCenter();
  34343. var zoom = this.getZoom();
  34344. center = applyTransform([], center, rawTransformMatrix);
  34345. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  34346. roamTransform.origin = center;
  34347. roamTransform.position = [
  34348. defaultCenter[0] - center[0],
  34349. defaultCenter[1] - center[1]
  34350. ];
  34351. roamTransform.scale = [zoom, zoom];
  34352. this._updateTransform();
  34353. },
  34354. /**
  34355. * Update transform from roam and mapLocation
  34356. * @private
  34357. */
  34358. _updateTransform: function () {
  34359. var roamTransformable = this._roamTransformable;
  34360. var rawTransformable = this._rawTransformable;
  34361. rawTransformable.parent = roamTransformable;
  34362. roamTransformable.updateTransform();
  34363. rawTransformable.updateTransform();
  34364. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  34365. this._rawTransform = rawTransformable.getLocalTransform();
  34366. this.invTransform = this.invTransform || [];
  34367. invert(this.invTransform, this.transform);
  34368. this.decomposeTransform();
  34369. },
  34370. /**
  34371. * @return {module:zrender/core/BoundingRect}
  34372. */
  34373. getViewRect: function () {
  34374. return this._viewRect;
  34375. },
  34376. /**
  34377. * Get view rect after roam transform
  34378. * @return {module:zrender/core/BoundingRect}
  34379. */
  34380. getViewRectAfterRoam: function () {
  34381. var rect = this.getBoundingRect().clone();
  34382. rect.applyTransform(this.transform);
  34383. return rect;
  34384. },
  34385. /**
  34386. * Convert a single (lon, lat) data item to (x, y) point.
  34387. * @param {Array.<number>} data
  34388. * @param {boolean} noRoam
  34389. * @param {Array.<number>} [out]
  34390. * @return {Array.<number>}
  34391. */
  34392. dataToPoint: function (data, noRoam, out) {
  34393. var transform = noRoam ? this._rawTransform : this.transform;
  34394. out = out || [];
  34395. return transform
  34396. ? v2ApplyTransform$1(out, data, transform)
  34397. : copy(out, data);
  34398. },
  34399. /**
  34400. * Convert a (x, y) point to (lon, lat) data
  34401. * @param {Array.<number>} point
  34402. * @return {Array.<number>}
  34403. */
  34404. pointToData: function (point) {
  34405. var invTransform = this.invTransform;
  34406. return invTransform
  34407. ? v2ApplyTransform$1([], point, invTransform)
  34408. : [point[0], point[1]];
  34409. },
  34410. /**
  34411. * @implements
  34412. * see {module:echarts/CoodinateSystem}
  34413. */
  34414. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  34415. /**
  34416. * @implements
  34417. * see {module:echarts/CoodinateSystem}
  34418. */
  34419. convertFromPixel: curry(doConvert$1, 'pointToData'),
  34420. /**
  34421. * @implements
  34422. * see {module:echarts/CoodinateSystem}
  34423. */
  34424. containPoint: function (point) {
  34425. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  34426. }
  34427. /**
  34428. * @return {number}
  34429. */
  34430. // getScalarScale: function () {
  34431. // // Use determinant square root of transform to mutiply scalar
  34432. // var m = this.transform;
  34433. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  34434. // return det;
  34435. // }
  34436. };
  34437. mixin(View, Transformable);
  34438. function doConvert$1(methodName, ecModel, finder, value) {
  34439. var seriesModel = finder.seriesModel;
  34440. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  34441. return coordSys === this ? coordSys[methodName](value) : null;
  34442. }
  34443. // Fix for 南海诸岛
  34444. var geoCoord = [126, 25];
  34445. var points$1 = [
  34446. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  34447. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  34448. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  34449. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  34450. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  34451. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  34452. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  34453. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  34454. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  34455. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  34456. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  34457. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  34458. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  34459. [1,92.4],[1,3.5],[0,3.5]]
  34460. ];
  34461. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  34462. for (var k = 0; k < points$1[i$1].length; k++) {
  34463. points$1[i$1][k][0] /= 10.5;
  34464. points$1[i$1][k][1] /= -10.5 / 0.75;
  34465. points$1[i$1][k][0] += geoCoord[0];
  34466. points$1[i$1][k][1] += geoCoord[1];
  34467. }
  34468. }
  34469. var fixNanhai = function (geo) {
  34470. if (geo.map === 'china') {
  34471. geo.regions.push(new Region(
  34472. '南海诸岛',
  34473. map(points$1, function (exterior) {
  34474. return {
  34475. type: 'polygon',
  34476. exterior: exterior
  34477. };
  34478. }), geoCoord
  34479. ));
  34480. }
  34481. };
  34482. var coordsOffsetMap = {
  34483. '南海诸岛' : [32, 80],
  34484. // 全国
  34485. '广东': [0, -10],
  34486. '香港': [10, 5],
  34487. '澳门': [-10, 10],
  34488. //'北京': [-10, 0],
  34489. '天津': [5, 5]
  34490. };
  34491. var fixTextCoord = function (geo) {
  34492. each$1(geo.regions, function (region) {
  34493. var coordFix = coordsOffsetMap[region.name];
  34494. if (coordFix) {
  34495. var cp = region.center;
  34496. cp[0] += coordFix[0] / 10.5;
  34497. cp[1] += -coordFix[1] / (10.5 / 0.75);
  34498. }
  34499. });
  34500. };
  34501. var geoCoordMap = {
  34502. 'Russia': [100, 60],
  34503. 'United States': [-99, 38],
  34504. 'United States of America': [-99, 38]
  34505. };
  34506. var fixGeoCoord = function (geo) {
  34507. each$1(geo.regions, function (region) {
  34508. var geoCoord = geoCoordMap[region.name];
  34509. if (geoCoord) {
  34510. var cp = region.center;
  34511. cp[0] = geoCoord[0];
  34512. cp[1] = geoCoord[1];
  34513. }
  34514. });
  34515. };
  34516. // Fix for 钓鱼岛
  34517. // var Region = require('../Region');
  34518. // var zrUtil = require('zrender/src/core/util');
  34519. // var geoCoord = [126, 25];
  34520. var points$2 = [
  34521. [
  34522. [123.45165252685547, 25.73527164402261],
  34523. [123.49731445312499, 25.73527164402261],
  34524. [123.49731445312499, 25.750734064600884],
  34525. [123.45165252685547, 25.750734064600884],
  34526. [123.45165252685547, 25.73527164402261]
  34527. ]
  34528. ];
  34529. var fixDiaoyuIsland = function (geo) {
  34530. if (geo.map === 'china') {
  34531. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  34532. if (geo.regions[i].name === '台湾') {
  34533. geo.regions[i].geometries.push({
  34534. type: 'polygon',
  34535. exterior: points$2[0]
  34536. });
  34537. }
  34538. }
  34539. }
  34540. };
  34541. // Geo fix functions
  34542. var geoFixFuncs = [
  34543. fixNanhai,
  34544. fixTextCoord,
  34545. fixGeoCoord,
  34546. fixDiaoyuIsland
  34547. ];
  34548. /**
  34549. * [Geo description]
  34550. * @param {string} name Geo name
  34551. * @param {string} map Map type
  34552. * @param {Object} geoJson
  34553. * @param {Object} [specialAreas]
  34554. * Specify the positioned areas by left, top, width, height
  34555. * @param {Object.<string, string>} [nameMap]
  34556. * Specify name alias
  34557. */
  34558. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  34559. View.call(this, name);
  34560. /**
  34561. * Map type
  34562. * @type {string}
  34563. */
  34564. this.map = map$$1;
  34565. this._nameCoordMap = createHashMap();
  34566. this.loadGeoJson(geoJson, specialAreas, nameMap);
  34567. }
  34568. Geo.prototype = {
  34569. constructor: Geo,
  34570. type: 'geo',
  34571. /**
  34572. * @param {Array.<string>}
  34573. * @readOnly
  34574. */
  34575. dimensions: ['lng', 'lat'],
  34576. /**
  34577. * If contain given lng,lat coord
  34578. * @param {Array.<number>}
  34579. * @readOnly
  34580. */
  34581. containCoord: function (coord) {
  34582. var regions = this.regions;
  34583. for (var i = 0; i < regions.length; i++) {
  34584. if (regions[i].contain(coord)) {
  34585. return true;
  34586. }
  34587. }
  34588. return false;
  34589. },
  34590. /**
  34591. * @param {Object} geoJson
  34592. * @param {Object} [specialAreas]
  34593. * Specify the positioned areas by left, top, width, height
  34594. * @param {Object.<string, string>} [nameMap]
  34595. * Specify name alias
  34596. */
  34597. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  34598. // https://jsperf.com/try-catch-performance-overhead
  34599. try {
  34600. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  34601. }
  34602. catch (e) {
  34603. throw 'Invalid geoJson format\n' + e.message;
  34604. }
  34605. specialAreas = specialAreas || {};
  34606. nameMap = nameMap || {};
  34607. var regions = this.regions;
  34608. var regionsMap = createHashMap();
  34609. for (var i = 0; i < regions.length; i++) {
  34610. var regionName = regions[i].name;
  34611. // Try use the alias in nameMap
  34612. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  34613. regions[i].name = regionName;
  34614. regionsMap.set(regionName, regions[i]);
  34615. // Add geoJson
  34616. this.addGeoCoord(regionName, regions[i].center);
  34617. // Some area like Alaska in USA map needs to be tansformed
  34618. // to look better
  34619. var specialArea = specialAreas[regionName];
  34620. if (specialArea) {
  34621. regions[i].transformTo(
  34622. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  34623. );
  34624. }
  34625. }
  34626. this._regionsMap = regionsMap;
  34627. this._rect = null;
  34628. each$1(geoFixFuncs, function (fixFunc) {
  34629. fixFunc(this);
  34630. }, this);
  34631. },
  34632. // Overwrite
  34633. transformTo: function (x, y, width, height) {
  34634. var rect = this.getBoundingRect();
  34635. rect = rect.clone();
  34636. // Longitute is inverted
  34637. rect.y = -rect.y - rect.height;
  34638. var rawTransformable = this._rawTransformable;
  34639. rawTransformable.transform = rect.calculateTransform(
  34640. new BoundingRect(x, y, width, height)
  34641. );
  34642. rawTransformable.decomposeTransform();
  34643. var scale = rawTransformable.scale;
  34644. scale[1] = -scale[1];
  34645. rawTransformable.updateTransform();
  34646. this._updateTransform();
  34647. },
  34648. /**
  34649. * @param {string} name
  34650. * @return {module:echarts/coord/geo/Region}
  34651. */
  34652. getRegion: function (name) {
  34653. return this._regionsMap.get(name);
  34654. },
  34655. getRegionByCoord: function (coord) {
  34656. var regions = this.regions;
  34657. for (var i = 0; i < regions.length; i++) {
  34658. if (regions[i].contain(coord)) {
  34659. return regions[i];
  34660. }
  34661. }
  34662. },
  34663. /**
  34664. * Add geoCoord for indexing by name
  34665. * @param {string} name
  34666. * @param {Array.<number>} geoCoord
  34667. */
  34668. addGeoCoord: function (name, geoCoord) {
  34669. this._nameCoordMap.set(name, geoCoord);
  34670. },
  34671. /**
  34672. * Get geoCoord by name
  34673. * @param {string} name
  34674. * @return {Array.<number>}
  34675. */
  34676. getGeoCoord: function (name) {
  34677. return this._nameCoordMap.get(name);
  34678. },
  34679. // Overwrite
  34680. getBoundingRect: function () {
  34681. if (this._rect) {
  34682. return this._rect;
  34683. }
  34684. var rect;
  34685. var regions = this.regions;
  34686. for (var i = 0; i < regions.length; i++) {
  34687. var regionRect = regions[i].getBoundingRect();
  34688. rect = rect || regionRect.clone();
  34689. rect.union(regionRect);
  34690. }
  34691. // FIXME Always return new ?
  34692. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  34693. },
  34694. /**
  34695. * @param {string|Array.<number>} data
  34696. * @param {boolean} noRoam
  34697. * @param {Array.<number>} [out]
  34698. * @return {Array.<number>}
  34699. */
  34700. dataToPoint: function (data, noRoam, out) {
  34701. if (typeof data === 'string') {
  34702. // Map area name to geoCoord
  34703. data = this.getGeoCoord(data);
  34704. }
  34705. if (data) {
  34706. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  34707. }
  34708. },
  34709. /**
  34710. * @inheritDoc
  34711. */
  34712. convertToPixel: curry(doConvert, 'dataToPoint'),
  34713. /**
  34714. * @inheritDoc
  34715. */
  34716. convertFromPixel: curry(doConvert, 'pointToData')
  34717. };
  34718. mixin(Geo, View);
  34719. function doConvert(methodName, ecModel, finder, value) {
  34720. var geoModel = finder.geoModel;
  34721. var seriesModel = finder.seriesModel;
  34722. var coordSys = geoModel
  34723. ? geoModel.coordinateSystem
  34724. : seriesModel
  34725. ? (
  34726. seriesModel.coordinateSystem // For map.
  34727. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  34728. )
  34729. : null;
  34730. return coordSys === this ? coordSys[methodName](value) : null;
  34731. }
  34732. /**
  34733. * Resize method bound to the geo
  34734. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  34735. * @param {module:echarts/ExtensionAPI} api
  34736. */
  34737. function resizeGeo(geoModel, api) {
  34738. var boundingCoords = geoModel.get('boundingCoords');
  34739. if (boundingCoords != null) {
  34740. var leftTop = boundingCoords[0];
  34741. var rightBottom = boundingCoords[1];
  34742. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  34743. if (__DEV__) {
  34744. console.error('Invalid boundingCoords');
  34745. }
  34746. }
  34747. else {
  34748. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  34749. }
  34750. }
  34751. var rect = this.getBoundingRect();
  34752. var boxLayoutOption;
  34753. var center = geoModel.get('layoutCenter');
  34754. var size = geoModel.get('layoutSize');
  34755. var viewWidth = api.getWidth();
  34756. var viewHeight = api.getHeight();
  34757. var aspectScale = geoModel.get('aspectScale') || 0.75;
  34758. var aspect = rect.width / rect.height * aspectScale;
  34759. var useCenterAndSize = false;
  34760. if (center && size) {
  34761. center = [
  34762. parsePercent$1(center[0], viewWidth),
  34763. parsePercent$1(center[1], viewHeight)
  34764. ];
  34765. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  34766. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  34767. useCenterAndSize = true;
  34768. }
  34769. else {
  34770. if (__DEV__) {
  34771. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  34772. }
  34773. }
  34774. }
  34775. var viewRect;
  34776. if (useCenterAndSize) {
  34777. var viewRect = {};
  34778. if (aspect > 1) {
  34779. // Width is same with size
  34780. viewRect.width = size;
  34781. viewRect.height = size / aspect;
  34782. }
  34783. else {
  34784. viewRect.height = size;
  34785. viewRect.width = size * aspect;
  34786. }
  34787. viewRect.y = center[1] - viewRect.height / 2;
  34788. viewRect.x = center[0] - viewRect.width / 2;
  34789. }
  34790. else {
  34791. // Use left/top/width/height
  34792. boxLayoutOption = geoModel.getBoxLayoutParams();
  34793. // 0.75 rate
  34794. boxLayoutOption.aspect = aspect;
  34795. viewRect = getLayoutRect(boxLayoutOption, {
  34796. width: viewWidth,
  34797. height: viewHeight
  34798. });
  34799. }
  34800. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  34801. this.setCenter(geoModel.get('center'));
  34802. this.setZoom(geoModel.get('zoom'));
  34803. }
  34804. /**
  34805. * @param {module:echarts/coord/Geo} geo
  34806. * @param {module:echarts/model/Model} model
  34807. * @inner
  34808. */
  34809. function setGeoCoords(geo, model) {
  34810. each$1(model.get('geoCoord'), function (geoCoord, name) {
  34811. geo.addGeoCoord(name, geoCoord);
  34812. });
  34813. }
  34814. if (__DEV__) {
  34815. var mapNotExistsError = function (name) {
  34816. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  34817. };
  34818. }
  34819. var geoCreator = {
  34820. // For deciding which dimensions to use when creating list data
  34821. dimensions: Geo.prototype.dimensions,
  34822. create: function (ecModel, api) {
  34823. var geoList = [];
  34824. // FIXME Create each time may be slow
  34825. ecModel.eachComponent('geo', function (geoModel, idx) {
  34826. var name = geoModel.get('map');
  34827. var mapData = getMap(name);
  34828. if (__DEV__) {
  34829. if (!mapData) {
  34830. mapNotExistsError(name);
  34831. }
  34832. }
  34833. var geo = new Geo(
  34834. name + idx, name,
  34835. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34836. geoModel.get('nameMap')
  34837. );
  34838. geo.zoomLimit = geoModel.get('scaleLimit');
  34839. geoList.push(geo);
  34840. setGeoCoords(geo, geoModel);
  34841. geoModel.coordinateSystem = geo;
  34842. geo.model = geoModel;
  34843. // Inject resize method
  34844. geo.resize = resizeGeo;
  34845. geo.resize(geoModel, api);
  34846. });
  34847. ecModel.eachSeries(function (seriesModel) {
  34848. var coordSys = seriesModel.get('coordinateSystem');
  34849. if (coordSys === 'geo') {
  34850. var geoIndex = seriesModel.get('geoIndex') || 0;
  34851. seriesModel.coordinateSystem = geoList[geoIndex];
  34852. }
  34853. });
  34854. // If has map series
  34855. var mapModelGroupBySeries = {};
  34856. ecModel.eachSeriesByType('map', function (seriesModel) {
  34857. if (!seriesModel.getHostGeoModel()) {
  34858. var mapType = seriesModel.getMapType();
  34859. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  34860. mapModelGroupBySeries[mapType].push(seriesModel);
  34861. }
  34862. });
  34863. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  34864. var mapData = getMap(mapType);
  34865. if (__DEV__) {
  34866. if (!mapData) {
  34867. mapNotExistsError(mapSeries[0].get('map'));
  34868. }
  34869. }
  34870. var nameMapList = map(mapSeries, function (singleMapSeries) {
  34871. return singleMapSeries.get('nameMap');
  34872. });
  34873. var geo = new Geo(
  34874. mapType, mapType,
  34875. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34876. mergeAll(nameMapList)
  34877. );
  34878. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  34879. return singleMapSeries.get('scaleLimit');
  34880. }));
  34881. geoList.push(geo);
  34882. // Inject resize method
  34883. geo.resize = resizeGeo;
  34884. geo.resize(mapSeries[0], api);
  34885. each$1(mapSeries, function (singleMapSeries) {
  34886. singleMapSeries.coordinateSystem = geo;
  34887. setGeoCoords(geo, singleMapSeries);
  34888. });
  34889. });
  34890. return geoList;
  34891. },
  34892. /**
  34893. * Fill given regions array
  34894. * @param {Array.<Object>} originRegionArr
  34895. * @param {string} mapName
  34896. * @param {Object} [nameMap]
  34897. * @return {Array}
  34898. */
  34899. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  34900. // Not use the original
  34901. var regionsArr = (originRegionArr || []).slice();
  34902. nameMap = nameMap || {};
  34903. var map$$1 = getMap(mapName);
  34904. var geoJson = map$$1 && map$$1.geoJson;
  34905. if (!geoJson) {
  34906. if (__DEV__) {
  34907. mapNotExistsError(mapName);
  34908. }
  34909. return originRegionArr;
  34910. }
  34911. var dataNameMap = createHashMap();
  34912. var features = geoJson.features;
  34913. for (var i = 0; i < regionsArr.length; i++) {
  34914. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  34915. }
  34916. for (var i = 0; i < features.length; i++) {
  34917. var name = features[i].properties.name;
  34918. if (!dataNameMap.get(name)) {
  34919. if (nameMap.hasOwnProperty(name)) {
  34920. name = nameMap[name];
  34921. }
  34922. regionsArr.push({
  34923. name: name
  34924. });
  34925. }
  34926. }
  34927. return regionsArr;
  34928. }
  34929. };
  34930. registerCoordinateSystem('geo', geoCreator);
  34931. var mapSymbolLayout = function (ecModel) {
  34932. var processedMapType = {};
  34933. ecModel.eachSeriesByType('map', function (mapSeries) {
  34934. var mapType = mapSeries.getMapType();
  34935. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  34936. return;
  34937. }
  34938. var mapSymbolOffsets = {};
  34939. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  34940. var geo = subMapSeries.coordinateSystem;
  34941. var data = subMapSeries.originalData;
  34942. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  34943. data.each(data.mapDimension('value'), function (value, idx) {
  34944. var name = data.getName(idx);
  34945. var region = geo.getRegion(name);
  34946. // If input series.data is [11, 22, '-'/null/undefined, 44],
  34947. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  34948. // not be drawn. So here must validate if value is NaN.
  34949. if (!region || isNaN(value)) {
  34950. return;
  34951. }
  34952. var offset = mapSymbolOffsets[name] || 0;
  34953. var point = geo.dataToPoint(region.center);
  34954. mapSymbolOffsets[name] = offset + 1;
  34955. data.setItemLayout(idx, {
  34956. point: point,
  34957. offset: offset
  34958. });
  34959. });
  34960. }
  34961. });
  34962. // Show label of those region not has legendSymbol(which is offset 0)
  34963. var data = mapSeries.getData();
  34964. data.each(function (idx) {
  34965. var name = data.getName(idx);
  34966. var layout = data.getItemLayout(idx) || {};
  34967. layout.showLabel = !mapSymbolOffsets[name];
  34968. data.setItemLayout(idx, layout);
  34969. });
  34970. processedMapType[mapType] = true;
  34971. });
  34972. };
  34973. var mapVisual = function (ecModel) {
  34974. ecModel.eachSeriesByType('map', function (seriesModel) {
  34975. var colorList = seriesModel.get('color');
  34976. var itemStyleModel = seriesModel.getModel('itemStyle');
  34977. var areaColor = itemStyleModel.get('areaColor');
  34978. var color = itemStyleModel.get('color')
  34979. || colorList[seriesModel.seriesIndex % colorList.length];
  34980. seriesModel.getData().setVisual({
  34981. 'areaColor': areaColor,
  34982. 'color': color
  34983. });
  34984. });
  34985. };
  34986. // FIXME 公用?
  34987. /**
  34988. * @param {Array.<module:echarts/data/List>} datas
  34989. * @param {string} statisticType 'average' 'sum'
  34990. * @inner
  34991. */
  34992. function dataStatistics(datas, statisticType) {
  34993. var dataNameMap = {};
  34994. each$1(datas, function (data) {
  34995. data.each(data.mapDimension('value'), function (value, idx) {
  34996. // Add prefix to avoid conflict with Object.prototype.
  34997. var mapKey = 'ec-' + data.getName(idx);
  34998. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  34999. if (!isNaN(value)) {
  35000. dataNameMap[mapKey].push(value);
  35001. }
  35002. });
  35003. });
  35004. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  35005. var mapKey = 'ec-' + datas[0].getName(idx);
  35006. var sum = 0;
  35007. var min = Infinity;
  35008. var max = -Infinity;
  35009. var len = dataNameMap[mapKey].length;
  35010. for (var i = 0; i < len; i++) {
  35011. min = Math.min(min, dataNameMap[mapKey][i]);
  35012. max = Math.max(max, dataNameMap[mapKey][i]);
  35013. sum += dataNameMap[mapKey][i];
  35014. }
  35015. var result;
  35016. if (statisticType === 'min') {
  35017. result = min;
  35018. }
  35019. else if (statisticType === 'max') {
  35020. result = max;
  35021. }
  35022. else if (statisticType === 'average') {
  35023. result = sum / len;
  35024. }
  35025. else {
  35026. result = sum;
  35027. }
  35028. return len === 0 ? NaN : result;
  35029. });
  35030. }
  35031. var mapDataStatistic = function (ecModel) {
  35032. var seriesGroups = {};
  35033. ecModel.eachSeriesByType('map', function (seriesModel) {
  35034. var hostGeoModel = seriesModel.getHostGeoModel();
  35035. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  35036. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  35037. });
  35038. each$1(seriesGroups, function (seriesList, key) {
  35039. var data = dataStatistics(
  35040. map(seriesList, function (seriesModel) {
  35041. return seriesModel.getData();
  35042. }),
  35043. seriesList[0].get('mapValueCalculation')
  35044. );
  35045. for (var i = 0; i < seriesList.length; i++) {
  35046. seriesList[i].originalData = seriesList[i].getData();
  35047. }
  35048. // FIXME Put where?
  35049. for (var i = 0; i < seriesList.length; i++) {
  35050. seriesList[i].seriesGroup = seriesList;
  35051. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  35052. seriesList[i].setData(data.cloneShallow());
  35053. seriesList[i].mainSeries = seriesList[0];
  35054. }
  35055. });
  35056. };
  35057. var backwardCompat$2 = function (option) {
  35058. // Save geoCoord
  35059. var mapSeries = [];
  35060. each$1(option.series, function (seriesOpt) {
  35061. if (seriesOpt && seriesOpt.type === 'map') {
  35062. mapSeries.push(seriesOpt);
  35063. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  35064. // Put x, y, width, height, x2, y2 in the top level
  35065. defaults(seriesOpt, seriesOpt.mapLocation);
  35066. }
  35067. });
  35068. };
  35069. registerLayout(mapSymbolLayout);
  35070. registerVisual(mapVisual);
  35071. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  35072. registerPreprocessor(backwardCompat$2);
  35073. createDataSelectAction('map', [{
  35074. type: 'mapToggleSelect',
  35075. event: 'mapselectchanged',
  35076. method: 'toggleSelected'
  35077. }, {
  35078. type: 'mapSelect',
  35079. event: 'mapselected',
  35080. method: 'select'
  35081. }, {
  35082. type: 'mapUnSelect',
  35083. event: 'mapunselected',
  35084. method: 'unSelect'
  35085. }]);
  35086. /**
  35087. * Link lists and struct (graph or tree)
  35088. */
  35089. var each$8 = each$1;
  35090. var DATAS = '\0__link_datas';
  35091. var MAIN_DATA = '\0__link_mainData';
  35092. // Caution:
  35093. // In most case, either list or its shallow clones (see list.cloneShallow)
  35094. // is active in echarts process. So considering heap memory consumption,
  35095. // we do not clone tree or graph, but share them among list and its shallow clones.
  35096. // But in some rare case, we have to keep old list (like do animation in chart). So
  35097. // please take care that both the old list and the new list share the same tree/graph.
  35098. /**
  35099. * @param {Object} opt
  35100. * @param {module:echarts/data/List} opt.mainData
  35101. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  35102. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  35103. * @param {Object} [opt.datas] {dataType: data},
  35104. * like: {node: nodeList, edge: edgeList}.
  35105. * Should contain mainData.
  35106. * @param {Object} [opt.datasAttr] {dataType: attr},
  35107. * designation: struct[datasAttr[dataType]] = list;
  35108. */
  35109. function linkList(opt) {
  35110. var mainData = opt.mainData;
  35111. var datas = opt.datas;
  35112. if (!datas) {
  35113. datas = {main: mainData};
  35114. opt.datasAttr = {main: 'data'};
  35115. }
  35116. opt.datas = opt.mainData = null;
  35117. linkAll(mainData, datas, opt);
  35118. // Porxy data original methods.
  35119. each$8(datas, function (data) {
  35120. each$8(mainData.TRANSFERABLE_METHODS, function (methodName) {
  35121. data.wrapMethod(methodName, curry(transferInjection, opt));
  35122. });
  35123. });
  35124. // Beyond transfer, additional features should be added to `cloneShallow`.
  35125. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  35126. // Only mainData trigger change, because struct.update may trigger
  35127. // another changable methods, which may bring about dead lock.
  35128. each$8(mainData.CHANGABLE_METHODS, function (methodName) {
  35129. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  35130. });
  35131. // Make sure datas contains mainData.
  35132. assert$1(datas[mainData.dataType] === mainData);
  35133. }
  35134. function transferInjection(opt, res) {
  35135. if (isMainData(this)) {
  35136. // Transfer datas to new main data.
  35137. var datas = extend({}, this[DATAS]);
  35138. datas[this.dataType] = res;
  35139. linkAll(res, datas, opt);
  35140. }
  35141. else {
  35142. // Modify the reference in main data to point newData.
  35143. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  35144. }
  35145. return res;
  35146. }
  35147. function changeInjection(opt, res) {
  35148. opt.struct && opt.struct.update(this);
  35149. return res;
  35150. }
  35151. function cloneShallowInjection(opt, res) {
  35152. // cloneShallow, which brings about some fragilities, may be inappropriate
  35153. // to be exposed as an API. So for implementation simplicity we can make
  35154. // the restriction that cloneShallow of not-mainData should not be invoked
  35155. // outside, but only be invoked here.
  35156. each$8(res[DATAS], function (data, dataType) {
  35157. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  35158. });
  35159. return res;
  35160. }
  35161. /**
  35162. * Supplement method to List.
  35163. *
  35164. * @public
  35165. * @param {string} [dataType] If not specified, return mainData.
  35166. * @return {module:echarts/data/List}
  35167. */
  35168. function getLinkedData(dataType) {
  35169. var mainData = this[MAIN_DATA];
  35170. return (dataType == null || mainData == null)
  35171. ? mainData
  35172. : mainData[DATAS][dataType];
  35173. }
  35174. function isMainData(data) {
  35175. return data[MAIN_DATA] === data;
  35176. }
  35177. function linkAll(mainData, datas, opt) {
  35178. mainData[DATAS] = {};
  35179. each$8(datas, function (data, dataType) {
  35180. linkSingle(data, dataType, mainData, opt);
  35181. });
  35182. }
  35183. function linkSingle(data, dataType, mainData, opt) {
  35184. mainData[DATAS][dataType] = data;
  35185. data[MAIN_DATA] = mainData;
  35186. data.dataType = dataType;
  35187. if (opt.struct) {
  35188. data[opt.structAttr] = opt.struct;
  35189. opt.struct[opt.datasAttr[dataType]] = data;
  35190. }
  35191. // Supplement method.
  35192. data.getLinkedData = getLinkedData;
  35193. }
  35194. /**
  35195. * Tree data structure
  35196. *
  35197. * @module echarts/data/Tree
  35198. */
  35199. /**
  35200. * @constructor module:echarts/data/Tree~TreeNode
  35201. * @param {string} name
  35202. * @param {module:echarts/data/Tree} hostTree
  35203. */
  35204. var TreeNode = function (name, hostTree) {
  35205. /**
  35206. * @type {string}
  35207. */
  35208. this.name = name || '';
  35209. /**
  35210. * Depth of node
  35211. *
  35212. * @type {number}
  35213. * @readOnly
  35214. */
  35215. this.depth = 0;
  35216. /**
  35217. * Height of the subtree rooted at this node.
  35218. * @type {number}
  35219. * @readOnly
  35220. */
  35221. this.height = 0;
  35222. /**
  35223. * @type {module:echarts/data/Tree~TreeNode}
  35224. * @readOnly
  35225. */
  35226. this.parentNode = null;
  35227. /**
  35228. * Reference to list item.
  35229. * Do not persistent dataIndex outside,
  35230. * besause it may be changed by list.
  35231. * If dataIndex -1,
  35232. * this node is logical deleted (filtered) in list.
  35233. *
  35234. * @type {Object}
  35235. * @readOnly
  35236. */
  35237. this.dataIndex = -1;
  35238. /**
  35239. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  35240. * @readOnly
  35241. */
  35242. this.children = [];
  35243. /**
  35244. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  35245. * @pubilc
  35246. */
  35247. this.viewChildren = [];
  35248. /**
  35249. * @type {moduel:echarts/data/Tree}
  35250. * @readOnly
  35251. */
  35252. this.hostTree = hostTree;
  35253. };
  35254. TreeNode.prototype = {
  35255. constructor: TreeNode,
  35256. /**
  35257. * The node is removed.
  35258. * @return {boolean} is removed.
  35259. */
  35260. isRemoved: function () {
  35261. return this.dataIndex < 0;
  35262. },
  35263. /**
  35264. * Travel this subtree (include this node).
  35265. * Usage:
  35266. * node.eachNode(function () { ... }); // preorder
  35267. * node.eachNode('preorder', function () { ... }); // preorder
  35268. * node.eachNode('postorder', function () { ... }); // postorder
  35269. * node.eachNode(
  35270. * {order: 'postorder', attr: 'viewChildren'},
  35271. * function () { ... }
  35272. * ); // postorder
  35273. *
  35274. * @param {(Object|string)} options If string, means order.
  35275. * @param {string=} options.order 'preorder' or 'postorder'
  35276. * @param {string=} options.attr 'children' or 'viewChildren'
  35277. * @param {Function} cb If in preorder and return false,
  35278. * its subtree will not be visited.
  35279. * @param {Object} [context]
  35280. */
  35281. eachNode: function (options, cb, context) {
  35282. if (typeof options === 'function') {
  35283. context = cb;
  35284. cb = options;
  35285. options = null;
  35286. }
  35287. options = options || {};
  35288. if (isString(options)) {
  35289. options = {order: options};
  35290. }
  35291. var order = options.order || 'preorder';
  35292. var children = this[options.attr || 'children'];
  35293. var suppressVisitSub;
  35294. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  35295. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  35296. children[i].eachNode(options, cb, context);
  35297. }
  35298. order === 'postorder' && cb.call(context, this);
  35299. },
  35300. /**
  35301. * Update depth and height of this subtree.
  35302. *
  35303. * @param {number} depth
  35304. */
  35305. updateDepthAndHeight: function (depth) {
  35306. var height = 0;
  35307. this.depth = depth;
  35308. for (var i = 0; i < this.children.length; i++) {
  35309. var child = this.children[i];
  35310. child.updateDepthAndHeight(depth + 1);
  35311. if (child.height > height) {
  35312. height = child.height;
  35313. }
  35314. }
  35315. this.height = height + 1;
  35316. },
  35317. /**
  35318. * @param {string} id
  35319. * @return {module:echarts/data/Tree~TreeNode}
  35320. */
  35321. getNodeById: function (id) {
  35322. if (this.getId() === id) {
  35323. return this;
  35324. }
  35325. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  35326. var res = children[i].getNodeById(id);
  35327. if (res) {
  35328. return res;
  35329. }
  35330. }
  35331. },
  35332. /**
  35333. * @param {module:echarts/data/Tree~TreeNode} node
  35334. * @return {boolean}
  35335. */
  35336. contains: function (node) {
  35337. if (node === this) {
  35338. return true;
  35339. }
  35340. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  35341. var res = children[i].contains(node);
  35342. if (res) {
  35343. return res;
  35344. }
  35345. }
  35346. },
  35347. /**
  35348. * @param {boolean} includeSelf Default false.
  35349. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  35350. */
  35351. getAncestors: function (includeSelf) {
  35352. var ancestors = [];
  35353. var node = includeSelf ? this : this.parentNode;
  35354. while (node) {
  35355. ancestors.push(node);
  35356. node = node.parentNode;
  35357. }
  35358. ancestors.reverse();
  35359. return ancestors;
  35360. },
  35361. /**
  35362. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  35363. * @return {number} Value.
  35364. */
  35365. getValue: function (dimension) {
  35366. var data = this.hostTree.data;
  35367. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  35368. },
  35369. /**
  35370. * @param {Object} layout
  35371. * @param {boolean=} [merge=false]
  35372. */
  35373. setLayout: function (layout, merge$$1) {
  35374. this.dataIndex >= 0
  35375. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  35376. },
  35377. /**
  35378. * @return {Object} layout
  35379. */
  35380. getLayout: function () {
  35381. return this.hostTree.data.getItemLayout(this.dataIndex);
  35382. },
  35383. /**
  35384. * @param {string} [path]
  35385. * @return {module:echarts/model/Model}
  35386. */
  35387. getModel: function (path) {
  35388. if (this.dataIndex < 0) {
  35389. return;
  35390. }
  35391. var hostTree = this.hostTree;
  35392. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  35393. var levelModel = this.getLevelModel();
  35394. var leavesModel;
  35395. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  35396. leavesModel = this.getLeavesModel();
  35397. }
  35398. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  35399. },
  35400. /**
  35401. * @return {module:echarts/model/Model}
  35402. */
  35403. getLevelModel: function () {
  35404. return (this.hostTree.levelModels || [])[this.depth];
  35405. },
  35406. /**
  35407. * @return {module:echarts/model/Model}
  35408. */
  35409. getLeavesModel: function () {
  35410. return this.hostTree.leavesModel;
  35411. },
  35412. /**
  35413. * @example
  35414. * setItemVisual('color', color);
  35415. * setItemVisual({
  35416. * 'color': color
  35417. * });
  35418. */
  35419. setVisual: function (key, value) {
  35420. this.dataIndex >= 0
  35421. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  35422. },
  35423. /**
  35424. * Get item visual
  35425. */
  35426. getVisual: function (key, ignoreParent) {
  35427. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  35428. },
  35429. /**
  35430. * @public
  35431. * @return {number}
  35432. */
  35433. getRawIndex: function () {
  35434. return this.hostTree.data.getRawIndex(this.dataIndex);
  35435. },
  35436. /**
  35437. * @public
  35438. * @return {string}
  35439. */
  35440. getId: function () {
  35441. return this.hostTree.data.getId(this.dataIndex);
  35442. },
  35443. /**
  35444. * if this is an ancestor of another node
  35445. *
  35446. * @public
  35447. * @param {TreeNode} node another node
  35448. * @return {boolean} if is ancestor
  35449. */
  35450. isAncestorOf: function (node) {
  35451. var parent = node.parentNode;
  35452. while (parent) {
  35453. if (parent === this) {
  35454. return true;
  35455. }
  35456. parent = parent.parentNode;
  35457. }
  35458. return false;
  35459. },
  35460. /**
  35461. * if this is an descendant of another node
  35462. *
  35463. * @public
  35464. * @param {TreeNode} node another node
  35465. * @return {boolean} if is descendant
  35466. */
  35467. isDescendantOf: function (node) {
  35468. return node !== this && node.isAncestorOf(this);
  35469. }
  35470. };
  35471. /**
  35472. * @constructor
  35473. * @alias module:echarts/data/Tree
  35474. * @param {module:echarts/model/Model} hostModel
  35475. * @param {Array.<Object>} levelOptions
  35476. * @param {Object} leavesOption
  35477. */
  35478. function Tree(hostModel, levelOptions, leavesOption) {
  35479. /**
  35480. * @type {module:echarts/data/Tree~TreeNode}
  35481. * @readOnly
  35482. */
  35483. this.root;
  35484. /**
  35485. * @type {module:echarts/data/List}
  35486. * @readOnly
  35487. */
  35488. this.data;
  35489. /**
  35490. * Index of each item is the same as the raw index of coresponding list item.
  35491. * @private
  35492. * @type {Array.<module:echarts/data/Tree~TreeNode}
  35493. */
  35494. this._nodes = [];
  35495. /**
  35496. * @private
  35497. * @readOnly
  35498. * @type {module:echarts/model/Model}
  35499. */
  35500. this.hostModel = hostModel;
  35501. /**
  35502. * @private
  35503. * @readOnly
  35504. * @type {Array.<module:echarts/model/Model}
  35505. */
  35506. this.levelModels = map(levelOptions || [], function (levelDefine) {
  35507. return new Model(levelDefine, hostModel, hostModel.ecModel);
  35508. });
  35509. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  35510. }
  35511. Tree.prototype = {
  35512. constructor: Tree,
  35513. type: 'tree',
  35514. /**
  35515. * Travel this subtree (include this node).
  35516. * Usage:
  35517. * node.eachNode(function () { ... }); // preorder
  35518. * node.eachNode('preorder', function () { ... }); // preorder
  35519. * node.eachNode('postorder', function () { ... }); // postorder
  35520. * node.eachNode(
  35521. * {order: 'postorder', attr: 'viewChildren'},
  35522. * function () { ... }
  35523. * ); // postorder
  35524. *
  35525. * @param {(Object|string)} options If string, means order.
  35526. * @param {string=} options.order 'preorder' or 'postorder'
  35527. * @param {string=} options.attr 'children' or 'viewChildren'
  35528. * @param {Function} cb
  35529. * @param {Object} [context]
  35530. */
  35531. eachNode: function(options, cb, context) {
  35532. this.root.eachNode(options, cb, context);
  35533. },
  35534. /**
  35535. * @param {number} dataIndex
  35536. * @return {module:echarts/data/Tree~TreeNode}
  35537. */
  35538. getNodeByDataIndex: function (dataIndex) {
  35539. var rawIndex = this.data.getRawIndex(dataIndex);
  35540. return this._nodes[rawIndex];
  35541. },
  35542. /**
  35543. * @param {string} name
  35544. * @return {module:echarts/data/Tree~TreeNode}
  35545. */
  35546. getNodeByName: function (name) {
  35547. return this.root.getNodeByName(name);
  35548. },
  35549. /**
  35550. * Update item available by list,
  35551. * when list has been performed options like 'filterSelf' or 'map'.
  35552. */
  35553. update: function () {
  35554. var data = this.data;
  35555. var nodes = this._nodes;
  35556. for (var i = 0, len = nodes.length; i < len; i++) {
  35557. nodes[i].dataIndex = -1;
  35558. }
  35559. for (var i = 0, len = data.count(); i < len; i++) {
  35560. nodes[data.getRawIndex(i)].dataIndex = i;
  35561. }
  35562. },
  35563. /**
  35564. * Clear all layouts
  35565. */
  35566. clearLayouts: function () {
  35567. this.data.clearItemLayouts();
  35568. }
  35569. };
  35570. /**
  35571. * data node format:
  35572. * {
  35573. * name: ...
  35574. * value: ...
  35575. * children: [
  35576. * {
  35577. * name: ...
  35578. * value: ...
  35579. * children: ...
  35580. * },
  35581. * ...
  35582. * ]
  35583. * }
  35584. *
  35585. * @static
  35586. * @param {Object} dataRoot Root node.
  35587. * @param {module:echarts/model/Model} hostModel
  35588. * @param {Object} treeOptions
  35589. * @param {Array.<Object>} treeOptions.levels
  35590. * @param {Array.<Object>} treeOptions.leaves
  35591. * @return module:echarts/data/Tree
  35592. */
  35593. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  35594. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  35595. var listData = [];
  35596. var dimMax = 1;
  35597. buildHierarchy(dataRoot);
  35598. function buildHierarchy(dataNode, parentNode) {
  35599. var value = dataNode.value;
  35600. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  35601. listData.push(dataNode);
  35602. var node = new TreeNode(dataNode.name, tree);
  35603. parentNode
  35604. ? addChild(node, parentNode)
  35605. : (tree.root = node);
  35606. tree._nodes.push(node);
  35607. var children = dataNode.children;
  35608. if (children) {
  35609. for (var i = 0; i < children.length; i++) {
  35610. buildHierarchy(children[i], node);
  35611. }
  35612. }
  35613. }
  35614. tree.root.updateDepthAndHeight(0);
  35615. var dimensionsInfo = createDimensions(listData, {
  35616. coordDimensions: ['value'],
  35617. dimensionsCount: dimMax
  35618. });
  35619. var list = new List(dimensionsInfo, hostModel);
  35620. list.initData(listData);
  35621. linkList({
  35622. mainData: list,
  35623. struct: tree,
  35624. structAttr: 'tree'
  35625. });
  35626. tree.update();
  35627. return tree;
  35628. };
  35629. /**
  35630. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  35631. * so this function is not ready and not necessary to be public.
  35632. *
  35633. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  35634. */
  35635. function addChild(child, node) {
  35636. var children = node.children;
  35637. if (child.parentNode === node) {
  35638. return;
  35639. }
  35640. children.push(child);
  35641. child.parentNode = node;
  35642. }
  35643. /**
  35644. * @file Create data struct and define tree view's series model
  35645. */
  35646. SeriesModel.extend({
  35647. type: 'series.tree',
  35648. layoutInfo: null,
  35649. // can support the position parameters 'left', 'top','right','bottom', 'width',
  35650. // 'height' in the setOption() with 'merge' mode normal.
  35651. layoutMode: 'box',
  35652. /**
  35653. * Init a tree data structure from data in option series
  35654. * @param {Object} option the object used to config echarts view
  35655. * @return {module:echarts/data/List} storage initial data
  35656. */
  35657. getInitialData: function (option) {
  35658. //create an virtual root
  35659. var root = {name: option.name, children: option.data};
  35660. var leaves = option.leaves || {};
  35661. var treeOption = {};
  35662. treeOption.leaves = leaves;
  35663. var tree = Tree.createTree(root, this, treeOption);
  35664. var treeDepth = 0;
  35665. tree.eachNode('preorder', function (node) {
  35666. if (node.depth > treeDepth) {
  35667. treeDepth = node.depth;
  35668. }
  35669. });
  35670. var expandAndCollapse = option.expandAndCollapse;
  35671. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  35672. ? option.initialTreeDepth : treeDepth;
  35673. tree.root.eachNode('preorder', function (node) {
  35674. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  35675. node.isExpand = (item && item.collapsed != null)
  35676. ? !item.collapsed
  35677. : node.depth <= expandTreeDepth;
  35678. });
  35679. return tree.data;
  35680. },
  35681. /**
  35682. * @override
  35683. * @param {number} dataIndex
  35684. */
  35685. formatTooltip: function (dataIndex) {
  35686. var tree = this.getData().tree;
  35687. var realRoot = tree.root.children[0];
  35688. var node = tree.getNodeByDataIndex(dataIndex);
  35689. var value = node.getValue();
  35690. var name = node.name;
  35691. while (node && (node !== realRoot)) {
  35692. name = node.parentNode.name + '.' + name;
  35693. node = node.parentNode;
  35694. }
  35695. return encodeHTML(name + (
  35696. (isNaN(value) || value == null) ? '' : ' : ' + value
  35697. ));
  35698. },
  35699. defaultOption: {
  35700. zlevel: 0,
  35701. z: 2,
  35702. // the position of the whole view
  35703. left: '12%',
  35704. top: '12%',
  35705. right: '12%',
  35706. bottom: '12%',
  35707. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  35708. layout: 'orthogonal',
  35709. // the orient of orthoginal layout, can be setted to 'horizontal' or 'vertical'
  35710. orient: 'horizontal',
  35711. symbol: 'emptyCircle',
  35712. symbolSize: 7,
  35713. expandAndCollapse: true,
  35714. initialTreeDepth: 2,
  35715. lineStyle: {
  35716. color: '#ccc',
  35717. width: 1.5,
  35718. curveness: 0.5
  35719. },
  35720. itemStyle: {
  35721. color: 'lightsteelblue',
  35722. borderColor: '#c23531',
  35723. borderWidth: 1.5
  35724. },
  35725. label: {
  35726. show: true,
  35727. color: '#555'
  35728. },
  35729. leaves: {
  35730. label: {
  35731. show: true
  35732. }
  35733. },
  35734. animationEasing: 'linear',
  35735. animationDuration: 700,
  35736. animationDurationUpdate: 1000
  35737. }
  35738. });
  35739. /**
  35740. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  35741. * the tree.
  35742. * @see https://github.com/d3/d3-hierarchy
  35743. */
  35744. /**
  35745. * Initialize all computational message for following algorithm
  35746. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  35747. */
  35748. function init$2(root) {
  35749. root.hierNode = {
  35750. defaultAncestor: null,
  35751. ancestor: root,
  35752. prelim: 0,
  35753. modifier: 0,
  35754. change: 0,
  35755. shift: 0,
  35756. i: 0,
  35757. thread: null
  35758. };
  35759. var nodes = [root];
  35760. var node;
  35761. var children;
  35762. while (node = nodes.pop()) { // jshint ignore:line
  35763. children = node.children;
  35764. if (node.isExpand && children.length) {
  35765. var n = children.length;
  35766. for (var i = n - 1; i >= 0; i--) {
  35767. var child = children[i];
  35768. child.hierNode = {
  35769. defaultAncestor: null,
  35770. ancestor: child,
  35771. prelim: 0,
  35772. modifier: 0,
  35773. change: 0,
  35774. shift: 0,
  35775. i: i,
  35776. thread: null
  35777. };
  35778. nodes.push(child);
  35779. }
  35780. }
  35781. }
  35782. }
  35783. /**
  35784. * Computes a preliminary x coordinate for node. Before that, this function is
  35785. * applied recursively to the children of node, as well as the function
  35786. * apportion(). After spacing out the children by calling executeShifts(), the
  35787. * node is placed to the midpoint of its outermost children.
  35788. * @param {module:echarts/data/Tree~TreeNode} node
  35789. * @param {Function} separation
  35790. */
  35791. function firstWalk(node, separation) {
  35792. var children = node.isExpand ? node.children : [];
  35793. var siblings = node.parentNode.children;
  35794. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  35795. if (children.length) {
  35796. executeShifts(node);
  35797. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  35798. if (subtreeW) {
  35799. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  35800. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  35801. }
  35802. else {
  35803. node.hierNode.prelim = midPoint;
  35804. }
  35805. }
  35806. else if (subtreeW) {
  35807. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  35808. }
  35809. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  35810. }
  35811. /**
  35812. * Computes all real x-coordinates by summing up the modifiers recursively.
  35813. * @param {module:echarts/data/Tree~TreeNode} node
  35814. */
  35815. function secondWalk(node) {
  35816. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  35817. node.setLayout({x: nodeX}, true);
  35818. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  35819. }
  35820. function separation(cb) {
  35821. return arguments.length ? cb : defaultSeparation;
  35822. }
  35823. /**
  35824. * Transform the common coordinate to radial coordinate
  35825. * @param {number} x
  35826. * @param {number} y
  35827. * @return {Object}
  35828. */
  35829. function radialCoordinate(x, y) {
  35830. var radialCoor = {};
  35831. x -= Math.PI / 2;
  35832. radialCoor.x = y * Math.cos(x);
  35833. radialCoor.y = y * Math.sin(x);
  35834. return radialCoor;
  35835. }
  35836. /**
  35837. * Get the layout position of the whole view
  35838. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  35839. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  35840. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  35841. */
  35842. function getViewRect(seriesModel, api) {
  35843. return getLayoutRect(
  35844. seriesModel.getBoxLayoutParams(), {
  35845. width: api.getWidth(),
  35846. height: api.getHeight()
  35847. }
  35848. );
  35849. }
  35850. /**
  35851. * All other shifts, applied to the smaller subtrees between w- and w+, are
  35852. * performed by this function.
  35853. * @param {module:echarts/data/Tree~TreeNode} node
  35854. */
  35855. function executeShifts(node) {
  35856. var children = node.children;
  35857. var n = children.length;
  35858. var shift = 0;
  35859. var change = 0;
  35860. while (--n >= 0) {
  35861. var child = children[n];
  35862. child.hierNode.prelim += shift;
  35863. child.hierNode.modifier += shift;
  35864. change += child.hierNode.change;
  35865. shift += child.hierNode.shift + change;
  35866. }
  35867. }
  35868. /**
  35869. * The core of the algorithm. Here, a new subtree is combined with the
  35870. * previous subtrees. Threads are used to traverse the inside and outside
  35871. * contours of the left and right subtree up to the highest common level.
  35872. * Whenever two nodes of the inside contours conflict, we compute the left
  35873. * one of the greatest uncommon ancestors using the function nextAncestor()
  35874. * and call moveSubtree() to shift the subtree and prepare the shifts of
  35875. * smaller subtrees. Finally, we add a new thread (if necessary).
  35876. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  35877. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  35878. * @param {module:echarts/data/Tree~TreeNode} ancestor
  35879. * @param {Function} separation
  35880. * @return {module:echarts/data/Tree~TreeNode}
  35881. */
  35882. function apportion(subtreeV, subtreeW, ancestor, separation) {
  35883. if (subtreeW) {
  35884. var nodeOutRight = subtreeV;
  35885. var nodeInRight = subtreeV;
  35886. var nodeOutLeft = nodeInRight.parentNode.children[0];
  35887. var nodeInLeft = subtreeW;
  35888. var sumOutRight = nodeOutRight.hierNode.modifier;
  35889. var sumInRight = nodeInRight.hierNode.modifier;
  35890. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  35891. var sumInLeft = nodeInLeft.hierNode.modifier;
  35892. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  35893. nodeOutRight = nextRight(nodeOutRight);
  35894. nodeOutLeft = nextLeft(nodeOutLeft);
  35895. nodeOutRight.hierNode.ancestor = subtreeV;
  35896. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  35897. - sumInRight + separation(nodeInLeft, nodeInRight);
  35898. if (shift > 0) {
  35899. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  35900. sumInRight += shift;
  35901. sumOutRight += shift;
  35902. }
  35903. sumInLeft += nodeInLeft.hierNode.modifier;
  35904. sumInRight += nodeInRight.hierNode.modifier;
  35905. sumOutRight += nodeOutRight.hierNode.modifier;
  35906. sumOutLeft += nodeOutLeft.hierNode.modifier;
  35907. }
  35908. if (nodeInLeft && !nextRight(nodeOutRight)) {
  35909. nodeOutRight.hierNode.thread = nodeInLeft;
  35910. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  35911. }
  35912. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  35913. nodeOutLeft.hierNode.thread = nodeInRight;
  35914. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  35915. ancestor = subtreeV;
  35916. }
  35917. }
  35918. return ancestor;
  35919. }
  35920. /**
  35921. * This function is used to traverse the right contour of a subtree.
  35922. * It returns the rightmost child of node or the thread of node. The function
  35923. * returns null if and only if node is on the highest depth of its subtree.
  35924. * @param {module:echarts/data/Tree~TreeNode} node
  35925. * @return {module:echarts/data/Tree~TreeNode}
  35926. */
  35927. function nextRight(node) {
  35928. var children = node.children;
  35929. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  35930. }
  35931. /**
  35932. * This function is used to traverse the left contour of a subtree (or a subforest).
  35933. * It returns the leftmost child of node or the thread of node. The function
  35934. * returns null if and only if node is on the highest depth of its subtree.
  35935. * @param {module:echarts/data/Tree~TreeNode} node
  35936. * @return {module:echarts/data/Tree~TreeNode}
  35937. */
  35938. function nextLeft(node) {
  35939. var children = node.children;
  35940. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  35941. }
  35942. /**
  35943. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  35944. * Otherwise, returns the specified ancestor.
  35945. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  35946. * @param {module:echarts/data/Tree~TreeNode} node
  35947. * @param {module:echarts/data/Tree~TreeNode} ancestor
  35948. * @return {module:echarts/data/Tree~TreeNode}
  35949. */
  35950. function nextAncestor(nodeInLeft, node, ancestor) {
  35951. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  35952. ? nodeInLeft.hierNode.ancestor : ancestor;
  35953. }
  35954. /**
  35955. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  35956. * @param {module:echarts/data/Tree~TreeNode} wl
  35957. * @param {module:echarts/data/Tree~TreeNode} wr
  35958. * @param {number} shift [description]
  35959. */
  35960. function moveSubtree(wl, wr,shift) {
  35961. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  35962. wr.hierNode.change -= change;
  35963. wr.hierNode.shift += shift;
  35964. wr.hierNode.modifier += shift;
  35965. wr.hierNode.prelim += shift;
  35966. wl.hierNode.change += change;
  35967. }
  35968. function defaultSeparation(node1, node2) {
  35969. return node1.parentNode === node2.parentNode ? 1 : 2;
  35970. }
  35971. /**
  35972. * @file This file used to draw tree view
  35973. */
  35974. extendChartView({
  35975. type: 'tree',
  35976. /**
  35977. * Init the chart
  35978. * @override
  35979. * @param {module:echarts/model/Global} ecModel
  35980. * @param {module:echarts/ExtensionAPI} api
  35981. */
  35982. init: function (ecModel, api) {
  35983. /**
  35984. * @private
  35985. * @type {module:echarts/data/Tree}
  35986. */
  35987. this._oldTree;
  35988. /**
  35989. * @private
  35990. * @type {module:zrender/container/Group}
  35991. */
  35992. this._mainGroup = new Group();
  35993. this.group.add(this._mainGroup);
  35994. },
  35995. render: function (seriesModel, ecModel, api, payload) {
  35996. var data = seriesModel.getData();
  35997. var layoutInfo = seriesModel.layoutInfo;
  35998. var group = this._mainGroup;
  35999. var layout = seriesModel.get('layout');
  36000. if (layout === 'radial') {
  36001. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  36002. }
  36003. else {
  36004. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  36005. }
  36006. var oldData = this._data;
  36007. var seriesScope = {
  36008. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  36009. layout: layout,
  36010. orient: seriesModel.get('orient'),
  36011. curvature: seriesModel.get('lineStyle.curveness'),
  36012. symbolRotate: seriesModel.get('symbolRotate'),
  36013. symbolOffset: seriesModel.get('symbolOffset'),
  36014. hoverAnimation: seriesModel.get('hoverAnimation'),
  36015. useNameLabel: true,
  36016. fadeIn: true
  36017. };
  36018. data.diff(oldData)
  36019. .add(function (newIdx) {
  36020. if (symbolNeedsDraw$1(data, newIdx)) {
  36021. // create node and edge
  36022. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  36023. }
  36024. })
  36025. .update(function (newIdx, oldIdx) {
  36026. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36027. if (!symbolNeedsDraw$1(data, newIdx)) {
  36028. symbolEl && removeNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36029. return;
  36030. }
  36031. // update node and edge
  36032. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36033. })
  36034. .remove(function (oldIdx) {
  36035. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36036. removeNode(data, oldIdx, symbolEl, group, seriesModel, seriesScope);
  36037. })
  36038. .execute();
  36039. if (seriesScope.expandAndCollapse === true) {
  36040. data.eachItemGraphicEl(function (el, dataIndex) {
  36041. el.off('click').on('click', function () {
  36042. api.dispatchAction({
  36043. type: 'treeExpandAndCollapse',
  36044. seriesId: seriesModel.id,
  36045. dataIndex: dataIndex
  36046. });
  36047. });
  36048. });
  36049. }
  36050. this._data = data;
  36051. },
  36052. dispose: function () {},
  36053. remove: function () {
  36054. this._mainGroup.removeAll();
  36055. this._data = null;
  36056. }
  36057. });
  36058. function symbolNeedsDraw$1(data, dataIndex) {
  36059. var layout = data.getItemLayout(dataIndex);
  36060. return layout
  36061. && !isNaN(layout.x) && !isNaN(layout.y)
  36062. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  36063. }
  36064. function getTreeNodeStyle(node, itemModel, seriesScope) {
  36065. seriesScope.itemModel = itemModel;
  36066. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  36067. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36068. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  36069. seriesScope.labelModel = itemModel.getModel('label');
  36070. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  36071. if (node.isExpand === false && node.children.length !== 0) {
  36072. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  36073. }
  36074. else {
  36075. seriesScope.symbolInnerColor = '#fff';
  36076. }
  36077. return seriesScope;
  36078. }
  36079. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36080. var isInit = !symbolEl;
  36081. var node = data.tree.getNodeByDataIndex(dataIndex);
  36082. var itemModel = node.getModel();
  36083. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36084. var virtualRoot = data.tree.root;
  36085. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36086. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  36087. var sourceLayout = source.getLayout();
  36088. var sourceOldLayout = sourceSymbolEl
  36089. ? {
  36090. x: sourceSymbolEl.position[0],
  36091. y: sourceSymbolEl.position[1],
  36092. rawX: sourceSymbolEl.__radialOldRawX,
  36093. rawY: sourceSymbolEl.__radialOldRawY
  36094. }
  36095. : sourceLayout;
  36096. var targetLayout = node.getLayout();
  36097. if (isInit) {
  36098. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  36099. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  36100. }
  36101. else {
  36102. symbolEl.updateData(data, dataIndex, seriesScope);
  36103. }
  36104. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  36105. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  36106. symbolEl.__radialRawX = targetLayout.rawX;
  36107. symbolEl.__radialRawY = targetLayout.rawY;
  36108. group.add(symbolEl);
  36109. data.setItemGraphicEl(dataIndex, symbolEl);
  36110. updateProps(symbolEl, {
  36111. position: [targetLayout.x, targetLayout.y]
  36112. }, seriesModel);
  36113. var symbolPath = symbolEl.getSymbolPath();
  36114. if (seriesScope.layout === 'radial') {
  36115. var realRoot = virtualRoot.children[0];
  36116. var rootLayout = realRoot.getLayout();
  36117. var length = realRoot.children.length;
  36118. var rad;
  36119. var isLeft;
  36120. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  36121. var center = {};
  36122. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  36123. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  36124. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  36125. if (rad < 0) {
  36126. rad = Math.PI * 2 + rad;
  36127. }
  36128. isLeft = center.x < rootLayout.x;
  36129. if (isLeft) {
  36130. rad = rad - Math.PI;
  36131. }
  36132. }
  36133. else {
  36134. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  36135. if (rad < 0) {
  36136. rad = Math.PI * 2 + rad;
  36137. }
  36138. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  36139. isLeft = targetLayout.x < rootLayout.x;
  36140. if (isLeft) {
  36141. rad = rad - Math.PI;
  36142. }
  36143. }
  36144. else {
  36145. isLeft = targetLayout.x > rootLayout.x;
  36146. if (!isLeft) {
  36147. rad = rad - Math.PI;
  36148. }
  36149. }
  36150. }
  36151. var textPosition = isLeft ? 'left' : 'right';
  36152. symbolPath.setStyle({
  36153. textPosition: textPosition,
  36154. textRotation: -rad,
  36155. textOrigin: 'center',
  36156. verticalAlign: 'middle'
  36157. });
  36158. }
  36159. if (node.parentNode && node.parentNode !== virtualRoot) {
  36160. var edge = symbolEl.__edge;
  36161. if (!edge) {
  36162. edge = symbolEl.__edge = new BezierCurve({
  36163. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  36164. style: defaults({opacity: 0}, seriesScope.lineStyle)
  36165. });
  36166. }
  36167. updateProps(edge, {
  36168. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  36169. style: {opacity: 1}
  36170. }, seriesModel);
  36171. group.add(edge);
  36172. }
  36173. }
  36174. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36175. var node = data.tree.getNodeByDataIndex(dataIndex);
  36176. var virtualRoot = data.tree.root;
  36177. var itemModel = node.getModel();
  36178. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36179. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36180. var sourceLayout;
  36181. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  36182. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  36183. }
  36184. updateProps(symbolEl, {
  36185. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  36186. }, seriesModel, function () {
  36187. group.remove(symbolEl);
  36188. data.setItemGraphicEl(dataIndex, null);
  36189. });
  36190. symbolEl.fadeOut(null, {keepLabel: true});
  36191. var edge = symbolEl.__edge;
  36192. if (edge) {
  36193. updateProps(edge, {
  36194. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  36195. style: {
  36196. opacity: 0
  36197. }
  36198. }, seriesModel, function () {
  36199. group.remove(edge);
  36200. });
  36201. }
  36202. }
  36203. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  36204. var cpx1;
  36205. var cpy1;
  36206. var cpx2;
  36207. var cpy2;
  36208. var orient = seriesScope.orient;
  36209. if (seriesScope.layout === 'radial') {
  36210. var x1 = sourceLayout.rawX;
  36211. var y1 = sourceLayout.rawY;
  36212. var x2 = targetLayout.rawX;
  36213. var y2 = targetLayout.rawY;
  36214. var radialCoor1 = radialCoordinate(x1, y1);
  36215. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  36216. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  36217. var radialCoor4 = radialCoordinate(x2, y2);
  36218. return {
  36219. x1: radialCoor1.x,
  36220. y1: radialCoor1.y,
  36221. x2: radialCoor4.x,
  36222. y2: radialCoor4.y,
  36223. cpx1: radialCoor2.x,
  36224. cpy1: radialCoor2.y,
  36225. cpx2: radialCoor3.x,
  36226. cpy2: radialCoor3.y
  36227. };
  36228. }
  36229. else {
  36230. var x1 = sourceLayout.x;
  36231. var y1 = sourceLayout.y;
  36232. var x2 = targetLayout.x;
  36233. var y2 = targetLayout.y;
  36234. if (orient === 'horizontal') {
  36235. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  36236. cpy1 = y1;
  36237. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  36238. cpy2 = y2;
  36239. }
  36240. if (orient === 'vertical') {
  36241. cpx1 = x1;
  36242. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  36243. cpx2 = x2;
  36244. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  36245. }
  36246. return {
  36247. x1: x1,
  36248. y1: y1,
  36249. x2: x2,
  36250. y2: y2,
  36251. cpx1: cpx1,
  36252. cpy1: cpy1,
  36253. cpx2: cpx2,
  36254. cpy2: cpy2
  36255. };
  36256. }
  36257. }
  36258. registerAction({
  36259. type: 'treeExpandAndCollapse',
  36260. event: 'treeExpandAndCollapse',
  36261. update: 'update'
  36262. }, function (payload, ecModel) {
  36263. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  36264. var dataIndex = payload.dataIndex;
  36265. var tree = seriesModel.getData().tree;
  36266. var node = tree.getNodeByDataIndex(dataIndex);
  36267. node.isExpand = !node.isExpand;
  36268. });
  36269. });
  36270. /**
  36271. * Traverse the tree from bottom to top and do something
  36272. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  36273. * @param {Function} callback
  36274. */
  36275. function eachAfter (root, callback, separation) {
  36276. var nodes = [root];
  36277. var next = [];
  36278. var node;
  36279. while (node = nodes.pop()) { // jshint ignore:line
  36280. next.push(node);
  36281. if (node.isExpand) {
  36282. var children = node.children;
  36283. if (children.length) {
  36284. for (var i = 0; i < children.length; i++) {
  36285. nodes.push(children[i]);
  36286. }
  36287. }
  36288. }
  36289. }
  36290. while (node = next.pop()) { // jshint ignore:line
  36291. callback(node, separation);
  36292. }
  36293. }
  36294. /**
  36295. * Traverse the tree from top to bottom and do something
  36296. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  36297. * @param {Function} callback
  36298. */
  36299. function eachBefore (root, callback) {
  36300. var nodes = [root];
  36301. var node;
  36302. while (node = nodes.pop()) { // jshint ignore:line
  36303. callback(node);
  36304. if (node.isExpand) {
  36305. var children = node.children;
  36306. if (children.length) {
  36307. for (var i = children.length - 1; i >= 0; i--) {
  36308. nodes.push(children[i]);
  36309. }
  36310. }
  36311. }
  36312. }
  36313. }
  36314. var commonLayout = function (seriesModel, api) {
  36315. var layoutInfo = getViewRect(seriesModel, api);
  36316. seriesModel.layoutInfo = layoutInfo;
  36317. var layout = seriesModel.get('layout');
  36318. var width = 0;
  36319. var height = 0;
  36320. var separation$$1 = null;
  36321. if (layout === 'radial') {
  36322. width = 2 * Math.PI;
  36323. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  36324. separation$$1 = separation(function (node1, node2) {
  36325. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  36326. });
  36327. }
  36328. else {
  36329. width = layoutInfo.width;
  36330. height = layoutInfo.height;
  36331. separation$$1 = separation();
  36332. }
  36333. var virtualRoot = seriesModel.getData().tree.root;
  36334. var realRoot = virtualRoot.children[0];
  36335. init$2(virtualRoot);
  36336. eachAfter(realRoot, firstWalk, separation$$1);
  36337. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  36338. eachBefore(realRoot, secondWalk);
  36339. var left = realRoot;
  36340. var right = realRoot;
  36341. var bottom = realRoot;
  36342. eachBefore(realRoot, function (node) {
  36343. var x = node.getLayout().x;
  36344. if (x < left.getLayout().x) {
  36345. left = node;
  36346. }
  36347. if (x > right.getLayout().x) {
  36348. right = node;
  36349. }
  36350. if (node.depth > bottom.depth) {
  36351. bottom = node;
  36352. }
  36353. });
  36354. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  36355. var tx = delta - left.getLayout().x;
  36356. var kx = 0;
  36357. var ky = 0;
  36358. var coorX = 0;
  36359. var coorY = 0;
  36360. if (layout === 'radial') {
  36361. kx = width / (right.getLayout().x + delta + tx);
  36362. // here we use (node.depth - 1), bucause the real root's depth is 1
  36363. ky = height/ ((bottom.depth - 1) || 1);
  36364. eachBefore(realRoot, function (node) {
  36365. coorX = (node.getLayout().x + tx) * kx;
  36366. coorY = (node.depth - 1) * ky;
  36367. var finalCoor = radialCoordinate(coorX, coorY);
  36368. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  36369. });
  36370. }
  36371. else {
  36372. if (seriesModel.get('orient') === 'horizontal') {
  36373. ky = height / (right.getLayout().x + delta + tx);
  36374. kx = width / ((bottom.depth - 1) || 1);
  36375. eachBefore(realRoot, function (node) {
  36376. coorY = (node.getLayout().x + tx) * ky;
  36377. coorX = (node.depth - 1) * kx;
  36378. node.setLayout({x: coorX, y: coorY}, true);
  36379. });
  36380. }
  36381. else {
  36382. kx = width / (right.getLayout().x + delta + tx);
  36383. ky = height / ((bottom.depth - 1) || 1);
  36384. eachBefore(realRoot, function (node) {
  36385. coorX = (node.getLayout().x + tx) * kx;
  36386. coorY = (node.depth - 1) * ky;
  36387. node.setLayout({x: coorX, y: coorY}, true);
  36388. });
  36389. }
  36390. }
  36391. };
  36392. var orthogonalLayout = function (ecModel, api) {
  36393. ecModel.eachSeriesByType('tree', function (seriesModel) {
  36394. commonLayout(seriesModel, api);
  36395. });
  36396. };
  36397. var radialLayout = function (ecModel, api) {
  36398. ecModel.eachSeriesByType('tree', function (seriesModel) {
  36399. commonLayout(seriesModel, api);
  36400. });
  36401. };
  36402. registerVisual(visualSymbol('tree', 'circle'));
  36403. registerLayout(orthogonalLayout);
  36404. registerLayout(radialLayout);
  36405. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  36406. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  36407. var root = seriesModel.getData().tree.root;
  36408. var targetNode = payload.targetNode;
  36409. if (targetNode && root.contains(targetNode)) {
  36410. return {node: targetNode};
  36411. }
  36412. var targetNodeId = payload.targetNodeId;
  36413. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  36414. return {node: targetNode};
  36415. }
  36416. }
  36417. }
  36418. // Not includes the given node at the last item.
  36419. function getPathToRoot(node) {
  36420. var path = [];
  36421. while (node) {
  36422. node = node.parentNode;
  36423. node && path.push(node);
  36424. }
  36425. return path.reverse();
  36426. }
  36427. function aboveViewRoot(viewRoot, node) {
  36428. var viewPath = getPathToRoot(viewRoot);
  36429. return indexOf(viewPath, node) >= 0;
  36430. }
  36431. // From root to the input node (the input node will be included).
  36432. function wrapTreePathInfo(node, seriesModel) {
  36433. var treePathInfo = [];
  36434. while (node) {
  36435. var nodeDataIndex = node.dataIndex;
  36436. treePathInfo.push({
  36437. name: node.name,
  36438. dataIndex: nodeDataIndex,
  36439. value: seriesModel.getRawValue(nodeDataIndex)
  36440. });
  36441. node = node.parentNode;
  36442. }
  36443. treePathInfo.reverse();
  36444. return treePathInfo;
  36445. }
  36446. SeriesModel.extend({
  36447. type: 'series.treemap',
  36448. layoutMode: 'box',
  36449. dependencies: ['grid', 'polar'],
  36450. /**
  36451. * @type {module:echarts/data/Tree~Node}
  36452. */
  36453. _viewRoot: null,
  36454. defaultOption: {
  36455. // Disable progressive rendering
  36456. progressive: 0,
  36457. hoverLayerThreshold: Infinity,
  36458. // center: ['50%', '50%'], // not supported in ec3.
  36459. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  36460. left: 'center',
  36461. top: 'middle',
  36462. right: null,
  36463. bottom: null,
  36464. width: '80%',
  36465. height: '80%',
  36466. sort: true, // Can be null or false or true
  36467. // (order by desc default, asc not supported yet (strange effect))
  36468. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  36469. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  36470. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  36471. // Count from zero (zero represents only view root).
  36472. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  36473. // to align specialized icon. ▷▶❒❐▼✚
  36474. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  36475. // target node area in the view area.
  36476. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  36477. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  36478. // If leafDepth is set and clicking a node which has children but
  36479. // be on left depth, the behaviour would be changing root. Otherwise
  36480. // use behavious defined above.
  36481. animation: true,
  36482. animationDurationUpdate: 900,
  36483. animationEasing: 'quinticInOut',
  36484. breadcrumb: {
  36485. show: true,
  36486. height: 22,
  36487. left: 'center',
  36488. top: 'bottom',
  36489. // right
  36490. // bottom
  36491. emptyItemWidth: 25, // Width of empty node.
  36492. itemStyle: {
  36493. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  36494. borderColor: 'rgba(255,255,255,0.7)',
  36495. borderWidth: 1,
  36496. shadowColor: 'rgba(150,150,150,1)',
  36497. shadowBlur: 3,
  36498. shadowOffsetX: 0,
  36499. shadowOffsetY: 0,
  36500. textStyle: {
  36501. color: '#fff'
  36502. }
  36503. },
  36504. emphasis: {
  36505. textStyle: {}
  36506. }
  36507. },
  36508. label: {
  36509. show: true,
  36510. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  36511. distance: 0,
  36512. padding: 5,
  36513. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  36514. // formatter: null,
  36515. color: '#fff',
  36516. ellipsis: true
  36517. // align
  36518. // verticalAlign
  36519. },
  36520. upperLabel: { // Label when node is parent.
  36521. show: false,
  36522. position: [0, '50%'],
  36523. height: 20,
  36524. // formatter: null,
  36525. color: '#fff',
  36526. ellipsis: true,
  36527. // align: null,
  36528. verticalAlign: 'middle'
  36529. },
  36530. itemStyle: {
  36531. color: null, // Can be 'none' if not necessary.
  36532. colorAlpha: null, // Can be 'none' if not necessary.
  36533. colorSaturation: null, // Can be 'none' if not necessary.
  36534. borderWidth: 0,
  36535. gapWidth: 0,
  36536. borderColor: '#fff',
  36537. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  36538. // border color is evaluated by color of current node and
  36539. // borderColorSaturation.
  36540. },
  36541. emphasis: {
  36542. upperLabel: {
  36543. show: true,
  36544. position: [0, '50%'],
  36545. color: '#fff',
  36546. ellipsis: true,
  36547. verticalAlign: 'middle'
  36548. }
  36549. },
  36550. visualDimension: 0, // Can be 0, 1, 2, 3.
  36551. visualMin: null,
  36552. visualMax: null,
  36553. color: [], // + treemapSeries.color should not be modified. Please only modified
  36554. // level[n].color (if necessary).
  36555. // + Specify color list of each level. level[0].color would be global
  36556. // color list if not specified. (see method `setDefault`).
  36557. // + But set as a empty array to forbid fetch color from global palette
  36558. // when using nodeModel.get('color'), otherwise nodes on deep level
  36559. // will always has color palette set and are not able to inherit color
  36560. // from parent node.
  36561. // + TreemapSeries.color can not be set as 'none', otherwise effect
  36562. // legend color fetching (see seriesColor.js).
  36563. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  36564. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  36565. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  36566. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  36567. // be rendered. Only works when sort is 'asc' or 'desc'.
  36568. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  36569. // grandchildren will not show.
  36570. // Why grandchildren? If not grandchildren but children,
  36571. // some siblings show children and some not,
  36572. // the appearance may be mess and not consistent,
  36573. levels: [] // Each item: {
  36574. // visibleMin, itemStyle, visualDimension, label
  36575. // }
  36576. // data: {
  36577. // value: [],
  36578. // children: [],
  36579. // link: 'http://xxx.xxx.xxx',
  36580. // target: 'blank' or 'self'
  36581. // }
  36582. },
  36583. /**
  36584. * @override
  36585. */
  36586. getInitialData: function (option, ecModel) {
  36587. // Create a virtual root.
  36588. var root = {name: option.name, children: option.data};
  36589. completeTreeValue(root);
  36590. var levels = option.levels || [];
  36591. levels = option.levels = setDefault(levels, ecModel);
  36592. var treeOption = {};
  36593. treeOption.levels = levels;
  36594. // Make sure always a new tree is created when setOption,
  36595. // in TreemapView, we check whether oldTree === newTree
  36596. // to choose mappings approach among old shapes and new shapes.
  36597. return Tree.createTree(root, this, treeOption).data;
  36598. },
  36599. optionUpdated: function () {
  36600. this.resetViewRoot();
  36601. },
  36602. /**
  36603. * @override
  36604. * @param {number} dataIndex
  36605. * @param {boolean} [mutipleSeries=false]
  36606. */
  36607. formatTooltip: function (dataIndex) {
  36608. var data = this.getData();
  36609. var value = this.getRawValue(dataIndex);
  36610. var formattedValue = isArray(value)
  36611. ? addCommas(value[0]) : addCommas(value);
  36612. var name = data.getName(dataIndex);
  36613. return encodeHTML(name + ': ' + formattedValue);
  36614. },
  36615. /**
  36616. * Add tree path to tooltip param
  36617. *
  36618. * @override
  36619. * @param {number} dataIndex
  36620. * @return {Object}
  36621. */
  36622. getDataParams: function (dataIndex) {
  36623. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  36624. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  36625. params.treePathInfo = wrapTreePathInfo(node, this);
  36626. return params;
  36627. },
  36628. /**
  36629. * @public
  36630. * @param {Object} layoutInfo {
  36631. * x: containerGroup x
  36632. * y: containerGroup y
  36633. * width: containerGroup width
  36634. * height: containerGroup height
  36635. * }
  36636. */
  36637. setLayoutInfo: function (layoutInfo) {
  36638. /**
  36639. * @readOnly
  36640. * @type {Object}
  36641. */
  36642. this.layoutInfo = this.layoutInfo || {};
  36643. extend(this.layoutInfo, layoutInfo);
  36644. },
  36645. /**
  36646. * @param {string} id
  36647. * @return {number} index
  36648. */
  36649. mapIdToIndex: function (id) {
  36650. // A feature is implemented:
  36651. // index is monotone increasing with the sequence of
  36652. // input id at the first time.
  36653. // This feature can make sure that each data item and its
  36654. // mapped color have the same index between data list and
  36655. // color list at the beginning, which is useful for user
  36656. // to adjust data-color mapping.
  36657. /**
  36658. * @private
  36659. * @type {Object}
  36660. */
  36661. var idIndexMap = this._idIndexMap;
  36662. if (!idIndexMap) {
  36663. idIndexMap = this._idIndexMap = createHashMap();
  36664. /**
  36665. * @private
  36666. * @type {number}
  36667. */
  36668. this._idIndexMapCount = 0;
  36669. }
  36670. var index = idIndexMap.get(id);
  36671. if (index == null) {
  36672. idIndexMap.set(id, index = this._idIndexMapCount++);
  36673. }
  36674. return index;
  36675. },
  36676. getViewRoot: function () {
  36677. return this._viewRoot;
  36678. },
  36679. /**
  36680. * @param {module:echarts/data/Tree~Node} [viewRoot]
  36681. */
  36682. resetViewRoot: function (viewRoot) {
  36683. viewRoot
  36684. ? (this._viewRoot = viewRoot)
  36685. : (viewRoot = this._viewRoot);
  36686. var root = this.getRawData().tree.root;
  36687. if (!viewRoot
  36688. || (viewRoot !== root && !root.contains(viewRoot))
  36689. ) {
  36690. this._viewRoot = root;
  36691. }
  36692. }
  36693. });
  36694. /**
  36695. * @param {Object} dataNode
  36696. */
  36697. function completeTreeValue(dataNode) {
  36698. // Postorder travel tree.
  36699. // If value of none-leaf node is not set,
  36700. // calculate it by suming up the value of all children.
  36701. var sum = 0;
  36702. each$1(dataNode.children, function (child) {
  36703. completeTreeValue(child);
  36704. var childValue = child.value;
  36705. isArray(childValue) && (childValue = childValue[0]);
  36706. sum += childValue;
  36707. });
  36708. var thisValue = dataNode.value;
  36709. if (isArray(thisValue)) {
  36710. thisValue = thisValue[0];
  36711. }
  36712. if (thisValue == null || isNaN(thisValue)) {
  36713. thisValue = sum;
  36714. }
  36715. // Value should not less than 0.
  36716. if (thisValue < 0) {
  36717. thisValue = 0;
  36718. }
  36719. isArray(dataNode.value)
  36720. ? (dataNode.value[0] = thisValue)
  36721. : (dataNode.value = thisValue);
  36722. }
  36723. /**
  36724. * set default to level configuration
  36725. */
  36726. function setDefault(levels, ecModel) {
  36727. var globalColorList = ecModel.get('color');
  36728. if (!globalColorList) {
  36729. return;
  36730. }
  36731. levels = levels || [];
  36732. var hasColorDefine;
  36733. each$1(levels, function (levelDefine) {
  36734. var model = new Model(levelDefine);
  36735. var modelColor = model.get('color');
  36736. if (model.get('itemStyle.color')
  36737. || (modelColor && modelColor !== 'none')
  36738. ) {
  36739. hasColorDefine = true;
  36740. }
  36741. });
  36742. if (!hasColorDefine) {
  36743. var level0 = levels[0] || (levels[0] = {});
  36744. level0.color = globalColorList.slice();
  36745. }
  36746. return levels;
  36747. }
  36748. var TEXT_PADDING = 8;
  36749. var ITEM_GAP = 8;
  36750. var ARRAY_LENGTH = 5;
  36751. function Breadcrumb(containerGroup) {
  36752. /**
  36753. * @private
  36754. * @type {module:zrender/container/Group}
  36755. */
  36756. this.group = new Group();
  36757. containerGroup.add(this.group);
  36758. }
  36759. Breadcrumb.prototype = {
  36760. constructor: Breadcrumb,
  36761. render: function (seriesModel, api, targetNode, onSelect) {
  36762. var model = seriesModel.getModel('breadcrumb');
  36763. var thisGroup = this.group;
  36764. thisGroup.removeAll();
  36765. if (!model.get('show') || !targetNode) {
  36766. return;
  36767. }
  36768. var normalStyleModel = model.getModel('itemStyle');
  36769. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  36770. var textStyleModel = normalStyleModel.getModel('textStyle');
  36771. var layoutParam = {
  36772. pos: {
  36773. left: model.get('left'),
  36774. right: model.get('right'),
  36775. top: model.get('top'),
  36776. bottom: model.get('bottom')
  36777. },
  36778. box: {
  36779. width: api.getWidth(),
  36780. height: api.getHeight()
  36781. },
  36782. emptyItemWidth: model.get('emptyItemWidth'),
  36783. totalWidth: 0,
  36784. renderList: []
  36785. };
  36786. this._prepare(targetNode, layoutParam, textStyleModel);
  36787. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  36788. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  36789. },
  36790. /**
  36791. * Prepare render list and total width
  36792. * @private
  36793. */
  36794. _prepare: function (targetNode, layoutParam, textStyleModel) {
  36795. for (var node = targetNode; node; node = node.parentNode) {
  36796. var text = node.getModel().get('name');
  36797. var textRect = textStyleModel.getTextRect(text);
  36798. var itemWidth = Math.max(
  36799. textRect.width + TEXT_PADDING * 2,
  36800. layoutParam.emptyItemWidth
  36801. );
  36802. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  36803. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  36804. }
  36805. },
  36806. /**
  36807. * @private
  36808. */
  36809. _renderContent: function (
  36810. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  36811. ) {
  36812. // Start rendering.
  36813. var lastX = 0;
  36814. var emptyItemWidth = layoutParam.emptyItemWidth;
  36815. var height = seriesModel.get('breadcrumb.height');
  36816. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  36817. var totalWidth = layoutParam.totalWidth;
  36818. var renderList = layoutParam.renderList;
  36819. for (var i = renderList.length - 1; i >= 0; i--) {
  36820. var item = renderList[i];
  36821. var itemNode = item.node;
  36822. var itemWidth = item.width;
  36823. var text = item.text;
  36824. // Hdie text and shorten width if necessary.
  36825. if (totalWidth > availableSize.width) {
  36826. totalWidth -= itemWidth - emptyItemWidth;
  36827. itemWidth = emptyItemWidth;
  36828. text = null;
  36829. }
  36830. var el = new Polygon({
  36831. shape: {
  36832. points: makeItemPoints(
  36833. lastX, 0, itemWidth, height,
  36834. i === renderList.length - 1, i === 0
  36835. )
  36836. },
  36837. style: defaults(
  36838. normalStyleModel.getItemStyle(),
  36839. {
  36840. lineJoin: 'bevel',
  36841. text: text,
  36842. textFill: textStyleModel.getTextColor(),
  36843. textFont: textStyleModel.getFont()
  36844. }
  36845. ),
  36846. z: 10,
  36847. onclick: curry(onSelect, itemNode)
  36848. });
  36849. this.group.add(el);
  36850. packEventData(el, seriesModel, itemNode);
  36851. lastX += itemWidth + ITEM_GAP;
  36852. }
  36853. },
  36854. /**
  36855. * @override
  36856. */
  36857. remove: function () {
  36858. this.group.removeAll();
  36859. }
  36860. };
  36861. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  36862. var points = [
  36863. [head ? x : x - ARRAY_LENGTH, y],
  36864. [x + itemWidth, y],
  36865. [x + itemWidth, y + itemHeight],
  36866. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  36867. ];
  36868. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  36869. !head && points.push([x, y + itemHeight / 2]);
  36870. return points;
  36871. }
  36872. // Package custom mouse event.
  36873. function packEventData(el, seriesModel, itemNode) {
  36874. el.eventData = {
  36875. componentType: 'series',
  36876. componentSubType: 'treemap',
  36877. seriesIndex: seriesModel.componentIndex,
  36878. seriesName: seriesModel.name,
  36879. seriesType: 'treemap',
  36880. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  36881. nodeData: {
  36882. dataIndex: itemNode && itemNode.dataIndex,
  36883. name: itemNode && itemNode.name
  36884. },
  36885. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  36886. };
  36887. }
  36888. /**
  36889. * @param {number} [time=500] Time in ms
  36890. * @param {string} [easing='linear']
  36891. * @param {number} [delay=0]
  36892. * @param {Function} [callback]
  36893. *
  36894. * @example
  36895. * // Animate position
  36896. * animation
  36897. * .createWrap()
  36898. * .add(el1, {position: [10, 10]})
  36899. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  36900. * .done(function () { // done })
  36901. * .start('cubicOut');
  36902. */
  36903. function createWrap() {
  36904. var storage = [];
  36905. var elExistsMap = {};
  36906. var doneCallback;
  36907. return {
  36908. /**
  36909. * Caution: a el can only be added once, otherwise 'done'
  36910. * might not be called. This method checks this (by el.id),
  36911. * suppresses adding and returns false when existing el found.
  36912. *
  36913. * @param {modele:zrender/Element} el
  36914. * @param {Object} target
  36915. * @param {number} [time=500]
  36916. * @param {number} [delay=0]
  36917. * @param {string} [easing='linear']
  36918. * @return {boolean} Whether adding succeeded.
  36919. *
  36920. * @example
  36921. * add(el, target, time, delay, easing);
  36922. * add(el, target, time, easing);
  36923. * add(el, target, time);
  36924. * add(el, target);
  36925. */
  36926. add: function (el, target, time, delay, easing) {
  36927. if (isString(delay)) {
  36928. easing = delay;
  36929. delay = 0;
  36930. }
  36931. if (elExistsMap[el.id]) {
  36932. return false;
  36933. }
  36934. elExistsMap[el.id] = 1;
  36935. storage.push(
  36936. {el: el, target: target, time: time, delay: delay, easing: easing}
  36937. );
  36938. return true;
  36939. },
  36940. /**
  36941. * Only execute when animation finished. Will not execute when any
  36942. * of 'stop' or 'stopAnimation' called.
  36943. *
  36944. * @param {Function} callback
  36945. */
  36946. done: function (callback) {
  36947. doneCallback = callback;
  36948. return this;
  36949. },
  36950. /**
  36951. * Will stop exist animation firstly.
  36952. */
  36953. start: function () {
  36954. var count = storage.length;
  36955. for (var i = 0, len = storage.length; i < len; i++) {
  36956. var item = storage[i];
  36957. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  36958. }
  36959. return this;
  36960. function done() {
  36961. count--;
  36962. if (!count) {
  36963. storage.length = 0;
  36964. elExistsMap = {};
  36965. doneCallback && doneCallback();
  36966. }
  36967. }
  36968. }
  36969. };
  36970. }
  36971. var bind$1 = bind;
  36972. var Group$2 = Group;
  36973. var Rect$1 = Rect;
  36974. var each$9 = each$1;
  36975. var DRAG_THRESHOLD = 3;
  36976. var PATH_LABEL_NOAMAL = ['label'];
  36977. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  36978. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  36979. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  36980. var Z_BASE = 10; // Should bigger than every z.
  36981. var Z_BG = 1;
  36982. var Z_CONTENT = 2;
  36983. var getItemStyleEmphasis = makeStyleMapper([
  36984. ['fill', 'color'],
  36985. // `borderColor` and `borderWidth` has been occupied,
  36986. // so use `stroke` to indicate the stroke of the rect.
  36987. ['stroke', 'strokeColor'],
  36988. ['lineWidth', 'strokeWidth'],
  36989. ['shadowBlur'],
  36990. ['shadowOffsetX'],
  36991. ['shadowOffsetY'],
  36992. ['shadowColor']
  36993. ]);
  36994. var getItemStyleNormal = function (model) {
  36995. // Normal style props should include emphasis style props.
  36996. var itemStyle = getItemStyleEmphasis(model);
  36997. // Clear styles set by emphasis.
  36998. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  36999. return itemStyle;
  37000. };
  37001. extendChartView({
  37002. type: 'treemap',
  37003. /**
  37004. * @override
  37005. */
  37006. init: function (o, api) {
  37007. /**
  37008. * @private
  37009. * @type {module:zrender/container/Group}
  37010. */
  37011. this._containerGroup;
  37012. /**
  37013. * @private
  37014. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  37015. */
  37016. this._storage = createStorage();
  37017. /**
  37018. * @private
  37019. * @type {module:echarts/data/Tree}
  37020. */
  37021. this._oldTree;
  37022. /**
  37023. * @private
  37024. * @type {module:echarts/chart/treemap/Breadcrumb}
  37025. */
  37026. this._breadcrumb;
  37027. /**
  37028. * @private
  37029. * @type {module:echarts/component/helper/RoamController}
  37030. */
  37031. this._controller;
  37032. /**
  37033. * 'ready', 'animating'
  37034. * @private
  37035. */
  37036. this._state = 'ready';
  37037. },
  37038. /**
  37039. * @override
  37040. */
  37041. render: function (seriesModel, ecModel, api, payload) {
  37042. var models = ecModel.findComponents({
  37043. mainType: 'series', subType: 'treemap', query: payload
  37044. });
  37045. if (indexOf(models, seriesModel) < 0) {
  37046. return;
  37047. }
  37048. this.seriesModel = seriesModel;
  37049. this.api = api;
  37050. this.ecModel = ecModel;
  37051. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  37052. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  37053. var payloadType = payload && payload.type;
  37054. var layoutInfo = seriesModel.layoutInfo;
  37055. var isInit = !this._oldTree;
  37056. var thisStorage = this._storage;
  37057. // Mark new root when action is treemapRootToNode.
  37058. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  37059. ? {
  37060. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  37061. direction: payload.direction
  37062. }
  37063. : null;
  37064. var containerGroup = this._giveContainerGroup(layoutInfo);
  37065. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  37066. (
  37067. !isInit && (
  37068. !payloadType
  37069. || payloadType === 'treemapZoomToNode'
  37070. || payloadType === 'treemapRootToNode'
  37071. )
  37072. )
  37073. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  37074. : renderResult.renderFinally();
  37075. this._resetController(api);
  37076. this._renderBreadcrumb(seriesModel, api, targetInfo);
  37077. },
  37078. /**
  37079. * @private
  37080. */
  37081. _giveContainerGroup: function (layoutInfo) {
  37082. var containerGroup = this._containerGroup;
  37083. if (!containerGroup) {
  37084. // FIXME
  37085. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  37086. containerGroup = this._containerGroup = new Group$2();
  37087. this._initEvents(containerGroup);
  37088. this.group.add(containerGroup);
  37089. }
  37090. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  37091. return containerGroup;
  37092. },
  37093. /**
  37094. * @private
  37095. */
  37096. _doRender: function (containerGroup, seriesModel, reRoot) {
  37097. var thisTree = seriesModel.getData().tree;
  37098. var oldTree = this._oldTree;
  37099. // Clear last shape records.
  37100. var lastsForAnimation = createStorage();
  37101. var thisStorage = createStorage();
  37102. var oldStorage = this._storage;
  37103. var willInvisibleEls = [];
  37104. var doRenderNode = curry(
  37105. renderNode, seriesModel,
  37106. thisStorage, oldStorage, reRoot,
  37107. lastsForAnimation, willInvisibleEls
  37108. );
  37109. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  37110. // the oldTree is actually losted, so we can not find all of the old graphic
  37111. // elements from tree. So we use this stragegy: make element storage, move
  37112. // from old storage to new storage, clear old storage.
  37113. dualTravel(
  37114. thisTree.root ? [thisTree.root] : [],
  37115. (oldTree && oldTree.root) ? [oldTree.root] : [],
  37116. containerGroup,
  37117. thisTree === oldTree || !oldTree,
  37118. 0
  37119. );
  37120. // Process all removing.
  37121. var willDeleteEls = clearStorage(oldStorage);
  37122. this._oldTree = thisTree;
  37123. this._storage = thisStorage;
  37124. return {
  37125. lastsForAnimation: lastsForAnimation,
  37126. willDeleteEls: willDeleteEls,
  37127. renderFinally: renderFinally
  37128. };
  37129. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  37130. // When 'render' is triggered by action,
  37131. // 'this' and 'old' may be the same tree,
  37132. // we use rawIndex in that case.
  37133. if (sameTree) {
  37134. oldViewChildren = thisViewChildren;
  37135. each$9(thisViewChildren, function (child, index) {
  37136. !child.isRemoved() && processNode(index, index);
  37137. });
  37138. }
  37139. // Diff hierarchically (diff only in each subtree, but not whole).
  37140. // because, consistency of view is important.
  37141. else {
  37142. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  37143. .add(processNode)
  37144. .update(processNode)
  37145. .remove(curry(processNode, null))
  37146. .execute();
  37147. }
  37148. function getKey(node) {
  37149. // Identify by name or raw index.
  37150. return node.getId();
  37151. }
  37152. function processNode(newIndex, oldIndex) {
  37153. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  37154. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  37155. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  37156. group && dualTravel(
  37157. thisNode && thisNode.viewChildren || [],
  37158. oldNode && oldNode.viewChildren || [],
  37159. group,
  37160. sameTree,
  37161. depth + 1
  37162. );
  37163. }
  37164. }
  37165. function clearStorage(storage) {
  37166. var willDeleteEls = createStorage();
  37167. storage && each$9(storage, function (store, storageName) {
  37168. var delEls = willDeleteEls[storageName];
  37169. each$9(store, function (el) {
  37170. el && (delEls.push(el), el.__tmWillDelete = 1);
  37171. });
  37172. });
  37173. return willDeleteEls;
  37174. }
  37175. function renderFinally() {
  37176. each$9(willDeleteEls, function (els) {
  37177. each$9(els, function (el) {
  37178. el.parent && el.parent.remove(el);
  37179. });
  37180. });
  37181. each$9(willInvisibleEls, function (el) {
  37182. el.invisible = true;
  37183. // Setting invisible is for optimizing, so no need to set dirty,
  37184. // just mark as invisible.
  37185. el.dirty();
  37186. });
  37187. }
  37188. },
  37189. /**
  37190. * @private
  37191. */
  37192. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  37193. if (!seriesModel.get('animation')) {
  37194. return;
  37195. }
  37196. var duration = seriesModel.get('animationDurationUpdate');
  37197. var easing = seriesModel.get('animationEasing');
  37198. var animationWrap = createWrap();
  37199. // Make delete animations.
  37200. each$9(renderResult.willDeleteEls, function (store, storageName) {
  37201. each$9(store, function (el, rawIndex) {
  37202. if (el.invisible) {
  37203. return;
  37204. }
  37205. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  37206. var target;
  37207. if (reRoot && reRoot.direction === 'drillDown') {
  37208. target = parent === reRoot.rootNodeGroup
  37209. // This is the content element of view root.
  37210. // Only `content` will enter this branch, because
  37211. // `background` and `nodeGroup` will not be deleted.
  37212. ? {
  37213. shape: {
  37214. x: 0,
  37215. y: 0,
  37216. width: parent.__tmNodeWidth,
  37217. height: parent.__tmNodeHeight
  37218. },
  37219. style: {
  37220. opacity: 0
  37221. }
  37222. }
  37223. // Others.
  37224. : {style: {opacity: 0}};
  37225. }
  37226. else {
  37227. var targetX = 0;
  37228. var targetY = 0;
  37229. if (!parent.__tmWillDelete) {
  37230. // Let node animate to right-bottom corner, cooperating with fadeout,
  37231. // which is appropriate for user understanding.
  37232. // Divided by 2 for reRoot rolling up effect.
  37233. targetX = parent.__tmNodeWidth / 2;
  37234. targetY = parent.__tmNodeHeight / 2;
  37235. }
  37236. target = storageName === 'nodeGroup'
  37237. ? {position: [targetX, targetY], style: {opacity: 0}}
  37238. : {
  37239. shape: {x: targetX, y: targetY, width: 0, height: 0},
  37240. style: {opacity: 0}
  37241. };
  37242. }
  37243. target && animationWrap.add(el, target, duration, easing);
  37244. });
  37245. });
  37246. // Make other animations
  37247. each$9(this._storage, function (store, storageName) {
  37248. each$9(store, function (el, rawIndex) {
  37249. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  37250. var target = {};
  37251. if (!last) {
  37252. return;
  37253. }
  37254. if (storageName === 'nodeGroup') {
  37255. if (last.old) {
  37256. target.position = el.position.slice();
  37257. el.attr('position', last.old);
  37258. }
  37259. }
  37260. else {
  37261. if (last.old) {
  37262. target.shape = extend({}, el.shape);
  37263. el.setShape(last.old);
  37264. }
  37265. if (last.fadein) {
  37266. el.setStyle('opacity', 0);
  37267. target.style = {opacity: 1};
  37268. }
  37269. // When animation is stopped for succedent animation starting,
  37270. // el.style.opacity might not be 1
  37271. else if (el.style.opacity !== 1) {
  37272. target.style = {opacity: 1};
  37273. }
  37274. }
  37275. animationWrap.add(el, target, duration, easing);
  37276. });
  37277. }, this);
  37278. this._state = 'animating';
  37279. animationWrap
  37280. .done(bind$1(function () {
  37281. this._state = 'ready';
  37282. renderResult.renderFinally();
  37283. }, this))
  37284. .start();
  37285. },
  37286. /**
  37287. * @private
  37288. */
  37289. _resetController: function (api) {
  37290. var controller = this._controller;
  37291. // Init controller.
  37292. if (!controller) {
  37293. controller = this._controller = new RoamController(api.getZr());
  37294. controller.enable(this.seriesModel.get('roam'));
  37295. controller.on('pan', bind$1(this._onPan, this));
  37296. controller.on('zoom', bind$1(this._onZoom, this));
  37297. }
  37298. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  37299. controller.setPointerChecker(function (e, x, y) {
  37300. return rect.contain(x, y);
  37301. });
  37302. },
  37303. /**
  37304. * @private
  37305. */
  37306. _clearController: function () {
  37307. var controller = this._controller;
  37308. if (controller) {
  37309. controller.dispose();
  37310. controller = null;
  37311. }
  37312. },
  37313. /**
  37314. * @private
  37315. */
  37316. _onPan: function (dx, dy) {
  37317. if (this._state !== 'animating'
  37318. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  37319. ) {
  37320. // These param must not be cached.
  37321. var root = this.seriesModel.getData().tree.root;
  37322. if (!root) {
  37323. return;
  37324. }
  37325. var rootLayout = root.getLayout();
  37326. if (!rootLayout) {
  37327. return;
  37328. }
  37329. this.api.dispatchAction({
  37330. type: 'treemapMove',
  37331. from: this.uid,
  37332. seriesId: this.seriesModel.id,
  37333. rootRect: {
  37334. x: rootLayout.x + dx, y: rootLayout.y + dy,
  37335. width: rootLayout.width, height: rootLayout.height
  37336. }
  37337. });
  37338. }
  37339. },
  37340. /**
  37341. * @private
  37342. */
  37343. _onZoom: function (scale, mouseX, mouseY) {
  37344. if (this._state !== 'animating') {
  37345. // These param must not be cached.
  37346. var root = this.seriesModel.getData().tree.root;
  37347. if (!root) {
  37348. return;
  37349. }
  37350. var rootLayout = root.getLayout();
  37351. if (!rootLayout) {
  37352. return;
  37353. }
  37354. var rect = new BoundingRect(
  37355. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  37356. );
  37357. var layoutInfo = this.seriesModel.layoutInfo;
  37358. // Transform mouse coord from global to containerGroup.
  37359. mouseX -= layoutInfo.x;
  37360. mouseY -= layoutInfo.y;
  37361. // Scale root bounding rect.
  37362. var m = create$1();
  37363. translate(m, m, [-mouseX, -mouseY]);
  37364. scale$1(m, m, [scale, scale]);
  37365. translate(m, m, [mouseX, mouseY]);
  37366. rect.applyTransform(m);
  37367. this.api.dispatchAction({
  37368. type: 'treemapRender',
  37369. from: this.uid,
  37370. seriesId: this.seriesModel.id,
  37371. rootRect: {
  37372. x: rect.x, y: rect.y,
  37373. width: rect.width, height: rect.height
  37374. }
  37375. });
  37376. }
  37377. },
  37378. /**
  37379. * @private
  37380. */
  37381. _initEvents: function (containerGroup) {
  37382. containerGroup.on('click', function (e) {
  37383. if (this._state !== 'ready') {
  37384. return;
  37385. }
  37386. var nodeClick = this.seriesModel.get('nodeClick', true);
  37387. if (!nodeClick) {
  37388. return;
  37389. }
  37390. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  37391. if (!targetInfo) {
  37392. return;
  37393. }
  37394. var node = targetInfo.node;
  37395. if (node.getLayout().isLeafRoot) {
  37396. this._rootToNode(targetInfo);
  37397. }
  37398. else {
  37399. if (nodeClick === 'zoomToNode') {
  37400. this._zoomToNode(targetInfo);
  37401. }
  37402. else if (nodeClick === 'link') {
  37403. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  37404. var link = itemModel.get('link', true);
  37405. var linkTarget = itemModel.get('target', true) || 'blank';
  37406. link && window.open(link, linkTarget);
  37407. }
  37408. }
  37409. }, this);
  37410. },
  37411. /**
  37412. * @private
  37413. */
  37414. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  37415. if (!targetInfo) {
  37416. targetInfo = seriesModel.get('leafDepth', true) != null
  37417. ? {node: seriesModel.getViewRoot()}
  37418. // FIXME
  37419. // better way?
  37420. // Find breadcrumb tail on center of containerGroup.
  37421. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  37422. if (!targetInfo) {
  37423. targetInfo = {node: seriesModel.getData().tree.root};
  37424. }
  37425. }
  37426. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  37427. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  37428. function onSelect(node) {
  37429. if (this._state !== 'animating') {
  37430. aboveViewRoot(seriesModel.getViewRoot(), node)
  37431. ? this._rootToNode({node: node})
  37432. : this._zoomToNode({node: node});
  37433. }
  37434. }
  37435. },
  37436. /**
  37437. * @override
  37438. */
  37439. remove: function () {
  37440. this._clearController();
  37441. this._containerGroup && this._containerGroup.removeAll();
  37442. this._storage = createStorage();
  37443. this._state = 'ready';
  37444. this._breadcrumb && this._breadcrumb.remove();
  37445. },
  37446. dispose: function () {
  37447. this._clearController();
  37448. },
  37449. /**
  37450. * @private
  37451. */
  37452. _zoomToNode: function (targetInfo) {
  37453. this.api.dispatchAction({
  37454. type: 'treemapZoomToNode',
  37455. from: this.uid,
  37456. seriesId: this.seriesModel.id,
  37457. targetNode: targetInfo.node
  37458. });
  37459. },
  37460. /**
  37461. * @private
  37462. */
  37463. _rootToNode: function (targetInfo) {
  37464. this.api.dispatchAction({
  37465. type: 'treemapRootToNode',
  37466. from: this.uid,
  37467. seriesId: this.seriesModel.id,
  37468. targetNode: targetInfo.node
  37469. });
  37470. },
  37471. /**
  37472. * @public
  37473. * @param {number} x Global coord x.
  37474. * @param {number} y Global coord y.
  37475. * @return {Object} info If not found, return undefined;
  37476. * @return {number} info.node Target node.
  37477. * @return {number} info.offsetX x refer to target node.
  37478. * @return {number} info.offsetY y refer to target node.
  37479. */
  37480. findTarget: function (x, y) {
  37481. var targetInfo;
  37482. var viewRoot = this.seriesModel.getViewRoot();
  37483. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  37484. var bgEl = this._storage.background[node.getRawIndex()];
  37485. // If invisible, there might be no element.
  37486. if (bgEl) {
  37487. var point = bgEl.transformCoordToLocal(x, y);
  37488. var shape = bgEl.shape;
  37489. // For performance consideration, dont use 'getBoundingRect'.
  37490. if (shape.x <= point[0]
  37491. && point[0] <= shape.x + shape.width
  37492. && shape.y <= point[1]
  37493. && point[1] <= shape.y + shape.height
  37494. ) {
  37495. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  37496. }
  37497. else {
  37498. return false; // Suppress visit subtree.
  37499. }
  37500. }
  37501. }, this);
  37502. return targetInfo;
  37503. }
  37504. });
  37505. /**
  37506. * @inner
  37507. */
  37508. function createStorage() {
  37509. return {nodeGroup: [], background: [], content: []};
  37510. }
  37511. /**
  37512. * @inner
  37513. * @return Return undefined means do not travel further.
  37514. */
  37515. function renderNode(
  37516. seriesModel, thisStorage, oldStorage, reRoot,
  37517. lastsForAnimation, willInvisibleEls,
  37518. thisNode, oldNode, parentGroup, depth
  37519. ) {
  37520. // Whether under viewRoot.
  37521. if (!thisNode) {
  37522. // Deleting nodes will be performed finally. This method just find
  37523. // element from old storage, or create new element, set them to new
  37524. // storage, and set styles.
  37525. return;
  37526. }
  37527. // -------------------------------------------------------------------
  37528. // Start of closure variables available in "Procedures in renderNode".
  37529. var thisLayout = thisNode.getLayout();
  37530. if (!thisLayout || !thisLayout.isInView) {
  37531. return;
  37532. }
  37533. var thisWidth = thisLayout.width;
  37534. var thisHeight = thisLayout.height;
  37535. var borderWidth = thisLayout.borderWidth;
  37536. var thisInvisible = thisLayout.invisible;
  37537. var thisRawIndex = thisNode.getRawIndex();
  37538. var oldRawIndex = oldNode && oldNode.getRawIndex();
  37539. var thisViewChildren = thisNode.viewChildren;
  37540. var upperHeight = thisLayout.upperHeight;
  37541. var isParent = thisViewChildren && thisViewChildren.length;
  37542. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  37543. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  37544. // End of closure ariables available in "Procedures in renderNode".
  37545. // -----------------------------------------------------------------
  37546. // Node group
  37547. var group = giveGraphic('nodeGroup', Group$2);
  37548. if (!group) {
  37549. return;
  37550. }
  37551. parentGroup.add(group);
  37552. // x,y are not set when el is above view root.
  37553. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  37554. group.__tmNodeWidth = thisWidth;
  37555. group.__tmNodeHeight = thisHeight;
  37556. if (thisLayout.isAboveViewRoot) {
  37557. return group;
  37558. }
  37559. // Background
  37560. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  37561. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  37562. // No children, render content.
  37563. if (!isParent) {
  37564. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  37565. content && renderContent(group, content);
  37566. }
  37567. return group;
  37568. // ----------------------------
  37569. // | Procedures in renderNode |
  37570. // ----------------------------
  37571. function renderBackground(group, bg, useUpperLabel) {
  37572. // For tooltip.
  37573. bg.dataIndex = thisNode.dataIndex;
  37574. bg.seriesIndex = seriesModel.seriesIndex;
  37575. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  37576. var visualBorderColor = thisNode.getVisual('borderColor', true);
  37577. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  37578. updateStyle(bg, function () {
  37579. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  37580. normalStyle.fill = visualBorderColor;
  37581. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  37582. emphasisStyle.fill = emphasisBorderColor;
  37583. if (useUpperLabel) {
  37584. var upperLabelWidth = thisWidth - 2 * borderWidth;
  37585. prepareText(
  37586. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  37587. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  37588. );
  37589. }
  37590. // For old bg.
  37591. else {
  37592. normalStyle.text = emphasisStyle.text = null;
  37593. }
  37594. bg.setStyle(normalStyle);
  37595. setHoverStyle(bg, emphasisStyle);
  37596. });
  37597. group.add(bg);
  37598. }
  37599. function renderContent(group, content) {
  37600. // For tooltip.
  37601. content.dataIndex = thisNode.dataIndex;
  37602. content.seriesIndex = seriesModel.seriesIndex;
  37603. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  37604. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  37605. content.culling = true;
  37606. content.setShape({
  37607. x: borderWidth,
  37608. y: borderWidth,
  37609. width: contentWidth,
  37610. height: contentHeight
  37611. });
  37612. var visualColor = thisNode.getVisual('color', true);
  37613. updateStyle(content, function () {
  37614. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  37615. normalStyle.fill = visualColor;
  37616. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  37617. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  37618. content.setStyle(normalStyle);
  37619. setHoverStyle(content, emphasisStyle);
  37620. });
  37621. group.add(content);
  37622. }
  37623. function updateStyle(element, cb) {
  37624. if (!thisInvisible) {
  37625. // If invisible, do not set visual, otherwise the element will
  37626. // change immediately before animation. We think it is OK to
  37627. // remain its origin color when moving out of the view window.
  37628. cb();
  37629. if (!element.__tmWillVisible) {
  37630. element.invisible = false;
  37631. }
  37632. }
  37633. else {
  37634. // Delay invisible setting utill animation finished,
  37635. // avoid element vanish suddenly before animation.
  37636. !element.invisible && willInvisibleEls.push(element);
  37637. }
  37638. }
  37639. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  37640. var nodeModel = thisNode.getModel();
  37641. var text = retrieve(
  37642. seriesModel.getFormattedLabel(
  37643. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  37644. ),
  37645. nodeModel.get('name')
  37646. );
  37647. if (!upperLabelRect && thisLayout.isLeafRoot) {
  37648. var iconChar = seriesModel.get('drillDownIcon', true);
  37649. text = iconChar ? iconChar + ' ' + text : text;
  37650. }
  37651. var normalLabelModel = nodeModel.getModel(
  37652. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  37653. );
  37654. var emphasisLabelModel = nodeModel.getModel(
  37655. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  37656. );
  37657. var isShow = normalLabelModel.getShallow('show');
  37658. setLabelStyle(
  37659. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  37660. {
  37661. defaultText: isShow ? text : null,
  37662. autoColor: visualColor,
  37663. isRectText: true
  37664. }
  37665. );
  37666. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  37667. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  37668. ? {
  37669. outerWidth: width,
  37670. outerHeight: height,
  37671. minChar: 2
  37672. }
  37673. : null;
  37674. }
  37675. function giveGraphic(storageName, Ctor, depth, z) {
  37676. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  37677. var lasts = lastsForAnimation[storageName];
  37678. if (element) {
  37679. // Remove from oldStorage
  37680. oldStorage[storageName][oldRawIndex] = null;
  37681. prepareAnimationWhenHasOld(lasts, element, storageName);
  37682. }
  37683. // If invisible and no old element, do not create new element (for optimizing).
  37684. else if (!thisInvisible) {
  37685. element = new Ctor({z: calculateZ(depth, z)});
  37686. element.__tmDepth = depth;
  37687. element.__tmStorageName = storageName;
  37688. prepareAnimationWhenNoOld(lasts, element, storageName);
  37689. }
  37690. // Set to thisStorage
  37691. return (thisStorage[storageName][thisRawIndex] = element);
  37692. }
  37693. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  37694. var lastCfg = lasts[thisRawIndex] = {};
  37695. lastCfg.old = storageName === 'nodeGroup'
  37696. ? element.position.slice()
  37697. : extend({}, element.shape);
  37698. }
  37699. // If a element is new, we need to find the animation start point carefully,
  37700. // otherwise it will looks strange when 'zoomToNode'.
  37701. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  37702. var lastCfg = lasts[thisRawIndex] = {};
  37703. var parentNode = thisNode.parentNode;
  37704. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  37705. var parentOldX = 0;
  37706. var parentOldY = 0;
  37707. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  37708. // For convenience, get old bounding rect from background.
  37709. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  37710. if (!reRoot && parentOldBg && parentOldBg.old) {
  37711. parentOldX = parentOldBg.old.width;
  37712. parentOldY = parentOldBg.old.height;
  37713. }
  37714. // When no parent old shape found, its parent is new too,
  37715. // so we can just use {x:0, y:0}.
  37716. lastCfg.old = storageName === 'nodeGroup'
  37717. ? [0, parentOldY]
  37718. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  37719. }
  37720. // Fade in, user can be aware that these nodes are new.
  37721. lastCfg.fadein = storageName !== 'nodeGroup';
  37722. }
  37723. }
  37724. // We can not set all backgroud with the same z, Because the behaviour of
  37725. // drill down and roll up differ background creation sequence from tree
  37726. // hierarchy sequence, which cause that lowser background element overlap
  37727. // upper ones. So we calculate z based on depth.
  37728. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  37729. // treemap with large z overlaps other components.
  37730. function calculateZ(depth, zInLevel) {
  37731. var zb = depth * Z_BASE + zInLevel;
  37732. return (zb - 1) / zb;
  37733. }
  37734. /**
  37735. * @file Treemap action
  37736. */
  37737. var noop$1 = function () {};
  37738. var actionTypes = [
  37739. 'treemapZoomToNode',
  37740. 'treemapRender',
  37741. 'treemapMove'
  37742. ];
  37743. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  37744. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  37745. }
  37746. registerAction(
  37747. {type: 'treemapRootToNode', update: 'updateView'},
  37748. function (payload, ecModel) {
  37749. ecModel.eachComponent(
  37750. {mainType: 'series', subType: 'treemap', query: payload},
  37751. handleRootToNode
  37752. );
  37753. function handleRootToNode(model, index) {
  37754. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  37755. var targetInfo = retrieveTargetInfo(payload, types, model);
  37756. if (targetInfo) {
  37757. var originViewRoot = model.getViewRoot();
  37758. if (originViewRoot) {
  37759. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  37760. ? 'rollUp' : 'drillDown';
  37761. }
  37762. model.resetViewRoot(targetInfo.node);
  37763. }
  37764. }
  37765. }
  37766. );
  37767. var each$10 = each$1;
  37768. var isObject$5 = isObject$1;
  37769. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  37770. /**
  37771. * @param {Object} option
  37772. * @param {string} [option.type] See visualHandlers.
  37773. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  37774. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  37775. * required when mappingMethod is 'linear'
  37776. * @param {Array.<Object>=} [option.pieceList] [
  37777. * {value: someValue},
  37778. * {interval: [min1, max1], visual: {...}},
  37779. * {interval: [min2, max2]}
  37780. * ],
  37781. * required when mappingMethod is 'piecewise'.
  37782. * Visual for only each piece can be specified.
  37783. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  37784. * required when mappingMethod is 'category'.
  37785. * If no option.categories, categories is set
  37786. * as [0, 1, 2, ...].
  37787. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  37788. * @param {(Array|Object|*)} [option.visual] Visual data.
  37789. * when mappingMethod is 'category',
  37790. * visual data can be array or object
  37791. * (like: {cate1: '#222', none: '#fff'})
  37792. * or primary types (which represents
  37793. * defualt category visual), otherwise visual
  37794. * can be array or primary (which will be
  37795. * normalized to array).
  37796. *
  37797. */
  37798. var VisualMapping = function (option) {
  37799. var mappingMethod = option.mappingMethod;
  37800. var visualType = option.type;
  37801. /**
  37802. * @readOnly
  37803. * @type {Object}
  37804. */
  37805. var thisOption = this.option = clone(option);
  37806. /**
  37807. * @readOnly
  37808. * @type {string}
  37809. */
  37810. this.type = visualType;
  37811. /**
  37812. * @readOnly
  37813. * @type {string}
  37814. */
  37815. this.mappingMethod = mappingMethod;
  37816. /**
  37817. * @private
  37818. * @type {Function}
  37819. */
  37820. this._normalizeData = normalizers[mappingMethod];
  37821. var visualHandler = visualHandlers[visualType];
  37822. /**
  37823. * @public
  37824. * @type {Function}
  37825. */
  37826. this.applyVisual = visualHandler.applyVisual;
  37827. /**
  37828. * @public
  37829. * @type {Function}
  37830. */
  37831. this.getColorMapper = visualHandler.getColorMapper;
  37832. /**
  37833. * @private
  37834. * @type {Function}
  37835. */
  37836. this._doMap = visualHandler._doMap[mappingMethod];
  37837. if (mappingMethod === 'piecewise') {
  37838. normalizeVisualRange(thisOption);
  37839. preprocessForPiecewise(thisOption);
  37840. }
  37841. else if (mappingMethod === 'category') {
  37842. thisOption.categories
  37843. ? preprocessForSpecifiedCategory(thisOption)
  37844. // categories is ordinal when thisOption.categories not specified,
  37845. // which need no more preprocess except normalize visual.
  37846. : normalizeVisualRange(thisOption, true);
  37847. }
  37848. else { // mappingMethod === 'linear' or 'fixed'
  37849. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  37850. normalizeVisualRange(thisOption);
  37851. }
  37852. };
  37853. VisualMapping.prototype = {
  37854. constructor: VisualMapping,
  37855. mapValueToVisual: function (value) {
  37856. var normalized = this._normalizeData(value);
  37857. return this._doMap(normalized, value);
  37858. },
  37859. getNormalizer: function () {
  37860. return bind(this._normalizeData, this);
  37861. }
  37862. };
  37863. var visualHandlers = VisualMapping.visualHandlers = {
  37864. color: {
  37865. applyVisual: makeApplyVisual('color'),
  37866. /**
  37867. * Create a mapper function
  37868. * @return {Function}
  37869. */
  37870. getColorMapper: function () {
  37871. var thisOption = this.option;
  37872. return bind(
  37873. thisOption.mappingMethod === 'category'
  37874. ? function (value, isNormalized) {
  37875. !isNormalized && (value = this._normalizeData(value));
  37876. return doMapCategory.call(this, value);
  37877. }
  37878. : function (value, isNormalized, out) {
  37879. // If output rgb array
  37880. // which will be much faster and useful in pixel manipulation
  37881. var returnRGBArray = !!out;
  37882. !isNormalized && (value = this._normalizeData(value));
  37883. out = fastLerp(value, thisOption.parsedVisual, out);
  37884. return returnRGBArray ? out : stringify(out, 'rgba');
  37885. },
  37886. this
  37887. );
  37888. },
  37889. _doMap: {
  37890. linear: function (normalized) {
  37891. return stringify(
  37892. fastLerp(normalized, this.option.parsedVisual),
  37893. 'rgba'
  37894. );
  37895. },
  37896. category: doMapCategory,
  37897. piecewise: function (normalized, value) {
  37898. var result = getSpecifiedVisual.call(this, value);
  37899. if (result == null) {
  37900. result = stringify(
  37901. fastLerp(normalized, this.option.parsedVisual),
  37902. 'rgba'
  37903. );
  37904. }
  37905. return result;
  37906. },
  37907. fixed: doMapFixed
  37908. }
  37909. },
  37910. colorHue: makePartialColorVisualHandler(function (color, value) {
  37911. return modifyHSL(color, value);
  37912. }),
  37913. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  37914. return modifyHSL(color, null, value);
  37915. }),
  37916. colorLightness: makePartialColorVisualHandler(function (color, value) {
  37917. return modifyHSL(color, null, null, value);
  37918. }),
  37919. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  37920. return modifyAlpha(color, value);
  37921. }),
  37922. opacity: {
  37923. applyVisual: makeApplyVisual('opacity'),
  37924. _doMap: makeDoMap([0, 1])
  37925. },
  37926. symbol: {
  37927. applyVisual: function (value, getter, setter) {
  37928. var symbolCfg = this.mapValueToVisual(value);
  37929. if (isString(symbolCfg)) {
  37930. setter('symbol', symbolCfg);
  37931. }
  37932. else if (isObject$5(symbolCfg)) {
  37933. for (var name in symbolCfg) {
  37934. if (symbolCfg.hasOwnProperty(name)) {
  37935. setter(name, symbolCfg[name]);
  37936. }
  37937. }
  37938. }
  37939. },
  37940. _doMap: {
  37941. linear: doMapToArray,
  37942. category: doMapCategory,
  37943. piecewise: function (normalized, value) {
  37944. var result = getSpecifiedVisual.call(this, value);
  37945. if (result == null) {
  37946. result = doMapToArray.call(this, normalized);
  37947. }
  37948. return result;
  37949. },
  37950. fixed: doMapFixed
  37951. }
  37952. },
  37953. symbolSize: {
  37954. applyVisual: makeApplyVisual('symbolSize'),
  37955. _doMap: makeDoMap([0, 1])
  37956. }
  37957. };
  37958. function preprocessForPiecewise(thisOption) {
  37959. var pieceList = thisOption.pieceList;
  37960. thisOption.hasSpecialVisual = false;
  37961. each$1(pieceList, function (piece, index) {
  37962. piece.originIndex = index;
  37963. // piece.visual is "result visual value" but not
  37964. // a visual range, so it does not need to be normalized.
  37965. if (piece.visual != null) {
  37966. thisOption.hasSpecialVisual = true;
  37967. }
  37968. });
  37969. }
  37970. function preprocessForSpecifiedCategory(thisOption) {
  37971. // Hash categories.
  37972. var categories = thisOption.categories;
  37973. var visual = thisOption.visual;
  37974. var categoryMap = thisOption.categoryMap = {};
  37975. each$10(categories, function (cate, index) {
  37976. categoryMap[cate] = index;
  37977. });
  37978. // Process visual map input.
  37979. if (!isArray(visual)) {
  37980. var visualArr = [];
  37981. if (isObject$1(visual)) {
  37982. each$10(visual, function (v, cate) {
  37983. var index = categoryMap[cate];
  37984. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  37985. });
  37986. }
  37987. else { // Is primary type, represents default visual.
  37988. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  37989. }
  37990. visual = setVisualToOption(thisOption, visualArr);
  37991. }
  37992. // Remove categories that has no visual,
  37993. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  37994. for (var i = categories.length - 1; i >= 0; i--) {
  37995. if (visual[i] == null) {
  37996. delete categoryMap[categories[i]];
  37997. categories.pop();
  37998. }
  37999. }
  38000. }
  38001. function normalizeVisualRange(thisOption, isCategory) {
  38002. var visual = thisOption.visual;
  38003. var visualArr = [];
  38004. if (isObject$1(visual)) {
  38005. each$10(visual, function (v) {
  38006. visualArr.push(v);
  38007. });
  38008. }
  38009. else if (visual != null) {
  38010. visualArr.push(visual);
  38011. }
  38012. var doNotNeedPair = {color: 1, symbol: 1};
  38013. if (!isCategory
  38014. && visualArr.length === 1
  38015. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  38016. ) {
  38017. // Do not care visualArr.length === 0, which is illegal.
  38018. visualArr[1] = visualArr[0];
  38019. }
  38020. setVisualToOption(thisOption, visualArr);
  38021. }
  38022. function makePartialColorVisualHandler(applyValue) {
  38023. return {
  38024. applyVisual: function (value, getter, setter) {
  38025. value = this.mapValueToVisual(value);
  38026. // Must not be array value
  38027. setter('color', applyValue(getter('color'), value));
  38028. },
  38029. _doMap: makeDoMap([0, 1])
  38030. };
  38031. }
  38032. function doMapToArray(normalized) {
  38033. var visual = this.option.visual;
  38034. return visual[
  38035. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  38036. ] || {};
  38037. }
  38038. function makeApplyVisual(visualType) {
  38039. return function (value, getter, setter) {
  38040. setter(visualType, this.mapValueToVisual(value));
  38041. };
  38042. }
  38043. function doMapCategory(normalized) {
  38044. var visual = this.option.visual;
  38045. return visual[
  38046. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  38047. ? normalized % visual.length
  38048. : normalized
  38049. ];
  38050. }
  38051. function doMapFixed() {
  38052. return this.option.visual[0];
  38053. }
  38054. function makeDoMap(sourceExtent) {
  38055. return {
  38056. linear: function (normalized) {
  38057. return linearMap(normalized, sourceExtent, this.option.visual, true);
  38058. },
  38059. category: doMapCategory,
  38060. piecewise: function (normalized, value) {
  38061. var result = getSpecifiedVisual.call(this, value);
  38062. if (result == null) {
  38063. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  38064. }
  38065. return result;
  38066. },
  38067. fixed: doMapFixed
  38068. };
  38069. }
  38070. function getSpecifiedVisual(value) {
  38071. var thisOption = this.option;
  38072. var pieceList = thisOption.pieceList;
  38073. if (thisOption.hasSpecialVisual) {
  38074. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  38075. var piece = pieceList[pieceIndex];
  38076. if (piece && piece.visual) {
  38077. return piece.visual[this.type];
  38078. }
  38079. }
  38080. }
  38081. function setVisualToOption(thisOption, visualArr) {
  38082. thisOption.visual = visualArr;
  38083. if (thisOption.type === 'color') {
  38084. thisOption.parsedVisual = map(visualArr, function (item) {
  38085. return parse(item);
  38086. });
  38087. }
  38088. return visualArr;
  38089. }
  38090. /**
  38091. * Normalizers by mapping methods.
  38092. */
  38093. var normalizers = {
  38094. linear: function (value) {
  38095. return linearMap(value, this.option.dataExtent, [0, 1], true);
  38096. },
  38097. piecewise: function (value) {
  38098. var pieceList = this.option.pieceList;
  38099. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  38100. if (pieceIndex != null) {
  38101. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  38102. }
  38103. },
  38104. category: function (value) {
  38105. var index = this.option.categories
  38106. ? this.option.categoryMap[value]
  38107. : value; // ordinal
  38108. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  38109. },
  38110. fixed: noop
  38111. };
  38112. /**
  38113. * List available visual types.
  38114. *
  38115. * @public
  38116. * @return {Array.<string>}
  38117. */
  38118. VisualMapping.listVisualTypes = function () {
  38119. var visualTypes = [];
  38120. each$1(visualHandlers, function (handler, key) {
  38121. visualTypes.push(key);
  38122. });
  38123. return visualTypes;
  38124. };
  38125. /**
  38126. * @public
  38127. */
  38128. VisualMapping.addVisualHandler = function (name, handler) {
  38129. visualHandlers[name] = handler;
  38130. };
  38131. /**
  38132. * @public
  38133. */
  38134. VisualMapping.isValidType = function (visualType) {
  38135. return visualHandlers.hasOwnProperty(visualType);
  38136. };
  38137. /**
  38138. * Convinent method.
  38139. * Visual can be Object or Array or primary type.
  38140. *
  38141. * @public
  38142. */
  38143. VisualMapping.eachVisual = function (visual, callback, context) {
  38144. if (isObject$1(visual)) {
  38145. each$1(visual, callback, context);
  38146. }
  38147. else {
  38148. callback.call(context, visual);
  38149. }
  38150. };
  38151. VisualMapping.mapVisual = function (visual, callback, context) {
  38152. var isPrimary;
  38153. var newVisual = isArray(visual)
  38154. ? []
  38155. : isObject$1(visual)
  38156. ? {}
  38157. : (isPrimary = true, null);
  38158. VisualMapping.eachVisual(visual, function (v, key) {
  38159. var newVal = callback.call(context, v, key);
  38160. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  38161. });
  38162. return newVisual;
  38163. };
  38164. /**
  38165. * @public
  38166. * @param {Object} obj
  38167. * @return {Object} new object containers visual values.
  38168. * If no visuals, return null.
  38169. */
  38170. VisualMapping.retrieveVisuals = function (obj) {
  38171. var ret = {};
  38172. var hasVisual;
  38173. obj && each$10(visualHandlers, function (h, visualType) {
  38174. if (obj.hasOwnProperty(visualType)) {
  38175. ret[visualType] = obj[visualType];
  38176. hasVisual = true;
  38177. }
  38178. });
  38179. return hasVisual ? ret : null;
  38180. };
  38181. /**
  38182. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  38183. *
  38184. * @public
  38185. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  38186. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  38187. * @return {Array.<string>} Sorted visual types.
  38188. */
  38189. VisualMapping.prepareVisualTypes = function (visualTypes) {
  38190. if (isObject$5(visualTypes)) {
  38191. var types = [];
  38192. each$10(visualTypes, function (item, type) {
  38193. types.push(type);
  38194. });
  38195. visualTypes = types;
  38196. }
  38197. else if (isArray(visualTypes)) {
  38198. visualTypes = visualTypes.slice();
  38199. }
  38200. else {
  38201. return [];
  38202. }
  38203. visualTypes.sort(function (type1, type2) {
  38204. // color should be front of colorSaturation, colorAlpha, ...
  38205. // symbol and symbolSize do not matter.
  38206. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  38207. ? 1 : -1;
  38208. });
  38209. return visualTypes;
  38210. };
  38211. /**
  38212. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  38213. * Other visuals are only depends on themself.
  38214. *
  38215. * @public
  38216. * @param {string} visualType1
  38217. * @param {string} visualType2
  38218. * @return {boolean}
  38219. */
  38220. VisualMapping.dependsOn = function (visualType1, visualType2) {
  38221. return visualType2 === 'color'
  38222. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  38223. : visualType1 === visualType2;
  38224. };
  38225. /**
  38226. * @param {number} value
  38227. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  38228. * Always from small to big.
  38229. * @param {boolean} [findClosestWhenOutside=false]
  38230. * @return {number} index
  38231. */
  38232. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  38233. var possibleI;
  38234. var abs = Infinity;
  38235. // value has the higher priority.
  38236. for (var i = 0, len = pieceList.length; i < len; i++) {
  38237. var pieceValue = pieceList[i].value;
  38238. if (pieceValue != null) {
  38239. if (pieceValue === value
  38240. // FIXME
  38241. // It is supposed to compare value according to value type of dimension,
  38242. // but currently value type can exactly be string or number.
  38243. // Compromise for numeric-like string (like '12'), especially
  38244. // in the case that visualMap.categories is ['22', '33'].
  38245. || (typeof pieceValue === 'string' && pieceValue === value + '')
  38246. ) {
  38247. return i;
  38248. }
  38249. findClosestWhenOutside && updatePossible(pieceValue, i);
  38250. }
  38251. }
  38252. for (var i = 0, len = pieceList.length; i < len; i++) {
  38253. var piece = pieceList[i];
  38254. var interval = piece.interval;
  38255. var close = piece.close;
  38256. if (interval) {
  38257. if (interval[0] === -Infinity) {
  38258. if (littleThan(close[1], value, interval[1])) {
  38259. return i;
  38260. }
  38261. }
  38262. else if (interval[1] === Infinity) {
  38263. if (littleThan(close[0], interval[0], value)) {
  38264. return i;
  38265. }
  38266. }
  38267. else if (
  38268. littleThan(close[0], interval[0], value)
  38269. && littleThan(close[1], value, interval[1])
  38270. ) {
  38271. return i;
  38272. }
  38273. findClosestWhenOutside && updatePossible(interval[0], i);
  38274. findClosestWhenOutside && updatePossible(interval[1], i);
  38275. }
  38276. }
  38277. if (findClosestWhenOutside) {
  38278. return value === Infinity
  38279. ? pieceList.length - 1
  38280. : value === -Infinity
  38281. ? 0
  38282. : possibleI;
  38283. }
  38284. function updatePossible(val, index) {
  38285. var newAbs = Math.abs(val - value);
  38286. if (newAbs < abs) {
  38287. abs = newAbs;
  38288. possibleI = index;
  38289. }
  38290. }
  38291. };
  38292. function littleThan(close, a, b) {
  38293. return close ? a <= b : a < b;
  38294. }
  38295. var isArray$2 = isArray;
  38296. var ITEM_STYLE_NORMAL = 'itemStyle';
  38297. var treemapVisual = {
  38298. seriesType: 'treemap',
  38299. reset: function (seriesModel, ecModel, api, payload) {
  38300. var tree = seriesModel.getData().tree;
  38301. var root = tree.root;
  38302. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  38303. if (root.isRemoved()) {
  38304. return;
  38305. }
  38306. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  38307. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  38308. });
  38309. travelTree(
  38310. root, // Visual should calculate from tree root but not view root.
  38311. {},
  38312. levelItemStyles,
  38313. seriesItemStyleModel,
  38314. seriesModel.getViewRoot().getAncestors(),
  38315. seriesModel
  38316. );
  38317. }
  38318. };
  38319. function travelTree(
  38320. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  38321. viewRootAncestors, seriesModel
  38322. ) {
  38323. var nodeModel = node.getModel();
  38324. var nodeLayout = node.getLayout();
  38325. // Optimize
  38326. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  38327. return;
  38328. }
  38329. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  38330. var levelItemStyle = levelItemStyles[node.depth];
  38331. var visuals = buildVisuals(
  38332. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  38333. );
  38334. // calculate border color
  38335. var borderColor = nodeItemStyleModel.get('borderColor');
  38336. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  38337. var thisNodeColor;
  38338. if (borderColorSaturation != null) {
  38339. // For performance, do not always execute 'calculateColor'.
  38340. thisNodeColor = calculateColor(visuals, node);
  38341. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  38342. }
  38343. node.setVisual('borderColor', borderColor);
  38344. var viewChildren = node.viewChildren;
  38345. if (!viewChildren || !viewChildren.length) {
  38346. thisNodeColor = calculateColor(visuals, node);
  38347. // Apply visual to this node.
  38348. node.setVisual('color', thisNodeColor);
  38349. }
  38350. else {
  38351. var mapping = buildVisualMapping(
  38352. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  38353. );
  38354. // Designate visual to children.
  38355. each$1(viewChildren, function (child, index) {
  38356. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  38357. if (child.depth >= viewRootAncestors.length
  38358. || child === viewRootAncestors[child.depth]
  38359. ) {
  38360. var childVisual = mapVisual$1(
  38361. nodeModel, visuals, child, index, mapping, seriesModel
  38362. );
  38363. travelTree(
  38364. child, childVisual, levelItemStyles, seriesItemStyleModel,
  38365. viewRootAncestors, seriesModel
  38366. );
  38367. }
  38368. });
  38369. }
  38370. }
  38371. function buildVisuals(
  38372. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  38373. ) {
  38374. var visuals = extend({}, designatedVisual);
  38375. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  38376. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  38377. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  38378. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  38379. val == null && (val = designatedVisual[visualName]);
  38380. val == null && (val = seriesItemStyleModel.get(visualName));
  38381. val != null && (visuals[visualName] = val);
  38382. });
  38383. return visuals;
  38384. }
  38385. function calculateColor(visuals) {
  38386. var color = getValueVisualDefine(visuals, 'color');
  38387. if (color) {
  38388. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  38389. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  38390. if (colorSaturation) {
  38391. color = modifyHSL(color, null, null, colorSaturation);
  38392. }
  38393. if (colorAlpha) {
  38394. color = modifyAlpha(color, colorAlpha);
  38395. }
  38396. return color;
  38397. }
  38398. }
  38399. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  38400. return thisNodeColor != null
  38401. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  38402. : null;
  38403. }
  38404. function getValueVisualDefine(visuals, name) {
  38405. var value = visuals[name];
  38406. if (value != null && value !== 'none') {
  38407. return value;
  38408. }
  38409. }
  38410. function buildVisualMapping(
  38411. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  38412. ) {
  38413. if (!viewChildren || !viewChildren.length) {
  38414. return;
  38415. }
  38416. var rangeVisual = getRangeVisual(nodeModel, 'color')
  38417. || (
  38418. visuals.color != null
  38419. && visuals.color !== 'none'
  38420. && (
  38421. getRangeVisual(nodeModel, 'colorAlpha')
  38422. || getRangeVisual(nodeModel, 'colorSaturation')
  38423. )
  38424. );
  38425. if (!rangeVisual) {
  38426. return;
  38427. }
  38428. var visualMin = nodeModel.get('visualMin');
  38429. var visualMax = nodeModel.get('visualMax');
  38430. var dataExtent = nodeLayout.dataExtent.slice();
  38431. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  38432. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  38433. var colorMappingBy = nodeModel.get('colorMappingBy');
  38434. var opt = {
  38435. type: rangeVisual.name,
  38436. dataExtent: dataExtent,
  38437. visual: rangeVisual.range
  38438. };
  38439. if (opt.type === 'color'
  38440. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  38441. ) {
  38442. opt.mappingMethod = 'category';
  38443. opt.loop = true;
  38444. // categories is ordinal, so do not set opt.categories.
  38445. }
  38446. else {
  38447. opt.mappingMethod = 'linear';
  38448. }
  38449. var mapping = new VisualMapping(opt);
  38450. mapping.__drColorMappingBy = colorMappingBy;
  38451. return mapping;
  38452. }
  38453. // Notice: If we dont have the attribute 'colorRange', but only use
  38454. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  38455. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  38456. // this problem will be encountered:
  38457. // If a level-1 node dont have children, and its siblings has children,
  38458. // and colorRange is set on level-1, then the node can not be colored.
  38459. // So we separate 'colorRange' and 'color' to different attributes.
  38460. function getRangeVisual(nodeModel, name) {
  38461. // 'colorRange', 'colorARange', 'colorSRange'.
  38462. // If not exsits on this node, fetch from levels and series.
  38463. var range = nodeModel.get(name);
  38464. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  38465. }
  38466. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  38467. var childVisuals = extend({}, visuals);
  38468. if (mapping) {
  38469. var mappingType = mapping.type;
  38470. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  38471. var value =
  38472. colorMappingBy === 'index'
  38473. ? index
  38474. : colorMappingBy === 'id'
  38475. ? seriesModel.mapIdToIndex(child.getId())
  38476. : child.getValue(nodeModel.get('visualDimension'));
  38477. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  38478. }
  38479. return childVisuals;
  38480. }
  38481. var mathMax$4 = Math.max;
  38482. var mathMin$4 = Math.min;
  38483. var retrieveValue = retrieve;
  38484. var each$11 = each$1;
  38485. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  38486. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  38487. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  38488. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  38489. /**
  38490. * @public
  38491. */
  38492. var treemapLayout = {
  38493. seriesType: 'treemap',
  38494. reset: function (seriesModel, ecModel, api, payload) {
  38495. // Layout result in each node:
  38496. // {x, y, width, height, area, borderWidth}
  38497. var ecWidth = api.getWidth();
  38498. var ecHeight = api.getHeight();
  38499. var seriesOption = seriesModel.option;
  38500. var layoutInfo = getLayoutRect(
  38501. seriesModel.getBoxLayoutParams(),
  38502. {
  38503. width: api.getWidth(),
  38504. height: api.getHeight()
  38505. }
  38506. );
  38507. var size = seriesOption.size || []; // Compatible with ec2.
  38508. var containerWidth = parsePercent$1(
  38509. retrieveValue(layoutInfo.width, size[0]),
  38510. ecWidth
  38511. );
  38512. var containerHeight = parsePercent$1(
  38513. retrieveValue(layoutInfo.height, size[1]),
  38514. ecHeight
  38515. );
  38516. // Fetch payload info.
  38517. var payloadType = payload && payload.type;
  38518. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  38519. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  38520. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  38521. ? payload.rootRect : null;
  38522. var viewRoot = seriesModel.getViewRoot();
  38523. var viewAbovePath = getPathToRoot(viewRoot);
  38524. if (payloadType !== 'treemapMove') {
  38525. var rootSize = payloadType === 'treemapZoomToNode'
  38526. ? estimateRootSize(
  38527. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  38528. )
  38529. : rootRect
  38530. ? [rootRect.width, rootRect.height]
  38531. : [containerWidth, containerHeight];
  38532. var sort = seriesOption.sort;
  38533. if (sort && sort !== 'asc' && sort !== 'desc') {
  38534. sort = 'desc';
  38535. }
  38536. var options = {
  38537. squareRatio: seriesOption.squareRatio,
  38538. sort: sort,
  38539. leafDepth: seriesOption.leafDepth
  38540. };
  38541. // layout should be cleared because using updateView but not update.
  38542. viewRoot.hostTree.clearLayouts();
  38543. // TODO
  38544. // optimize: if out of view clip, do not layout.
  38545. // But take care that if do not render node out of view clip,
  38546. // how to calculate start po
  38547. var viewRootLayout = {
  38548. x: 0, y: 0,
  38549. width: rootSize[0], height: rootSize[1],
  38550. area: rootSize[0] * rootSize[1]
  38551. };
  38552. viewRoot.setLayout(viewRootLayout);
  38553. squarify(viewRoot, options, false, 0);
  38554. // Supplement layout.
  38555. var viewRootLayout = viewRoot.getLayout();
  38556. each$11(viewAbovePath, function (node, index) {
  38557. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  38558. node.setLayout(extend(
  38559. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  38560. viewRootLayout
  38561. ));
  38562. });
  38563. }
  38564. var treeRoot = seriesModel.getData().tree.root;
  38565. treeRoot.setLayout(
  38566. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  38567. true
  38568. );
  38569. seriesModel.setLayoutInfo(layoutInfo);
  38570. // FIXME
  38571. // 现在没有clip功能,暂时取ec高宽。
  38572. prunning(
  38573. treeRoot,
  38574. // Transform to base element coordinate system.
  38575. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  38576. viewAbovePath,
  38577. viewRoot,
  38578. 0
  38579. );
  38580. }
  38581. };
  38582. /**
  38583. * Layout treemap with squarify algorithm.
  38584. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  38585. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  38586. *
  38587. * @protected
  38588. * @param {module:echarts/data/Tree~TreeNode} node
  38589. * @param {Object} options
  38590. * @param {string} options.sort 'asc' or 'desc'
  38591. * @param {number} options.squareRatio
  38592. * @param {boolean} hideChildren
  38593. * @param {number} depth
  38594. */
  38595. function squarify(node, options, hideChildren, depth) {
  38596. var width;
  38597. var height;
  38598. if (node.isRemoved()) {
  38599. return;
  38600. }
  38601. var thisLayout = node.getLayout();
  38602. width = thisLayout.width;
  38603. height = thisLayout.height;
  38604. // Considering border and gap
  38605. var nodeModel = node.getModel();
  38606. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  38607. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  38608. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  38609. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  38610. var layoutOffset = borderWidth - halfGapWidth;
  38611. var layoutOffsetUpper = upperHeight - halfGapWidth;
  38612. var nodeModel = node.getModel();
  38613. node.setLayout({
  38614. borderWidth: borderWidth,
  38615. upperHeight: upperHeight,
  38616. upperLabelHeight: upperLabelHeight
  38617. }, true);
  38618. width = mathMax$4(width - 2 * layoutOffset, 0);
  38619. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  38620. var totalArea = width * height;
  38621. var viewChildren = initChildren(
  38622. node, nodeModel, totalArea, options, hideChildren, depth
  38623. );
  38624. if (!viewChildren.length) {
  38625. return;
  38626. }
  38627. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  38628. var rowFixedLength = mathMin$4(width, height);
  38629. var best = Infinity; // the best row score so far
  38630. var row = [];
  38631. row.area = 0;
  38632. for (var i = 0, len = viewChildren.length; i < len;) {
  38633. var child = viewChildren[i];
  38634. row.push(child);
  38635. row.area += child.getLayout().area;
  38636. var score = worst(row, rowFixedLength, options.squareRatio);
  38637. // continue with this orientation
  38638. if (score <= best) {
  38639. i++;
  38640. best = score;
  38641. }
  38642. // abort, and try a different orientation
  38643. else {
  38644. row.area -= row.pop().getLayout().area;
  38645. position(row, rowFixedLength, rect, halfGapWidth, false);
  38646. rowFixedLength = mathMin$4(rect.width, rect.height);
  38647. row.length = row.area = 0;
  38648. best = Infinity;
  38649. }
  38650. }
  38651. if (row.length) {
  38652. position(row, rowFixedLength, rect, halfGapWidth, true);
  38653. }
  38654. if (!hideChildren) {
  38655. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  38656. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  38657. hideChildren = true;
  38658. }
  38659. }
  38660. for (var i = 0, len = viewChildren.length; i < len; i++) {
  38661. squarify(viewChildren[i], options, hideChildren, depth + 1);
  38662. }
  38663. }
  38664. /**
  38665. * Set area to each child, and calculate data extent for visual coding.
  38666. */
  38667. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  38668. var viewChildren = node.children || [];
  38669. var orderBy = options.sort;
  38670. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  38671. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  38672. // leafDepth has higher priority.
  38673. if (hideChildren && !overLeafDepth) {
  38674. return (node.viewChildren = []);
  38675. }
  38676. // Sort children, order by desc.
  38677. viewChildren = filter(viewChildren, function (child) {
  38678. return !child.isRemoved();
  38679. });
  38680. sort$1(viewChildren, orderBy);
  38681. var info = statistic(nodeModel, viewChildren, orderBy);
  38682. if (info.sum === 0) {
  38683. return (node.viewChildren = []);
  38684. }
  38685. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  38686. if (info.sum === 0) {
  38687. return (node.viewChildren = []);
  38688. }
  38689. // Set area to each child.
  38690. for (var i = 0, len = viewChildren.length; i < len; i++) {
  38691. var area = viewChildren[i].getValue() / info.sum * totalArea;
  38692. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  38693. viewChildren[i].setLayout({area: area});
  38694. }
  38695. if (overLeafDepth) {
  38696. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  38697. viewChildren.length = 0;
  38698. }
  38699. node.viewChildren = viewChildren;
  38700. node.setLayout({dataExtent: info.dataExtent}, true);
  38701. return viewChildren;
  38702. }
  38703. /**
  38704. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  38705. */
  38706. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  38707. // visibleMin is not supported yet when no option.sort.
  38708. if (!orderBy) {
  38709. return sum;
  38710. }
  38711. var visibleMin = nodeModel.get('visibleMin');
  38712. var len = orderedChildren.length;
  38713. var deletePoint = len;
  38714. // Always travel from little value to big value.
  38715. for (var i = len - 1; i >= 0; i--) {
  38716. var value = orderedChildren[
  38717. orderBy === 'asc' ? len - i - 1 : i
  38718. ].getValue();
  38719. if (value / sum * totalArea < visibleMin) {
  38720. deletePoint = i;
  38721. sum -= value;
  38722. }
  38723. }
  38724. orderBy === 'asc'
  38725. ? orderedChildren.splice(0, len - deletePoint)
  38726. : orderedChildren.splice(deletePoint, len - deletePoint);
  38727. return sum;
  38728. }
  38729. /**
  38730. * Sort
  38731. */
  38732. function sort$1(viewChildren, orderBy) {
  38733. if (orderBy) {
  38734. viewChildren.sort(function (a, b) {
  38735. var diff = orderBy === 'asc'
  38736. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  38737. return diff === 0
  38738. ? (orderBy === 'asc'
  38739. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  38740. )
  38741. : diff;
  38742. });
  38743. }
  38744. return viewChildren;
  38745. }
  38746. /**
  38747. * Statistic
  38748. */
  38749. function statistic(nodeModel, children, orderBy) {
  38750. // Calculate sum.
  38751. var sum = 0;
  38752. for (var i = 0, len = children.length; i < len; i++) {
  38753. sum += children[i].getValue();
  38754. }
  38755. // Statistic data extent for latter visual coding.
  38756. // Notice: data extent should be calculate based on raw children
  38757. // but not filtered view children, otherwise visual mapping will not
  38758. // be stable when zoom (where children is filtered by visibleMin).
  38759. var dimension = nodeModel.get('visualDimension');
  38760. var dataExtent;
  38761. // The same as area dimension.
  38762. if (!children || !children.length) {
  38763. dataExtent = [NaN, NaN];
  38764. }
  38765. else if (dimension === 'value' && orderBy) {
  38766. dataExtent = [
  38767. children[children.length - 1].getValue(),
  38768. children[0].getValue()
  38769. ];
  38770. orderBy === 'asc' && dataExtent.reverse();
  38771. }
  38772. // Other dimension.
  38773. else {
  38774. var dataExtent = [Infinity, -Infinity];
  38775. each$11(children, function (child) {
  38776. var value = child.getValue(dimension);
  38777. value < dataExtent[0] && (dataExtent[0] = value);
  38778. value > dataExtent[1] && (dataExtent[1] = value);
  38779. });
  38780. }
  38781. return {sum: sum, dataExtent: dataExtent};
  38782. }
  38783. /**
  38784. * Computes the score for the specified row,
  38785. * as the worst aspect ratio.
  38786. */
  38787. function worst(row, rowFixedLength, ratio) {
  38788. var areaMax = 0;
  38789. var areaMin = Infinity;
  38790. for (var i = 0, area, len = row.length; i < len; i++) {
  38791. area = row[i].getLayout().area;
  38792. if (area) {
  38793. area < areaMin && (areaMin = area);
  38794. area > areaMax && (areaMax = area);
  38795. }
  38796. }
  38797. var squareArea = row.area * row.area;
  38798. var f = rowFixedLength * rowFixedLength * ratio;
  38799. return squareArea
  38800. ? mathMax$4(
  38801. (f * areaMax) / squareArea,
  38802. squareArea / (f * areaMin)
  38803. )
  38804. : Infinity;
  38805. }
  38806. /**
  38807. * Positions the specified row of nodes. Modifies `rect`.
  38808. */
  38809. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  38810. // When rowFixedLength === rect.width,
  38811. // it is horizontal subdivision,
  38812. // rowFixedLength is the width of the subdivision,
  38813. // rowOtherLength is the height of the subdivision,
  38814. // and nodes will be positioned from left to right.
  38815. // wh[idx0WhenH] means: when horizontal,
  38816. // wh[idx0WhenH] => wh[0] => 'width'.
  38817. // xy[idx1WhenH] => xy[1] => 'y'.
  38818. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  38819. var idx1WhenH = 1 - idx0WhenH;
  38820. var xy = ['x', 'y'];
  38821. var wh = ['width', 'height'];
  38822. var last = rect[xy[idx0WhenH]];
  38823. var rowOtherLength = rowFixedLength
  38824. ? row.area / rowFixedLength : 0;
  38825. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  38826. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  38827. }
  38828. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  38829. var node = row[i];
  38830. var nodeLayout = {};
  38831. var step = rowOtherLength
  38832. ? node.getLayout().area / rowOtherLength : 0;
  38833. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  38834. // We use Math.max/min to avoid negative width/height when considering gap width.
  38835. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  38836. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  38837. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  38838. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  38839. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  38840. last += modWH;
  38841. node.setLayout(nodeLayout, true);
  38842. }
  38843. rect[xy[idx1WhenH]] += rowOtherLength;
  38844. rect[wh[idx1WhenH]] -= rowOtherLength;
  38845. }
  38846. // Return [containerWidth, containerHeight] as defualt.
  38847. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  38848. // If targetInfo.node exists, we zoom to the node,
  38849. // so estimate whold width and heigth by target node.
  38850. var currNode = (targetInfo || {}).node;
  38851. var defaultSize = [containerWidth, containerHeight];
  38852. if (!currNode || currNode === viewRoot) {
  38853. return defaultSize;
  38854. }
  38855. var parent;
  38856. var viewArea = containerWidth * containerHeight;
  38857. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  38858. while (parent = currNode.parentNode) { // jshint ignore:line
  38859. var sum = 0;
  38860. var siblings = parent.children;
  38861. for (var i = 0, len = siblings.length; i < len; i++) {
  38862. sum += siblings[i].getValue();
  38863. }
  38864. var currNodeValue = currNode.getValue();
  38865. if (currNodeValue === 0) {
  38866. return defaultSize;
  38867. }
  38868. area *= sum / currNodeValue;
  38869. // Considering border, suppose aspect ratio is 1.
  38870. var parentModel = parent.getModel();
  38871. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  38872. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  38873. area += 4 * borderWidth * borderWidth
  38874. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  38875. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  38876. currNode = parent;
  38877. }
  38878. area < viewArea && (area = viewArea);
  38879. var scale = Math.pow(area / viewArea, 0.5);
  38880. return [containerWidth * scale, containerHeight * scale];
  38881. }
  38882. // Root postion base on coord of containerGroup
  38883. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  38884. if (rootRect) {
  38885. return {x: rootRect.x, y: rootRect.y};
  38886. }
  38887. var defaultPosition = {x: 0, y: 0};
  38888. if (!targetInfo) {
  38889. return defaultPosition;
  38890. }
  38891. // If targetInfo is fetched by 'retrieveTargetInfo',
  38892. // old tree and new tree are the same tree,
  38893. // so the node still exists and we can visit it.
  38894. var targetNode = targetInfo.node;
  38895. var layout = targetNode.getLayout();
  38896. if (!layout) {
  38897. return defaultPosition;
  38898. }
  38899. // Transform coord from local to container.
  38900. var targetCenter = [layout.width / 2, layout.height / 2];
  38901. var node = targetNode;
  38902. while (node) {
  38903. var nodeLayout = node.getLayout();
  38904. targetCenter[0] += nodeLayout.x;
  38905. targetCenter[1] += nodeLayout.y;
  38906. node = node.parentNode;
  38907. }
  38908. return {
  38909. x: layoutInfo.width / 2 - targetCenter[0],
  38910. y: layoutInfo.height / 2 - targetCenter[1]
  38911. };
  38912. }
  38913. // Mark nodes visible for prunning when visual coding and rendering.
  38914. // Prunning depends on layout and root position, so we have to do it after layout.
  38915. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  38916. var nodeLayout = node.getLayout();
  38917. var nodeInViewAbovePath = viewAbovePath[depth];
  38918. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  38919. if (
  38920. (nodeInViewAbovePath && !isAboveViewRoot)
  38921. || (depth === viewAbovePath.length && node !== viewRoot)
  38922. ) {
  38923. return;
  38924. }
  38925. node.setLayout({
  38926. // isInView means: viewRoot sub tree + viewAbovePath
  38927. isInView: true,
  38928. // invisible only means: outside view clip so that the node can not
  38929. // see but still layout for animation preparation but not render.
  38930. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  38931. isAboveViewRoot: isAboveViewRoot
  38932. }, true);
  38933. // Transform to child coordinate.
  38934. var childClipRect = new BoundingRect(
  38935. clipRect.x - nodeLayout.x,
  38936. clipRect.y - nodeLayout.y,
  38937. clipRect.width,
  38938. clipRect.height
  38939. );
  38940. each$11(node.viewChildren || [], function (child) {
  38941. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  38942. });
  38943. }
  38944. function getUpperLabelHeight(model) {
  38945. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  38946. }
  38947. registerVisual(treemapVisual);
  38948. registerLayout(treemapLayout);
  38949. /**
  38950. * Graph data structure
  38951. *
  38952. * @module echarts/data/Graph
  38953. * @author Yi Shen(https://www.github.com/pissang)
  38954. */
  38955. // id may be function name of Object, add a prefix to avoid this problem.
  38956. function generateNodeKey (id) {
  38957. return '_EC_' + id;
  38958. }
  38959. /**
  38960. * @alias module:echarts/data/Graph
  38961. * @constructor
  38962. * @param {boolean} directed
  38963. */
  38964. var Graph = function(directed) {
  38965. /**
  38966. * 是否是有向图
  38967. * @type {boolean}
  38968. * @private
  38969. */
  38970. this._directed = directed || false;
  38971. /**
  38972. * @type {Array.<module:echarts/data/Graph.Node>}
  38973. * @readOnly
  38974. */
  38975. this.nodes = [];
  38976. /**
  38977. * @type {Array.<module:echarts/data/Graph.Edge>}
  38978. * @readOnly
  38979. */
  38980. this.edges = [];
  38981. /**
  38982. * @type {Object.<string, module:echarts/data/Graph.Node>}
  38983. * @private
  38984. */
  38985. this._nodesMap = {};
  38986. /**
  38987. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  38988. * @private
  38989. */
  38990. this._edgesMap = {};
  38991. /**
  38992. * @type {module:echarts/data/List}
  38993. * @readOnly
  38994. */
  38995. this.data;
  38996. /**
  38997. * @type {module:echarts/data/List}
  38998. * @readOnly
  38999. */
  39000. this.edgeData;
  39001. };
  39002. var graphProto = Graph.prototype;
  39003. /**
  39004. * @type {string}
  39005. */
  39006. graphProto.type = 'graph';
  39007. /**
  39008. * If is directed graph
  39009. * @return {boolean}
  39010. */
  39011. graphProto.isDirected = function () {
  39012. return this._directed;
  39013. };
  39014. /**
  39015. * Add a new node
  39016. * @param {string} id
  39017. * @param {number} [dataIndex]
  39018. */
  39019. graphProto.addNode = function (id, dataIndex) {
  39020. id = id || ('' + dataIndex);
  39021. var nodesMap = this._nodesMap;
  39022. if (nodesMap[generateNodeKey(id)]) {
  39023. if (__DEV__) {
  39024. console.error('Graph nodes have duplicate name or id');
  39025. }
  39026. return;
  39027. }
  39028. var node = new Node(id, dataIndex);
  39029. node.hostGraph = this;
  39030. this.nodes.push(node);
  39031. nodesMap[generateNodeKey(id)] = node;
  39032. return node;
  39033. };
  39034. /**
  39035. * Get node by data index
  39036. * @param {number} dataIndex
  39037. * @return {module:echarts/data/Graph~Node}
  39038. */
  39039. graphProto.getNodeByIndex = function (dataIndex) {
  39040. var rawIdx = this.data.getRawIndex(dataIndex);
  39041. return this.nodes[rawIdx];
  39042. };
  39043. /**
  39044. * Get node by id
  39045. * @param {string} id
  39046. * @return {module:echarts/data/Graph.Node}
  39047. */
  39048. graphProto.getNodeById = function (id) {
  39049. return this._nodesMap[generateNodeKey(id)];
  39050. };
  39051. /**
  39052. * Add a new edge
  39053. * @param {number|string|module:echarts/data/Graph.Node} n1
  39054. * @param {number|string|module:echarts/data/Graph.Node} n2
  39055. * @param {number} [dataIndex=-1]
  39056. * @return {module:echarts/data/Graph.Edge}
  39057. */
  39058. graphProto.addEdge = function (n1, n2, dataIndex) {
  39059. var nodesMap = this._nodesMap;
  39060. var edgesMap = this._edgesMap;
  39061. // PNEDING
  39062. if (typeof n1 === 'number') {
  39063. n1 = this.nodes[n1];
  39064. }
  39065. if (typeof n2 === 'number') {
  39066. n2 = this.nodes[n2];
  39067. }
  39068. if (!Node.isInstance(n1)) {
  39069. n1 = nodesMap[generateNodeKey(n1)];
  39070. }
  39071. if (!Node.isInstance(n2)) {
  39072. n2 = nodesMap[generateNodeKey(n2)];
  39073. }
  39074. if (!n1 || !n2) {
  39075. return;
  39076. }
  39077. var key = n1.id + '-' + n2.id;
  39078. // PENDING
  39079. if (edgesMap[key]) {
  39080. return;
  39081. }
  39082. var edge = new Edge(n1, n2, dataIndex);
  39083. edge.hostGraph = this;
  39084. if (this._directed) {
  39085. n1.outEdges.push(edge);
  39086. n2.inEdges.push(edge);
  39087. }
  39088. n1.edges.push(edge);
  39089. if (n1 !== n2) {
  39090. n2.edges.push(edge);
  39091. }
  39092. this.edges.push(edge);
  39093. edgesMap[key] = edge;
  39094. return edge;
  39095. };
  39096. /**
  39097. * Get edge by data index
  39098. * @param {number} dataIndex
  39099. * @return {module:echarts/data/Graph~Node}
  39100. */
  39101. graphProto.getEdgeByIndex = function (dataIndex) {
  39102. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  39103. return this.edges[rawIdx];
  39104. };
  39105. /**
  39106. * Get edge by two linked nodes
  39107. * @param {module:echarts/data/Graph.Node|string} n1
  39108. * @param {module:echarts/data/Graph.Node|string} n2
  39109. * @return {module:echarts/data/Graph.Edge}
  39110. */
  39111. graphProto.getEdge = function (n1, n2) {
  39112. if (Node.isInstance(n1)) {
  39113. n1 = n1.id;
  39114. }
  39115. if (Node.isInstance(n2)) {
  39116. n2 = n2.id;
  39117. }
  39118. var edgesMap = this._edgesMap;
  39119. if (this._directed) {
  39120. return edgesMap[n1 + '-' + n2];
  39121. } else {
  39122. return edgesMap[n1 + '-' + n2]
  39123. || edgesMap[n2 + '-' + n1];
  39124. }
  39125. };
  39126. /**
  39127. * Iterate all nodes
  39128. * @param {Function} cb
  39129. * @param {*} [context]
  39130. */
  39131. graphProto.eachNode = function (cb, context) {
  39132. var nodes = this.nodes;
  39133. var len = nodes.length;
  39134. for (var i = 0; i < len; i++) {
  39135. if (nodes[i].dataIndex >= 0) {
  39136. cb.call(context, nodes[i], i);
  39137. }
  39138. }
  39139. };
  39140. /**
  39141. * Iterate all edges
  39142. * @param {Function} cb
  39143. * @param {*} [context]
  39144. */
  39145. graphProto.eachEdge = function (cb, context) {
  39146. var edges = this.edges;
  39147. var len = edges.length;
  39148. for (var i = 0; i < len; i++) {
  39149. if (edges[i].dataIndex >= 0
  39150. && edges[i].node1.dataIndex >= 0
  39151. && edges[i].node2.dataIndex >= 0
  39152. ) {
  39153. cb.call(context, edges[i], i);
  39154. }
  39155. }
  39156. };
  39157. /**
  39158. * Breadth first traverse
  39159. * @param {Function} cb
  39160. * @param {module:echarts/data/Graph.Node} startNode
  39161. * @param {string} [direction='none'] 'none'|'in'|'out'
  39162. * @param {*} [context]
  39163. */
  39164. graphProto.breadthFirstTraverse = function (
  39165. cb, startNode, direction, context
  39166. ) {
  39167. if (!Node.isInstance(startNode)) {
  39168. startNode = this._nodesMap[generateNodeKey(startNode)];
  39169. }
  39170. if (!startNode) {
  39171. return;
  39172. }
  39173. var edgeType = direction === 'out'
  39174. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  39175. for (var i = 0; i < this.nodes.length; i++) {
  39176. this.nodes[i].__visited = false;
  39177. }
  39178. if (cb.call(context, startNode, null)) {
  39179. return;
  39180. }
  39181. var queue = [startNode];
  39182. while (queue.length) {
  39183. var currentNode = queue.shift();
  39184. var edges = currentNode[edgeType];
  39185. for (var i = 0; i < edges.length; i++) {
  39186. var e = edges[i];
  39187. var otherNode = e.node1 === currentNode
  39188. ? e.node2 : e.node1;
  39189. if (!otherNode.__visited) {
  39190. if (cb.call(context, otherNode, currentNode)) {
  39191. // Stop traversing
  39192. return;
  39193. }
  39194. queue.push(otherNode);
  39195. otherNode.__visited = true;
  39196. }
  39197. }
  39198. }
  39199. };
  39200. // TODO
  39201. // graphProto.depthFirstTraverse = function (
  39202. // cb, startNode, direction, context
  39203. // ) {
  39204. // };
  39205. // Filter update
  39206. graphProto.update = function () {
  39207. var data = this.data;
  39208. var edgeData = this.edgeData;
  39209. var nodes = this.nodes;
  39210. var edges = this.edges;
  39211. for (var i = 0, len = nodes.length; i < len; i++) {
  39212. nodes[i].dataIndex = -1;
  39213. }
  39214. for (var i = 0, len = data.count(); i < len; i++) {
  39215. nodes[data.getRawIndex(i)].dataIndex = i;
  39216. }
  39217. edgeData.filterSelf(function (idx) {
  39218. var edge = edges[edgeData.getRawIndex(idx)];
  39219. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  39220. });
  39221. // Update edge
  39222. for (var i = 0, len = edges.length; i < len; i++) {
  39223. edges[i].dataIndex = -1;
  39224. }
  39225. for (var i = 0, len = edgeData.count(); i < len; i++) {
  39226. edges[edgeData.getRawIndex(i)].dataIndex = i;
  39227. }
  39228. };
  39229. /**
  39230. * @return {module:echarts/data/Graph}
  39231. */
  39232. graphProto.clone = function () {
  39233. var graph = new Graph(this._directed);
  39234. var nodes = this.nodes;
  39235. var edges = this.edges;
  39236. for (var i = 0; i < nodes.length; i++) {
  39237. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  39238. }
  39239. for (var i = 0; i < edges.length; i++) {
  39240. var e = edges[i];
  39241. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  39242. }
  39243. return graph;
  39244. };
  39245. /**
  39246. * @alias module:echarts/data/Graph.Node
  39247. */
  39248. function Node(id, dataIndex) {
  39249. /**
  39250. * @type {string}
  39251. */
  39252. this.id = id == null ? '' : id;
  39253. /**
  39254. * @type {Array.<module:echarts/data/Graph.Edge>}
  39255. */
  39256. this.inEdges = [];
  39257. /**
  39258. * @type {Array.<module:echarts/data/Graph.Edge>}
  39259. */
  39260. this.outEdges = [];
  39261. /**
  39262. * @type {Array.<module:echarts/data/Graph.Edge>}
  39263. */
  39264. this.edges = [];
  39265. /**
  39266. * @type {module:echarts/data/Graph}
  39267. */
  39268. this.hostGraph;
  39269. /**
  39270. * @type {number}
  39271. */
  39272. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  39273. }
  39274. Node.prototype = {
  39275. constructor: Node,
  39276. /**
  39277. * @return {number}
  39278. */
  39279. degree: function () {
  39280. return this.edges.length;
  39281. },
  39282. /**
  39283. * @return {number}
  39284. */
  39285. inDegree: function () {
  39286. return this.inEdges.length;
  39287. },
  39288. /**
  39289. * @return {number}
  39290. */
  39291. outDegree: function () {
  39292. return this.outEdges.length;
  39293. },
  39294. /**
  39295. * @param {string} [path]
  39296. * @return {module:echarts/model/Model}
  39297. */
  39298. getModel: function (path) {
  39299. if (this.dataIndex < 0) {
  39300. return;
  39301. }
  39302. var graph = this.hostGraph;
  39303. var itemModel = graph.data.getItemModel(this.dataIndex);
  39304. return itemModel.getModel(path);
  39305. }
  39306. };
  39307. /**
  39308. * 图边
  39309. * @alias module:echarts/data/Graph.Edge
  39310. * @param {module:echarts/data/Graph.Node} n1
  39311. * @param {module:echarts/data/Graph.Node} n2
  39312. * @param {number} [dataIndex=-1]
  39313. */
  39314. function Edge(n1, n2, dataIndex) {
  39315. /**
  39316. * 节点1,如果是有向图则为源节点
  39317. * @type {module:echarts/data/Graph.Node}
  39318. */
  39319. this.node1 = n1;
  39320. /**
  39321. * 节点2,如果是有向图则为目标节点
  39322. * @type {module:echarts/data/Graph.Node}
  39323. */
  39324. this.node2 = n2;
  39325. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  39326. }
  39327. /**
  39328. * @param {string} [path]
  39329. * @return {module:echarts/model/Model}
  39330. */
  39331. Edge.prototype.getModel = function (path) {
  39332. if (this.dataIndex < 0) {
  39333. return;
  39334. }
  39335. var graph = this.hostGraph;
  39336. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  39337. return itemModel.getModel(path);
  39338. };
  39339. var createGraphDataProxyMixin = function (hostName, dataName) {
  39340. return {
  39341. /**
  39342. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  39343. * @return {number}
  39344. */
  39345. getValue: function (dimension) {
  39346. var data = this[hostName][dataName];
  39347. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  39348. },
  39349. /**
  39350. * @param {Object|string} key
  39351. * @param {*} [value]
  39352. */
  39353. setVisual: function (key, value) {
  39354. this.dataIndex >= 0
  39355. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  39356. },
  39357. /**
  39358. * @param {string} key
  39359. * @return {boolean}
  39360. */
  39361. getVisual: function (key, ignoreParent) {
  39362. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  39363. },
  39364. /**
  39365. * @param {Object} layout
  39366. * @return {boolean} [merge=false]
  39367. */
  39368. setLayout: function (layout, merge$$1) {
  39369. this.dataIndex >= 0
  39370. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  39371. },
  39372. /**
  39373. * @return {Object}
  39374. */
  39375. getLayout: function () {
  39376. return this[hostName][dataName].getItemLayout(this.dataIndex);
  39377. },
  39378. /**
  39379. * @return {module:zrender/Element}
  39380. */
  39381. getGraphicEl: function () {
  39382. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  39383. },
  39384. /**
  39385. * @return {number}
  39386. */
  39387. getRawIndex: function () {
  39388. return this[hostName][dataName].getRawIndex(this.dataIndex);
  39389. }
  39390. };
  39391. };
  39392. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  39393. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  39394. Graph.Node = Node;
  39395. Graph.Edge = Edge;
  39396. enableClassCheck(Node);
  39397. enableClassCheck(Edge);
  39398. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  39399. // ??? TODO
  39400. // support dataset?
  39401. var graph = new Graph(directed);
  39402. for (var i = 0; i < nodes.length; i++) {
  39403. graph.addNode(retrieve(
  39404. // Id, name, dataIndex
  39405. nodes[i].id, nodes[i].name, i
  39406. ), i);
  39407. }
  39408. var linkNameList = [];
  39409. var validEdges = [];
  39410. var linkCount = 0;
  39411. for (var i = 0; i < edges.length; i++) {
  39412. var link = edges[i];
  39413. var source = link.source;
  39414. var target = link.target;
  39415. // addEdge may fail when source or target not exists
  39416. if (graph.addEdge(source, target, linkCount)) {
  39417. validEdges.push(link);
  39418. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  39419. linkCount++;
  39420. }
  39421. }
  39422. var coordSys = seriesModel.get('coordinateSystem');
  39423. var nodeData;
  39424. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  39425. nodeData = createListFromArray(nodes, seriesModel);
  39426. }
  39427. else {
  39428. // FIXME
  39429. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  39430. // FIXME
  39431. var dimensionNames = createDimensions(nodes, {
  39432. coordDimensions: (
  39433. (coordSysCtor && coordSysCtor.type !== 'view')
  39434. ? (coordSysCtor.dimensions || []) : []
  39435. ).concat(['value'])
  39436. });
  39437. nodeData = new List(dimensionNames, seriesModel);
  39438. nodeData.initData(nodes);
  39439. }
  39440. var edgeData = new List(['value'], seriesModel);
  39441. edgeData.initData(validEdges, linkNameList);
  39442. beforeLink && beforeLink(nodeData, edgeData);
  39443. linkList({
  39444. mainData: nodeData,
  39445. struct: graph,
  39446. structAttr: 'graph',
  39447. datas: {node: nodeData, edge: edgeData},
  39448. datasAttr: {node: 'data', edge: 'edgeData'}
  39449. });
  39450. // Update dataIndex of nodes and edges because invalid edge may be removed
  39451. graph.update();
  39452. return graph;
  39453. };
  39454. var GraphSeries = extendSeriesModel({
  39455. type: 'series.graph',
  39456. init: function (option) {
  39457. GraphSeries.superApply(this, 'init', arguments);
  39458. // Provide data for legend select
  39459. this.legendDataProvider = function () {
  39460. return this._categoriesData;
  39461. };
  39462. this.fillDataTextStyle(option.edges || option.links);
  39463. this._updateCategoriesData();
  39464. },
  39465. mergeOption: function (option) {
  39466. GraphSeries.superApply(this, 'mergeOption', arguments);
  39467. this.fillDataTextStyle(option.edges || option.links);
  39468. this._updateCategoriesData();
  39469. },
  39470. mergeDefaultAndTheme: function (option) {
  39471. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  39472. defaultEmphasis(option, ['edgeLabel'], ['show']);
  39473. },
  39474. getInitialData: function (option, ecModel) {
  39475. var edges = option.edges || option.links || [];
  39476. var nodes = option.data || option.nodes || [];
  39477. var self = this;
  39478. if (nodes && edges) {
  39479. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  39480. }
  39481. function beforeLink(nodeData, edgeData) {
  39482. // Overwrite nodeData.getItemModel to
  39483. nodeData.wrapMethod('getItemModel', function (model) {
  39484. var categoriesModels = self._categoriesModels;
  39485. var categoryIdx = model.getShallow('category');
  39486. var categoryModel = categoriesModels[categoryIdx];
  39487. if (categoryModel) {
  39488. categoryModel.parentModel = model.parentModel;
  39489. model.parentModel = categoryModel;
  39490. }
  39491. return model;
  39492. });
  39493. var edgeLabelModel = self.getModel('edgeLabel');
  39494. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  39495. var fakeSeriesModel = new Model(
  39496. {label: edgeLabelModel.option},
  39497. edgeLabelModel.parentModel,
  39498. ecModel
  39499. );
  39500. edgeData.wrapMethod('getItemModel', function (model) {
  39501. model.customizeGetParent(edgeGetParent);
  39502. return model;
  39503. });
  39504. function edgeGetParent(path) {
  39505. path = this.parsePath(path);
  39506. return (path && path[0] === 'label')
  39507. ? fakeSeriesModel
  39508. : this.parentModel;
  39509. }
  39510. }
  39511. },
  39512. /**
  39513. * @return {module:echarts/data/Graph}
  39514. */
  39515. getGraph: function () {
  39516. return this.getData().graph;
  39517. },
  39518. /**
  39519. * @return {module:echarts/data/List}
  39520. */
  39521. getEdgeData: function () {
  39522. return this.getGraph().edgeData;
  39523. },
  39524. /**
  39525. * @return {module:echarts/data/List}
  39526. */
  39527. getCategoriesData: function () {
  39528. return this._categoriesData;
  39529. },
  39530. /**
  39531. * @override
  39532. */
  39533. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  39534. if (dataType === 'edge') {
  39535. var nodeData = this.getData();
  39536. var params = this.getDataParams(dataIndex, dataType);
  39537. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  39538. var sourceName = nodeData.getName(edge.node1.dataIndex);
  39539. var targetName = nodeData.getName(edge.node2.dataIndex);
  39540. var html = [];
  39541. sourceName != null && html.push(sourceName);
  39542. targetName != null && html.push(targetName);
  39543. html = encodeHTML(html.join(' > '));
  39544. if (params.value) {
  39545. html += ' : ' + encodeHTML(params.value);
  39546. }
  39547. return html;
  39548. }
  39549. else { // dataType === 'node' or empty
  39550. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  39551. }
  39552. },
  39553. _updateCategoriesData: function () {
  39554. var categories = map(this.option.categories || [], function (category) {
  39555. // Data must has value
  39556. return category.value != null ? category : extend({
  39557. value: 0
  39558. }, category);
  39559. });
  39560. var categoriesData = new List(['value'], this);
  39561. categoriesData.initData(categories);
  39562. this._categoriesData = categoriesData;
  39563. this._categoriesModels = categoriesData.mapArray(function (idx) {
  39564. return categoriesData.getItemModel(idx, true);
  39565. });
  39566. },
  39567. setZoom: function (zoom) {
  39568. this.option.zoom = zoom;
  39569. },
  39570. setCenter: function (center) {
  39571. this.option.center = center;
  39572. },
  39573. isAnimationEnabled: function () {
  39574. return GraphSeries.superCall(this, 'isAnimationEnabled')
  39575. // Not enable animation when do force layout
  39576. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  39577. },
  39578. defaultOption: {
  39579. zlevel: 0,
  39580. z: 2,
  39581. coordinateSystem: 'view',
  39582. // Default option for all coordinate systems
  39583. // xAxisIndex: 0,
  39584. // yAxisIndex: 0,
  39585. // polarIndex: 0,
  39586. // geoIndex: 0,
  39587. legendHoverLink: true,
  39588. hoverAnimation: true,
  39589. layout: null,
  39590. focusNodeAdjacency: false,
  39591. // Configuration of circular layout
  39592. circular: {
  39593. rotateLabel: false
  39594. },
  39595. // Configuration of force directed layout
  39596. force: {
  39597. initLayout: null,
  39598. // Node repulsion. Can be an array to represent range.
  39599. repulsion: [0, 50],
  39600. gravity: 0.1,
  39601. // Edge length. Can be an array to represent range.
  39602. edgeLength: 30,
  39603. layoutAnimation: true
  39604. },
  39605. left: 'center',
  39606. top: 'center',
  39607. // right: null,
  39608. // bottom: null,
  39609. // width: '80%',
  39610. // height: '80%',
  39611. symbol: 'circle',
  39612. symbolSize: 10,
  39613. edgeSymbol: ['none', 'none'],
  39614. edgeSymbolSize: 10,
  39615. edgeLabel: {
  39616. position: 'middle'
  39617. },
  39618. draggable: false,
  39619. roam: false,
  39620. // Default on center of graph
  39621. center: null,
  39622. zoom: 1,
  39623. // Symbol size scale ratio in roam
  39624. nodeScaleRatio: 0.6,
  39625. // cursor: null,
  39626. // categories: [],
  39627. // data: []
  39628. // Or
  39629. // nodes: []
  39630. //
  39631. // links: []
  39632. // Or
  39633. // edges: []
  39634. label: {
  39635. show: false,
  39636. formatter: '{b}'
  39637. },
  39638. itemStyle: {},
  39639. lineStyle: {
  39640. color: '#aaa',
  39641. width: 1,
  39642. curveness: 0,
  39643. opacity: 0.5
  39644. },
  39645. emphasis: {
  39646. label: {
  39647. show: true
  39648. }
  39649. }
  39650. }
  39651. });
  39652. /**
  39653. * Line path for bezier and straight line draw
  39654. */
  39655. var straightLineProto = Line.prototype;
  39656. var bezierCurveProto = BezierCurve.prototype;
  39657. function isLine(shape) {
  39658. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  39659. }
  39660. var LinePath = extendShape({
  39661. type: 'ec-line',
  39662. style: {
  39663. stroke: '#000',
  39664. fill: null
  39665. },
  39666. shape: {
  39667. x1: 0,
  39668. y1: 0,
  39669. x2: 0,
  39670. y2: 0,
  39671. percent: 1,
  39672. cpx1: null,
  39673. cpy1: null
  39674. },
  39675. buildPath: function (ctx, shape) {
  39676. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  39677. },
  39678. pointAt: function (t) {
  39679. return isLine(this.shape)
  39680. ? straightLineProto.pointAt.call(this, t)
  39681. : bezierCurveProto.pointAt.call(this, t);
  39682. },
  39683. tangentAt: function (t) {
  39684. var shape = this.shape;
  39685. var p = isLine(shape)
  39686. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  39687. : bezierCurveProto.tangentAt.call(this, t);
  39688. return normalize(p, p);
  39689. }
  39690. });
  39691. /**
  39692. * @module echarts/chart/helper/Line
  39693. */
  39694. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  39695. function makeSymbolTypeKey(symbolCategory) {
  39696. return '_' + symbolCategory + 'Type';
  39697. }
  39698. /**
  39699. * @inner
  39700. */
  39701. function createSymbol$1(name, lineData, idx) {
  39702. var color = lineData.getItemVisual(idx, 'color');
  39703. var symbolType = lineData.getItemVisual(idx, name);
  39704. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  39705. if (!symbolType || symbolType === 'none') {
  39706. return;
  39707. }
  39708. if (!isArray(symbolSize)) {
  39709. symbolSize = [symbolSize, symbolSize];
  39710. }
  39711. var symbolPath = createSymbol(
  39712. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  39713. symbolSize[0], symbolSize[1], color
  39714. );
  39715. symbolPath.name = name;
  39716. return symbolPath;
  39717. }
  39718. function createLine(points) {
  39719. var line = new LinePath({
  39720. name: 'line'
  39721. });
  39722. setLinePoints(line.shape, points);
  39723. return line;
  39724. }
  39725. function setLinePoints(targetShape, points) {
  39726. var p1 = points[0];
  39727. var p2 = points[1];
  39728. var cp1 = points[2];
  39729. targetShape.x1 = p1[0];
  39730. targetShape.y1 = p1[1];
  39731. targetShape.x2 = p2[0];
  39732. targetShape.y2 = p2[1];
  39733. targetShape.percent = 1;
  39734. if (cp1) {
  39735. targetShape.cpx1 = cp1[0];
  39736. targetShape.cpy1 = cp1[1];
  39737. }
  39738. else {
  39739. targetShape.cpx1 = NaN;
  39740. targetShape.cpy1 = NaN;
  39741. }
  39742. }
  39743. function updateSymbolAndLabelBeforeLineUpdate () {
  39744. var lineGroup = this;
  39745. var symbolFrom = lineGroup.childOfName('fromSymbol');
  39746. var symbolTo = lineGroup.childOfName('toSymbol');
  39747. var label = lineGroup.childOfName('label');
  39748. // Quick reject
  39749. if (!symbolFrom && !symbolTo && label.ignore) {
  39750. return;
  39751. }
  39752. var invScale = 1;
  39753. var parentNode = this.parent;
  39754. while (parentNode) {
  39755. if (parentNode.scale) {
  39756. invScale /= parentNode.scale[0];
  39757. }
  39758. parentNode = parentNode.parent;
  39759. }
  39760. var line = lineGroup.childOfName('line');
  39761. // If line not changed
  39762. // FIXME Parent scale changed
  39763. if (!this.__dirty && !line.__dirty) {
  39764. return;
  39765. }
  39766. var percent = line.shape.percent;
  39767. var fromPos = line.pointAt(0);
  39768. var toPos = line.pointAt(percent);
  39769. var d = sub([], toPos, fromPos);
  39770. normalize(d, d);
  39771. if (symbolFrom) {
  39772. symbolFrom.attr('position', fromPos);
  39773. var tangent = line.tangentAt(0);
  39774. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  39775. tangent[1], tangent[0]
  39776. ));
  39777. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  39778. }
  39779. if (symbolTo) {
  39780. symbolTo.attr('position', toPos);
  39781. var tangent = line.tangentAt(1);
  39782. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  39783. tangent[1], tangent[0]
  39784. ));
  39785. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  39786. }
  39787. if (!label.ignore) {
  39788. label.attr('position', toPos);
  39789. var textPosition;
  39790. var textAlign;
  39791. var textVerticalAlign;
  39792. var distance$$1 = 5 * invScale;
  39793. // End
  39794. if (label.__position === 'end') {
  39795. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  39796. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  39797. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  39798. }
  39799. // Middle
  39800. else if (label.__position === 'middle') {
  39801. var halfPercent = percent / 2;
  39802. var tangent = line.tangentAt(halfPercent);
  39803. var n = [tangent[1], -tangent[0]];
  39804. var cp = line.pointAt(halfPercent);
  39805. if (n[1] > 0) {
  39806. n[0] = -n[0];
  39807. n[1] = -n[1];
  39808. }
  39809. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  39810. textAlign = 'center';
  39811. textVerticalAlign = 'bottom';
  39812. var rotation = -Math.atan2(tangent[1], tangent[0]);
  39813. if (toPos[0] < fromPos[0]) {
  39814. rotation = Math.PI + rotation;
  39815. }
  39816. label.attr('rotation', rotation);
  39817. }
  39818. // Start
  39819. else {
  39820. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  39821. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  39822. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  39823. }
  39824. label.attr({
  39825. style: {
  39826. // Use the user specified text align and baseline first
  39827. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  39828. textAlign: label.__textAlign || textAlign
  39829. },
  39830. position: textPosition,
  39831. scale: [invScale, invScale]
  39832. });
  39833. }
  39834. }
  39835. /**
  39836. * @constructor
  39837. * @extends {module:zrender/graphic/Group}
  39838. * @alias {module:echarts/chart/helper/Line}
  39839. */
  39840. function Line$1(lineData, idx, seriesScope) {
  39841. Group.call(this);
  39842. this._createLine(lineData, idx, seriesScope);
  39843. }
  39844. var lineProto = Line$1.prototype;
  39845. // Update symbol position and rotation
  39846. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  39847. lineProto._createLine = function (lineData, idx, seriesScope) {
  39848. var seriesModel = lineData.hostModel;
  39849. var linePoints = lineData.getItemLayout(idx);
  39850. var line = createLine(linePoints);
  39851. line.shape.percent = 0;
  39852. initProps(line, {
  39853. shape: {
  39854. percent: 1
  39855. }
  39856. }, seriesModel, idx);
  39857. this.add(line);
  39858. var label = new Text({
  39859. name: 'label'
  39860. });
  39861. this.add(label);
  39862. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  39863. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  39864. // symbols must added after line to make sure
  39865. // it will be updated after line#update.
  39866. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  39867. this.add(symbol);
  39868. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  39869. }, this);
  39870. this._updateCommonStl(lineData, idx, seriesScope);
  39871. };
  39872. lineProto.updateData = function (lineData, idx, seriesScope) {
  39873. var seriesModel = lineData.hostModel;
  39874. var line = this.childOfName('line');
  39875. var linePoints = lineData.getItemLayout(idx);
  39876. var target = {
  39877. shape: {}
  39878. };
  39879. setLinePoints(target.shape, linePoints);
  39880. updateProps(line, target, seriesModel, idx);
  39881. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  39882. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  39883. var key = makeSymbolTypeKey(symbolCategory);
  39884. // Symbol changed
  39885. if (this[key] !== symbolType) {
  39886. this.remove(this.childOfName(symbolCategory));
  39887. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  39888. this.add(symbol);
  39889. }
  39890. this[key] = symbolType;
  39891. }, this);
  39892. this._updateCommonStl(lineData, idx, seriesScope);
  39893. };
  39894. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  39895. var seriesModel = lineData.hostModel;
  39896. var line = this.childOfName('line');
  39897. var lineStyle = seriesScope && seriesScope.lineStyle;
  39898. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  39899. var labelModel = seriesScope && seriesScope.labelModel;
  39900. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  39901. // Optimization for large dataset
  39902. if (!seriesScope || lineData.hasItemOption) {
  39903. var itemModel = lineData.getItemModel(idx);
  39904. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  39905. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  39906. labelModel = itemModel.getModel('label');
  39907. hoverLabelModel = itemModel.getModel('emphasis.label');
  39908. }
  39909. var visualColor = lineData.getItemVisual(idx, 'color');
  39910. var visualOpacity = retrieve3(
  39911. lineData.getItemVisual(idx, 'opacity'),
  39912. lineStyle.opacity,
  39913. 1
  39914. );
  39915. line.useStyle(defaults(
  39916. {
  39917. strokeNoScale: true,
  39918. fill: 'none',
  39919. stroke: visualColor,
  39920. opacity: visualOpacity
  39921. },
  39922. lineStyle
  39923. ));
  39924. line.hoverStyle = hoverLineStyle;
  39925. // Update symbol
  39926. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  39927. var symbol = this.childOfName(symbolCategory);
  39928. if (symbol) {
  39929. symbol.setColor(visualColor);
  39930. symbol.setStyle({
  39931. opacity: visualOpacity
  39932. });
  39933. }
  39934. }, this);
  39935. var showLabel = labelModel.getShallow('show');
  39936. var hoverShowLabel = hoverLabelModel.getShallow('show');
  39937. var label = this.childOfName('label');
  39938. var defaultLabelColor;
  39939. var normalText;
  39940. var emphasisText;
  39941. if (showLabel || hoverShowLabel) {
  39942. defaultLabelColor = visualColor || '#000';
  39943. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  39944. if (normalText == null) {
  39945. var rawVal = seriesModel.getRawValue(idx);
  39946. normalText = rawVal == null
  39947. ? lineData.getName(idx)
  39948. : isFinite(rawVal)
  39949. ? round$1(rawVal)
  39950. : rawVal;
  39951. }
  39952. emphasisText = retrieve2(
  39953. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  39954. normalText
  39955. );
  39956. }
  39957. // label.afterUpdate = lineAfterUpdate;
  39958. if (showLabel) {
  39959. var labelStyle = setTextStyle(label.style, labelModel, {
  39960. text: normalText
  39961. }, {
  39962. autoColor: defaultLabelColor
  39963. });
  39964. label.__textAlign = labelStyle.textAlign;
  39965. label.__verticalAlign = labelStyle.textVerticalAlign;
  39966. // 'start', 'middle', 'end'
  39967. label.__position = labelModel.get('position') || 'middle';
  39968. }
  39969. else {
  39970. label.setStyle('text', null);
  39971. }
  39972. if (hoverShowLabel) {
  39973. // Only these properties supported in this emphasis style here.
  39974. label.hoverStyle = {
  39975. text: emphasisText,
  39976. textFill: hoverLabelModel.getTextColor(true),
  39977. // For merging hover style to normal style, do not use
  39978. // `hoverLabelModel.getFont()` here.
  39979. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  39980. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  39981. fontSize: hoverLabelModel.getShallow('fontSize'),
  39982. fontFamily: hoverLabelModel.getShallow('fontFamily')
  39983. };
  39984. }
  39985. else {
  39986. label.hoverStyle = {
  39987. text: null
  39988. };
  39989. }
  39990. label.ignore = !showLabel && !hoverShowLabel;
  39991. setHoverStyle(this);
  39992. };
  39993. lineProto.highlight = function () {
  39994. this.trigger('emphasis');
  39995. };
  39996. lineProto.downplay = function () {
  39997. this.trigger('normal');
  39998. };
  39999. lineProto.updateLayout = function (lineData, idx) {
  40000. this.setLinePoints(lineData.getItemLayout(idx));
  40001. };
  40002. lineProto.setLinePoints = function (points) {
  40003. var linePath = this.childOfName('line');
  40004. setLinePoints(linePath.shape, points);
  40005. linePath.dirty();
  40006. };
  40007. inherits(Line$1, Group);
  40008. /**
  40009. * @module echarts/chart/helper/LineDraw
  40010. */
  40011. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  40012. /**
  40013. * @alias module:echarts/component/marker/LineDraw
  40014. * @constructor
  40015. */
  40016. function LineDraw(ctor) {
  40017. this._ctor = ctor || Line$1;
  40018. this.group = new Group();
  40019. }
  40020. var lineDrawProto = LineDraw.prototype;
  40021. lineDrawProto.isPersistent = function () {
  40022. return true;
  40023. };
  40024. /**
  40025. * @param {module:echarts/data/List} lineData
  40026. */
  40027. lineDrawProto.updateData = function (lineData) {
  40028. var lineDraw = this;
  40029. var group = lineDraw.group;
  40030. var oldLineData = lineDraw._lineData;
  40031. lineDraw._lineData = lineData;
  40032. // There is no oldLineData only when first rendering or switching from
  40033. // stream mode to normal mode, where previous elements should be removed.
  40034. if (!oldLineData) {
  40035. group.removeAll();
  40036. }
  40037. var seriesScope = makeSeriesScope$1(lineData);
  40038. lineData.diff(oldLineData)
  40039. .add(function (idx) {
  40040. doAdd(lineDraw, lineData, idx, seriesScope);
  40041. })
  40042. .update(function (newIdx, oldIdx) {
  40043. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  40044. })
  40045. .remove(function (idx) {
  40046. group.remove(oldLineData.getItemGraphicEl(idx));
  40047. })
  40048. .execute();
  40049. };
  40050. function doAdd(lineDraw, lineData, idx, seriesScope) {
  40051. var itemLayout = lineData.getItemLayout(idx);
  40052. if (!lineNeedsDraw(itemLayout)) {
  40053. return;
  40054. }
  40055. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  40056. lineData.setItemGraphicEl(idx, el);
  40057. lineDraw.group.add(el);
  40058. }
  40059. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  40060. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  40061. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  40062. lineDraw.group.remove(itemEl);
  40063. return;
  40064. }
  40065. if (!itemEl) {
  40066. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  40067. }
  40068. else {
  40069. itemEl.updateData(newLineData, newIdx, seriesScope);
  40070. }
  40071. newLineData.setItemGraphicEl(newIdx, itemEl);
  40072. lineDraw.group.add(itemEl);
  40073. }
  40074. lineDrawProto.updateLayout = function () {
  40075. var lineData = this._lineData;
  40076. lineData.eachItemGraphicEl(function (el, idx) {
  40077. el.updateLayout(lineData, idx);
  40078. }, this);
  40079. };
  40080. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  40081. this._seriesScope = makeSeriesScope$1(lineData);
  40082. this._lineData = null;
  40083. this.group.removeAll();
  40084. };
  40085. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  40086. function updateIncrementalAndHover(el) {
  40087. if (!el.isGroup) {
  40088. el.incremental = el.useHoverLayer = true;
  40089. }
  40090. }
  40091. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  40092. var itemLayout = lineData.getItemLayout(idx);
  40093. if (lineNeedsDraw(itemLayout)) {
  40094. var el = new this._ctor(lineData, idx, this._seriesScope);
  40095. el.traverse(updateIncrementalAndHover);
  40096. this.group.add(el);
  40097. }
  40098. }
  40099. };
  40100. function makeSeriesScope$1(lineData) {
  40101. var hostModel = lineData.hostModel;
  40102. return {
  40103. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  40104. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  40105. labelModel: hostModel.getModel('label'),
  40106. hoverLabelModel: hostModel.getModel('emphasis.label')
  40107. };
  40108. }
  40109. lineDrawProto.remove = function () {
  40110. this._clearIncremental();
  40111. this._incremental = null;
  40112. this.group.removeAll();
  40113. };
  40114. lineDrawProto._clearIncremental = function () {
  40115. var incremental = this._incremental;
  40116. if (incremental) {
  40117. incremental.clearDisplaybles();
  40118. }
  40119. };
  40120. function isPointNaN(pt) {
  40121. return isNaN(pt[0]) || isNaN(pt[1]);
  40122. }
  40123. function lineNeedsDraw(pts) {
  40124. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  40125. }
  40126. var v1 = [];
  40127. var v2 = [];
  40128. var v3 = [];
  40129. var quadraticAt$1 = quadraticAt;
  40130. var v2DistSquare = distSquare;
  40131. var mathAbs$1 = Math.abs;
  40132. function intersectCurveCircle(curvePoints, center, radius) {
  40133. var p0 = curvePoints[0];
  40134. var p1 = curvePoints[1];
  40135. var p2 = curvePoints[2];
  40136. var d = Infinity;
  40137. var t;
  40138. var radiusSquare = radius * radius;
  40139. var interval = 0.1;
  40140. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  40141. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  40142. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  40143. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  40144. if (diff < d) {
  40145. d = diff;
  40146. t = _t;
  40147. }
  40148. }
  40149. // Assume the segment is monotone,Find root through Bisection method
  40150. // At most 32 iteration
  40151. for (var i = 0; i < 32; i++) {
  40152. // var prev = t - interval;
  40153. var next = t + interval;
  40154. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  40155. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  40156. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  40157. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  40158. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  40159. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  40160. var diff = v2DistSquare(v2, center) - radiusSquare;
  40161. if (mathAbs$1(diff) < 1e-2) {
  40162. break;
  40163. }
  40164. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  40165. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  40166. interval /= 2;
  40167. if (diff < 0) {
  40168. if (nextDiff >= 0) {
  40169. t = t + interval;
  40170. }
  40171. else {
  40172. t = t - interval;
  40173. }
  40174. }
  40175. else {
  40176. if (nextDiff >= 0) {
  40177. t = t - interval;
  40178. }
  40179. else {
  40180. t = t + interval;
  40181. }
  40182. }
  40183. }
  40184. return t;
  40185. }
  40186. // Adjust edge to avoid
  40187. var adjustEdge = function (graph, scale$$1) {
  40188. var tmp0 = [];
  40189. var quadraticSubdivide$$1 = quadraticSubdivide;
  40190. var pts = [[], [], []];
  40191. var pts2 = [[], []];
  40192. var v = [];
  40193. scale$$1 /= 2;
  40194. function getSymbolSize(node) {
  40195. var symbolSize = node.getVisual('symbolSize');
  40196. if (symbolSize instanceof Array) {
  40197. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  40198. }
  40199. return symbolSize;
  40200. }
  40201. graph.eachEdge(function (edge, idx) {
  40202. var linePoints = edge.getLayout();
  40203. var fromSymbol = edge.getVisual('fromSymbol');
  40204. var toSymbol = edge.getVisual('toSymbol');
  40205. if (!linePoints.__original) {
  40206. linePoints.__original = [
  40207. clone$1(linePoints[0]),
  40208. clone$1(linePoints[1])
  40209. ];
  40210. if (linePoints[2]) {
  40211. linePoints.__original.push(clone$1(linePoints[2]));
  40212. }
  40213. }
  40214. var originalPoints = linePoints.__original;
  40215. // Quadratic curve
  40216. if (linePoints[2] != null) {
  40217. copy(pts[0], originalPoints[0]);
  40218. copy(pts[1], originalPoints[2]);
  40219. copy(pts[2], originalPoints[1]);
  40220. if (fromSymbol && fromSymbol != 'none') {
  40221. var symbolSize = getSymbolSize(edge.node1);
  40222. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  40223. // Subdivide and get the second
  40224. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  40225. pts[0][0] = tmp0[3];
  40226. pts[1][0] = tmp0[4];
  40227. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  40228. pts[0][1] = tmp0[3];
  40229. pts[1][1] = tmp0[4];
  40230. }
  40231. if (toSymbol && toSymbol != 'none') {
  40232. var symbolSize = getSymbolSize(edge.node2);
  40233. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  40234. // Subdivide and get the first
  40235. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  40236. pts[1][0] = tmp0[1];
  40237. pts[2][0] = tmp0[2];
  40238. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  40239. pts[1][1] = tmp0[1];
  40240. pts[2][1] = tmp0[2];
  40241. }
  40242. // Copy back to layout
  40243. copy(linePoints[0], pts[0]);
  40244. copy(linePoints[1], pts[2]);
  40245. copy(linePoints[2], pts[1]);
  40246. }
  40247. // Line
  40248. else {
  40249. copy(pts2[0], originalPoints[0]);
  40250. copy(pts2[1], originalPoints[1]);
  40251. sub(v, pts2[1], pts2[0]);
  40252. normalize(v, v);
  40253. if (fromSymbol && fromSymbol != 'none') {
  40254. var symbolSize = getSymbolSize(edge.node1);
  40255. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  40256. }
  40257. if (toSymbol && toSymbol != 'none') {
  40258. var symbolSize = getSymbolSize(edge.node2);
  40259. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  40260. }
  40261. copy(linePoints[0], pts2[0]);
  40262. copy(linePoints[1], pts2[1]);
  40263. }
  40264. });
  40265. };
  40266. var nodeOpacityPath = ['itemStyle', 'opacity'];
  40267. var lineOpacityPath = ['lineStyle', 'opacity'];
  40268. function getItemOpacity(item, opacityPath) {
  40269. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  40270. }
  40271. function fadeOutItem(item, opacityPath, opacityRatio) {
  40272. var el = item.getGraphicEl();
  40273. var opacity = getItemOpacity(item, opacityPath);
  40274. if (opacityRatio != null) {
  40275. opacity == null && (opacity = 1);
  40276. opacity *= opacityRatio;
  40277. }
  40278. el.downplay && el.downplay();
  40279. el.traverse(function (child) {
  40280. if (child.type !== 'group') {
  40281. child.setStyle('opacity', opacity);
  40282. }
  40283. });
  40284. }
  40285. function fadeInItem(item, opacityPath) {
  40286. var opacity = getItemOpacity(item, opacityPath);
  40287. var el = item.getGraphicEl();
  40288. el.highlight && el.highlight();
  40289. el.traverse(function (child) {
  40290. if (child.type !== 'group') {
  40291. child.setStyle('opacity', opacity);
  40292. }
  40293. });
  40294. }
  40295. extendChartView({
  40296. type: 'graph',
  40297. init: function (ecModel, api) {
  40298. var symbolDraw = new SymbolDraw();
  40299. var lineDraw = new LineDraw();
  40300. var group = this.group;
  40301. this._controller = new RoamController(api.getZr());
  40302. this._controllerHost = {target: group};
  40303. group.add(symbolDraw.group);
  40304. group.add(lineDraw.group);
  40305. this._symbolDraw = symbolDraw;
  40306. this._lineDraw = lineDraw;
  40307. this._firstRender = true;
  40308. },
  40309. render: function (seriesModel, ecModel, api) {
  40310. var coordSys = seriesModel.coordinateSystem;
  40311. this._model = seriesModel;
  40312. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  40313. var symbolDraw = this._symbolDraw;
  40314. var lineDraw = this._lineDraw;
  40315. var group = this.group;
  40316. if (coordSys.type === 'view') {
  40317. var groupNewProp = {
  40318. position: coordSys.position,
  40319. scale: coordSys.scale
  40320. };
  40321. if (this._firstRender) {
  40322. group.attr(groupNewProp);
  40323. }
  40324. else {
  40325. updateProps(group, groupNewProp, seriesModel);
  40326. }
  40327. }
  40328. // Fix edge contact point with node
  40329. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  40330. var data = seriesModel.getData();
  40331. symbolDraw.updateData(data);
  40332. var edgeData = seriesModel.getEdgeData();
  40333. lineDraw.updateData(edgeData);
  40334. this._updateNodeAndLinkScale();
  40335. this._updateController(seriesModel, ecModel, api);
  40336. clearTimeout(this._layoutTimeout);
  40337. var forceLayout = seriesModel.forceLayout;
  40338. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  40339. if (forceLayout) {
  40340. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  40341. }
  40342. data.eachItemGraphicEl(function (el, idx) {
  40343. var itemModel = data.getItemModel(idx);
  40344. // Update draggable
  40345. el.off('drag').off('dragend');
  40346. var draggable = data.getItemModel(idx).get('draggable');
  40347. if (draggable) {
  40348. el.on('drag', function () {
  40349. if (forceLayout) {
  40350. forceLayout.warmUp();
  40351. !this._layouting
  40352. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  40353. forceLayout.setFixed(idx);
  40354. // Write position back to layout
  40355. data.setItemLayout(idx, el.position);
  40356. }
  40357. }, this).on('dragend', function () {
  40358. if (forceLayout) {
  40359. forceLayout.setUnfixed(idx);
  40360. }
  40361. }, this);
  40362. }
  40363. el.setDraggable(draggable && forceLayout);
  40364. el.off('mouseover', el.__focusNodeAdjacency);
  40365. el.off('mouseout', el.__unfocusNodeAdjacency);
  40366. if (itemModel.get('focusNodeAdjacency')) {
  40367. el.on('mouseover', el.__focusNodeAdjacency = function () {
  40368. api.dispatchAction({
  40369. type: 'focusNodeAdjacency',
  40370. seriesId: seriesModel.id,
  40371. dataIndex: el.dataIndex
  40372. });
  40373. });
  40374. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  40375. api.dispatchAction({
  40376. type: 'unfocusNodeAdjacency',
  40377. seriesId: seriesModel.id
  40378. });
  40379. });
  40380. }
  40381. }, this);
  40382. data.graph.eachEdge(function (edge) {
  40383. var el = edge.getGraphicEl();
  40384. el.off('mouseover', el.__focusNodeAdjacency);
  40385. el.off('mouseout', el.__unfocusNodeAdjacency);
  40386. if (edge.getModel().get('focusNodeAdjacency')) {
  40387. el.on('mouseover', el.__focusNodeAdjacency = function () {
  40388. api.dispatchAction({
  40389. type: 'focusNodeAdjacency',
  40390. seriesId: seriesModel.id,
  40391. edgeDataIndex: edge.dataIndex
  40392. });
  40393. });
  40394. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  40395. api.dispatchAction({
  40396. type: 'unfocusNodeAdjacency',
  40397. seriesId: seriesModel.id
  40398. });
  40399. });
  40400. }
  40401. });
  40402. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  40403. && seriesModel.get('circular.rotateLabel');
  40404. var cx = data.getLayout('cx');
  40405. var cy = data.getLayout('cy');
  40406. data.eachItemGraphicEl(function (el, idx) {
  40407. var symbolPath = el.getSymbolPath();
  40408. if (circularRotateLabel) {
  40409. var pos = data.getItemLayout(idx);
  40410. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  40411. if (rad < 0) {
  40412. rad = Math.PI * 2 + rad;
  40413. }
  40414. var isLeft = pos[0] < cx;
  40415. if (isLeft) {
  40416. rad = rad - Math.PI;
  40417. }
  40418. var textPosition = isLeft ? 'left' : 'right';
  40419. symbolPath.setStyle({
  40420. textRotation: -rad,
  40421. textPosition: textPosition,
  40422. textOrigin: 'center'
  40423. });
  40424. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  40425. }
  40426. else {
  40427. symbolPath.setStyle({
  40428. textRotation: 0
  40429. });
  40430. }
  40431. });
  40432. this._firstRender = false;
  40433. },
  40434. dispose: function () {
  40435. this._controller && this._controller.dispose();
  40436. this._controllerHost = {};
  40437. },
  40438. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  40439. var data = this._model.getData();
  40440. var graph = data.graph;
  40441. var dataIndex = payload.dataIndex;
  40442. var edgeDataIndex = payload.edgeDataIndex;
  40443. var node = graph.getNodeByIndex(dataIndex);
  40444. var edge = graph.getEdgeByIndex(edgeDataIndex);
  40445. if (!node && !edge) {
  40446. return;
  40447. }
  40448. graph.eachNode(function (node) {
  40449. fadeOutItem(node, nodeOpacityPath, 0.1);
  40450. });
  40451. graph.eachEdge(function (edge) {
  40452. fadeOutItem(edge, lineOpacityPath, 0.1);
  40453. });
  40454. if (node) {
  40455. fadeInItem(node, nodeOpacityPath);
  40456. each$1(node.edges, function (adjacentEdge) {
  40457. if (adjacentEdge.dataIndex < 0) {
  40458. return;
  40459. }
  40460. fadeInItem(adjacentEdge, lineOpacityPath);
  40461. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  40462. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  40463. });
  40464. }
  40465. if (edge) {
  40466. fadeInItem(edge, lineOpacityPath);
  40467. fadeInItem(edge.node1, nodeOpacityPath);
  40468. fadeInItem(edge.node2, nodeOpacityPath);
  40469. }
  40470. },
  40471. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  40472. var graph = this._model.getData().graph;
  40473. graph.eachNode(function (node) {
  40474. fadeOutItem(node, nodeOpacityPath);
  40475. });
  40476. graph.eachEdge(function (edge) {
  40477. fadeOutItem(edge, lineOpacityPath);
  40478. });
  40479. },
  40480. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  40481. var self = this;
  40482. (function step() {
  40483. forceLayout.step(function (stopped) {
  40484. self.updateLayout(self._model);
  40485. (self._layouting = !stopped) && (
  40486. layoutAnimation
  40487. ? (self._layoutTimeout = setTimeout(step, 16))
  40488. : step()
  40489. );
  40490. });
  40491. })();
  40492. },
  40493. _updateController: function (seriesModel, ecModel, api) {
  40494. var controller = this._controller;
  40495. var controllerHost = this._controllerHost;
  40496. var group = this.group;
  40497. controller.setPointerChecker(function (e, x, y) {
  40498. var rect = group.getBoundingRect();
  40499. rect.applyTransform(group.transform);
  40500. return rect.contain(x, y)
  40501. && !onIrrelevantElement(e, api, seriesModel);
  40502. });
  40503. if (seriesModel.coordinateSystem.type !== 'view') {
  40504. controller.disable();
  40505. return;
  40506. }
  40507. controller.enable(seriesModel.get('roam'));
  40508. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  40509. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  40510. controller
  40511. .off('pan')
  40512. .off('zoom')
  40513. .on('pan', function (dx, dy) {
  40514. updateViewOnPan(controllerHost, dx, dy);
  40515. api.dispatchAction({
  40516. seriesId: seriesModel.id,
  40517. type: 'graphRoam',
  40518. dx: dx,
  40519. dy: dy
  40520. });
  40521. })
  40522. .on('zoom', function (zoom, mouseX, mouseY) {
  40523. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  40524. api.dispatchAction({
  40525. seriesId: seriesModel.id,
  40526. type: 'graphRoam',
  40527. zoom: zoom,
  40528. originX: mouseX,
  40529. originY: mouseY
  40530. });
  40531. this._updateNodeAndLinkScale();
  40532. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  40533. this._lineDraw.updateLayout();
  40534. }, this);
  40535. },
  40536. _updateNodeAndLinkScale: function () {
  40537. var seriesModel = this._model;
  40538. var data = seriesModel.getData();
  40539. var nodeScale = this._getNodeGlobalScale(seriesModel);
  40540. var invScale = [nodeScale, nodeScale];
  40541. data.eachItemGraphicEl(function (el, idx) {
  40542. el.attr('scale', invScale);
  40543. });
  40544. },
  40545. _getNodeGlobalScale: function (seriesModel) {
  40546. var coordSys = seriesModel.coordinateSystem;
  40547. if (coordSys.type !== 'view') {
  40548. return 1;
  40549. }
  40550. var nodeScaleRatio = this._nodeScaleRatio;
  40551. var groupScale = coordSys.scale;
  40552. var groupZoom = (groupScale && groupScale[0]) || 1;
  40553. // Scale node when zoom changes
  40554. var roamZoom = coordSys.getZoom();
  40555. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  40556. return nodeScale / groupZoom;
  40557. },
  40558. updateLayout: function (seriesModel) {
  40559. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  40560. this._symbolDraw.updateLayout();
  40561. this._lineDraw.updateLayout();
  40562. },
  40563. remove: function (ecModel, api) {
  40564. this._symbolDraw && this._symbolDraw.remove();
  40565. this._lineDraw && this._lineDraw.remove();
  40566. }
  40567. });
  40568. var actionInfo = {
  40569. type: 'graphRoam',
  40570. event: 'graphRoam',
  40571. update: 'none'
  40572. };
  40573. /**
  40574. * @payload
  40575. * @property {string} name Series name
  40576. * @property {number} [dx]
  40577. * @property {number} [dy]
  40578. * @property {number} [zoom]
  40579. * @property {number} [originX]
  40580. * @property {number} [originY]
  40581. */
  40582. registerAction(actionInfo, function (payload, ecModel) {
  40583. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  40584. var coordSys = seriesModel.coordinateSystem;
  40585. var res = updateCenterAndZoom(coordSys, payload);
  40586. seriesModel.setCenter
  40587. && seriesModel.setCenter(res.center);
  40588. seriesModel.setZoom
  40589. && seriesModel.setZoom(res.zoom);
  40590. });
  40591. });
  40592. /**
  40593. * @payload
  40594. * @property {number} [seriesIndex]
  40595. * @property {string} [seriesId]
  40596. * @property {string} [seriesName]
  40597. * @property {number} [dataIndex]
  40598. */
  40599. registerAction({
  40600. type: 'focusNodeAdjacency',
  40601. event: 'focusNodeAdjacency',
  40602. update: 'series.graph:focusNodeAdjacency'
  40603. }, function () {});
  40604. /**
  40605. * @payload
  40606. * @property {number} [seriesIndex]
  40607. * @property {string} [seriesId]
  40608. * @property {string} [seriesName]
  40609. */
  40610. registerAction({
  40611. type: 'unfocusNodeAdjacency',
  40612. event: 'unfocusNodeAdjacency',
  40613. update: 'series.graph:unfocusNodeAdjacency'
  40614. }, function () {});
  40615. var categoryFilter = function (ecModel) {
  40616. var legendModels = ecModel.findComponents({
  40617. mainType: 'legend'
  40618. });
  40619. if (!legendModels || !legendModels.length) {
  40620. return;
  40621. }
  40622. ecModel.eachSeriesByType('graph', function (graphSeries) {
  40623. var categoriesData = graphSeries.getCategoriesData();
  40624. var graph = graphSeries.getGraph();
  40625. var data = graph.data;
  40626. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  40627. data.filterSelf(function (idx) {
  40628. var model = data.getItemModel(idx);
  40629. var category = model.getShallow('category');
  40630. if (category != null) {
  40631. if (typeof category === 'number') {
  40632. category = categoryNames[category];
  40633. }
  40634. // If in any legend component the status is not selected.
  40635. for (var i = 0; i < legendModels.length; i++) {
  40636. if (!legendModels[i].isSelected(category)) {
  40637. return false;
  40638. }
  40639. }
  40640. }
  40641. return true;
  40642. });
  40643. }, this);
  40644. };
  40645. var categoryVisual = function (ecModel) {
  40646. var paletteScope = {};
  40647. ecModel.eachSeriesByType('graph', function (seriesModel) {
  40648. var categoriesData = seriesModel.getCategoriesData();
  40649. var data = seriesModel.getData();
  40650. var categoryNameIdxMap = {};
  40651. categoriesData.each(function (idx) {
  40652. var name = categoriesData.getName(idx);
  40653. // Add prefix to avoid conflict with Object.prototype.
  40654. categoryNameIdxMap['ec-' + name] = idx;
  40655. var itemModel = categoriesData.getItemModel(idx);
  40656. var color = itemModel.get('itemStyle.color')
  40657. || seriesModel.getColorFromPalette(name, paletteScope);
  40658. categoriesData.setItemVisual(idx, 'color', color);
  40659. });
  40660. // Assign category color to visual
  40661. if (categoriesData.count()) {
  40662. data.each(function (idx) {
  40663. var model = data.getItemModel(idx);
  40664. var category = model.getShallow('category');
  40665. if (category != null) {
  40666. if (typeof category === 'string') {
  40667. category = categoryNameIdxMap['ec-' + category];
  40668. }
  40669. if (!data.getItemVisual(idx, 'color', true)) {
  40670. data.setItemVisual(
  40671. idx, 'color',
  40672. categoriesData.getItemVisual(category, 'color')
  40673. );
  40674. }
  40675. }
  40676. });
  40677. }
  40678. });
  40679. };
  40680. function normalize$1(a) {
  40681. if (!(a instanceof Array)) {
  40682. a = [a, a];
  40683. }
  40684. return a;
  40685. }
  40686. var edgeVisual = function (ecModel) {
  40687. ecModel.eachSeriesByType('graph', function (seriesModel) {
  40688. var graph = seriesModel.getGraph();
  40689. var edgeData = seriesModel.getEdgeData();
  40690. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  40691. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  40692. var colorQuery = 'lineStyle.color'.split('.');
  40693. var opacityQuery = 'lineStyle.opacity'.split('.');
  40694. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  40695. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  40696. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  40697. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  40698. edgeData.setVisual('color', seriesModel.get(colorQuery));
  40699. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  40700. edgeData.each(function (idx) {
  40701. var itemModel = edgeData.getItemModel(idx);
  40702. var edge = graph.getEdgeByIndex(idx);
  40703. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  40704. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  40705. // Edge visual must after node visual
  40706. var color = itemModel.get(colorQuery);
  40707. var opacity = itemModel.get(opacityQuery);
  40708. switch (color) {
  40709. case 'source':
  40710. color = edge.node1.getVisual('color');
  40711. break;
  40712. case 'target':
  40713. color = edge.node2.getVisual('color');
  40714. break;
  40715. }
  40716. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  40717. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  40718. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  40719. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  40720. edge.setVisual('color', color);
  40721. edge.setVisual('opacity', opacity);
  40722. });
  40723. });
  40724. };
  40725. function simpleLayout$1(seriesModel) {
  40726. var coordSys = seriesModel.coordinateSystem;
  40727. if (coordSys && coordSys.type !== 'view') {
  40728. return;
  40729. }
  40730. var graph = seriesModel.getGraph();
  40731. graph.eachNode(function (node) {
  40732. var model = node.getModel();
  40733. node.setLayout([+model.get('x'), +model.get('y')]);
  40734. });
  40735. simpleLayoutEdge(graph);
  40736. }
  40737. function simpleLayoutEdge(graph) {
  40738. graph.eachEdge(function (edge) {
  40739. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  40740. var p1 = clone$1(edge.node1.getLayout());
  40741. var p2 = clone$1(edge.node2.getLayout());
  40742. var points = [p1, p2];
  40743. if (+curveness) {
  40744. points.push([
  40745. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  40746. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  40747. ]);
  40748. }
  40749. edge.setLayout(points);
  40750. });
  40751. }
  40752. var simpleLayout = function (ecModel, api) {
  40753. ecModel.eachSeriesByType('graph', function (seriesModel) {
  40754. var layout = seriesModel.get('layout');
  40755. var coordSys = seriesModel.coordinateSystem;
  40756. if (coordSys && coordSys.type !== 'view') {
  40757. var data = seriesModel.getData();
  40758. var dimensions = [];
  40759. each$1(coordSys.dimensions, function (coordDim) {
  40760. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  40761. });
  40762. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  40763. var value = [];
  40764. var hasValue = false;
  40765. for (var i = 0; i < dimensions.length; i++) {
  40766. var val = data.get(dimensions[i], dataIndex);
  40767. if (!isNaN(val)) {
  40768. hasValue = true;
  40769. }
  40770. value.push(val);
  40771. }
  40772. if (hasValue) {
  40773. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  40774. }
  40775. else {
  40776. // Also {Array.<number>}, not undefined to avoid if...else... statement
  40777. data.setItemLayout(dataIndex, [NaN, NaN]);
  40778. }
  40779. }
  40780. simpleLayoutEdge(data.graph);
  40781. }
  40782. else if (!layout || layout === 'none') {
  40783. simpleLayout$1(seriesModel);
  40784. }
  40785. });
  40786. };
  40787. function circularLayout$1(seriesModel) {
  40788. var coordSys = seriesModel.coordinateSystem;
  40789. if (coordSys && coordSys.type !== 'view') {
  40790. return;
  40791. }
  40792. var rect = coordSys.getBoundingRect();
  40793. var nodeData = seriesModel.getData();
  40794. var graph = nodeData.graph;
  40795. var angle = 0;
  40796. var sum = nodeData.getSum('value');
  40797. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  40798. var cx = rect.width / 2 + rect.x;
  40799. var cy = rect.height / 2 + rect.y;
  40800. var r = Math.min(rect.width, rect.height) / 2;
  40801. graph.eachNode(function (node) {
  40802. var value = node.getValue('value');
  40803. angle += unitAngle * (sum ? value : 1) / 2;
  40804. node.setLayout([
  40805. r * Math.cos(angle) + cx,
  40806. r * Math.sin(angle) + cy
  40807. ]);
  40808. angle += unitAngle * (sum ? value : 1) / 2;
  40809. });
  40810. nodeData.setLayout({
  40811. cx: cx,
  40812. cy: cy
  40813. });
  40814. graph.eachEdge(function (edge) {
  40815. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  40816. var p1 = clone$1(edge.node1.getLayout());
  40817. var p2 = clone$1(edge.node2.getLayout());
  40818. var cp1;
  40819. var x12 = (p1[0] + p2[0]) / 2;
  40820. var y12 = (p1[1] + p2[1]) / 2;
  40821. if (+curveness) {
  40822. curveness *= 3;
  40823. cp1 = [
  40824. cx * curveness + x12 * (1 - curveness),
  40825. cy * curveness + y12 * (1 - curveness)
  40826. ];
  40827. }
  40828. edge.setLayout([p1, p2, cp1]);
  40829. });
  40830. }
  40831. var circularLayout = function (ecModel) {
  40832. ecModel.eachSeriesByType('graph', function (seriesModel) {
  40833. if (seriesModel.get('layout') === 'circular') {
  40834. circularLayout$1(seriesModel);
  40835. }
  40836. });
  40837. };
  40838. var scaleAndAdd$2 = scaleAndAdd;
  40839. // function adjacentNode(n, e) {
  40840. // return e.n1 === n ? e.n2 : e.n1;
  40841. // }
  40842. function forceLayout$1(nodes, edges, opts) {
  40843. var rect = opts.rect;
  40844. var width = rect.width;
  40845. var height = rect.height;
  40846. var center = [rect.x + width / 2, rect.y + height / 2];
  40847. // var scale = opts.scale || 1;
  40848. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  40849. // for (var i = 0; i < edges.length; i++) {
  40850. // var e = edges[i];
  40851. // var n1 = e.n1;
  40852. // var n2 = e.n2;
  40853. // n1.edges = n1.edges || [];
  40854. // n2.edges = n2.edges || [];
  40855. // n1.edges.push(e);
  40856. // n2.edges.push(e);
  40857. // }
  40858. // Init position
  40859. for (var i = 0; i < nodes.length; i++) {
  40860. var n = nodes[i];
  40861. if (!n.p) {
  40862. // Use the position from first adjecent node with defined position
  40863. // Or use a random position
  40864. // From d3
  40865. // if (n.edges) {
  40866. // var j = -1;
  40867. // while (++j < n.edges.length) {
  40868. // var e = n.edges[j];
  40869. // var other = adjacentNode(n, e);
  40870. // if (other.p) {
  40871. // n.p = vec2.clone(other.p);
  40872. // break;
  40873. // }
  40874. // }
  40875. // }
  40876. // if (!n.p) {
  40877. n.p = create(
  40878. width * (Math.random() - 0.5) + center[0],
  40879. height * (Math.random() - 0.5) + center[1]
  40880. );
  40881. // }
  40882. }
  40883. n.pp = clone$1(n.p);
  40884. n.edges = null;
  40885. }
  40886. // Formula in 'Graph Drawing by Force-directed Placement'
  40887. // var k = scale * Math.sqrt(width * height / nodes.length);
  40888. // var k2 = k * k;
  40889. var friction = 0.6;
  40890. return {
  40891. warmUp: function () {
  40892. friction = 0.5;
  40893. },
  40894. setFixed: function (idx) {
  40895. nodes[idx].fixed = true;
  40896. },
  40897. setUnfixed: function (idx) {
  40898. nodes[idx].fixed = false;
  40899. },
  40900. step: function (cb) {
  40901. var v12 = [];
  40902. var nLen = nodes.length;
  40903. for (var i = 0; i < edges.length; i++) {
  40904. var e = edges[i];
  40905. var n1 = e.n1;
  40906. var n2 = e.n2;
  40907. sub(v12, n2.p, n1.p);
  40908. var d = len(v12) - e.d;
  40909. var w = n2.w / (n1.w + n2.w);
  40910. if (isNaN(w)) {
  40911. w = 0;
  40912. }
  40913. normalize(v12, v12);
  40914. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  40915. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  40916. }
  40917. // Gravity
  40918. for (var i = 0; i < nLen; i++) {
  40919. var n = nodes[i];
  40920. if (!n.fixed) {
  40921. sub(v12, center, n.p);
  40922. // var d = vec2.len(v12);
  40923. // vec2.scale(v12, v12, 1 / d);
  40924. // var gravityFactor = gravity;
  40925. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  40926. }
  40927. }
  40928. // Repulsive
  40929. // PENDING
  40930. for (var i = 0; i < nLen; i++) {
  40931. var n1 = nodes[i];
  40932. for (var j = i + 1; j < nLen; j++) {
  40933. var n2 = nodes[j];
  40934. sub(v12, n2.p, n1.p);
  40935. var d = len(v12);
  40936. if (d === 0) {
  40937. // Random repulse
  40938. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  40939. d = 1;
  40940. }
  40941. var repFact = (n1.rep + n2.rep) / d / d;
  40942. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  40943. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  40944. }
  40945. }
  40946. var v = [];
  40947. for (var i = 0; i < nLen; i++) {
  40948. var n = nodes[i];
  40949. if (!n.fixed) {
  40950. sub(v, n.p, n.pp);
  40951. scaleAndAdd$2(n.p, n.p, v, friction);
  40952. copy(n.pp, n.p);
  40953. }
  40954. }
  40955. friction = friction * 0.992;
  40956. cb && cb(nodes, edges, friction < 0.01);
  40957. }
  40958. };
  40959. }
  40960. var forceLayout = function (ecModel) {
  40961. ecModel.eachSeriesByType('graph', function (graphSeries) {
  40962. var coordSys = graphSeries.coordinateSystem;
  40963. if (coordSys && coordSys.type !== 'view') {
  40964. return;
  40965. }
  40966. if (graphSeries.get('layout') === 'force') {
  40967. var preservedPoints = graphSeries.preservedPoints || {};
  40968. var graph = graphSeries.getGraph();
  40969. var nodeData = graph.data;
  40970. var edgeData = graph.edgeData;
  40971. var forceModel = graphSeries.getModel('force');
  40972. var initLayout = forceModel.get('initLayout');
  40973. if (graphSeries.preservedPoints) {
  40974. nodeData.each(function (idx) {
  40975. var id = nodeData.getId(idx);
  40976. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  40977. });
  40978. }
  40979. else if (!initLayout || initLayout === 'none') {
  40980. simpleLayout$1(graphSeries);
  40981. }
  40982. else if (initLayout === 'circular') {
  40983. circularLayout$1(graphSeries);
  40984. }
  40985. var nodeDataExtent = nodeData.getDataExtent('value');
  40986. var edgeDataExtent = edgeData.getDataExtent('value');
  40987. // var edgeDataExtent = edgeData.getDataExtent('value');
  40988. var repulsion = forceModel.get('repulsion');
  40989. var edgeLength = forceModel.get('edgeLength');
  40990. if (!isArray(repulsion)) {
  40991. repulsion = [repulsion, repulsion];
  40992. }
  40993. if (!isArray(edgeLength)) {
  40994. edgeLength = [edgeLength, edgeLength];
  40995. }
  40996. // Larger value has smaller length
  40997. edgeLength = [edgeLength[1], edgeLength[0]];
  40998. var nodes = nodeData.mapArray('value', function (value, idx) {
  40999. var point = nodeData.getItemLayout(idx);
  41000. var rep = linearMap(value, nodeDataExtent, repulsion);
  41001. if (isNaN(rep)) {
  41002. rep = (repulsion[0] + repulsion[1]) / 2;
  41003. }
  41004. return {
  41005. w: rep,
  41006. rep: rep,
  41007. fixed: nodeData.getItemModel(idx).get('fixed'),
  41008. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  41009. };
  41010. });
  41011. var edges = edgeData.mapArray('value', function (value, idx) {
  41012. var edge = graph.getEdgeByIndex(idx);
  41013. var d = linearMap(value, edgeDataExtent, edgeLength);
  41014. if (isNaN(d)) {
  41015. d = (edgeLength[0] + edgeLength[1]) / 2;
  41016. }
  41017. return {
  41018. n1: nodes[edge.node1.dataIndex],
  41019. n2: nodes[edge.node2.dataIndex],
  41020. d: d,
  41021. curveness: edge.getModel().get('lineStyle.curveness') || 0
  41022. };
  41023. });
  41024. var coordSys = graphSeries.coordinateSystem;
  41025. var rect = coordSys.getBoundingRect();
  41026. var forceInstance = forceLayout$1(nodes, edges, {
  41027. rect: rect,
  41028. gravity: forceModel.get('gravity')
  41029. });
  41030. var oldStep = forceInstance.step;
  41031. forceInstance.step = function (cb) {
  41032. for (var i = 0, l = nodes.length; i < l; i++) {
  41033. if (nodes[i].fixed) {
  41034. // Write back to layout instance
  41035. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  41036. }
  41037. }
  41038. oldStep(function (nodes, edges, stopped) {
  41039. for (var i = 0, l = nodes.length; i < l; i++) {
  41040. if (!nodes[i].fixed) {
  41041. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  41042. }
  41043. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  41044. }
  41045. for (var i = 0, l = edges.length; i < l; i++) {
  41046. var e = edges[i];
  41047. var edge = graph.getEdgeByIndex(i);
  41048. var p1 = e.n1.p;
  41049. var p2 = e.n2.p;
  41050. var points = edge.getLayout();
  41051. points = points ? points.slice() : [];
  41052. points[0] = points[0] || [];
  41053. points[1] = points[1] || [];
  41054. copy(points[0], p1);
  41055. copy(points[1], p2);
  41056. if (+e.curveness) {
  41057. points[2] = [
  41058. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  41059. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  41060. ];
  41061. }
  41062. edge.setLayout(points);
  41063. }
  41064. // Update layout
  41065. cb && cb(stopped);
  41066. });
  41067. };
  41068. graphSeries.forceLayout = forceInstance;
  41069. graphSeries.preservedPoints = preservedPoints;
  41070. // Step to get the layout
  41071. forceInstance.step();
  41072. }
  41073. else {
  41074. // Remove prev injected forceLayout instance
  41075. graphSeries.forceLayout = null;
  41076. }
  41077. });
  41078. };
  41079. // FIXME Where to create the simple view coordinate system
  41080. function getViewRect$1(seriesModel, api, aspect) {
  41081. var option = seriesModel.getBoxLayoutParams();
  41082. option.aspect = aspect;
  41083. return getLayoutRect(option, {
  41084. width: api.getWidth(),
  41085. height: api.getHeight()
  41086. });
  41087. }
  41088. var createView = function (ecModel, api) {
  41089. var viewList = [];
  41090. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41091. var coordSysType = seriesModel.get('coordinateSystem');
  41092. if (!coordSysType || coordSysType === 'view') {
  41093. var data = seriesModel.getData();
  41094. var positions = data.mapArray(function (idx) {
  41095. var itemModel = data.getItemModel(idx);
  41096. return [+itemModel.get('x'), +itemModel.get('y')];
  41097. });
  41098. var min = [];
  41099. var max = [];
  41100. fromPoints(positions, min, max);
  41101. // If width or height is 0
  41102. if (max[0] - min[0] === 0) {
  41103. max[0] += 1;
  41104. min[0] -= 1;
  41105. }
  41106. if (max[1] - min[1] === 0) {
  41107. max[1] += 1;
  41108. min[1] -= 1;
  41109. }
  41110. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  41111. // FIXME If get view rect after data processed?
  41112. var viewRect = getViewRect$1(seriesModel, api, aspect);
  41113. // Position may be NaN, use view rect instead
  41114. if (isNaN(aspect)) {
  41115. min = [viewRect.x, viewRect.y];
  41116. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  41117. }
  41118. var bbWidth = max[0] - min[0];
  41119. var bbHeight = max[1] - min[1];
  41120. var viewWidth = viewRect.width;
  41121. var viewHeight = viewRect.height;
  41122. var viewCoordSys = seriesModel.coordinateSystem = new View();
  41123. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  41124. viewCoordSys.setBoundingRect(
  41125. min[0], min[1], bbWidth, bbHeight
  41126. );
  41127. viewCoordSys.setViewRect(
  41128. viewRect.x, viewRect.y, viewWidth, viewHeight
  41129. );
  41130. // Update roam info
  41131. viewCoordSys.setCenter(seriesModel.get('center'));
  41132. viewCoordSys.setZoom(seriesModel.get('zoom'));
  41133. viewList.push(viewCoordSys);
  41134. }
  41135. });
  41136. return viewList;
  41137. };
  41138. registerProcessor(categoryFilter);
  41139. registerVisual(visualSymbol('graph', 'circle', null));
  41140. registerVisual(categoryVisual);
  41141. registerVisual(edgeVisual);
  41142. registerLayout(simpleLayout);
  41143. registerLayout(circularLayout);
  41144. registerLayout(forceLayout);
  41145. // Graph view coordinate system
  41146. registerCoordinateSystem('graphView', {
  41147. create: createView
  41148. });
  41149. var GaugeSeries = SeriesModel.extend({
  41150. type: 'series.gauge',
  41151. getInitialData: function (option, ecModel) {
  41152. var dataOpt = option.data || [];
  41153. if (!isArray(dataOpt)) {
  41154. dataOpt = [dataOpt];
  41155. }
  41156. option.data = dataOpt;
  41157. return createListSimply(this, ['value']);
  41158. },
  41159. defaultOption: {
  41160. zlevel: 0,
  41161. z: 2,
  41162. // 默认全局居中
  41163. center: ['50%', '50%'],
  41164. legendHoverLink: true,
  41165. radius: '75%',
  41166. startAngle: 225,
  41167. endAngle: -45,
  41168. clockwise: true,
  41169. // 最小值
  41170. min: 0,
  41171. // 最大值
  41172. max: 100,
  41173. // 分割段数,默认为10
  41174. splitNumber: 10,
  41175. // 坐标轴线
  41176. axisLine: {
  41177. // 默认显示,属性show控制显示与否
  41178. show: true,
  41179. lineStyle: { // 属性lineStyle控制线条样式
  41180. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  41181. width: 30
  41182. }
  41183. },
  41184. // 分隔线
  41185. splitLine: {
  41186. // 默认显示,属性show控制显示与否
  41187. show: true,
  41188. // 属性length控制线长
  41189. length: 30,
  41190. // 属性lineStyle(详见lineStyle)控制线条样式
  41191. lineStyle: {
  41192. color: '#eee',
  41193. width: 2,
  41194. type: 'solid'
  41195. }
  41196. },
  41197. // 坐标轴小标记
  41198. axisTick: {
  41199. // 属性show控制显示与否,默认不显示
  41200. show: true,
  41201. // 每份split细分多少段
  41202. splitNumber: 5,
  41203. // 属性length控制线长
  41204. length: 8,
  41205. // 属性lineStyle控制线条样式
  41206. lineStyle: {
  41207. color: '#eee',
  41208. width: 1,
  41209. type: 'solid'
  41210. }
  41211. },
  41212. axisLabel: {
  41213. show: true,
  41214. distance: 5,
  41215. // formatter: null,
  41216. color: 'auto'
  41217. },
  41218. pointer: {
  41219. show: true,
  41220. length: '80%',
  41221. width: 8
  41222. },
  41223. itemStyle: {
  41224. color: 'auto'
  41225. },
  41226. title: {
  41227. show: true,
  41228. // x, y,单位px
  41229. offsetCenter: [0, '-40%'],
  41230. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  41231. color: '#333',
  41232. fontSize: 15
  41233. },
  41234. detail: {
  41235. show: true,
  41236. backgroundColor: 'rgba(0,0,0,0)',
  41237. borderWidth: 0,
  41238. borderColor: '#ccc',
  41239. width: 100,
  41240. height: null, // self-adaption
  41241. padding: [5, 10],
  41242. // x, y,单位px
  41243. offsetCenter: [0, '40%'],
  41244. // formatter: null,
  41245. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  41246. color: 'auto',
  41247. fontSize: 30
  41248. }
  41249. }
  41250. });
  41251. var PointerPath = Path.extend({
  41252. type: 'echartsGaugePointer',
  41253. shape: {
  41254. angle: 0,
  41255. width: 10,
  41256. r: 10,
  41257. x: 0,
  41258. y: 0
  41259. },
  41260. buildPath: function (ctx, shape) {
  41261. var mathCos = Math.cos;
  41262. var mathSin = Math.sin;
  41263. var r = shape.r;
  41264. var width = shape.width;
  41265. var angle = shape.angle;
  41266. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  41267. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  41268. angle = shape.angle - Math.PI / 2;
  41269. ctx.moveTo(x, y);
  41270. ctx.lineTo(
  41271. shape.x + mathCos(angle) * width,
  41272. shape.y + mathSin(angle) * width
  41273. );
  41274. ctx.lineTo(
  41275. shape.x + mathCos(shape.angle) * r,
  41276. shape.y + mathSin(shape.angle) * r
  41277. );
  41278. ctx.lineTo(
  41279. shape.x - mathCos(angle) * width,
  41280. shape.y - mathSin(angle) * width
  41281. );
  41282. ctx.lineTo(x, y);
  41283. return;
  41284. }
  41285. });
  41286. function parsePosition(seriesModel, api) {
  41287. var center = seriesModel.get('center');
  41288. var width = api.getWidth();
  41289. var height = api.getHeight();
  41290. var size = Math.min(width, height);
  41291. var cx = parsePercent$1(center[0], api.getWidth());
  41292. var cy = parsePercent$1(center[1], api.getHeight());
  41293. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  41294. return {
  41295. cx: cx,
  41296. cy: cy,
  41297. r: r
  41298. };
  41299. }
  41300. function formatLabel(label, labelFormatter) {
  41301. if (labelFormatter) {
  41302. if (typeof labelFormatter === 'string') {
  41303. label = labelFormatter.replace('{value}', label != null ? label : '');
  41304. }
  41305. else if (typeof labelFormatter === 'function') {
  41306. label = labelFormatter(label);
  41307. }
  41308. }
  41309. return label;
  41310. }
  41311. var PI2$5 = Math.PI * 2;
  41312. var GaugeView = Chart.extend({
  41313. type: 'gauge',
  41314. render: function (seriesModel, ecModel, api) {
  41315. this.group.removeAll();
  41316. var colorList = seriesModel.get('axisLine.lineStyle.color');
  41317. var posInfo = parsePosition(seriesModel, api);
  41318. this._renderMain(
  41319. seriesModel, ecModel, api, colorList, posInfo
  41320. );
  41321. },
  41322. dispose: function () {},
  41323. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  41324. var group = this.group;
  41325. var axisLineModel = seriesModel.getModel('axisLine');
  41326. var lineStyleModel = axisLineModel.getModel('lineStyle');
  41327. var clockwise = seriesModel.get('clockwise');
  41328. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  41329. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  41330. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  41331. var prevEndAngle = startAngle;
  41332. var axisLineWidth = lineStyleModel.get('width');
  41333. for (var i = 0; i < colorList.length; i++) {
  41334. // Clamp
  41335. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  41336. var endAngle = startAngle + angleRangeSpan * percent;
  41337. var sector = new Sector({
  41338. shape: {
  41339. startAngle: prevEndAngle,
  41340. endAngle: endAngle,
  41341. cx: posInfo.cx,
  41342. cy: posInfo.cy,
  41343. clockwise: clockwise,
  41344. r0: posInfo.r - axisLineWidth,
  41345. r: posInfo.r
  41346. },
  41347. silent: true
  41348. });
  41349. sector.setStyle({
  41350. fill: colorList[i][1]
  41351. });
  41352. sector.setStyle(lineStyleModel.getLineStyle(
  41353. // Because we use sector to simulate arc
  41354. // so the properties for stroking are useless
  41355. ['color', 'borderWidth', 'borderColor']
  41356. ));
  41357. group.add(sector);
  41358. prevEndAngle = endAngle;
  41359. }
  41360. var getColor = function (percent) {
  41361. // Less than 0
  41362. if (percent <= 0) {
  41363. return colorList[0][1];
  41364. }
  41365. for (var i = 0; i < colorList.length; i++) {
  41366. if (colorList[i][0] >= percent
  41367. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  41368. ) {
  41369. return colorList[i][1];
  41370. }
  41371. }
  41372. // More than 1
  41373. return colorList[i - 1][1];
  41374. };
  41375. if (!clockwise) {
  41376. var tmp = startAngle;
  41377. startAngle = endAngle;
  41378. endAngle = tmp;
  41379. }
  41380. this._renderTicks(
  41381. seriesModel, ecModel, api, getColor, posInfo,
  41382. startAngle, endAngle, clockwise
  41383. );
  41384. this._renderPointer(
  41385. seriesModel, ecModel, api, getColor, posInfo,
  41386. startAngle, endAngle, clockwise
  41387. );
  41388. this._renderTitle(
  41389. seriesModel, ecModel, api, getColor, posInfo
  41390. );
  41391. this._renderDetail(
  41392. seriesModel, ecModel, api, getColor, posInfo
  41393. );
  41394. },
  41395. _renderTicks: function (
  41396. seriesModel, ecModel, api, getColor, posInfo,
  41397. startAngle, endAngle, clockwise
  41398. ) {
  41399. var group = this.group;
  41400. var cx = posInfo.cx;
  41401. var cy = posInfo.cy;
  41402. var r = posInfo.r;
  41403. var minVal = +seriesModel.get('min');
  41404. var maxVal = +seriesModel.get('max');
  41405. var splitLineModel = seriesModel.getModel('splitLine');
  41406. var tickModel = seriesModel.getModel('axisTick');
  41407. var labelModel = seriesModel.getModel('axisLabel');
  41408. var splitNumber = seriesModel.get('splitNumber');
  41409. var subSplitNumber = tickModel.get('splitNumber');
  41410. var splitLineLen = parsePercent$1(
  41411. splitLineModel.get('length'), r
  41412. );
  41413. var tickLen = parsePercent$1(
  41414. tickModel.get('length'), r
  41415. );
  41416. var angle = startAngle;
  41417. var step = (endAngle - startAngle) / splitNumber;
  41418. var subStep = step / subSplitNumber;
  41419. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  41420. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  41421. for (var i = 0; i <= splitNumber; i++) {
  41422. var unitX = Math.cos(angle);
  41423. var unitY = Math.sin(angle);
  41424. // Split line
  41425. if (splitLineModel.get('show')) {
  41426. var splitLine = new Line({
  41427. shape: {
  41428. x1: unitX * r + cx,
  41429. y1: unitY * r + cy,
  41430. x2: unitX * (r - splitLineLen) + cx,
  41431. y2: unitY * (r - splitLineLen) + cy
  41432. },
  41433. style: splitLineStyle,
  41434. silent: true
  41435. });
  41436. if (splitLineStyle.stroke === 'auto') {
  41437. splitLine.setStyle({
  41438. stroke: getColor(i / splitNumber)
  41439. });
  41440. }
  41441. group.add(splitLine);
  41442. }
  41443. // Label
  41444. if (labelModel.get('show')) {
  41445. var label = formatLabel(
  41446. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  41447. labelModel.get('formatter')
  41448. );
  41449. var distance = labelModel.get('distance');
  41450. var autoColor = getColor(i / splitNumber);
  41451. group.add(new Text({
  41452. style: setTextStyle({}, labelModel, {
  41453. text: label,
  41454. x: unitX * (r - splitLineLen - distance) + cx,
  41455. y: unitY * (r - splitLineLen - distance) + cy,
  41456. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  41457. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  41458. }, {autoColor: autoColor}),
  41459. silent: true
  41460. }));
  41461. }
  41462. // Axis tick
  41463. if (tickModel.get('show') && i !== splitNumber) {
  41464. for (var j = 0; j <= subSplitNumber; j++) {
  41465. var unitX = Math.cos(angle);
  41466. var unitY = Math.sin(angle);
  41467. var tickLine = new Line({
  41468. shape: {
  41469. x1: unitX * r + cx,
  41470. y1: unitY * r + cy,
  41471. x2: unitX * (r - tickLen) + cx,
  41472. y2: unitY * (r - tickLen) + cy
  41473. },
  41474. silent: true,
  41475. style: tickLineStyle
  41476. });
  41477. if (tickLineStyle.stroke === 'auto') {
  41478. tickLine.setStyle({
  41479. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  41480. });
  41481. }
  41482. group.add(tickLine);
  41483. angle += subStep;
  41484. }
  41485. angle -= subStep;
  41486. }
  41487. else {
  41488. angle += step;
  41489. }
  41490. }
  41491. },
  41492. _renderPointer: function (
  41493. seriesModel, ecModel, api, getColor, posInfo,
  41494. startAngle, endAngle, clockwise
  41495. ) {
  41496. var group = this.group;
  41497. var oldData = this._data;
  41498. if (!seriesModel.get('pointer.show')) {
  41499. // Remove old element
  41500. oldData && oldData.eachItemGraphicEl(function (el) {
  41501. group.remove(el);
  41502. });
  41503. return;
  41504. }
  41505. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  41506. var angleExtent = [startAngle, endAngle];
  41507. var data = seriesModel.getData();
  41508. var valueDim = data.mapDimension('value');
  41509. data.diff(oldData)
  41510. .add(function (idx) {
  41511. var pointer = new PointerPath({
  41512. shape: {
  41513. angle: startAngle
  41514. }
  41515. });
  41516. initProps(pointer, {
  41517. shape: {
  41518. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  41519. }
  41520. }, seriesModel);
  41521. group.add(pointer);
  41522. data.setItemGraphicEl(idx, pointer);
  41523. })
  41524. .update(function (newIdx, oldIdx) {
  41525. var pointer = oldData.getItemGraphicEl(oldIdx);
  41526. updateProps(pointer, {
  41527. shape: {
  41528. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  41529. }
  41530. }, seriesModel);
  41531. group.add(pointer);
  41532. data.setItemGraphicEl(newIdx, pointer);
  41533. })
  41534. .remove(function (idx) {
  41535. var pointer = oldData.getItemGraphicEl(idx);
  41536. group.remove(pointer);
  41537. })
  41538. .execute();
  41539. data.eachItemGraphicEl(function (pointer, idx) {
  41540. var itemModel = data.getItemModel(idx);
  41541. var pointerModel = itemModel.getModel('pointer');
  41542. pointer.setShape({
  41543. x: posInfo.cx,
  41544. y: posInfo.cy,
  41545. width: parsePercent$1(
  41546. pointerModel.get('width'), posInfo.r
  41547. ),
  41548. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  41549. });
  41550. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  41551. if (pointer.style.fill === 'auto') {
  41552. pointer.setStyle('fill', getColor(
  41553. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  41554. ));
  41555. }
  41556. setHoverStyle(
  41557. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  41558. );
  41559. });
  41560. this._data = data;
  41561. },
  41562. _renderTitle: function (
  41563. seriesModel, ecModel, api, getColor, posInfo
  41564. ) {
  41565. var data = seriesModel.getData();
  41566. var valueDim = data.mapDimension('value');
  41567. var titleModel = seriesModel.getModel('title');
  41568. if (titleModel.get('show')) {
  41569. var offsetCenter = titleModel.get('offsetCenter');
  41570. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  41571. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  41572. var minVal = +seriesModel.get('min');
  41573. var maxVal = +seriesModel.get('max');
  41574. var value = seriesModel.getData().get(valueDim, 0);
  41575. var autoColor = getColor(
  41576. linearMap(value, [minVal, maxVal], [0, 1], true)
  41577. );
  41578. this.group.add(new Text({
  41579. silent: true,
  41580. style: setTextStyle({}, titleModel, {
  41581. x: x,
  41582. y: y,
  41583. // FIXME First data name ?
  41584. text: data.getName(0),
  41585. textAlign: 'center',
  41586. textVerticalAlign: 'middle'
  41587. }, {autoColor: autoColor, forceRich: true})
  41588. }));
  41589. }
  41590. },
  41591. _renderDetail: function (
  41592. seriesModel, ecModel, api, getColor, posInfo
  41593. ) {
  41594. var detailModel = seriesModel.getModel('detail');
  41595. var minVal = +seriesModel.get('min');
  41596. var maxVal = +seriesModel.get('max');
  41597. if (detailModel.get('show')) {
  41598. var offsetCenter = detailModel.get('offsetCenter');
  41599. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  41600. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  41601. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  41602. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  41603. var data = seriesModel.getData();
  41604. var value = data.get(data.mapDimension('value'), 0);
  41605. var autoColor = getColor(
  41606. linearMap(value, [minVal, maxVal], [0, 1], true)
  41607. );
  41608. this.group.add(new Text({
  41609. silent: true,
  41610. style: setTextStyle({}, detailModel, {
  41611. x: x,
  41612. y: y,
  41613. text: formatLabel(
  41614. // FIXME First data name ?
  41615. value, detailModel.get('formatter')
  41616. ),
  41617. textWidth: isNaN(width) ? null : width,
  41618. textHeight: isNaN(height) ? null : height,
  41619. textAlign: 'center',
  41620. textVerticalAlign: 'middle'
  41621. }, {autoColor: autoColor, forceRich: true})
  41622. }));
  41623. }
  41624. }
  41625. });
  41626. var FunnelSeries = extendSeriesModel({
  41627. type: 'series.funnel',
  41628. init: function (option) {
  41629. FunnelSeries.superApply(this, 'init', arguments);
  41630. // Enable legend selection for each data item
  41631. // Use a function instead of direct access because data reference may changed
  41632. this.legendDataProvider = function () {
  41633. return this.getRawData();
  41634. };
  41635. // Extend labelLine emphasis
  41636. this._defaultLabelLine(option);
  41637. },
  41638. getInitialData: function (option, ecModel) {
  41639. return createListSimply(this, ['value']);
  41640. },
  41641. _defaultLabelLine: function (option) {
  41642. // Extend labelLine emphasis
  41643. defaultEmphasis(option, 'labelLine', ['show']);
  41644. var labelLineNormalOpt = option.labelLine;
  41645. var labelLineEmphasisOpt = option.emphasis.labelLine;
  41646. // Not show label line if `label.normal.show = false`
  41647. labelLineNormalOpt.show = labelLineNormalOpt.show
  41648. && option.label.show;
  41649. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  41650. && option.emphasis.label.show;
  41651. },
  41652. // Overwrite
  41653. getDataParams: function (dataIndex) {
  41654. var data = this.getData();
  41655. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  41656. var valueDim = data.mapDimension('value');
  41657. var sum = data.getSum(valueDim);
  41658. // Percent is 0 if sum is 0
  41659. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  41660. params.$vars.push('percent');
  41661. return params;
  41662. },
  41663. defaultOption: {
  41664. zlevel: 0, // 一级层叠
  41665. z: 2, // 二级层叠
  41666. legendHoverLink: true,
  41667. left: 80,
  41668. top: 60,
  41669. right: 80,
  41670. bottom: 60,
  41671. // width: {totalWidth} - left - right,
  41672. // height: {totalHeight} - top - bottom,
  41673. // 默认取数据最小最大值
  41674. // min: 0,
  41675. // max: 100,
  41676. minSize: '0%',
  41677. maxSize: '100%',
  41678. sort: 'descending', // 'ascending', 'descending'
  41679. gap: 0,
  41680. funnelAlign: 'center',
  41681. label: {
  41682. show: true,
  41683. position: 'outer'
  41684. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  41685. },
  41686. labelLine: {
  41687. show: true,
  41688. length: 20,
  41689. lineStyle: {
  41690. // color: 各异,
  41691. width: 1,
  41692. type: 'solid'
  41693. }
  41694. },
  41695. itemStyle: {
  41696. // color: 各异,
  41697. borderColor: '#fff',
  41698. borderWidth: 1
  41699. },
  41700. emphasis: {
  41701. label: {
  41702. show: true
  41703. }
  41704. }
  41705. }
  41706. });
  41707. /**
  41708. * Piece of pie including Sector, Label, LabelLine
  41709. * @constructor
  41710. * @extends {module:zrender/graphic/Group}
  41711. */
  41712. function FunnelPiece(data, idx) {
  41713. Group.call(this);
  41714. var polygon = new Polygon();
  41715. var labelLine = new Polyline();
  41716. var text = new Text();
  41717. this.add(polygon);
  41718. this.add(labelLine);
  41719. this.add(text);
  41720. this.updateData(data, idx, true);
  41721. // Hover to change label and labelLine
  41722. function onEmphasis() {
  41723. labelLine.ignore = labelLine.hoverIgnore;
  41724. text.ignore = text.hoverIgnore;
  41725. }
  41726. function onNormal() {
  41727. labelLine.ignore = labelLine.normalIgnore;
  41728. text.ignore = text.normalIgnore;
  41729. }
  41730. this.on('emphasis', onEmphasis)
  41731. .on('normal', onNormal)
  41732. .on('mouseover', onEmphasis)
  41733. .on('mouseout', onNormal);
  41734. }
  41735. var funnelPieceProto = FunnelPiece.prototype;
  41736. var opacityAccessPath = ['itemStyle', 'opacity'];
  41737. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  41738. var polygon = this.childAt(0);
  41739. var seriesModel = data.hostModel;
  41740. var itemModel = data.getItemModel(idx);
  41741. var layout = data.getItemLayout(idx);
  41742. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  41743. opacity = opacity == null ? 1 : opacity;
  41744. // Reset style
  41745. polygon.useStyle({});
  41746. if (firstCreate) {
  41747. polygon.setShape({
  41748. points: layout.points
  41749. });
  41750. polygon.setStyle({ opacity : 0 });
  41751. initProps(polygon, {
  41752. style: {
  41753. opacity: opacity
  41754. }
  41755. }, seriesModel, idx);
  41756. }
  41757. else {
  41758. updateProps(polygon, {
  41759. style: {
  41760. opacity: opacity
  41761. },
  41762. shape: {
  41763. points: layout.points
  41764. }
  41765. }, seriesModel, idx);
  41766. }
  41767. // Update common style
  41768. var itemStyleModel = itemModel.getModel('itemStyle');
  41769. var visualColor = data.getItemVisual(idx, 'color');
  41770. polygon.setStyle(
  41771. defaults(
  41772. {
  41773. lineJoin: 'round',
  41774. fill: visualColor
  41775. },
  41776. itemStyleModel.getItemStyle(['opacity'])
  41777. )
  41778. );
  41779. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  41780. this._updateLabel(data, idx);
  41781. setHoverStyle(this);
  41782. };
  41783. funnelPieceProto._updateLabel = function (data, idx) {
  41784. var labelLine = this.childAt(1);
  41785. var labelText = this.childAt(2);
  41786. var seriesModel = data.hostModel;
  41787. var itemModel = data.getItemModel(idx);
  41788. var layout = data.getItemLayout(idx);
  41789. var labelLayout = layout.label;
  41790. var visualColor = data.getItemVisual(idx, 'color');
  41791. updateProps(labelLine, {
  41792. shape: {
  41793. points: labelLayout.linePoints || labelLayout.linePoints
  41794. }
  41795. }, seriesModel, idx);
  41796. updateProps(labelText, {
  41797. style: {
  41798. x: labelLayout.x,
  41799. y: labelLayout.y
  41800. }
  41801. }, seriesModel, idx);
  41802. labelText.attr({
  41803. rotation: labelLayout.rotation,
  41804. origin: [labelLayout.x, labelLayout.y],
  41805. z2: 10
  41806. });
  41807. var labelModel = itemModel.getModel('label');
  41808. var labelHoverModel = itemModel.getModel('emphasis.label');
  41809. var labelLineModel = itemModel.getModel('labelLine');
  41810. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  41811. var visualColor = data.getItemVisual(idx, 'color');
  41812. setLabelStyle(
  41813. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  41814. {
  41815. labelFetcher: data.hostModel,
  41816. labelDataIndex: idx,
  41817. defaultText: data.getName(idx),
  41818. autoColor: visualColor,
  41819. useInsideStyle: !!labelLayout.inside
  41820. },
  41821. {
  41822. textAlign: labelLayout.textAlign,
  41823. textVerticalAlign: labelLayout.verticalAlign
  41824. }
  41825. );
  41826. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  41827. labelText.hoverIgnore = !labelHoverModel.get('show');
  41828. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  41829. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  41830. // Default use item visual color
  41831. labelLine.setStyle({
  41832. stroke: visualColor
  41833. });
  41834. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  41835. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  41836. };
  41837. inherits(FunnelPiece, Group);
  41838. var FunnelView = Chart.extend({
  41839. type: 'funnel',
  41840. render: function (seriesModel, ecModel, api) {
  41841. var data = seriesModel.getData();
  41842. var oldData = this._data;
  41843. var group = this.group;
  41844. data.diff(oldData)
  41845. .add(function (idx) {
  41846. var funnelPiece = new FunnelPiece(data, idx);
  41847. data.setItemGraphicEl(idx, funnelPiece);
  41848. group.add(funnelPiece);
  41849. })
  41850. .update(function (newIdx, oldIdx) {
  41851. var piePiece = oldData.getItemGraphicEl(oldIdx);
  41852. piePiece.updateData(data, newIdx);
  41853. group.add(piePiece);
  41854. data.setItemGraphicEl(newIdx, piePiece);
  41855. })
  41856. .remove(function (idx) {
  41857. var piePiece = oldData.getItemGraphicEl(idx);
  41858. group.remove(piePiece);
  41859. })
  41860. .execute();
  41861. this._data = data;
  41862. },
  41863. remove: function () {
  41864. this.group.removeAll();
  41865. this._data = null;
  41866. },
  41867. dispose: function () {}
  41868. });
  41869. function getViewRect$2(seriesModel, api) {
  41870. return getLayoutRect(
  41871. seriesModel.getBoxLayoutParams(), {
  41872. width: api.getWidth(),
  41873. height: api.getHeight()
  41874. }
  41875. );
  41876. }
  41877. function getSortedIndices(data, sort) {
  41878. var valueDim = data.mapDimension('value');
  41879. var valueArr = data.mapArray(valueDim, function (val) {
  41880. return val;
  41881. });
  41882. var indices = [];
  41883. var isAscending = sort === 'ascending';
  41884. for (var i = 0, len = data.count(); i < len; i++) {
  41885. indices[i] = i;
  41886. }
  41887. // Add custom sortable function & none sortable opetion by "options.sort"
  41888. if (typeof sort === 'function') {
  41889. indices.sort(sort);
  41890. } else if (sort !== 'none') {
  41891. indices.sort(function (a, b) {
  41892. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  41893. });
  41894. }
  41895. return indices;
  41896. }
  41897. function labelLayout$1(data) {
  41898. data.each(function (idx) {
  41899. var itemModel = data.getItemModel(idx);
  41900. var labelModel = itemModel.getModel('label');
  41901. var labelPosition = labelModel.get('position');
  41902. var labelLineModel = itemModel.getModel('labelLine');
  41903. var layout = data.getItemLayout(idx);
  41904. var points = layout.points;
  41905. var isLabelInside = labelPosition === 'inner'
  41906. || labelPosition === 'inside' || labelPosition === 'center';
  41907. var textAlign;
  41908. var textX;
  41909. var textY;
  41910. var linePoints;
  41911. if (isLabelInside) {
  41912. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  41913. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  41914. textAlign = 'center';
  41915. linePoints = [
  41916. [textX, textY], [textX, textY]
  41917. ];
  41918. }
  41919. else {
  41920. var x1;
  41921. var y1;
  41922. var x2;
  41923. var labelLineLen = labelLineModel.get('length');
  41924. if (labelPosition === 'left') {
  41925. // Left side
  41926. x1 = (points[3][0] + points[0][0]) / 2;
  41927. y1 = (points[3][1] + points[0][1]) / 2;
  41928. x2 = x1 - labelLineLen;
  41929. textX = x2 - 5;
  41930. textAlign = 'right';
  41931. }
  41932. else {
  41933. // Right side
  41934. x1 = (points[1][0] + points[2][0]) / 2;
  41935. y1 = (points[1][1] + points[2][1]) / 2;
  41936. x2 = x1 + labelLineLen;
  41937. textX = x2 + 5;
  41938. textAlign = 'left';
  41939. }
  41940. var y2 = y1;
  41941. linePoints = [[x1, y1], [x2, y2]];
  41942. textY = y2;
  41943. }
  41944. layout.label = {
  41945. linePoints: linePoints,
  41946. x: textX,
  41947. y: textY,
  41948. verticalAlign: 'middle',
  41949. textAlign: textAlign,
  41950. inside: isLabelInside
  41951. };
  41952. });
  41953. }
  41954. var funnelLayout = function (ecModel, api, payload) {
  41955. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  41956. var data = seriesModel.getData();
  41957. var valueDim = data.mapDimension('value');
  41958. var sort = seriesModel.get('sort');
  41959. var viewRect = getViewRect$2(seriesModel, api);
  41960. var indices = getSortedIndices(data, sort);
  41961. var sizeExtent = [
  41962. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  41963. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  41964. ];
  41965. var dataExtent = data.getDataExtent(valueDim);
  41966. var min = seriesModel.get('min');
  41967. var max = seriesModel.get('max');
  41968. if (min == null) {
  41969. min = Math.min(dataExtent[0], 0);
  41970. }
  41971. if (max == null) {
  41972. max = dataExtent[1];
  41973. }
  41974. var funnelAlign = seriesModel.get('funnelAlign');
  41975. var gap = seriesModel.get('gap');
  41976. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  41977. var y = viewRect.y;
  41978. var getLinePoints = function (idx, offY) {
  41979. // End point index is data.count() and we assign it 0
  41980. var val = data.get(valueDim, idx) || 0;
  41981. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  41982. var x0;
  41983. switch (funnelAlign) {
  41984. case 'left':
  41985. x0 = viewRect.x;
  41986. break;
  41987. case 'center':
  41988. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  41989. break;
  41990. case 'right':
  41991. x0 = viewRect.x + viewRect.width - itemWidth;
  41992. break;
  41993. }
  41994. return [
  41995. [x0, offY],
  41996. [x0 + itemWidth, offY]
  41997. ];
  41998. };
  41999. if (sort === 'ascending') {
  42000. // From bottom to top
  42001. itemHeight = -itemHeight;
  42002. gap = -gap;
  42003. y += viewRect.height;
  42004. indices = indices.reverse();
  42005. }
  42006. for (var i = 0; i < indices.length; i++) {
  42007. var idx = indices[i];
  42008. var nextIdx = indices[i + 1];
  42009. var itemModel = data.getItemModel(idx);
  42010. var height = itemModel.get('itemStyle.height');
  42011. if (height == null) {
  42012. height = itemHeight;
  42013. }
  42014. else {
  42015. height = parsePercent$1(height, viewRect.height);
  42016. if (sort === 'ascending') {
  42017. height = -height;
  42018. }
  42019. }
  42020. var start = getLinePoints(idx, y);
  42021. var end = getLinePoints(nextIdx, y + height);
  42022. y += height + gap;
  42023. data.setItemLayout(idx, {
  42024. points: start.concat(end.slice().reverse())
  42025. });
  42026. }
  42027. labelLayout$1(data);
  42028. });
  42029. };
  42030. registerVisual(dataColor('funnel'));
  42031. registerLayout(funnelLayout);
  42032. registerProcessor(dataFilter('funnel'));
  42033. var parallelPreprocessor = function (option) {
  42034. createParallelIfNeeded(option);
  42035. mergeAxisOptionFromParallel(option);
  42036. };
  42037. /**
  42038. * Create a parallel coordinate if not exists.
  42039. * @inner
  42040. */
  42041. function createParallelIfNeeded(option) {
  42042. if (option.parallel) {
  42043. return;
  42044. }
  42045. var hasParallelSeries = false;
  42046. each$1(option.series, function (seriesOpt) {
  42047. if (seriesOpt && seriesOpt.type === 'parallel') {
  42048. hasParallelSeries = true;
  42049. }
  42050. });
  42051. if (hasParallelSeries) {
  42052. option.parallel = [{}];
  42053. }
  42054. }
  42055. /**
  42056. * Merge aixs definition from parallel option (if exists) to axis option.
  42057. * @inner
  42058. */
  42059. function mergeAxisOptionFromParallel(option) {
  42060. var axes = normalizeToArray(option.parallelAxis);
  42061. each$1(axes, function (axisOption) {
  42062. if (!isObject$1(axisOption)) {
  42063. return;
  42064. }
  42065. var parallelIndex = axisOption.parallelIndex || 0;
  42066. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  42067. if (parallelOption && parallelOption.parallelAxisDefault) {
  42068. merge(axisOption, parallelOption.parallelAxisDefault, false);
  42069. }
  42070. });
  42071. }
  42072. /**
  42073. * @constructor module:echarts/coord/parallel/ParallelAxis
  42074. * @extends {module:echarts/coord/Axis}
  42075. * @param {string} dim
  42076. * @param {*} scale
  42077. * @param {Array.<number>} coordExtent
  42078. * @param {string} axisType
  42079. */
  42080. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  42081. Axis.call(this, dim, scale, coordExtent);
  42082. /**
  42083. * Axis type
  42084. * - 'category'
  42085. * - 'value'
  42086. * - 'time'
  42087. * - 'log'
  42088. * @type {string}
  42089. */
  42090. this.type = axisType || 'value';
  42091. /**
  42092. * @type {number}
  42093. * @readOnly
  42094. */
  42095. this.axisIndex = axisIndex;
  42096. };
  42097. ParallelAxis.prototype = {
  42098. constructor: ParallelAxis,
  42099. /**
  42100. * Axis model
  42101. * @param {module:echarts/coord/parallel/AxisModel}
  42102. */
  42103. model: null,
  42104. /**
  42105. * @override
  42106. */
  42107. isHorizontal: function () {
  42108. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  42109. }
  42110. };
  42111. inherits(ParallelAxis, Axis);
  42112. /**
  42113. * Calculate slider move result.
  42114. * Usage:
  42115. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  42116. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  42117. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  42118. *
  42119. * @param {number} delta Move length.
  42120. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  42121. * handleEnds will be modified in this method.
  42122. * @param {Array.<number>} extent handleEnds is restricted by extent.
  42123. * extent[0] should less or equals than extent[1].
  42124. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  42125. * where the input minSpan and maxSpan will not work.
  42126. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  42127. * If not set, handle0 and cross handle1. If set as a non-negative
  42128. * number (including `0`), handles will push each other when reaching
  42129. * the minSpan.
  42130. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  42131. * @return {Array.<number>} The input handleEnds.
  42132. */
  42133. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  42134. // Normalize firstly.
  42135. handleEnds[0] = restrict$1(handleEnds[0], extent);
  42136. handleEnds[1] = restrict$1(handleEnds[1], extent);
  42137. delta = delta || 0;
  42138. var extentSpan = extent[1] - extent[0];
  42139. // Notice maxSpan and minSpan can be null/undefined.
  42140. if (minSpan != null) {
  42141. minSpan = restrict$1(minSpan, [0, extentSpan]);
  42142. }
  42143. if (maxSpan != null) {
  42144. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  42145. }
  42146. if (handleIndex === 'all') {
  42147. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  42148. handleIndex = 0;
  42149. }
  42150. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  42151. handleEnds[handleIndex] += delta;
  42152. // Restrict in extent.
  42153. var extentMinSpan = minSpan || 0;
  42154. var realExtent = extent.slice();
  42155. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  42156. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  42157. // Expand span.
  42158. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42159. if (minSpan != null && (
  42160. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  42161. )) {
  42162. // If minSpan exists, 'cross' is forbinden.
  42163. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  42164. }
  42165. // Shrink span.
  42166. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42167. if (maxSpan != null && currDistSign.span > maxSpan) {
  42168. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  42169. }
  42170. return handleEnds;
  42171. };
  42172. function getSpanSign(handleEnds, handleIndex) {
  42173. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  42174. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  42175. // is at left of handleEnds[1] for non-cross case.
  42176. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  42177. }
  42178. function restrict$1(value, extend) {
  42179. return Math.min(extend[1], Math.max(extend[0], value));
  42180. }
  42181. /**
  42182. * Parallel Coordinates
  42183. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  42184. */
  42185. var each$12 = each$1;
  42186. var mathMin$5 = Math.min;
  42187. var mathMax$5 = Math.max;
  42188. var mathFloor$2 = Math.floor;
  42189. var mathCeil$2 = Math.ceil;
  42190. var round$2 = round$1;
  42191. var PI$3 = Math.PI;
  42192. function Parallel(parallelModel, ecModel, api) {
  42193. /**
  42194. * key: dimension
  42195. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  42196. * @private
  42197. */
  42198. this._axesMap = createHashMap();
  42199. /**
  42200. * key: dimension
  42201. * value: {position: [], rotation, }
  42202. * @type {Object.<string, Object>}
  42203. * @private
  42204. */
  42205. this._axesLayout = {};
  42206. /**
  42207. * Always follow axis order.
  42208. * @type {Array.<string>}
  42209. * @readOnly
  42210. */
  42211. this.dimensions = parallelModel.dimensions;
  42212. /**
  42213. * @type {module:zrender/core/BoundingRect}
  42214. */
  42215. this._rect;
  42216. /**
  42217. * @type {module:echarts/coord/parallel/ParallelModel}
  42218. */
  42219. this._model = parallelModel;
  42220. this._init(parallelModel, ecModel, api);
  42221. }
  42222. Parallel.prototype = {
  42223. type: 'parallel',
  42224. constructor: Parallel,
  42225. /**
  42226. * Initialize cartesian coordinate systems
  42227. * @private
  42228. */
  42229. _init: function (parallelModel, ecModel, api) {
  42230. var dimensions = parallelModel.dimensions;
  42231. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  42232. each$12(dimensions, function (dim, idx) {
  42233. var axisIndex = parallelAxisIndex[idx];
  42234. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  42235. var axis = this._axesMap.set(dim, new ParallelAxis(
  42236. dim,
  42237. createScaleByModel(axisModel),
  42238. [0, 0],
  42239. axisModel.get('type'),
  42240. axisIndex
  42241. ));
  42242. var isCategory = axis.type === 'category';
  42243. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42244. axis.inverse = axisModel.get('inverse');
  42245. // Injection
  42246. axisModel.axis = axis;
  42247. axis.model = axisModel;
  42248. axis.coordinateSystem = axisModel.coordinateSystem = this;
  42249. }, this);
  42250. },
  42251. /**
  42252. * Update axis scale after data processed
  42253. * @param {module:echarts/model/Global} ecModel
  42254. * @param {module:echarts/ExtensionAPI} api
  42255. */
  42256. update: function (ecModel, api) {
  42257. this._updateAxesFromSeries(this._model, ecModel);
  42258. },
  42259. /**
  42260. * @override
  42261. */
  42262. containPoint: function (point) {
  42263. var layoutInfo = this._makeLayoutInfo();
  42264. var axisBase = layoutInfo.axisBase;
  42265. var layoutBase = layoutInfo.layoutBase;
  42266. var pixelDimIndex = layoutInfo.pixelDimIndex;
  42267. var pAxis = point[1 - pixelDimIndex];
  42268. var pLayout = point[pixelDimIndex];
  42269. return pAxis >= axisBase
  42270. && pAxis <= axisBase + layoutInfo.axisLength
  42271. && pLayout >= layoutBase
  42272. && pLayout <= layoutBase + layoutInfo.layoutLength;
  42273. },
  42274. getModel: function () {
  42275. return this._model;
  42276. },
  42277. /**
  42278. * Update properties from series
  42279. * @private
  42280. */
  42281. _updateAxesFromSeries: function (parallelModel, ecModel) {
  42282. ecModel.eachSeries(function (seriesModel) {
  42283. if (!parallelModel.contains(seriesModel, ecModel)) {
  42284. return;
  42285. }
  42286. var data = seriesModel.getData();
  42287. each$12(this.dimensions, function (dim) {
  42288. var axis = this._axesMap.get(dim);
  42289. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  42290. niceScaleExtent(axis.scale, axis.model);
  42291. }, this);
  42292. }, this);
  42293. },
  42294. /**
  42295. * Resize the parallel coordinate system.
  42296. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  42297. * @param {module:echarts/ExtensionAPI} api
  42298. */
  42299. resize: function (parallelModel, api) {
  42300. this._rect = getLayoutRect(
  42301. parallelModel.getBoxLayoutParams(),
  42302. {
  42303. width: api.getWidth(),
  42304. height: api.getHeight()
  42305. }
  42306. );
  42307. this._layoutAxes();
  42308. },
  42309. /**
  42310. * @return {module:zrender/core/BoundingRect}
  42311. */
  42312. getRect: function () {
  42313. return this._rect;
  42314. },
  42315. /**
  42316. * @private
  42317. */
  42318. _makeLayoutInfo: function () {
  42319. var parallelModel = this._model;
  42320. var rect = this._rect;
  42321. var xy = ['x', 'y'];
  42322. var wh = ['width', 'height'];
  42323. var layout = parallelModel.get('layout');
  42324. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  42325. var layoutLength = rect[wh[pixelDimIndex]];
  42326. var layoutExtent = [0, layoutLength];
  42327. var axisCount = this.dimensions.length;
  42328. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  42329. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  42330. var axisExpandable = parallelModel.get('axisExpandable')
  42331. && axisCount > 3
  42332. && axisCount > axisExpandCount
  42333. && axisExpandCount > 1
  42334. && axisExpandWidth > 0
  42335. && layoutLength > 0;
  42336. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  42337. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  42338. // where collapsed axes should be overlapped.
  42339. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  42340. var winSize;
  42341. if (!axisExpandWindow) {
  42342. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  42343. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  42344. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  42345. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  42346. }
  42347. else {
  42348. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  42349. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  42350. }
  42351. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  42352. // Avoid axisCollapseWidth is too small.
  42353. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  42354. // Find the first and last indices > ewin[0] and < ewin[1].
  42355. var winInnerIndices = [
  42356. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  42357. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  42358. ];
  42359. // Pos in ec coordinates.
  42360. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  42361. return {
  42362. layout: layout,
  42363. pixelDimIndex: pixelDimIndex,
  42364. layoutBase: rect[xy[pixelDimIndex]],
  42365. layoutLength: layoutLength,
  42366. axisBase: rect[xy[1 - pixelDimIndex]],
  42367. axisLength: rect[wh[1 - pixelDimIndex]],
  42368. axisExpandable: axisExpandable,
  42369. axisExpandWidth: axisExpandWidth,
  42370. axisCollapseWidth: axisCollapseWidth,
  42371. axisExpandWindow: axisExpandWindow,
  42372. axisCount: axisCount,
  42373. winInnerIndices: winInnerIndices,
  42374. axisExpandWindow0Pos: axisExpandWindow0Pos
  42375. };
  42376. },
  42377. /**
  42378. * @private
  42379. */
  42380. _layoutAxes: function () {
  42381. var rect = this._rect;
  42382. var axes = this._axesMap;
  42383. var dimensions = this.dimensions;
  42384. var layoutInfo = this._makeLayoutInfo();
  42385. var layout = layoutInfo.layout;
  42386. axes.each(function (axis) {
  42387. var axisExtent = [0, layoutInfo.axisLength];
  42388. var idx = axis.inverse ? 1 : 0;
  42389. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  42390. });
  42391. each$12(dimensions, function (dim, idx) {
  42392. var posInfo = (layoutInfo.axisExpandable
  42393. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  42394. )(idx, layoutInfo);
  42395. var positionTable = {
  42396. horizontal: {
  42397. x: posInfo.position,
  42398. y: layoutInfo.axisLength
  42399. },
  42400. vertical: {
  42401. x: 0,
  42402. y: posInfo.position
  42403. }
  42404. };
  42405. var rotationTable = {
  42406. horizontal: PI$3 / 2,
  42407. vertical: 0
  42408. };
  42409. var position = [
  42410. positionTable[layout].x + rect.x,
  42411. positionTable[layout].y + rect.y
  42412. ];
  42413. var rotation = rotationTable[layout];
  42414. var transform = create$1();
  42415. rotate(transform, transform, rotation);
  42416. translate(transform, transform, position);
  42417. // TODO
  42418. // tick等排布信息。
  42419. // TODO
  42420. // 根据axis order 更新 dimensions顺序。
  42421. this._axesLayout[dim] = {
  42422. position: position,
  42423. rotation: rotation,
  42424. transform: transform,
  42425. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  42426. axisLabelShow: posInfo.axisLabelShow,
  42427. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  42428. tickDirection: 1,
  42429. labelDirection: 1,
  42430. labelInterval: axes.get(dim).getLabelInterval()
  42431. };
  42432. }, this);
  42433. },
  42434. /**
  42435. * Get axis by dim.
  42436. * @param {string} dim
  42437. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  42438. */
  42439. getAxis: function (dim) {
  42440. return this._axesMap.get(dim);
  42441. },
  42442. /**
  42443. * Convert a dim value of a single item of series data to Point.
  42444. * @param {*} value
  42445. * @param {string} dim
  42446. * @return {Array}
  42447. */
  42448. dataToPoint: function (value, dim) {
  42449. return this.axisCoordToPoint(
  42450. this._axesMap.get(dim).dataToCoord(value),
  42451. dim
  42452. );
  42453. },
  42454. /**
  42455. * Travel data for one time, get activeState of each data item.
  42456. * @param {module:echarts/data/List} data
  42457. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  42458. * {number} dataIndex
  42459. * @param {Object} context
  42460. */
  42461. eachActiveState: function (data, callback, context) {
  42462. var dimensions = this.dimensions;
  42463. var dataDimensions = map(dimensions, function (axisDim) {
  42464. return data.mapDimension(axisDim);
  42465. });
  42466. var axesMap = this._axesMap;
  42467. var hasActiveSet = this.hasAxisBrushed();
  42468. for (var i = 0, len = data.count(); i < len; i++) {
  42469. var values = data.getValues(dataDimensions, i);
  42470. var activeState;
  42471. if (!hasActiveSet) {
  42472. activeState = 'normal';
  42473. }
  42474. else {
  42475. activeState = 'active';
  42476. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  42477. var dimName = dimensions[j];
  42478. var state = axesMap.get(dimName).model.getActiveState(values[j], j);
  42479. if (state === 'inactive') {
  42480. activeState = 'inactive';
  42481. break;
  42482. }
  42483. }
  42484. }
  42485. callback.call(context, activeState, i);
  42486. }
  42487. },
  42488. /**
  42489. * Whether has any activeSet.
  42490. * @return {boolean}
  42491. */
  42492. hasAxisBrushed: function () {
  42493. var dimensions = this.dimensions;
  42494. var axesMap = this._axesMap;
  42495. var hasActiveSet = false;
  42496. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  42497. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  42498. hasActiveSet = true;
  42499. }
  42500. }
  42501. return hasActiveSet;
  42502. },
  42503. /**
  42504. * Convert coords of each axis to Point.
  42505. * Return point. For example: [10, 20]
  42506. * @param {Array.<number>} coords
  42507. * @param {string} dim
  42508. * @return {Array.<number>}
  42509. */
  42510. axisCoordToPoint: function (coord, dim) {
  42511. var axisLayout = this._axesLayout[dim];
  42512. return applyTransform$1([coord, 0], axisLayout.transform);
  42513. },
  42514. /**
  42515. * Get axis layout.
  42516. */
  42517. getAxisLayout: function (dim) {
  42518. return clone(this._axesLayout[dim]);
  42519. },
  42520. /**
  42521. * @param {Array.<number>} point
  42522. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  42523. */
  42524. getSlidedAxisExpandWindow: function (point) {
  42525. var layoutInfo = this._makeLayoutInfo();
  42526. var pixelDimIndex = layoutInfo.pixelDimIndex;
  42527. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  42528. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  42529. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  42530. // Out of the area of coordinate system.
  42531. if (!this.containPoint(point)) {
  42532. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  42533. }
  42534. // Conver the point from global to expand coordinates.
  42535. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  42536. // For dragging operation convenience, the window should not be
  42537. // slided when mouse is the center area of the window.
  42538. var delta;
  42539. var behavior = 'slide';
  42540. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  42541. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  42542. // But consider touch device, jump is necessary.
  42543. var useJump = triggerArea[0] != null;
  42544. if (axisCollapseWidth) {
  42545. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  42546. behavior = 'jump';
  42547. delta = pointCoord - winSize * triggerArea[2];
  42548. }
  42549. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  42550. behavior = 'jump';
  42551. delta = pointCoord - winSize * (1 - triggerArea[2]);
  42552. }
  42553. else {
  42554. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  42555. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  42556. && (delta = 0);
  42557. }
  42558. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  42559. delta
  42560. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  42561. // Avoid nonsense triger on mousemove.
  42562. : (behavior = 'none');
  42563. }
  42564. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  42565. else {
  42566. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  42567. var pos = extent[1] * pointCoord / winSize;
  42568. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  42569. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  42570. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  42571. }
  42572. return {
  42573. axisExpandWindow: axisExpandWindow,
  42574. behavior: behavior
  42575. };
  42576. }
  42577. };
  42578. function restrict(len, extent) {
  42579. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  42580. }
  42581. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  42582. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  42583. return {
  42584. position: step * axisIndex,
  42585. axisNameAvailableWidth: step,
  42586. axisLabelShow: true
  42587. };
  42588. }
  42589. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  42590. var layoutLength = layoutInfo.layoutLength;
  42591. var axisExpandWidth = layoutInfo.axisExpandWidth;
  42592. var axisCount = layoutInfo.axisCount;
  42593. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  42594. var winInnerIndices = layoutInfo.winInnerIndices;
  42595. var position;
  42596. var axisNameAvailableWidth = axisCollapseWidth;
  42597. var axisLabelShow = false;
  42598. var nameTruncateMaxWidth;
  42599. if (axisIndex < winInnerIndices[0]) {
  42600. position = axisIndex * axisCollapseWidth;
  42601. nameTruncateMaxWidth = axisCollapseWidth;
  42602. }
  42603. else if (axisIndex <= winInnerIndices[1]) {
  42604. position = layoutInfo.axisExpandWindow0Pos
  42605. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  42606. axisNameAvailableWidth = axisExpandWidth;
  42607. axisLabelShow = true;
  42608. }
  42609. else {
  42610. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  42611. nameTruncateMaxWidth = axisCollapseWidth;
  42612. }
  42613. return {
  42614. position: position,
  42615. axisNameAvailableWidth: axisNameAvailableWidth,
  42616. axisLabelShow: axisLabelShow,
  42617. nameTruncateMaxWidth: nameTruncateMaxWidth
  42618. };
  42619. }
  42620. /**
  42621. * Parallel coordinate system creater.
  42622. */
  42623. function create$2(ecModel, api) {
  42624. var coordSysList = [];
  42625. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  42626. var coordSys = new Parallel(parallelModel, ecModel, api);
  42627. coordSys.name = 'parallel_' + idx;
  42628. coordSys.resize(parallelModel, api);
  42629. parallelModel.coordinateSystem = coordSys;
  42630. coordSys.model = parallelModel;
  42631. coordSysList.push(coordSys);
  42632. });
  42633. // Inject the coordinateSystems into seriesModel
  42634. ecModel.eachSeries(function (seriesModel) {
  42635. if (seriesModel.get('coordinateSystem') === 'parallel') {
  42636. var parallelModel = ecModel.queryComponents({
  42637. mainType: 'parallel',
  42638. index: seriesModel.get('parallelIndex'),
  42639. id: seriesModel.get('parallelId')
  42640. })[0];
  42641. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  42642. }
  42643. });
  42644. return coordSysList;
  42645. }
  42646. CoordinateSystemManager.register('parallel', {create: create$2});
  42647. var AxisModel$2 = ComponentModel.extend({
  42648. type: 'baseParallelAxis',
  42649. /**
  42650. * @type {module:echarts/coord/parallel/Axis}
  42651. */
  42652. axis: null,
  42653. /**
  42654. * @type {Array.<Array.<number>}
  42655. * @readOnly
  42656. */
  42657. activeIntervals: [],
  42658. /**
  42659. * @return {Object}
  42660. */
  42661. getAreaSelectStyle: function () {
  42662. return makeStyleMapper(
  42663. [
  42664. ['fill', 'color'],
  42665. ['lineWidth', 'borderWidth'],
  42666. ['stroke', 'borderColor'],
  42667. ['width', 'width'],
  42668. ['opacity', 'opacity']
  42669. ]
  42670. )(this.getModel('areaSelectStyle'));
  42671. },
  42672. /**
  42673. * The code of this feature is put on AxisModel but not ParallelAxis,
  42674. * because axisModel can be alive after echarts updating but instance of
  42675. * ParallelAxis having been disposed. this._activeInterval should be kept
  42676. * when action dispatched (i.e. legend click).
  42677. *
  42678. * @param {Array.<Array<number>>} intervals interval.length === 0
  42679. * means set all active.
  42680. * @public
  42681. */
  42682. setActiveIntervals: function (intervals) {
  42683. var activeIntervals = this.activeIntervals = clone(intervals);
  42684. // Normalize
  42685. if (activeIntervals) {
  42686. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  42687. asc(activeIntervals[i]);
  42688. }
  42689. }
  42690. },
  42691. /**
  42692. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  42693. * value can not be input.
  42694. * @return {string} 'normal': no activeIntervals set,
  42695. * 'active',
  42696. * 'inactive'.
  42697. * @public
  42698. */
  42699. getActiveState: function (value) {
  42700. var activeIntervals = this.activeIntervals;
  42701. if (!activeIntervals.length) {
  42702. return 'normal';
  42703. }
  42704. if (value == null) {
  42705. return 'inactive';
  42706. }
  42707. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  42708. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  42709. return 'active';
  42710. }
  42711. }
  42712. return 'inactive';
  42713. }
  42714. });
  42715. var defaultOption$1 = {
  42716. type: 'value',
  42717. /**
  42718. * @type {Array.<number>}
  42719. */
  42720. dim: null, // 0, 1, 2, ...
  42721. // parallelIndex: null,
  42722. areaSelectStyle: {
  42723. width: 20,
  42724. borderWidth: 1,
  42725. borderColor: 'rgba(160,197,232)',
  42726. color: 'rgba(160,197,232)',
  42727. opacity: 0.3
  42728. },
  42729. realtime: true, // Whether realtime update view when select.
  42730. z: 10
  42731. };
  42732. merge(AxisModel$2.prototype, axisModelCommonMixin);
  42733. function getAxisType$1(axisName, option) {
  42734. return option.type || (option.data ? 'category' : 'value');
  42735. }
  42736. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  42737. ComponentModel.extend({
  42738. type: 'parallel',
  42739. dependencies: ['parallelAxis'],
  42740. /**
  42741. * @type {module:echarts/coord/parallel/Parallel}
  42742. */
  42743. coordinateSystem: null,
  42744. /**
  42745. * Each item like: 'dim0', 'dim1', 'dim2', ...
  42746. * @type {Array.<string>}
  42747. * @readOnly
  42748. */
  42749. dimensions: null,
  42750. /**
  42751. * Coresponding to dimensions.
  42752. * @type {Array.<number>}
  42753. * @readOnly
  42754. */
  42755. parallelAxisIndex: null,
  42756. layoutMode: 'box',
  42757. defaultOption: {
  42758. zlevel: 0,
  42759. z: 0,
  42760. left: 80,
  42761. top: 60,
  42762. right: 80,
  42763. bottom: 60,
  42764. // width: {totalWidth} - left - right,
  42765. // height: {totalHeight} - top - bottom,
  42766. layout: 'horizontal', // 'horizontal' or 'vertical'
  42767. // FIXME
  42768. // naming?
  42769. axisExpandable: false,
  42770. axisExpandCenter: null,
  42771. axisExpandCount: 0,
  42772. axisExpandWidth: 50, // FIXME '10%' ?
  42773. axisExpandRate: 17,
  42774. axisExpandDebounce: 50,
  42775. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  42776. // Do not doc to user until necessary.
  42777. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  42778. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  42779. parallelAxisDefault: null
  42780. },
  42781. /**
  42782. * @override
  42783. */
  42784. init: function () {
  42785. ComponentModel.prototype.init.apply(this, arguments);
  42786. this.mergeOption({});
  42787. },
  42788. /**
  42789. * @override
  42790. */
  42791. mergeOption: function (newOption) {
  42792. var thisOption = this.option;
  42793. newOption && merge(thisOption, newOption, true);
  42794. this._initDimensions();
  42795. },
  42796. /**
  42797. * Whether series or axis is in this coordinate system.
  42798. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  42799. * @param {module:echarts/model/Global} ecModel
  42800. */
  42801. contains: function (model, ecModel) {
  42802. var parallelIndex = model.get('parallelIndex');
  42803. return parallelIndex != null
  42804. && ecModel.getComponent('parallel', parallelIndex) === this;
  42805. },
  42806. setAxisExpand: function (opt) {
  42807. each$1(
  42808. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  42809. function (name) {
  42810. if (opt.hasOwnProperty(name)) {
  42811. this.option[name] = opt[name];
  42812. }
  42813. },
  42814. this
  42815. );
  42816. },
  42817. /**
  42818. * @private
  42819. */
  42820. _initDimensions: function () {
  42821. var dimensions = this.dimensions = [];
  42822. var parallelAxisIndex = this.parallelAxisIndex = [];
  42823. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  42824. // Can not use this.contains here, because
  42825. // initialization has not been completed yet.
  42826. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  42827. }, this);
  42828. each$1(axisModels, function (axisModel) {
  42829. dimensions.push('dim' + axisModel.get('dim'));
  42830. parallelAxisIndex.push(axisModel.componentIndex);
  42831. });
  42832. }
  42833. });
  42834. /**
  42835. * @payload
  42836. * @property {string} parallelAxisId
  42837. * @property {Array.<Array.<number>>} intervals
  42838. */
  42839. var actionInfo$1 = {
  42840. type: 'axisAreaSelect',
  42841. event: 'axisAreaSelected'
  42842. // update: 'updateVisual'
  42843. };
  42844. registerAction(actionInfo$1, function (payload, ecModel) {
  42845. ecModel.eachComponent(
  42846. {mainType: 'parallelAxis', query: payload},
  42847. function (parallelAxisModel) {
  42848. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  42849. }
  42850. );
  42851. });
  42852. /**
  42853. * @payload
  42854. */
  42855. registerAction('parallelAxisExpand', function (payload, ecModel) {
  42856. ecModel.eachComponent(
  42857. {mainType: 'parallel', query: payload},
  42858. function (parallelModel) {
  42859. parallelModel.setAxisExpand(payload);
  42860. }
  42861. );
  42862. });
  42863. var curry$2 = curry;
  42864. var each$13 = each$1;
  42865. var map$2 = map;
  42866. var mathMin$6 = Math.min;
  42867. var mathMax$6 = Math.max;
  42868. var mathPow$2 = Math.pow;
  42869. var COVER_Z = 10000;
  42870. var UNSELECT_THRESHOLD = 6;
  42871. var MIN_RESIZE_LINE_WIDTH = 6;
  42872. var MUTEX_RESOURCE_KEY = 'globalPan';
  42873. var DIRECTION_MAP = {
  42874. w: [0, 0],
  42875. e: [0, 1],
  42876. n: [1, 0],
  42877. s: [1, 1]
  42878. };
  42879. var CURSOR_MAP = {
  42880. w: 'ew',
  42881. e: 'ew',
  42882. n: 'ns',
  42883. s: 'ns',
  42884. ne: 'nesw',
  42885. sw: 'nesw',
  42886. nw: 'nwse',
  42887. se: 'nwse'
  42888. };
  42889. var DEFAULT_BRUSH_OPT = {
  42890. brushStyle: {
  42891. lineWidth: 2,
  42892. stroke: 'rgba(0,0,0,0.3)',
  42893. fill: 'rgba(0,0,0,0.1)'
  42894. },
  42895. transformable: true,
  42896. brushMode: 'single',
  42897. removeOnClick: false
  42898. };
  42899. var baseUID = 0;
  42900. /**
  42901. * @alias module:echarts/component/helper/BrushController
  42902. * @constructor
  42903. * @mixin {module:zrender/mixin/Eventful}
  42904. * @event module:echarts/component/helper/BrushController#brush
  42905. * params:
  42906. * areas: Array.<Array>, coord relates to container group,
  42907. * If no container specified, to global.
  42908. * opt {
  42909. * isEnd: boolean,
  42910. * removeOnClick: boolean
  42911. * }
  42912. *
  42913. * @param {module:zrender/zrender~ZRender} zr
  42914. */
  42915. function BrushController(zr) {
  42916. if (__DEV__) {
  42917. assert$1(zr);
  42918. }
  42919. Eventful.call(this);
  42920. /**
  42921. * @type {module:zrender/zrender~ZRender}
  42922. * @private
  42923. */
  42924. this._zr = zr;
  42925. /**
  42926. * @type {module:zrender/container/Group}
  42927. * @readOnly
  42928. */
  42929. this.group = new Group();
  42930. /**
  42931. * Only for drawing (after enabledBrush).
  42932. * 'line', 'rect', 'polygon' or false
  42933. * If passing false/null/undefined, disable brush.
  42934. * If passing 'auto', determined by panel.defaultBrushType
  42935. * @private
  42936. * @type {string}
  42937. */
  42938. this._brushType;
  42939. /**
  42940. * Only for drawing (after enabledBrush).
  42941. *
  42942. * @private
  42943. * @type {Object}
  42944. */
  42945. this._brushOption;
  42946. /**
  42947. * @private
  42948. * @type {Object}
  42949. */
  42950. this._panels;
  42951. /**
  42952. * @private
  42953. * @type {Array.<nubmer>}
  42954. */
  42955. this._track = [];
  42956. /**
  42957. * @private
  42958. * @type {boolean}
  42959. */
  42960. this._dragging;
  42961. /**
  42962. * @private
  42963. * @type {Array}
  42964. */
  42965. this._covers = [];
  42966. /**
  42967. * @private
  42968. * @type {moudule:zrender/container/Group}
  42969. */
  42970. this._creatingCover;
  42971. /**
  42972. * `true` means global panel
  42973. * @private
  42974. * @type {module:zrender/container/Group|boolean}
  42975. */
  42976. this._creatingPanel;
  42977. /**
  42978. * @private
  42979. * @type {boolean}
  42980. */
  42981. this._enableGlobalPan;
  42982. /**
  42983. * @private
  42984. * @type {boolean}
  42985. */
  42986. if (__DEV__) {
  42987. this._mounted;
  42988. }
  42989. /**
  42990. * @private
  42991. * @type {string}
  42992. */
  42993. this._uid = 'brushController_' + baseUID++;
  42994. /**
  42995. * @private
  42996. * @type {Object}
  42997. */
  42998. this._handlers = {};
  42999. each$13(mouseHandlers, function (handler, eventName) {
  43000. this._handlers[eventName] = bind(handler, this);
  43001. }, this);
  43002. }
  43003. BrushController.prototype = {
  43004. constructor: BrushController,
  43005. /**
  43006. * If set to null/undefined/false, select disabled.
  43007. * @param {Object} brushOption
  43008. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  43009. * If passing false/null/undefined, disable brush.
  43010. * If passing 'auto', determined by panel.defaultBrushType.
  43011. * ('auto' can not be used in global panel)
  43012. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  43013. * @param {boolean} [brushOption.transformable=true]
  43014. * @param {boolean} [brushOption.removeOnClick=false]
  43015. * @param {Object} [brushOption.brushStyle]
  43016. * @param {number} [brushOption.brushStyle.width]
  43017. * @param {number} [brushOption.brushStyle.lineWidth]
  43018. * @param {string} [brushOption.brushStyle.stroke]
  43019. * @param {string} [brushOption.brushStyle.fill]
  43020. * @param {number} [brushOption.z]
  43021. */
  43022. enableBrush: function (brushOption) {
  43023. if (__DEV__) {
  43024. assert$1(this._mounted);
  43025. }
  43026. this._brushType && doDisableBrush(this);
  43027. brushOption.brushType && doEnableBrush(this, brushOption);
  43028. return this;
  43029. },
  43030. /**
  43031. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  43032. * Each items: {
  43033. * panelId, // mandatory.
  43034. * clipPath, // mandatory. function.
  43035. * isTargetByCursor, // mandatory. function.
  43036. * defaultBrushType, // optional, only used when brushType is 'auto'.
  43037. * getLinearBrushOtherExtent, // optional. function.
  43038. * }
  43039. */
  43040. setPanels: function (panelOpts) {
  43041. if (panelOpts && panelOpts.length) {
  43042. var panels = this._panels = {};
  43043. each$1(panelOpts, function (panelOpts) {
  43044. panels[panelOpts.panelId] = clone(panelOpts);
  43045. });
  43046. }
  43047. else {
  43048. this._panels = null;
  43049. }
  43050. return this;
  43051. },
  43052. /**
  43053. * @param {Object} [opt]
  43054. * @return {boolean} [opt.enableGlobalPan=false]
  43055. */
  43056. mount: function (opt) {
  43057. opt = opt || {};
  43058. if (__DEV__) {
  43059. this._mounted = true; // should be at first.
  43060. }
  43061. this._enableGlobalPan = opt.enableGlobalPan;
  43062. var thisGroup = this.group;
  43063. this._zr.add(thisGroup);
  43064. thisGroup.attr({
  43065. position: opt.position || [0, 0],
  43066. rotation: opt.rotation || 0,
  43067. scale: opt.scale || [1, 1]
  43068. });
  43069. this._transform = thisGroup.getLocalTransform();
  43070. return this;
  43071. },
  43072. eachCover: function (cb, context) {
  43073. each$13(this._covers, cb, context);
  43074. },
  43075. /**
  43076. * Update covers.
  43077. * @param {Array.<Object>} brushOptionList Like:
  43078. * [
  43079. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  43080. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  43081. * ...
  43082. * ]
  43083. * `brushType` is required in each cover info. (can not be 'auto')
  43084. * `id` is not mandatory.
  43085. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  43086. * If brushOptionList is null/undefined, all covers removed.
  43087. */
  43088. updateCovers: function (brushOptionList) {
  43089. if (__DEV__) {
  43090. assert$1(this._mounted);
  43091. }
  43092. brushOptionList = map(brushOptionList, function (brushOption) {
  43093. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43094. });
  43095. var tmpIdPrefix = '\0-brush-index-';
  43096. var oldCovers = this._covers;
  43097. var newCovers = this._covers = [];
  43098. var controller = this;
  43099. var creatingCover = this._creatingCover;
  43100. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  43101. .add(addOrUpdate)
  43102. .update(addOrUpdate)
  43103. .remove(remove)
  43104. .execute();
  43105. return this;
  43106. function getKey(brushOption, index) {
  43107. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  43108. + '-' + brushOption.brushType;
  43109. }
  43110. function oldGetKey(cover, index) {
  43111. return getKey(cover.__brushOption, index);
  43112. }
  43113. function addOrUpdate(newIndex, oldIndex) {
  43114. var newBrushOption = brushOptionList[newIndex];
  43115. // Consider setOption in event listener of brushSelect,
  43116. // where updating cover when creating should be forbiden.
  43117. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  43118. newCovers[newIndex] = oldCovers[oldIndex];
  43119. }
  43120. else {
  43121. var cover = newCovers[newIndex] = oldIndex != null
  43122. ? (
  43123. oldCovers[oldIndex].__brushOption = newBrushOption,
  43124. oldCovers[oldIndex]
  43125. )
  43126. : endCreating(controller, createCover(controller, newBrushOption));
  43127. updateCoverAfterCreation(controller, cover);
  43128. }
  43129. }
  43130. function remove(oldIndex) {
  43131. if (oldCovers[oldIndex] !== creatingCover) {
  43132. controller.group.remove(oldCovers[oldIndex]);
  43133. }
  43134. }
  43135. },
  43136. unmount: function () {
  43137. if (__DEV__) {
  43138. if (!this._mounted) {
  43139. return;
  43140. }
  43141. }
  43142. this.enableBrush(false);
  43143. // container may 'removeAll' outside.
  43144. clearCovers(this);
  43145. this._zr.remove(this.group);
  43146. if (__DEV__) {
  43147. this._mounted = false; // should be at last.
  43148. }
  43149. return this;
  43150. },
  43151. dispose: function () {
  43152. this.unmount();
  43153. this.off();
  43154. }
  43155. };
  43156. mixin(BrushController, Eventful);
  43157. function doEnableBrush(controller, brushOption) {
  43158. var zr = controller._zr;
  43159. // Consider roam, which takes globalPan too.
  43160. if (!controller._enableGlobalPan) {
  43161. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43162. }
  43163. each$13(controller._handlers, function (handler, eventName) {
  43164. zr.on(eventName, handler);
  43165. });
  43166. controller._brushType = brushOption.brushType;
  43167. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43168. }
  43169. function doDisableBrush(controller) {
  43170. var zr = controller._zr;
  43171. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43172. each$13(controller._handlers, function (handler, eventName) {
  43173. zr.off(eventName, handler);
  43174. });
  43175. controller._brushType = controller._brushOption = null;
  43176. }
  43177. function createCover(controller, brushOption) {
  43178. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  43179. cover.__brushOption = brushOption;
  43180. updateZ$1(cover, brushOption);
  43181. controller.group.add(cover);
  43182. return cover;
  43183. }
  43184. function endCreating(controller, creatingCover) {
  43185. var coverRenderer = getCoverRenderer(creatingCover);
  43186. if (coverRenderer.endCreating) {
  43187. coverRenderer.endCreating(controller, creatingCover);
  43188. updateZ$1(creatingCover, creatingCover.__brushOption);
  43189. }
  43190. return creatingCover;
  43191. }
  43192. function updateCoverShape(controller, cover) {
  43193. var brushOption = cover.__brushOption;
  43194. getCoverRenderer(cover).updateCoverShape(
  43195. controller, cover, brushOption.range, brushOption
  43196. );
  43197. }
  43198. function updateZ$1(cover, brushOption) {
  43199. var z = brushOption.z;
  43200. z == null && (z = COVER_Z);
  43201. cover.traverse(function (el) {
  43202. el.z = z;
  43203. el.z2 = z; // Consider in given container.
  43204. });
  43205. }
  43206. function updateCoverAfterCreation(controller, cover) {
  43207. getCoverRenderer(cover).updateCommon(controller, cover);
  43208. updateCoverShape(controller, cover);
  43209. }
  43210. function getCoverRenderer(cover) {
  43211. return coverRenderers[cover.__brushOption.brushType];
  43212. }
  43213. // return target panel or `true` (means global panel)
  43214. function getPanelByPoint(controller, e, localCursorPoint) {
  43215. var panels = controller._panels;
  43216. if (!panels) {
  43217. return true; // Global panel
  43218. }
  43219. var panel;
  43220. var transform = controller._transform;
  43221. each$13(panels, function (pn) {
  43222. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  43223. });
  43224. return panel;
  43225. }
  43226. // Return a panel or true
  43227. function getPanelByCover(controller, cover) {
  43228. var panels = controller._panels;
  43229. if (!panels) {
  43230. return true; // Global panel
  43231. }
  43232. var panelId = cover.__brushOption.panelId;
  43233. // User may give cover without coord sys info,
  43234. // which is then treated as global panel.
  43235. return panelId != null ? panels[panelId] : true;
  43236. }
  43237. function clearCovers(controller) {
  43238. var covers = controller._covers;
  43239. var originalLength = covers.length;
  43240. each$13(covers, function (cover) {
  43241. controller.group.remove(cover);
  43242. }, controller);
  43243. covers.length = 0;
  43244. return !!originalLength;
  43245. }
  43246. function trigger(controller, opt) {
  43247. var areas = map$2(controller._covers, function (cover) {
  43248. var brushOption = cover.__brushOption;
  43249. var range = clone(brushOption.range);
  43250. return {
  43251. brushType: brushOption.brushType,
  43252. panelId: brushOption.panelId,
  43253. range: range
  43254. };
  43255. });
  43256. controller.trigger('brush', areas, {
  43257. isEnd: !!opt.isEnd,
  43258. removeOnClick: !!opt.removeOnClick
  43259. });
  43260. }
  43261. function shouldShowCover(controller) {
  43262. var track = controller._track;
  43263. if (!track.length) {
  43264. return false;
  43265. }
  43266. var p2 = track[track.length - 1];
  43267. var p1 = track[0];
  43268. var dx = p2[0] - p1[0];
  43269. var dy = p2[1] - p1[1];
  43270. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  43271. return dist > UNSELECT_THRESHOLD;
  43272. }
  43273. function getTrackEnds(track) {
  43274. var tail = track.length - 1;
  43275. tail < 0 && (tail = 0);
  43276. return [track[0], track[tail]];
  43277. }
  43278. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  43279. var cover = new Group();
  43280. cover.add(new Rect({
  43281. name: 'main',
  43282. style: makeStyle(brushOption),
  43283. silent: true,
  43284. draggable: true,
  43285. cursor: 'move',
  43286. drift: curry$2(doDrift, controller, cover, 'nswe'),
  43287. ondragend: curry$2(trigger, controller, {isEnd: true})
  43288. }));
  43289. each$13(
  43290. edgeNames,
  43291. function (name) {
  43292. cover.add(new Rect({
  43293. name: name,
  43294. style: {opacity: 0},
  43295. draggable: true,
  43296. silent: true,
  43297. invisible: true,
  43298. drift: curry$2(doDrift, controller, cover, name),
  43299. ondragend: curry$2(trigger, controller, {isEnd: true})
  43300. }));
  43301. }
  43302. );
  43303. return cover;
  43304. }
  43305. function updateBaseRect(controller, cover, localRange, brushOption) {
  43306. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  43307. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  43308. var x = localRange[0][0];
  43309. var y = localRange[1][0];
  43310. var xa = x - lineWidth / 2;
  43311. var ya = y - lineWidth / 2;
  43312. var x2 = localRange[0][1];
  43313. var y2 = localRange[1][1];
  43314. var x2a = x2 - handleSize + lineWidth / 2;
  43315. var y2a = y2 - handleSize + lineWidth / 2;
  43316. var width = x2 - x;
  43317. var height = y2 - y;
  43318. var widtha = width + lineWidth;
  43319. var heighta = height + lineWidth;
  43320. updateRectShape(controller, cover, 'main', x, y, width, height);
  43321. if (brushOption.transformable) {
  43322. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  43323. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  43324. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  43325. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  43326. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  43327. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  43328. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  43329. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  43330. }
  43331. }
  43332. function updateCommon(controller, cover) {
  43333. var brushOption = cover.__brushOption;
  43334. var transformable = brushOption.transformable;
  43335. var mainEl = cover.childAt(0);
  43336. mainEl.useStyle(makeStyle(brushOption));
  43337. mainEl.attr({
  43338. silent: !transformable,
  43339. cursor: transformable ? 'move' : 'default'
  43340. });
  43341. each$13(
  43342. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  43343. function (name) {
  43344. var el = cover.childOfName(name);
  43345. var globalDir = getGlobalDirection(controller, name);
  43346. el && el.attr({
  43347. silent: !transformable,
  43348. invisible: !transformable,
  43349. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  43350. });
  43351. }
  43352. );
  43353. }
  43354. function updateRectShape(controller, cover, name, x, y, w, h) {
  43355. var el = cover.childOfName(name);
  43356. el && el.setShape(pointsToRect(
  43357. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  43358. ));
  43359. }
  43360. function makeStyle(brushOption) {
  43361. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  43362. }
  43363. function formatRectRange(x, y, x2, y2) {
  43364. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  43365. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  43366. return [
  43367. [min[0], max[0]], // x range
  43368. [min[1], max[1]] // y range
  43369. ];
  43370. }
  43371. function getTransform$1(controller) {
  43372. return getTransform(controller.group);
  43373. }
  43374. function getGlobalDirection(controller, localDirection) {
  43375. if (localDirection.length > 1) {
  43376. localDirection = localDirection.split('');
  43377. var globalDir = [
  43378. getGlobalDirection(controller, localDirection[0]),
  43379. getGlobalDirection(controller, localDirection[1])
  43380. ];
  43381. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  43382. return globalDir.join('');
  43383. }
  43384. else {
  43385. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  43386. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  43387. var globalDir = transformDirection(
  43388. map$$1[localDirection], getTransform$1(controller)
  43389. );
  43390. return inverseMap[globalDir];
  43391. }
  43392. }
  43393. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  43394. var brushOption = cover.__brushOption;
  43395. var rectRange = toRectRange(brushOption.range);
  43396. var localDelta = toLocalDelta(controller, dx, dy);
  43397. each$13(name.split(''), function (namePart) {
  43398. var ind = DIRECTION_MAP[namePart];
  43399. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  43400. });
  43401. brushOption.range = fromRectRange(formatRectRange(
  43402. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  43403. ));
  43404. updateCoverAfterCreation(controller, cover);
  43405. trigger(controller, {isEnd: false});
  43406. }
  43407. function driftPolygon(controller, cover, dx, dy, e) {
  43408. var range = cover.__brushOption.range;
  43409. var localDelta = toLocalDelta(controller, dx, dy);
  43410. each$13(range, function (point) {
  43411. point[0] += localDelta[0];
  43412. point[1] += localDelta[1];
  43413. });
  43414. updateCoverAfterCreation(controller, cover);
  43415. trigger(controller, {isEnd: false});
  43416. }
  43417. function toLocalDelta(controller, dx, dy) {
  43418. var thisGroup = controller.group;
  43419. var localD = thisGroup.transformCoordToLocal(dx, dy);
  43420. var localZero = thisGroup.transformCoordToLocal(0, 0);
  43421. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  43422. }
  43423. function clipByPanel(controller, cover, data) {
  43424. var panel = getPanelByCover(controller, cover);
  43425. return (panel && panel !== true)
  43426. ? panel.clipPath(data, controller._transform)
  43427. : clone(data);
  43428. }
  43429. function pointsToRect(points) {
  43430. var xmin = mathMin$6(points[0][0], points[1][0]);
  43431. var ymin = mathMin$6(points[0][1], points[1][1]);
  43432. var xmax = mathMax$6(points[0][0], points[1][0]);
  43433. var ymax = mathMax$6(points[0][1], points[1][1]);
  43434. return {
  43435. x: xmin,
  43436. y: ymin,
  43437. width: xmax - xmin,
  43438. height: ymax - ymin
  43439. };
  43440. }
  43441. function resetCursor(controller, e, localCursorPoint) {
  43442. // Check active
  43443. if (!controller._brushType) {
  43444. return;
  43445. }
  43446. var zr = controller._zr;
  43447. var covers = controller._covers;
  43448. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  43449. // Check whether in covers.
  43450. if (!controller._dragging) {
  43451. for (var i = 0; i < covers.length; i++) {
  43452. var brushOption = covers[i].__brushOption;
  43453. if (currPanel
  43454. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  43455. && coverRenderers[brushOption.brushType].contain(
  43456. covers[i], localCursorPoint[0], localCursorPoint[1]
  43457. )
  43458. ) {
  43459. // Use cursor style set on cover.
  43460. return;
  43461. }
  43462. }
  43463. }
  43464. currPanel && zr.setCursorStyle('crosshair');
  43465. }
  43466. function preventDefault(e) {
  43467. var rawE = e.event;
  43468. rawE.preventDefault && rawE.preventDefault();
  43469. }
  43470. function mainShapeContain(cover, x, y) {
  43471. return cover.childOfName('main').contain(x, y);
  43472. }
  43473. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  43474. var creatingCover = controller._creatingCover;
  43475. var panel = controller._creatingPanel;
  43476. var thisBrushOption = controller._brushOption;
  43477. var eventParams;
  43478. controller._track.push(localCursorPoint.slice());
  43479. if (shouldShowCover(controller) || creatingCover) {
  43480. if (panel && !creatingCover) {
  43481. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  43482. var brushOption = clone(thisBrushOption);
  43483. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  43484. brushOption.panelId = panel === true ? null : panel.panelId;
  43485. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  43486. controller._covers.push(creatingCover);
  43487. }
  43488. if (creatingCover) {
  43489. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  43490. var coverBrushOption = creatingCover.__brushOption;
  43491. coverBrushOption.range = coverRenderer.getCreatingRange(
  43492. clipByPanel(controller, creatingCover, controller._track)
  43493. );
  43494. if (isEnd) {
  43495. endCreating(controller, creatingCover);
  43496. coverRenderer.updateCommon(controller, creatingCover);
  43497. }
  43498. updateCoverShape(controller, creatingCover);
  43499. eventParams = {isEnd: isEnd};
  43500. }
  43501. }
  43502. else if (
  43503. isEnd
  43504. && thisBrushOption.brushMode === 'single'
  43505. && thisBrushOption.removeOnClick
  43506. ) {
  43507. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  43508. // But a single click do not clear covers, because user may have casual
  43509. // clicks (for example, click on other component and do not expect covers
  43510. // disappear).
  43511. // Only some cover removed, trigger action, but not every click trigger action.
  43512. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  43513. eventParams = {isEnd: isEnd, removeOnClick: true};
  43514. }
  43515. }
  43516. return eventParams;
  43517. }
  43518. function determineBrushType(brushType, panel) {
  43519. if (brushType === 'auto') {
  43520. if (__DEV__) {
  43521. assert$1(
  43522. panel && panel.defaultBrushType,
  43523. 'MUST have defaultBrushType when brushType is "atuo"'
  43524. );
  43525. }
  43526. return panel.defaultBrushType;
  43527. }
  43528. return brushType;
  43529. }
  43530. var mouseHandlers = {
  43531. mousedown: function (e) {
  43532. if (this._dragging) {
  43533. // In case some browser do not support globalOut,
  43534. // and release mose out side the browser.
  43535. handleDragEnd.call(this, e);
  43536. }
  43537. else if (!e.target || !e.target.draggable) {
  43538. preventDefault(e);
  43539. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  43540. this._creatingCover = null;
  43541. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  43542. if (panel) {
  43543. this._dragging = true;
  43544. this._track = [localCursorPoint.slice()];
  43545. }
  43546. }
  43547. },
  43548. mousemove: function (e) {
  43549. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  43550. resetCursor(this, e, localCursorPoint);
  43551. if (this._dragging) {
  43552. preventDefault(e);
  43553. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  43554. eventParams && trigger(this, eventParams);
  43555. }
  43556. },
  43557. mouseup: handleDragEnd //,
  43558. // FIXME
  43559. // in tooltip, globalout should not be triggered.
  43560. // globalout: handleDragEnd
  43561. };
  43562. function handleDragEnd(e) {
  43563. if (this._dragging) {
  43564. preventDefault(e);
  43565. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  43566. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  43567. this._dragging = false;
  43568. this._track = [];
  43569. this._creatingCover = null;
  43570. // trigger event shoule be at final, after procedure will be nested.
  43571. eventParams && trigger(this, eventParams);
  43572. }
  43573. }
  43574. /**
  43575. * key: brushType
  43576. * @type {Object}
  43577. */
  43578. var coverRenderers = {
  43579. lineX: getLineRenderer(0),
  43580. lineY: getLineRenderer(1),
  43581. rect: {
  43582. createCover: function (controller, brushOption) {
  43583. return createBaseRectCover(
  43584. curry$2(
  43585. driftRect,
  43586. function (range) {
  43587. return range;
  43588. },
  43589. function (range) {
  43590. return range;
  43591. }
  43592. ),
  43593. controller,
  43594. brushOption,
  43595. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  43596. );
  43597. },
  43598. getCreatingRange: function (localTrack) {
  43599. var ends = getTrackEnds(localTrack);
  43600. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  43601. },
  43602. updateCoverShape: function (controller, cover, localRange, brushOption) {
  43603. updateBaseRect(controller, cover, localRange, brushOption);
  43604. },
  43605. updateCommon: updateCommon,
  43606. contain: mainShapeContain
  43607. },
  43608. polygon: {
  43609. createCover: function (controller, brushOption) {
  43610. var cover = new Group();
  43611. // Do not use graphic.Polygon because graphic.Polyline do not close the
  43612. // border of the shape when drawing, which is a better experience for user.
  43613. cover.add(new Polyline({
  43614. name: 'main',
  43615. style: makeStyle(brushOption),
  43616. silent: true
  43617. }));
  43618. return cover;
  43619. },
  43620. getCreatingRange: function (localTrack) {
  43621. return localTrack;
  43622. },
  43623. endCreating: function (controller, cover) {
  43624. cover.remove(cover.childAt(0));
  43625. // Use graphic.Polygon close the shape.
  43626. cover.add(new Polygon({
  43627. name: 'main',
  43628. draggable: true,
  43629. drift: curry$2(driftPolygon, controller, cover),
  43630. ondragend: curry$2(trigger, controller, {isEnd: true})
  43631. }));
  43632. },
  43633. updateCoverShape: function (controller, cover, localRange, brushOption) {
  43634. cover.childAt(0).setShape({
  43635. points: clipByPanel(controller, cover, localRange)
  43636. });
  43637. },
  43638. updateCommon: updateCommon,
  43639. contain: mainShapeContain
  43640. }
  43641. };
  43642. function getLineRenderer(xyIndex) {
  43643. return {
  43644. createCover: function (controller, brushOption) {
  43645. return createBaseRectCover(
  43646. curry$2(
  43647. driftRect,
  43648. function (range) {
  43649. var rectRange = [range, [0, 100]];
  43650. xyIndex && rectRange.reverse();
  43651. return rectRange;
  43652. },
  43653. function (rectRange) {
  43654. return rectRange[xyIndex];
  43655. }
  43656. ),
  43657. controller,
  43658. brushOption,
  43659. [['w', 'e'], ['n', 's']][xyIndex]
  43660. );
  43661. },
  43662. getCreatingRange: function (localTrack) {
  43663. var ends = getTrackEnds(localTrack);
  43664. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  43665. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  43666. return [min, max];
  43667. },
  43668. updateCoverShape: function (controller, cover, localRange, brushOption) {
  43669. var otherExtent;
  43670. // If brushWidth not specified, fit the panel.
  43671. var panel = getPanelByCover(controller, cover);
  43672. if (panel !== true && panel.getLinearBrushOtherExtent) {
  43673. otherExtent = panel.getLinearBrushOtherExtent(
  43674. xyIndex, controller._transform
  43675. );
  43676. }
  43677. else {
  43678. var zr = controller._zr;
  43679. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  43680. }
  43681. var rectRange = [localRange, otherExtent];
  43682. xyIndex && rectRange.reverse();
  43683. updateBaseRect(controller, cover, rectRange, brushOption);
  43684. },
  43685. updateCommon: updateCommon,
  43686. contain: mainShapeContain
  43687. };
  43688. }
  43689. function makeRectPanelClipPath(rect) {
  43690. rect = normalizeRect(rect);
  43691. return function (localPoints, transform) {
  43692. return clipPointsByRect(localPoints, rect);
  43693. };
  43694. }
  43695. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  43696. rect = normalizeRect(rect);
  43697. return function (xyIndex) {
  43698. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  43699. var brushWidth = idx ? rect.width : rect.height;
  43700. var base = idx ? rect.x : rect.y;
  43701. return [base, base + (brushWidth || 0)];
  43702. };
  43703. }
  43704. function makeRectIsTargetByCursor(rect, api, targetModel) {
  43705. rect = normalizeRect(rect);
  43706. return function (e, localCursorPoint, transform) {
  43707. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  43708. && !onIrrelevantElement(e, api, targetModel);
  43709. };
  43710. }
  43711. // Consider width/height is negative.
  43712. function normalizeRect(rect) {
  43713. return BoundingRect.create(rect);
  43714. }
  43715. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  43716. var AxisView$2 = extendComponentView({
  43717. type: 'parallelAxis',
  43718. /**
  43719. * @override
  43720. */
  43721. init: function (ecModel, api) {
  43722. AxisView$2.superApply(this, 'init', arguments);
  43723. /**
  43724. * @type {module:echarts/component/helper/BrushController}
  43725. */
  43726. (this._brushController = new BrushController(api.getZr()))
  43727. .on('brush', bind(this._onBrush, this));
  43728. },
  43729. /**
  43730. * @override
  43731. */
  43732. render: function (axisModel, ecModel, api, payload) {
  43733. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  43734. return;
  43735. }
  43736. this.axisModel = axisModel;
  43737. this.api = api;
  43738. this.group.removeAll();
  43739. var oldAxisGroup = this._axisGroup;
  43740. this._axisGroup = new Group();
  43741. this.group.add(this._axisGroup);
  43742. if (!axisModel.get('show')) {
  43743. return;
  43744. }
  43745. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  43746. var coordSys = coordSysModel.coordinateSystem;
  43747. var areaSelectStyle = axisModel.getAreaSelectStyle();
  43748. var areaWidth = areaSelectStyle.width;
  43749. var dim = axisModel.axis.dim;
  43750. var axisLayout = coordSys.getAxisLayout(dim);
  43751. var builderOpt = extend(
  43752. {strokeContainThreshold: areaWidth},
  43753. axisLayout
  43754. );
  43755. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  43756. each$1(elementList, axisBuilder.add, axisBuilder);
  43757. this._axisGroup.add(axisBuilder.getGroup());
  43758. this._refreshBrushController(
  43759. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  43760. );
  43761. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  43762. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  43763. },
  43764. // /**
  43765. // * @override
  43766. // */
  43767. // updateVisual: function (axisModel, ecModel, api, payload) {
  43768. // this._brushController && this._brushController
  43769. // .updateCovers(getCoverInfoList(axisModel));
  43770. // },
  43771. _refreshBrushController: function (
  43772. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  43773. ) {
  43774. // After filtering, axis may change, select area needs to be update.
  43775. var extent = axisModel.axis.getExtent();
  43776. var extentLen = extent[1] - extent[0];
  43777. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  43778. // width/height might be negative, which will be
  43779. // normalized in BoundingRect.
  43780. var rect = BoundingRect.create({
  43781. x: extent[0],
  43782. y: -areaWidth / 2,
  43783. width: extentLen,
  43784. height: areaWidth
  43785. });
  43786. rect.x -= extra;
  43787. rect.width += 2 * extra;
  43788. this._brushController
  43789. .mount({
  43790. enableGlobalPan: true,
  43791. rotation: builderOpt.rotation,
  43792. position: builderOpt.position
  43793. })
  43794. .setPanels([{
  43795. panelId: 'pl',
  43796. clipPath: makeRectPanelClipPath(rect),
  43797. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  43798. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  43799. }])
  43800. .enableBrush({
  43801. brushType: 'lineX',
  43802. brushStyle: areaSelectStyle,
  43803. removeOnClick: true
  43804. })
  43805. .updateCovers(getCoverInfoList(axisModel));
  43806. },
  43807. _onBrush: function (coverInfoList, opt) {
  43808. // Do not cache these object, because the mey be changed.
  43809. var axisModel = this.axisModel;
  43810. var axis = axisModel.axis;
  43811. var intervals = map(coverInfoList, function (coverInfo) {
  43812. return [
  43813. axis.coordToData(coverInfo.range[0], true),
  43814. axis.coordToData(coverInfo.range[1], true)
  43815. ];
  43816. });
  43817. // If realtime is true, action is not dispatched on drag end, because
  43818. // the drag end emits the same params with the last drag move event,
  43819. // and may have some delay when using touch pad.
  43820. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  43821. this.api.dispatchAction({
  43822. type: 'axisAreaSelect',
  43823. parallelAxisId: axisModel.id,
  43824. intervals: intervals
  43825. });
  43826. }
  43827. },
  43828. /**
  43829. * @override
  43830. */
  43831. dispose: function () {
  43832. this._brushController.dispose();
  43833. }
  43834. });
  43835. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  43836. return payload
  43837. && payload.type === 'axisAreaSelect'
  43838. && ecModel.findComponents(
  43839. {mainType: 'parallelAxis', query: payload}
  43840. )[0] === axisModel;
  43841. }
  43842. function getCoverInfoList(axisModel) {
  43843. var axis = axisModel.axis;
  43844. return map(axisModel.activeIntervals, function (interval) {
  43845. return {
  43846. brushType: 'lineX',
  43847. panelId: 'pl',
  43848. range: [
  43849. axis.dataToCoord(interval[0], true),
  43850. axis.dataToCoord(interval[1], true)
  43851. ]
  43852. };
  43853. });
  43854. }
  43855. function getCoordSysModel(axisModel, ecModel) {
  43856. return ecModel.getComponent(
  43857. 'parallel', axisModel.get('parallelIndex')
  43858. );
  43859. }
  43860. var CLICK_THRESHOLD = 5; // > 4
  43861. // Parallel view
  43862. extendComponentView({
  43863. type: 'parallel',
  43864. render: function (parallelModel, ecModel, api) {
  43865. this._model = parallelModel;
  43866. this._api = api;
  43867. if (!this._handlers) {
  43868. this._handlers = {};
  43869. each$1(handlers, function (handler, eventName) {
  43870. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  43871. }, this);
  43872. }
  43873. createOrUpdate(
  43874. this,
  43875. '_throttledDispatchExpand',
  43876. parallelModel.get('axisExpandRate'),
  43877. 'fixRate'
  43878. );
  43879. },
  43880. dispose: function (ecModel, api) {
  43881. each$1(this._handlers, function (handler, eventName) {
  43882. api.getZr().off(eventName, handler);
  43883. });
  43884. this._handlers = null;
  43885. },
  43886. /**
  43887. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  43888. */
  43889. _throttledDispatchExpand: function (opt) {
  43890. this._dispatchExpand(opt);
  43891. },
  43892. _dispatchExpand: function (opt) {
  43893. opt && this._api.dispatchAction(
  43894. extend({type: 'parallelAxisExpand'}, opt)
  43895. );
  43896. }
  43897. });
  43898. var handlers = {
  43899. mousedown: function (e) {
  43900. if (checkTrigger(this, 'click')) {
  43901. this._mouseDownPoint = [e.offsetX, e.offsetY];
  43902. }
  43903. },
  43904. mouseup: function (e) {
  43905. var mouseDownPoint = this._mouseDownPoint;
  43906. if (checkTrigger(this, 'click') && mouseDownPoint) {
  43907. var point = [e.offsetX, e.offsetY];
  43908. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  43909. + Math.pow(mouseDownPoint[1] - point[1], 2);
  43910. if (dist > CLICK_THRESHOLD) {
  43911. return;
  43912. }
  43913. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  43914. [e.offsetX, e.offsetY]
  43915. );
  43916. result.behavior !== 'none' && this._dispatchExpand({
  43917. axisExpandWindow: result.axisExpandWindow
  43918. });
  43919. }
  43920. this._mouseDownPoint = null;
  43921. },
  43922. mousemove: function (e) {
  43923. // Should do nothing when brushing.
  43924. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  43925. return;
  43926. }
  43927. var model = this._model;
  43928. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  43929. [e.offsetX, e.offsetY]
  43930. );
  43931. var behavior = result.behavior;
  43932. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  43933. this._throttledDispatchExpand(
  43934. behavior === 'none'
  43935. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  43936. : {
  43937. axisExpandWindow: result.axisExpandWindow,
  43938. // Jumping uses animation, and sliding suppresses animation.
  43939. animation: behavior === 'jump' ? null : false
  43940. }
  43941. );
  43942. }
  43943. };
  43944. function checkTrigger(view, triggerOn) {
  43945. var model = view._model;
  43946. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  43947. }
  43948. registerPreprocessor(parallelPreprocessor);
  43949. SeriesModel.extend({
  43950. type: 'series.parallel',
  43951. dependencies: ['parallel'],
  43952. visualColorAccessPath: 'lineStyle.color',
  43953. getInitialData: function (option, ecModel) {
  43954. // Anication is forbiden in progressive data mode.
  43955. if (this.option.progressive) {
  43956. this.option.animation = false;
  43957. }
  43958. var source = this.getSource();
  43959. setEncodeAndDimensions(source, this);
  43960. return createListFromArray(source, this);
  43961. },
  43962. /**
  43963. * User can get data raw indices on 'axisAreaSelected' event received.
  43964. *
  43965. * @public
  43966. * @param {string} activeState 'active' or 'inactive' or 'normal'
  43967. * @return {Array.<number>} Raw indices
  43968. */
  43969. getRawIndicesByActiveState: function (activeState) {
  43970. var coordSys = this.coordinateSystem;
  43971. var data = this.getData();
  43972. var indices = [];
  43973. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  43974. if (activeState === theActiveState) {
  43975. indices.push(data.getRawIndex(dataIndex));
  43976. }
  43977. });
  43978. return indices;
  43979. },
  43980. defaultOption: {
  43981. zlevel: 0, // 一级层叠
  43982. z: 2, // 二级层叠
  43983. coordinateSystem: 'parallel',
  43984. parallelIndex: 0,
  43985. label: {
  43986. show: false
  43987. },
  43988. inactiveOpacity: 0.05,
  43989. activeOpacity: 1,
  43990. lineStyle: {
  43991. width: 1,
  43992. opacity: 0.45,
  43993. type: 'solid'
  43994. },
  43995. emphasis: {
  43996. label: {
  43997. show: false
  43998. }
  43999. },
  44000. progressive: false, // 100
  44001. smooth: false,
  44002. animationEasing: 'linear'
  44003. }
  44004. });
  44005. function setEncodeAndDimensions(source, seriesModel) {
  44006. // The mapping of parallelAxis dimension to data dimension can
  44007. // be specified in parallelAxis.option.dim. For example, if
  44008. // parallelAxis.option.dim is 'dim3', it mapping to the third
  44009. // dimension of data. But `data.encode` has higher priority.
  44010. // Moreover, parallelModel.dimension should not be regarded as data
  44011. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  44012. if (source.encodeDefine) {
  44013. return;
  44014. }
  44015. var parallelModel = seriesModel.ecModel.getComponent(
  44016. 'parallel', seriesModel.get('parallelIndex')
  44017. );
  44018. if (!parallelModel) {
  44019. return;
  44020. }
  44021. var encodeDefine = source.encodeDefine = createHashMap();
  44022. each$1(parallelModel.dimensions, function (axisDim) {
  44023. var dataDimIndex = convertDimNameToNumber(axisDim);
  44024. encodeDefine.set(axisDim, dataDimIndex);
  44025. });
  44026. }
  44027. function convertDimNameToNumber(dimName) {
  44028. return +dimName.replace('dim', '');
  44029. }
  44030. var SMOOTH = 0.3;
  44031. var ParallelView = Chart.extend({
  44032. type: 'parallel',
  44033. init: function () {
  44034. /**
  44035. * @type {module:zrender/container/Group}
  44036. * @private
  44037. */
  44038. this._dataGroup = new Group();
  44039. this.group.add(this._dataGroup);
  44040. /**
  44041. * @type {module:echarts/data/List}
  44042. */
  44043. this._data;
  44044. },
  44045. /**
  44046. * @override
  44047. */
  44048. render: function (seriesModel, ecModel, api, payload) {
  44049. this._renderForNormal(seriesModel, payload);
  44050. // this[
  44051. // seriesModel.option.progressive
  44052. // ? '_renderForProgressive'
  44053. // : '_renderForNormal'
  44054. // ](seriesModel);
  44055. },
  44056. dispose: function () {},
  44057. /**
  44058. * @private
  44059. */
  44060. _renderForNormal: function (seriesModel, payload) {
  44061. var dataGroup = this._dataGroup;
  44062. var data = seriesModel.getData();
  44063. var oldData = this._data;
  44064. var coordSys = seriesModel.coordinateSystem;
  44065. var dimensions = coordSys.dimensions;
  44066. var option = seriesModel.option;
  44067. var smooth = option.smooth ? SMOOTH : null;
  44068. // Consider switch between progressive and not.
  44069. // oldData && oldData.__plProgressive && dataGroup.removeAll();
  44070. data.diff(oldData)
  44071. .add(add)
  44072. .update(update)
  44073. .remove(remove)
  44074. .execute();
  44075. // Update style
  44076. updateElCommon(data, smooth);
  44077. // First create
  44078. if (!this._data) {
  44079. var clipPath = createGridClipShape$1(
  44080. coordSys, seriesModel, function () {
  44081. // Callback will be invoked immediately if there is no animation
  44082. setTimeout(function () {
  44083. dataGroup.removeClipPath();
  44084. });
  44085. }
  44086. );
  44087. dataGroup.setClipPath(clipPath);
  44088. }
  44089. this._data = data;
  44090. function add(newDataIndex) {
  44091. addEl(data, dataGroup, newDataIndex, dimensions, coordSys, null, smooth);
  44092. }
  44093. function update(newDataIndex, oldDataIndex) {
  44094. var line = oldData.getItemGraphicEl(oldDataIndex);
  44095. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  44096. data.setItemGraphicEl(newDataIndex, line);
  44097. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  44098. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  44099. }
  44100. function remove(oldDataIndex) {
  44101. var line = oldData.getItemGraphicEl(oldDataIndex);
  44102. dataGroup.remove(line);
  44103. }
  44104. },
  44105. /**
  44106. * @private
  44107. */
  44108. // _renderForProgressive: function (seriesModel) {
  44109. // var dataGroup = this._dataGroup;
  44110. // var data = seriesModel.getData();
  44111. // var oldData = this._data;
  44112. // var coordSys = seriesModel.coordinateSystem;
  44113. // var dimensions = coordSys.dimensions;
  44114. // var option = seriesModel.option;
  44115. // var progressive = option.progressive;
  44116. // var smooth = option.smooth ? SMOOTH : null;
  44117. // // In progressive animation is disabled, so use simple data diff,
  44118. // // which effects performance less.
  44119. // // (Typically performance for data with length 7000+ like:
  44120. // // simpleDiff: 60ms, addEl: 184ms,
  44121. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  44122. // if (simpleDiff(oldData, data, dimensions)) {
  44123. // dataGroup.removeAll();
  44124. // data.each(function (dataIndex) {
  44125. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  44126. // });
  44127. // }
  44128. // updateElCommon(data, progressive, smooth);
  44129. // // Consider switch between progressive and not.
  44130. // data.__plProgressive = true;
  44131. // this._data = data;
  44132. // },
  44133. /**
  44134. * @override
  44135. */
  44136. remove: function () {
  44137. this._dataGroup && this._dataGroup.removeAll();
  44138. this._data = null;
  44139. }
  44140. });
  44141. function createGridClipShape$1(coordSys, seriesModel, cb) {
  44142. var parallelModel = coordSys.model;
  44143. var rect = coordSys.getRect();
  44144. var rectEl = new Rect({
  44145. shape: {
  44146. x: rect.x,
  44147. y: rect.y,
  44148. width: rect.width,
  44149. height: rect.height
  44150. }
  44151. });
  44152. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  44153. rectEl.setShape(dim, 0);
  44154. initProps(rectEl, {
  44155. shape: {
  44156. width: rect.width,
  44157. height: rect.height
  44158. }
  44159. }, seriesModel, cb);
  44160. return rectEl;
  44161. }
  44162. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  44163. var points = [];
  44164. for (var i = 0; i < dimensions.length; i++) {
  44165. var dimName = dimensions[i];
  44166. var value = data.get(data.mapDimension(dimName), dataIndex);
  44167. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  44168. points.push(coordSys.dataToPoint(value, dimName));
  44169. }
  44170. }
  44171. return points;
  44172. }
  44173. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  44174. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  44175. var line = new Polyline({
  44176. shape: {points: points},
  44177. silent: true,
  44178. z2: 10
  44179. });
  44180. dataGroup.add(line);
  44181. data.setItemGraphicEl(dataIndex, line);
  44182. }
  44183. function updateElCommon(data, smooth) {
  44184. var seriesStyleModel = data.hostModel.getModel('lineStyle');
  44185. var lineStyle = seriesStyleModel.getLineStyle();
  44186. data.eachItemGraphicEl(function (line, dataIndex) {
  44187. if (data.hasItemOption) {
  44188. var itemModel = data.getItemModel(dataIndex);
  44189. var lineStyleModel = itemModel.getModel('lineStyle', seriesStyleModel);
  44190. lineStyle = lineStyleModel.getLineStyle(['color', 'stroke']);
  44191. }
  44192. line.useStyle(extend(lineStyle, {
  44193. fill: null,
  44194. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  44195. stroke: data.getItemVisual(dataIndex, 'color'),
  44196. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  44197. opacity: data.getItemVisual(dataIndex, 'opacity')
  44198. }));
  44199. line.shape.smooth = smooth;
  44200. });
  44201. }
  44202. // function simpleDiff(oldData, newData, dimensions) {
  44203. // var oldLen;
  44204. // if (!oldData
  44205. // || !oldData.__plProgressive
  44206. // || (oldLen = oldData.count()) !== newData.count()
  44207. // ) {
  44208. // return true;
  44209. // }
  44210. // var dimLen = dimensions.length;
  44211. // for (var i = 0; i < oldLen; i++) {
  44212. // for (var j = 0; j < dimLen; j++) {
  44213. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  44214. // return true;
  44215. // }
  44216. // }
  44217. // }
  44218. // return false;
  44219. // }
  44220. // FIXME
  44221. // 公用方法?
  44222. function isEmptyValue(val, axisType) {
  44223. return axisType === 'category'
  44224. ? val == null
  44225. : (val == null || isNaN(val)); // axisType === 'value'
  44226. }
  44227. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  44228. var parallelVisual = function (ecModel) {
  44229. ecModel.eachSeriesByType('parallel', function (seriesModel) {
  44230. var itemStyleModel = seriesModel.getModel('itemStyle');
  44231. var lineStyleModel = seriesModel.getModel('lineStyle');
  44232. var globalColors = ecModel.get('color');
  44233. var color = lineStyleModel.get('color')
  44234. || itemStyleModel.get('color')
  44235. || globalColors[seriesModel.seriesIndex % globalColors.length];
  44236. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  44237. var activeOpacity = seriesModel.get('activeOpacity');
  44238. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  44239. var coordSys = seriesModel.coordinateSystem;
  44240. var data = seriesModel.getData();
  44241. var opacityMap = {
  44242. normal: lineStyle.opacity,
  44243. active: activeOpacity,
  44244. inactive: inactiveOpacity
  44245. };
  44246. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  44247. var itemModel = data.getItemModel(dataIndex);
  44248. var opacity = opacityMap[activeState];
  44249. if (activeState === 'normal') {
  44250. var itemOpacity = itemModel.get(opacityAccessPath$1, true);
  44251. itemOpacity != null && (opacity = itemOpacity);
  44252. }
  44253. data.setItemVisual(dataIndex, 'opacity', opacity);
  44254. });
  44255. data.setVisual('color', color);
  44256. });
  44257. };
  44258. registerVisual(parallelVisual);
  44259. /**
  44260. * @file Get initial data and define sankey view's series model
  44261. * @author Deqing Li(annong035@gmail.com)
  44262. */
  44263. var SankeySeries = SeriesModel.extend({
  44264. type: 'series.sankey',
  44265. layoutInfo: null,
  44266. /**
  44267. * Init a graph data structure from data in option series
  44268. *
  44269. * @param {Object} option the object used to config echarts view
  44270. * @return {module:echarts/data/List} storage initial data
  44271. */
  44272. getInitialData: function (option) {
  44273. var links = option.edges || option.links;
  44274. var nodes = option.data || option.nodes;
  44275. if (nodes && links) {
  44276. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  44277. return graph.data;
  44278. }
  44279. },
  44280. /**
  44281. * Return the graphic data structure
  44282. *
  44283. * @return {module:echarts/data/Graph} graphic data structure
  44284. */
  44285. getGraph: function () {
  44286. return this.getData().graph;
  44287. },
  44288. /**
  44289. * Get edge data of graphic data structure
  44290. *
  44291. * @return {module:echarts/data/List} data structure of list
  44292. */
  44293. getEdgeData: function () {
  44294. return this.getGraph().edgeData;
  44295. },
  44296. /**
  44297. * @override
  44298. */
  44299. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  44300. // dataType === 'node' or empty do not show tooltip by default
  44301. if (dataType === 'edge') {
  44302. var params = this.getDataParams(dataIndex, dataType);
  44303. var rawDataOpt = params.data;
  44304. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  44305. if (params.value) {
  44306. html += ' : ' + params.value;
  44307. }
  44308. return encodeHTML(html);
  44309. }
  44310. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  44311. },
  44312. defaultOption: {
  44313. zlevel: 0,
  44314. z: 2,
  44315. coordinateSystem: 'view',
  44316. layout: null,
  44317. // the position of the whole view
  44318. left: '5%',
  44319. top: '5%',
  44320. right: '20%',
  44321. bottom: '5%',
  44322. // the dx of the node
  44323. nodeWidth: 20,
  44324. // the vertical distance between two nodes
  44325. nodeGap: 8,
  44326. // the number of iterations to change the position of the node
  44327. layoutIterations: 32,
  44328. label: {
  44329. show: true,
  44330. position: 'right',
  44331. color: '#000',
  44332. fontSize: 12
  44333. },
  44334. itemStyle: {
  44335. borderWidth: 1,
  44336. borderColor: '#333'
  44337. },
  44338. lineStyle: {
  44339. color: '#314656',
  44340. opacity: 0.2,
  44341. curveness: 0.5
  44342. },
  44343. emphasis: {
  44344. label: {
  44345. show: true
  44346. },
  44347. lineStyle: {
  44348. opacity: 0.6
  44349. }
  44350. },
  44351. animationEasing: 'linear',
  44352. animationDuration: 1000
  44353. }
  44354. });
  44355. /**
  44356. * @file The file used to draw sankey view
  44357. * @author Deqing Li(annong035@gmail.com)
  44358. */
  44359. var SankeyShape = extendShape({
  44360. shape: {
  44361. x1: 0, y1: 0,
  44362. x2: 0, y2: 0,
  44363. cpx1: 0, cpy1: 0,
  44364. cpx2: 0, cpy2: 0,
  44365. extent: 0
  44366. },
  44367. buildPath: function (ctx, shape) {
  44368. var halfExtent = shape.extent / 2;
  44369. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  44370. ctx.bezierCurveTo(
  44371. shape.cpx1, shape.cpy1 - halfExtent,
  44372. shape.cpx2, shape.cpy2 - halfExtent,
  44373. shape.x2, shape.y2 - halfExtent
  44374. );
  44375. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  44376. ctx.bezierCurveTo(
  44377. shape.cpx2, shape.cpy2 + halfExtent,
  44378. shape.cpx1, shape.cpy1 + halfExtent,
  44379. shape.x1, shape.y1 + halfExtent
  44380. );
  44381. ctx.closePath();
  44382. }
  44383. });
  44384. extendChartView({
  44385. type: 'sankey',
  44386. /**
  44387. * @private
  44388. * @type {module:echarts/chart/sankey/SankeySeries}
  44389. */
  44390. _model: null,
  44391. render: function (seriesModel, ecModel, api) {
  44392. var graph = seriesModel.getGraph();
  44393. var group = this.group;
  44394. var layoutInfo = seriesModel.layoutInfo;
  44395. var nodeData = seriesModel.getData();
  44396. var edgeData = seriesModel.getData('edge');
  44397. this._model = seriesModel;
  44398. group.removeAll();
  44399. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  44400. // generate a bezire Curve for each edge
  44401. graph.eachEdge(function (edge) {
  44402. var curve = new SankeyShape();
  44403. curve.dataIndex = edge.dataIndex;
  44404. curve.seriesIndex = seriesModel.seriesIndex;
  44405. curve.dataType = 'edge';
  44406. var lineStyleModel = edge.getModel('lineStyle');
  44407. var curvature = lineStyleModel.get('curveness');
  44408. var n1Layout = edge.node1.getLayout();
  44409. var n2Layout = edge.node2.getLayout();
  44410. var edgeLayout = edge.getLayout();
  44411. curve.shape.extent = Math.max(1, edgeLayout.dy);
  44412. var x1 = n1Layout.x + n1Layout.dx;
  44413. var y1 = n1Layout.y + edgeLayout.sy + edgeLayout.dy / 2;
  44414. var x2 = n2Layout.x;
  44415. var y2 = n2Layout.y + edgeLayout.ty + edgeLayout.dy / 2;
  44416. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  44417. var cpy1 = y1;
  44418. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  44419. var cpy2 = y2;
  44420. curve.setShape({
  44421. x1: x1,
  44422. y1: y1,
  44423. x2: x2,
  44424. y2: y2,
  44425. cpx1: cpx1,
  44426. cpy1: cpy1,
  44427. cpx2: cpx2,
  44428. cpy2: cpy2
  44429. });
  44430. curve.setStyle(lineStyleModel.getItemStyle());
  44431. // Special color, use source node color or target node color
  44432. switch (curve.style.fill) {
  44433. case 'source':
  44434. curve.style.fill = edge.node1.getVisual('color');
  44435. break;
  44436. case 'target':
  44437. curve.style.fill = edge.node2.getVisual('color');
  44438. break;
  44439. }
  44440. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  44441. group.add(curve);
  44442. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  44443. });
  44444. // generate a rect for each node
  44445. graph.eachNode(function (node) {
  44446. var layout = node.getLayout();
  44447. var itemModel = node.getModel();
  44448. var labelModel = itemModel.getModel('label');
  44449. var labelHoverModel = itemModel.getModel('emphasis.label');
  44450. var rect = new Rect({
  44451. shape: {
  44452. x: layout.x,
  44453. y: layout.y,
  44454. width: node.getLayout().dx,
  44455. height: node.getLayout().dy
  44456. },
  44457. style: itemModel.getModel('itemStyle').getItemStyle()
  44458. });
  44459. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  44460. setLabelStyle(
  44461. rect.style, hoverStyle, labelModel, labelHoverModel,
  44462. {
  44463. labelFetcher: seriesModel,
  44464. labelDataIndex: node.dataIndex,
  44465. defaultText: node.id,
  44466. isRectText: true
  44467. }
  44468. );
  44469. rect.setStyle('fill', node.getVisual('color'));
  44470. setHoverStyle(rect, hoverStyle);
  44471. group.add(rect);
  44472. nodeData.setItemGraphicEl(node.dataIndex, rect);
  44473. rect.dataType = 'node';
  44474. });
  44475. if (!this._data && seriesModel.get('animation')) {
  44476. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  44477. group.removeClipPath();
  44478. }));
  44479. }
  44480. this._data = seriesModel.getData();
  44481. },
  44482. dispose: function () {}
  44483. });
  44484. // add animation to the view
  44485. function createGridClipShape$2(rect, seriesModel, cb) {
  44486. var rectEl = new Rect({
  44487. shape: {
  44488. x: rect.x - 10,
  44489. y: rect.y - 10,
  44490. width: 0,
  44491. height: rect.height + 20
  44492. }
  44493. });
  44494. initProps(rectEl, {
  44495. shape: {
  44496. width: rect.width + 20,
  44497. height: rect.height + 20
  44498. }
  44499. }, seriesModel, cb);
  44500. return rectEl;
  44501. }
  44502. /**
  44503. * nest helper used to group by the array.
  44504. * can specified the keys and sort the keys.
  44505. */
  44506. function nest() {
  44507. var keysFunction = [];
  44508. var sortKeysFunction = [];
  44509. /**
  44510. * map an Array into the mapObject.
  44511. * @param {Array} array
  44512. * @param {number} depth
  44513. */
  44514. function map$$1(array, depth) {
  44515. if (depth >= keysFunction.length) {
  44516. return array;
  44517. }
  44518. var i = -1;
  44519. var n = array.length;
  44520. var keyFunction = keysFunction[depth++];
  44521. var mapObject = {};
  44522. var valuesByKey = {};
  44523. while (++i < n) {
  44524. var keyValue = keyFunction(array[i]);
  44525. var values = valuesByKey[keyValue];
  44526. if (values) {
  44527. values.push(array[i]);
  44528. }
  44529. else {
  44530. valuesByKey[keyValue] = [array[i]];
  44531. }
  44532. }
  44533. each$1(valuesByKey, function (value, key) {
  44534. mapObject[key] = map$$1(value, depth);
  44535. });
  44536. return mapObject;
  44537. }
  44538. /**
  44539. * transform the Map Object to multidimensional Array
  44540. * @param {Object} map
  44541. * @param {number} depth
  44542. */
  44543. function entriesMap(mapObject, depth) {
  44544. if (depth >= keysFunction.length) {
  44545. return mapObject;
  44546. }
  44547. var array = [];
  44548. var sortKeyFunction = sortKeysFunction[depth++];
  44549. each$1(mapObject, function (value, key) {
  44550. array.push({
  44551. key: key, values: entriesMap(value, depth)
  44552. });
  44553. });
  44554. if (sortKeyFunction) {
  44555. return array.sort(function (a, b) {
  44556. return sortKeyFunction(a.key, b.key);
  44557. });
  44558. }
  44559. else {
  44560. return array;
  44561. }
  44562. }
  44563. return {
  44564. /**
  44565. * specified the key to groupby the arrays.
  44566. * users can specified one more keys.
  44567. * @param {Function} d
  44568. */
  44569. key: function (d) {
  44570. keysFunction.push(d);
  44571. return this;
  44572. },
  44573. /**
  44574. * specified the comparator to sort the keys
  44575. * @param {Function} order
  44576. */
  44577. sortKeys: function (order) {
  44578. sortKeysFunction[keysFunction.length - 1] = order;
  44579. return this;
  44580. },
  44581. /**
  44582. * the array to be grouped by.
  44583. * @param {Array} array
  44584. */
  44585. entries: function (array) {
  44586. return entriesMap(map$$1(array, 0), 0);
  44587. }
  44588. };
  44589. }
  44590. /**
  44591. * @file The layout algorithm of sankey view
  44592. * @author Deqing Li(annong035@gmail.com)
  44593. */
  44594. var sankeyLayout = function (ecModel, api, payload) {
  44595. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  44596. var nodeWidth = seriesModel.get('nodeWidth');
  44597. var nodeGap = seriesModel.get('nodeGap');
  44598. var layoutInfo = getViewRect$3(seriesModel, api);
  44599. seriesModel.layoutInfo = layoutInfo;
  44600. var width = layoutInfo.width;
  44601. var height = layoutInfo.height;
  44602. var graph = seriesModel.getGraph();
  44603. var nodes = graph.nodes;
  44604. var edges = graph.edges;
  44605. computeNodeValues(nodes);
  44606. var filteredNodes = filter(nodes, function (node) {
  44607. return node.getLayout().value === 0;
  44608. });
  44609. var iterations = filteredNodes.length !== 0
  44610. ? 0 : seriesModel.get('layoutIterations');
  44611. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  44612. });
  44613. };
  44614. /**
  44615. * Get the layout position of the whole view
  44616. *
  44617. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  44618. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  44619. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  44620. */
  44621. function getViewRect$3(seriesModel, api) {
  44622. return getLayoutRect(
  44623. seriesModel.getBoxLayoutParams(), {
  44624. width: api.getWidth(),
  44625. height: api.getHeight()
  44626. }
  44627. );
  44628. }
  44629. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  44630. computeNodeBreadths(nodes, nodeWidth, width);
  44631. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  44632. computeEdgeDepths(nodes);
  44633. }
  44634. /**
  44635. * Compute the value of each node by summing the associated edge's value
  44636. *
  44637. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44638. */
  44639. function computeNodeValues(nodes) {
  44640. each$1(nodes, function (node) {
  44641. var value1 = sum(node.outEdges, getEdgeValue);
  44642. var value2 = sum(node.inEdges, getEdgeValue);
  44643. var value = Math.max(value1, value2);
  44644. node.setLayout({value: value}, true);
  44645. });
  44646. }
  44647. /**
  44648. * Compute the x-position for each node
  44649. *
  44650. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44651. * @param {number} nodeWidth the dx of the node
  44652. * @param {number} width the whole width of the area to draw the view
  44653. */
  44654. function computeNodeBreadths(nodes, nodeWidth, width) {
  44655. var remainNodes = nodes;
  44656. var nextNode = null;
  44657. var x = 0;
  44658. var kx = 0;
  44659. while (remainNodes.length) {
  44660. nextNode = [];
  44661. for (var i = 0, len = remainNodes.length; i < len; i++) {
  44662. var node = remainNodes[i];
  44663. node.setLayout({x: x}, true);
  44664. node.setLayout({dx: nodeWidth}, true);
  44665. for (var j = 0, lenj = node.outEdges.length; j < lenj; j++) {
  44666. nextNode.push(node.outEdges[j].node2);
  44667. }
  44668. }
  44669. remainNodes = nextNode;
  44670. ++x;
  44671. }
  44672. moveSinksRight(nodes, x);
  44673. kx = (width - nodeWidth) / (x - 1);
  44674. scaleNodeBreadths(nodes, kx);
  44675. }
  44676. /**
  44677. * All the node without outEgdes are assigned maximum x-position and
  44678. * be aligned in the last column.
  44679. *
  44680. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44681. * @param {number} x value (x-1) use to assign to node without outEdges
  44682. * as x-position
  44683. */
  44684. function moveSinksRight(nodes, x) {
  44685. each$1(nodes, function (node) {
  44686. if (!node.outEdges.length) {
  44687. node.setLayout({x: x - 1}, true);
  44688. }
  44689. });
  44690. }
  44691. /**
  44692. * Scale node x-position to the width
  44693. *
  44694. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44695. * @param {number} kx multiple used to scale nodes
  44696. */
  44697. function scaleNodeBreadths(nodes, kx) {
  44698. each$1(nodes, function (node) {
  44699. var nodeX = node.getLayout().x * kx;
  44700. node.setLayout({x: nodeX}, true);
  44701. });
  44702. }
  44703. /**
  44704. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  44705. *
  44706. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44707. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  44708. * @param {number} height the whole height of the area to draw the view
  44709. * @param {number} nodeGap the vertical distance between two nodes
  44710. * in the same column.
  44711. * @param {number} iterations the number of iterations for the algorithm
  44712. */
  44713. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  44714. var nodesByBreadth = nest()
  44715. .key(function (d) {
  44716. return d.getLayout().x;
  44717. })
  44718. .sortKeys(ascending)
  44719. .entries(nodes)
  44720. .map(function (d) {
  44721. return d.values;
  44722. });
  44723. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  44724. resolveCollisions(nodesByBreadth, nodeGap, height);
  44725. for (var alpha = 1; iterations > 0; iterations--) {
  44726. // 0.99 is a experience parameter, ensure that each iterations of
  44727. // changes as small as possible.
  44728. alpha *= 0.99;
  44729. relaxRightToLeft(nodesByBreadth, alpha);
  44730. resolveCollisions(nodesByBreadth, nodeGap, height);
  44731. relaxLeftToRight(nodesByBreadth, alpha);
  44732. resolveCollisions(nodesByBreadth, nodeGap, height);
  44733. }
  44734. }
  44735. /**
  44736. * Compute the original y-position for each node
  44737. *
  44738. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44739. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  44740. * group by the array of all sankey nodes based on the nodes x-position.
  44741. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  44742. * @param {number} height the whole height of the area to draw the view
  44743. * @param {number} nodeGap the vertical distance between two nodes
  44744. */
  44745. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  44746. var kyArray = [];
  44747. each$1(nodesByBreadth, function (nodes) {
  44748. var n = nodes.length;
  44749. var sum = 0;
  44750. each$1(nodes, function (node) {
  44751. sum += node.getLayout().value;
  44752. });
  44753. var ky = (height - (n - 1) * nodeGap) / sum;
  44754. kyArray.push(ky);
  44755. });
  44756. kyArray.sort(function (a, b) {
  44757. return a - b;
  44758. });
  44759. var ky0 = kyArray[0];
  44760. each$1(nodesByBreadth, function (nodes) {
  44761. each$1(nodes, function (node, i) {
  44762. node.setLayout({y: i}, true);
  44763. var nodeDy = node.getLayout().value * ky0;
  44764. node.setLayout({dy: nodeDy}, true);
  44765. });
  44766. });
  44767. each$1(edges, function (edge) {
  44768. var edgeDy = +edge.getValue() * ky0;
  44769. edge.setLayout({dy: edgeDy}, true);
  44770. });
  44771. }
  44772. /**
  44773. * Resolve the collision of initialized depth (y-position)
  44774. *
  44775. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  44776. * group by the array of all sankey nodes based on the nodes x-position.
  44777. * @param {number} nodeGap the vertical distance between two nodes
  44778. * @param {number} height the whole height of the area to draw the view
  44779. */
  44780. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  44781. each$1(nodesByBreadth, function (nodes) {
  44782. var node;
  44783. var dy;
  44784. var y0 = 0;
  44785. var n = nodes.length;
  44786. var i;
  44787. nodes.sort(ascendingDepth);
  44788. for (i = 0; i < n; i++) {
  44789. node = nodes[i];
  44790. dy = y0 - node.getLayout().y;
  44791. if (dy > 0) {
  44792. var nodeY = node.getLayout().y + dy;
  44793. node.setLayout({y: nodeY}, true);
  44794. }
  44795. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  44796. }
  44797. // if the bottommost node goes outside the bounds, push it back up
  44798. dy = y0 - nodeGap - height;
  44799. if (dy > 0) {
  44800. var nodeY = node.getLayout().y - dy;
  44801. node.setLayout({y: nodeY}, true);
  44802. y0 = node.getLayout().y;
  44803. for (i = n - 2; i >= 0; --i) {
  44804. node = nodes[i];
  44805. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  44806. if (dy > 0) {
  44807. nodeY = node.getLayout().y - dy;
  44808. node.setLayout({y: nodeY}, true);
  44809. }
  44810. y0 = node.getLayout().y;
  44811. }
  44812. }
  44813. });
  44814. }
  44815. /**
  44816. * Change the y-position of the nodes, except most the right side nodes
  44817. *
  44818. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  44819. * group by the array of all sankey nodes based on the node x-position.
  44820. * @param {number} alpha parameter used to adjust the nodes y-position
  44821. */
  44822. function relaxRightToLeft(nodesByBreadth, alpha) {
  44823. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  44824. each$1(nodes, function (node) {
  44825. if (node.outEdges.length) {
  44826. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  44827. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  44828. node.setLayout({y: nodeY}, true);
  44829. }
  44830. });
  44831. });
  44832. }
  44833. function weightedTarget(edge) {
  44834. return center$1(edge.node2) * edge.getValue();
  44835. }
  44836. /**
  44837. * Change the y-position of the nodes, except most the left side nodes
  44838. *
  44839. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  44840. * group by the array of all sankey nodes based on the node x-position.
  44841. * @param {number} alpha parameter used to adjust the nodes y-position
  44842. */
  44843. function relaxLeftToRight(nodesByBreadth, alpha) {
  44844. each$1(nodesByBreadth, function (nodes) {
  44845. each$1(nodes, function (node) {
  44846. if (node.inEdges.length) {
  44847. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  44848. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  44849. node.setLayout({y: nodeY}, true);
  44850. }
  44851. });
  44852. });
  44853. }
  44854. function weightedSource(edge) {
  44855. return center$1(edge.node1) * edge.getValue();
  44856. }
  44857. /**
  44858. * Compute the depth(y-position) of each edge
  44859. *
  44860. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  44861. */
  44862. function computeEdgeDepths(nodes) {
  44863. each$1(nodes, function (node) {
  44864. node.outEdges.sort(ascendingTargetDepth);
  44865. node.inEdges.sort(ascendingSourceDepth);
  44866. });
  44867. each$1(nodes, function (node) {
  44868. var sy = 0;
  44869. var ty = 0;
  44870. each$1(node.outEdges, function (edge) {
  44871. edge.setLayout({sy: sy}, true);
  44872. sy += edge.getLayout().dy;
  44873. });
  44874. each$1(node.inEdges, function (edge) {
  44875. edge.setLayout({ty: ty}, true);
  44876. ty += edge.getLayout().dy;
  44877. });
  44878. });
  44879. }
  44880. function ascendingTargetDepth(a, b) {
  44881. return a.node2.getLayout().y - b.node2.getLayout().y;
  44882. }
  44883. function ascendingSourceDepth(a, b) {
  44884. return a.node1.getLayout().y - b.node1.getLayout().y;
  44885. }
  44886. function sum(array, f) {
  44887. var sum = 0;
  44888. var len = array.length;
  44889. var i = -1;
  44890. while (++i < len) {
  44891. var value = +f.call(array, array[i], i);
  44892. if (!isNaN(value)) {
  44893. sum += value;
  44894. }
  44895. }
  44896. return sum;
  44897. }
  44898. function center$1(node) {
  44899. return node.getLayout().y + node.getLayout().dy / 2;
  44900. }
  44901. function ascendingDepth(a, b) {
  44902. return a.getLayout().y - b.getLayout().y;
  44903. }
  44904. function ascending(a, b) {
  44905. return a < b ? -1 : a > b ? 1 : a === b ? 0 : NaN;
  44906. }
  44907. function getEdgeValue(edge) {
  44908. return edge.getValue();
  44909. }
  44910. /**
  44911. * @file Visual encoding for sankey view
  44912. * @author Deqing Li(annong035@gmail.com)
  44913. */
  44914. var sankeyVisual = function (ecModel, payload) {
  44915. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  44916. var graph = seriesModel.getGraph();
  44917. var nodes = graph.nodes;
  44918. nodes.sort(function (a, b) {
  44919. return a.getLayout().value - b.getLayout().value;
  44920. });
  44921. var minValue = nodes[0].getLayout().value;
  44922. var maxValue = nodes[nodes.length - 1].getLayout().value;
  44923. each$1(nodes, function (node) {
  44924. var mapping = new VisualMapping({
  44925. type: 'color',
  44926. mappingMethod: 'linear',
  44927. dataExtent: [minValue, maxValue],
  44928. visual: seriesModel.get('color')
  44929. });
  44930. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  44931. node.setVisual('color', mapValueToColor);
  44932. // If set itemStyle.normal.color
  44933. var itemModel = node.getModel();
  44934. var customColor = itemModel.get('itemStyle.color');
  44935. if (customColor != null) {
  44936. node.setVisual('color', customColor);
  44937. }
  44938. });
  44939. });
  44940. };
  44941. registerLayout(sankeyLayout);
  44942. registerVisual(sankeyVisual);
  44943. /**
  44944. * @module echarts/chart/helper/Symbol
  44945. */
  44946. var WhiskerPath = Path.extend({
  44947. type: 'whiskerInBox',
  44948. shape: {},
  44949. buildPath: function (ctx, shape) {
  44950. for (var i in shape) {
  44951. if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
  44952. var pts = shape[i];
  44953. ctx.moveTo(pts[0][0], pts[0][1]);
  44954. ctx.lineTo(pts[1][0], pts[1][1]);
  44955. }
  44956. }
  44957. }
  44958. });
  44959. /**
  44960. * @constructor
  44961. * @alias {module:echarts/chart/helper/WhiskerBox}
  44962. * @param {module:echarts/data/List} data
  44963. * @param {number} idx
  44964. * @param {Function} styleUpdater
  44965. * @param {boolean} isInit
  44966. * @extends {module:zrender/graphic/Group}
  44967. */
  44968. function WhiskerBox(data, idx, styleUpdater, isInit) {
  44969. Group.call(this);
  44970. /**
  44971. * @type {number}
  44972. * @readOnly
  44973. */
  44974. this.bodyIndex;
  44975. /**
  44976. * @type {number}
  44977. * @readOnly
  44978. */
  44979. this.whiskerIndex;
  44980. /**
  44981. * @type {Function}
  44982. */
  44983. this.styleUpdater = styleUpdater;
  44984. this._createContent(data, idx, isInit);
  44985. this.updateData(data, idx, isInit);
  44986. /**
  44987. * Last series model.
  44988. * @type {module:echarts/model/Series}
  44989. */
  44990. this._seriesModel;
  44991. }
  44992. var whiskerBoxProto = WhiskerBox.prototype;
  44993. whiskerBoxProto._createContent = function (data, idx, isInit) {
  44994. var itemLayout = data.getItemLayout(idx);
  44995. var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
  44996. var count = 0;
  44997. // Whisker element.
  44998. this.add(new Polygon({
  44999. shape: {
  45000. points: isInit
  45001. ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
  45002. : itemLayout.bodyEnds
  45003. },
  45004. style: {strokeNoScale: true},
  45005. z2: 100
  45006. }));
  45007. this.bodyIndex = count++;
  45008. // Box element.
  45009. var whiskerEnds = map(itemLayout.whiskerEnds, function (ends) {
  45010. return isInit ? transInit(ends, constDim, itemLayout) : ends;
  45011. });
  45012. this.add(new WhiskerPath({
  45013. shape: makeWhiskerEndsShape(whiskerEnds),
  45014. style: {strokeNoScale: true},
  45015. z2: 100
  45016. }));
  45017. this.whiskerIndex = count++;
  45018. };
  45019. function transInit(points, dim, itemLayout) {
  45020. return map(points, function (point) {
  45021. point = point.slice();
  45022. point[dim] = itemLayout.initBaseline;
  45023. return point;
  45024. });
  45025. }
  45026. function makeWhiskerEndsShape(whiskerEnds) {
  45027. // zr animation only support 2-dim array.
  45028. var shape = {};
  45029. each$1(whiskerEnds, function (ends, i) {
  45030. shape['ends' + i] = ends;
  45031. });
  45032. return shape;
  45033. }
  45034. /**
  45035. * Update symbol properties
  45036. * @param {module:echarts/data/List} data
  45037. * @param {number} idx
  45038. */
  45039. whiskerBoxProto.updateData = function (data, idx, isInit) {
  45040. var seriesModel = this._seriesModel = data.hostModel;
  45041. var itemLayout = data.getItemLayout(idx);
  45042. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  45043. // this.childAt(this.bodyIndex).stopAnimation(true);
  45044. // this.childAt(this.whiskerIndex).stopAnimation(true);
  45045. updateMethod(
  45046. this.childAt(this.bodyIndex),
  45047. {shape: {points: itemLayout.bodyEnds}},
  45048. seriesModel, idx
  45049. );
  45050. updateMethod(
  45051. this.childAt(this.whiskerIndex),
  45052. {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
  45053. seriesModel, idx
  45054. );
  45055. this.styleUpdater.call(null, this, data, idx);
  45056. };
  45057. inherits(WhiskerBox, Group);
  45058. /**
  45059. * @constructor
  45060. * @alias module:echarts/chart/helper/WhiskerBoxDraw
  45061. */
  45062. function WhiskerBoxDraw(styleUpdater) {
  45063. this.group = new Group();
  45064. this.styleUpdater = styleUpdater;
  45065. }
  45066. var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;
  45067. /**
  45068. * Update symbols draw by new data
  45069. * @param {module:echarts/data/List} data
  45070. */
  45071. whiskerBoxDrawProto.updateData = function (data) {
  45072. var group = this.group;
  45073. var oldData = this._data;
  45074. var styleUpdater = this.styleUpdater;
  45075. data.diff(oldData)
  45076. .add(function (newIdx) {
  45077. if (data.hasValue(newIdx)) {
  45078. var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
  45079. data.setItemGraphicEl(newIdx, symbolEl);
  45080. group.add(symbolEl);
  45081. }
  45082. })
  45083. .update(function (newIdx, oldIdx) {
  45084. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45085. // Empty data
  45086. if (!data.hasValue(newIdx)) {
  45087. group.remove(symbolEl);
  45088. return;
  45089. }
  45090. if (!symbolEl) {
  45091. symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
  45092. }
  45093. else {
  45094. symbolEl.updateData(data, newIdx);
  45095. }
  45096. // Add back
  45097. group.add(symbolEl);
  45098. data.setItemGraphicEl(newIdx, symbolEl);
  45099. })
  45100. .remove(function (oldIdx) {
  45101. var el = oldData.getItemGraphicEl(oldIdx);
  45102. el && group.remove(el);
  45103. })
  45104. .execute();
  45105. this._data = data;
  45106. };
  45107. /**
  45108. * Remove symbols.
  45109. * @param {module:echarts/data/List} data
  45110. */
  45111. whiskerBoxDrawProto.remove = function () {
  45112. var group = this.group;
  45113. var data = this._data;
  45114. this._data = null;
  45115. data && data.eachItemGraphicEl(function (el) {
  45116. el && group.remove(el);
  45117. });
  45118. };
  45119. var seriesModelMixin = {
  45120. /**
  45121. * @private
  45122. * @type {string}
  45123. */
  45124. _baseAxisDim: null,
  45125. /**
  45126. * @override
  45127. */
  45128. getInitialData: function (option, ecModel) {
  45129. // When both types of xAxis and yAxis are 'value', layout is
  45130. // needed to be specified by user. Otherwise, layout can be
  45131. // judged by which axis is category.
  45132. var ordinalMeta;
  45133. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  45134. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  45135. var xAxisType = xAxisModel.get('type');
  45136. var yAxisType = yAxisModel.get('type');
  45137. var addOrdinal;
  45138. // FIXME
  45139. // 考虑时间轴
  45140. if (xAxisType === 'category') {
  45141. option.layout = 'horizontal';
  45142. ordinalMeta = xAxisModel.getOrdinalMeta();
  45143. addOrdinal = true;
  45144. }
  45145. else if (yAxisType === 'category') {
  45146. option.layout = 'vertical';
  45147. ordinalMeta = yAxisModel.getOrdinalMeta();
  45148. addOrdinal = true;
  45149. }
  45150. else {
  45151. option.layout = option.layout || 'horizontal';
  45152. }
  45153. var coordDims = ['x', 'y'];
  45154. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  45155. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  45156. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  45157. var axisModels = [xAxisModel, yAxisModel];
  45158. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  45159. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  45160. var data = option.data;
  45161. // ??? FIXME make a stage to perform data transfrom.
  45162. // MUST create a new data, consider setOption({}) again.
  45163. if (data && addOrdinal) {
  45164. var newOptionData = [];
  45165. each$1(data, function (item, index) {
  45166. var newItem;
  45167. if (item.value && isArray(item.value)) {
  45168. newItem = item.value.slice();
  45169. item.value.unshift(index);
  45170. }
  45171. else if (isArray(item)) {
  45172. newItem = item.slice();
  45173. item.unshift(index);
  45174. }
  45175. else {
  45176. newItem = item;
  45177. }
  45178. newOptionData.push(newItem);
  45179. });
  45180. option.data = newOptionData;
  45181. }
  45182. var defaultValueDimensions = this.defaultValueDimensions;
  45183. return createListSimply(
  45184. this,
  45185. {
  45186. coordDimensions: [{
  45187. name: baseAxisDim,
  45188. type: getDimensionTypeByAxis(baseAxisType),
  45189. ordinalMeta: ordinalMeta,
  45190. otherDims: {
  45191. tooltip: false,
  45192. itemName: 0
  45193. },
  45194. dimsDef: ['base']
  45195. }, {
  45196. name: otherAxisDim,
  45197. type: getDimensionTypeByAxis(otherAxisType),
  45198. dimsDef: defaultValueDimensions.slice()
  45199. }],
  45200. dimensionsCount: defaultValueDimensions.length + 1
  45201. }
  45202. );
  45203. },
  45204. /**
  45205. * If horizontal, base axis is x, otherwise y.
  45206. * @override
  45207. */
  45208. getBaseAxis: function () {
  45209. var dim = this._baseAxisDim;
  45210. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  45211. }
  45212. };
  45213. var viewMixin = {
  45214. init: function () {
  45215. /**
  45216. * Old data.
  45217. * @private
  45218. * @type {module:echarts/chart/helper/WhiskerBoxDraw}
  45219. */
  45220. var whiskerBoxDraw = this._whiskerBoxDraw = new WhiskerBoxDraw(
  45221. this.getStyleUpdater()
  45222. );
  45223. this.group.add(whiskerBoxDraw.group);
  45224. },
  45225. render: function (seriesModel, ecModel, api) {
  45226. this._whiskerBoxDraw.updateData(seriesModel.getData());
  45227. },
  45228. remove: function (ecModel) {
  45229. this._whiskerBoxDraw.remove();
  45230. }
  45231. };
  45232. var BoxplotSeries = SeriesModel.extend({
  45233. type: 'series.boxplot',
  45234. dependencies: ['xAxis', 'yAxis', 'grid'],
  45235. // TODO
  45236. // box width represents group size, so dimension should have 'size'.
  45237. /**
  45238. * @see <https://en.wikipedia.org/wiki/Box_plot>
  45239. * The meanings of 'min' and 'max' depend on user,
  45240. * and echarts do not need to know it.
  45241. * @readOnly
  45242. */
  45243. defaultValueDimensions: ['min', 'Q1', 'median', 'Q3', 'max'],
  45244. /**
  45245. * @type {Array.<string>}
  45246. * @readOnly
  45247. */
  45248. dimensions: null,
  45249. /**
  45250. * @override
  45251. */
  45252. defaultOption: {
  45253. zlevel: 0, // 一级层叠
  45254. z: 2, // 二级层叠
  45255. coordinateSystem: 'cartesian2d',
  45256. legendHoverLink: true,
  45257. hoverAnimation: true,
  45258. // xAxisIndex: 0,
  45259. // yAxisIndex: 0,
  45260. layout: null, // 'horizontal' or 'vertical'
  45261. boxWidth: [7, 50], // [min, max] can be percent of band width.
  45262. itemStyle: {
  45263. color: '#fff',
  45264. borderWidth: 1
  45265. },
  45266. emphasis: {
  45267. itemStyle: {
  45268. borderWidth: 2,
  45269. shadowBlur: 5,
  45270. shadowOffsetX: 2,
  45271. shadowOffsetY: 2,
  45272. shadowColor: 'rgba(0,0,0,0.4)'
  45273. }
  45274. },
  45275. animationEasing: 'elasticOut',
  45276. animationDuration: 800
  45277. }
  45278. });
  45279. mixin(BoxplotSeries, seriesModelMixin, true);
  45280. var BoxplotView = Chart.extend({
  45281. type: 'boxplot',
  45282. getStyleUpdater: function () {
  45283. return updateStyle$1;
  45284. },
  45285. dispose: noop
  45286. });
  45287. mixin(BoxplotView, viewMixin, true);
  45288. // Update common properties
  45289. var normalStyleAccessPath$1 = ['itemStyle'];
  45290. var emphasisStyleAccessPath$1 = ['emphasis', 'itemStyle'];
  45291. function updateStyle$1(itemGroup, data, idx) {
  45292. var itemModel = data.getItemModel(idx);
  45293. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$1);
  45294. var borderColor = data.getItemVisual(idx, 'color');
  45295. // Exclude borderColor.
  45296. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  45297. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  45298. whiskerEl.style.set(itemStyle);
  45299. whiskerEl.style.stroke = borderColor;
  45300. whiskerEl.dirty();
  45301. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  45302. bodyEl.style.set(itemStyle);
  45303. bodyEl.style.stroke = borderColor;
  45304. bodyEl.dirty();
  45305. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$1).getItemStyle();
  45306. setHoverStyle(itemGroup, hoverStyle);
  45307. }
  45308. var borderColorQuery = ['itemStyle', 'borderColor'];
  45309. var boxplotVisual = function (ecModel, api) {
  45310. var globalColors = ecModel.get('color');
  45311. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  45312. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  45313. var data = seriesModel.getData();
  45314. data.setVisual({
  45315. legendSymbol: 'roundRect',
  45316. // Use name 'color' but not 'borderColor' for legend usage and
  45317. // visual coding from other component like dataRange.
  45318. color: seriesModel.get(borderColorQuery) || defaulColor
  45319. });
  45320. // Only visible series has each data be visual encoded
  45321. if (!ecModel.isSeriesFiltered(seriesModel)) {
  45322. data.each(function (idx) {
  45323. var itemModel = data.getItemModel(idx);
  45324. data.setItemVisual(
  45325. idx,
  45326. {color: itemModel.get(borderColorQuery, true)}
  45327. );
  45328. });
  45329. }
  45330. });
  45331. };
  45332. var each$14 = each$1;
  45333. var boxplotLayout = function (ecModel) {
  45334. var groupResult = groupSeriesByAxis(ecModel);
  45335. each$14(groupResult, function (groupItem) {
  45336. var seriesModels = groupItem.seriesModels;
  45337. if (!seriesModels.length) {
  45338. return;
  45339. }
  45340. calculateBase(groupItem);
  45341. each$14(seriesModels, function (seriesModel, idx) {
  45342. layoutSingleSeries(
  45343. seriesModel,
  45344. groupItem.boxOffsetList[idx],
  45345. groupItem.boxWidthList[idx]
  45346. );
  45347. });
  45348. });
  45349. };
  45350. /**
  45351. * Group series by axis.
  45352. */
  45353. function groupSeriesByAxis(ecModel) {
  45354. var result = [];
  45355. var axisList = [];
  45356. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  45357. var baseAxis = seriesModel.getBaseAxis();
  45358. var idx = indexOf(axisList, baseAxis);
  45359. if (idx < 0) {
  45360. idx = axisList.length;
  45361. axisList[idx] = baseAxis;
  45362. result[idx] = {axis: baseAxis, seriesModels: []};
  45363. }
  45364. result[idx].seriesModels.push(seriesModel);
  45365. });
  45366. return result;
  45367. }
  45368. /**
  45369. * Calculate offset and box width for each series.
  45370. */
  45371. function calculateBase(groupItem) {
  45372. var extent;
  45373. var baseAxis = groupItem.axis;
  45374. var seriesModels = groupItem.seriesModels;
  45375. var seriesCount = seriesModels.length;
  45376. var boxWidthList = groupItem.boxWidthList = [];
  45377. var boxOffsetList = groupItem.boxOffsetList = [];
  45378. var boundList = [];
  45379. var bandWidth;
  45380. if (baseAxis.type === 'category') {
  45381. bandWidth = baseAxis.getBandWidth();
  45382. }
  45383. else {
  45384. var maxDataCount = 0;
  45385. each$14(seriesModels, function (seriesModel) {
  45386. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  45387. });
  45388. extent = baseAxis.getExtent(),
  45389. Math.abs(extent[1] - extent[0]) / maxDataCount;
  45390. }
  45391. each$14(seriesModels, function (seriesModel) {
  45392. var boxWidthBound = seriesModel.get('boxWidth');
  45393. if (!isArray(boxWidthBound)) {
  45394. boxWidthBound = [boxWidthBound, boxWidthBound];
  45395. }
  45396. boundList.push([
  45397. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  45398. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  45399. ]);
  45400. });
  45401. var availableWidth = bandWidth * 0.8 - 2;
  45402. var boxGap = availableWidth / seriesCount * 0.3;
  45403. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  45404. var base = boxWidth / 2 - availableWidth / 2;
  45405. each$14(seriesModels, function (seriesModel, idx) {
  45406. boxOffsetList.push(base);
  45407. base += boxGap + boxWidth;
  45408. boxWidthList.push(
  45409. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  45410. );
  45411. });
  45412. }
  45413. /**
  45414. * Calculate points location for each series.
  45415. */
  45416. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  45417. var coordSys = seriesModel.coordinateSystem;
  45418. var data = seriesModel.getData();
  45419. var halfWidth = boxWidth / 2;
  45420. var chartLayout = seriesModel.get('layout');
  45421. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  45422. var constDim = 1 - variableDim;
  45423. var coordDims = ['x', 'y'];
  45424. var vDims = [];
  45425. var cDim;
  45426. each$1(data.dimensions, function (dimName) {
  45427. var dimInfo = data.getDimensionInfo(dimName);
  45428. var coordDim = dimInfo.coordDim;
  45429. if (coordDim === coordDims[constDim]) {
  45430. vDims.push(dimName);
  45431. }
  45432. else if (coordDim === coordDims[variableDim]) {
  45433. cDim = dimName;
  45434. }
  45435. });
  45436. if (cDim == null || vDims.length < 5) {
  45437. return;
  45438. }
  45439. data.each([cDim].concat(vDims), function () {
  45440. var args = arguments;
  45441. var axisDimVal = args[0];
  45442. var idx = args[vDims.length + 1];
  45443. var median = getPoint(args[3]);
  45444. var end1 = getPoint(args[1]);
  45445. var end5 = getPoint(args[5]);
  45446. var whiskerEnds = [
  45447. [end1, getPoint(args[2])],
  45448. [end5, getPoint(args[4])]
  45449. ];
  45450. layEndLine(end1);
  45451. layEndLine(end5);
  45452. layEndLine(median);
  45453. var bodyEnds = [];
  45454. addBodyEnd(whiskerEnds[0][1], 0);
  45455. addBodyEnd(whiskerEnds[1][1], 1);
  45456. data.setItemLayout(idx, {
  45457. chartLayout: chartLayout,
  45458. initBaseline: median[constDim],
  45459. median: median,
  45460. bodyEnds: bodyEnds,
  45461. whiskerEnds: whiskerEnds
  45462. });
  45463. function getPoint(val) {
  45464. var p = [];
  45465. p[variableDim] = axisDimVal;
  45466. p[constDim] = val;
  45467. var point;
  45468. if (isNaN(axisDimVal) || isNaN(val)) {
  45469. point = [NaN, NaN];
  45470. }
  45471. else {
  45472. point = coordSys.dataToPoint(p);
  45473. point[variableDim] += offset;
  45474. }
  45475. return point;
  45476. }
  45477. function addBodyEnd(point, start) {
  45478. var point1 = point.slice();
  45479. var point2 = point.slice();
  45480. point1[variableDim] += halfWidth;
  45481. point2[variableDim] -= halfWidth;
  45482. start
  45483. ? bodyEnds.push(point1, point2)
  45484. : bodyEnds.push(point2, point1);
  45485. }
  45486. function layEndLine(endCenter) {
  45487. var line = [endCenter.slice(), endCenter.slice()];
  45488. line[0][variableDim] -= halfWidth;
  45489. line[1][variableDim] += halfWidth;
  45490. whiskerEnds.push(line);
  45491. }
  45492. });
  45493. }
  45494. registerVisual(boxplotVisual);
  45495. registerLayout(boxplotLayout);
  45496. var CandlestickSeries = SeriesModel.extend({
  45497. type: 'series.candlestick',
  45498. dependencies: ['xAxis', 'yAxis', 'grid'],
  45499. /**
  45500. * @readOnly
  45501. */
  45502. defaultValueDimensions: ['open', 'close', 'lowest', 'highest'],
  45503. /**
  45504. * @type {Array.<string>}
  45505. * @readOnly
  45506. */
  45507. dimensions: null,
  45508. /**
  45509. * @override
  45510. */
  45511. defaultOption: {
  45512. zlevel: 0, // 一级层叠
  45513. z: 2, // 二级层叠
  45514. coordinateSystem: 'cartesian2d',
  45515. legendHoverLink: true,
  45516. hoverAnimation: true,
  45517. // xAxisIndex: 0,
  45518. // yAxisIndex: 0,
  45519. layout: null, // 'horizontal' or 'vertical'
  45520. itemStyle: {
  45521. color: '#c23531', // 阳线 positive
  45522. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  45523. borderWidth: 1,
  45524. // FIXME
  45525. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  45526. borderColor: '#c23531',
  45527. borderColor0: '#314656'
  45528. },
  45529. emphasis: {
  45530. itemStyle: {
  45531. borderWidth: 2
  45532. }
  45533. },
  45534. barMaxWidth: null,
  45535. barMinWidth: null,
  45536. barWidth: null,
  45537. animationUpdate: false,
  45538. animationEasing: 'linear',
  45539. animationDuration: 300
  45540. },
  45541. /**
  45542. * Get dimension for shadow in dataZoom
  45543. * @return {string} dimension name
  45544. */
  45545. getShadowDim: function () {
  45546. return 'open';
  45547. },
  45548. brushSelector: function (dataIndex, data, selectors) {
  45549. var itemLayout = data.getItemLayout(dataIndex);
  45550. return selectors.rect(itemLayout.brushRect);
  45551. }
  45552. });
  45553. mixin(CandlestickSeries, seriesModelMixin, true);
  45554. var CandlestickView = Chart.extend({
  45555. type: 'candlestick',
  45556. getStyleUpdater: function () {
  45557. return updateStyle$2;
  45558. },
  45559. dispose: noop
  45560. });
  45561. mixin(CandlestickView, viewMixin, true);
  45562. // Update common properties
  45563. var normalStyleAccessPath$2 = ['itemStyle'];
  45564. var emphasisStyleAccessPath$2 = ['emphasis', 'itemStyle'];
  45565. function updateStyle$2(itemGroup, data, idx) {
  45566. var itemModel = data.getItemModel(idx);
  45567. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$2);
  45568. var color = data.getItemVisual(idx, 'color');
  45569. var borderColor = data.getItemVisual(idx, 'borderColor') || color;
  45570. // Color must be excluded.
  45571. // Because symbol provide setColor individually to set fill and stroke
  45572. var itemStyle = normalItemStyleModel.getItemStyle(
  45573. ['color', 'color0', 'borderColor', 'borderColor0']
  45574. );
  45575. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  45576. whiskerEl.useStyle(itemStyle);
  45577. whiskerEl.style.stroke = borderColor;
  45578. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  45579. bodyEl.useStyle(itemStyle);
  45580. bodyEl.style.fill = color;
  45581. bodyEl.style.stroke = borderColor;
  45582. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$2).getItemStyle();
  45583. setHoverStyle(itemGroup, hoverStyle);
  45584. }
  45585. var preprocessor = function (option) {
  45586. if (!option || !isArray(option.series)) {
  45587. return;
  45588. }
  45589. // Translate 'k' to 'candlestick'.
  45590. each$1(option.series, function (seriesItem) {
  45591. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  45592. seriesItem.type = 'candlestick';
  45593. }
  45594. });
  45595. };
  45596. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  45597. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  45598. var positiveColorQuery = ['itemStyle', 'color'];
  45599. var negativeColorQuery = ['itemStyle', 'color0'];
  45600. var candlestickVisual = function (ecModel, api) {
  45601. ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
  45602. var data = seriesModel.getData();
  45603. data.setVisual({
  45604. legendSymbol: 'roundRect'
  45605. });
  45606. // Only visible series has each data be visual encoded
  45607. if (!ecModel.isSeriesFiltered(seriesModel)) {
  45608. data.each(function (idx) {
  45609. var itemModel = data.getItemModel(idx);
  45610. var sign = data.getItemLayout(idx).sign;
  45611. data.setItemVisual(
  45612. idx,
  45613. {
  45614. color: itemModel.get(
  45615. sign > 0 ? positiveColorQuery : negativeColorQuery
  45616. ),
  45617. borderColor: itemModel.get(
  45618. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  45619. )
  45620. }
  45621. );
  45622. });
  45623. }
  45624. });
  45625. };
  45626. var retrieve2$1 = retrieve2;
  45627. var candlestickLayout = function (ecModel) {
  45628. ecModel.eachSeriesByType('candlestick', function (seriesModel) {
  45629. var coordSys = seriesModel.coordinateSystem;
  45630. var data = seriesModel.getData();
  45631. var candleWidth = calculateCandleWidth(seriesModel, data);
  45632. var chartLayout = seriesModel.get('layout');
  45633. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  45634. var constDim = 1 - variableDim;
  45635. var coordDims = ['x', 'y'];
  45636. var vDims = [];
  45637. var cDim;
  45638. each$1(data.dimensions, function (dimName) {
  45639. var dimInfo = data.getDimensionInfo(dimName);
  45640. var coordDim = dimInfo.coordDim;
  45641. if (coordDim === coordDims[constDim]) {
  45642. vDims.push(dimName);
  45643. }
  45644. else if (coordDim === coordDims[variableDim]) {
  45645. cDim = dimName;
  45646. }
  45647. });
  45648. if (cDim == null || vDims.length < 4) {
  45649. return;
  45650. }
  45651. var dataIndex = 0;
  45652. data.each([cDim].concat(vDims), function () {
  45653. var args = arguments;
  45654. var axisDimVal = args[0];
  45655. var idx = args[vDims.length + 1];
  45656. var openVal = args[1];
  45657. var closeVal = args[2];
  45658. var lowestVal = args[3];
  45659. var highestVal = args[4];
  45660. var ocLow = Math.min(openVal, closeVal);
  45661. var ocHigh = Math.max(openVal, closeVal);
  45662. var ocLowPoint = getPoint(ocLow);
  45663. var ocHighPoint = getPoint(ocHigh);
  45664. var lowestPoint = getPoint(lowestVal);
  45665. var highestPoint = getPoint(highestVal);
  45666. var whiskerEnds = [
  45667. [
  45668. subPixelOptimizePoint(highestPoint),
  45669. subPixelOptimizePoint(ocHighPoint)
  45670. ],
  45671. [
  45672. subPixelOptimizePoint(lowestPoint),
  45673. subPixelOptimizePoint(ocLowPoint)
  45674. ]
  45675. ];
  45676. var bodyEnds = [];
  45677. addBodyEnd(ocHighPoint, 0);
  45678. addBodyEnd(ocLowPoint, 1);
  45679. var sign;
  45680. if (openVal > closeVal) {
  45681. sign = -1;
  45682. }
  45683. else if (openVal < closeVal) {
  45684. sign = 1;
  45685. }
  45686. else {
  45687. // If close === open, compare with close of last record
  45688. if (dataIndex > 0) {
  45689. sign = data.getItemModel(dataIndex - 1).get()[2]
  45690. <= closeVal
  45691. ? 1
  45692. : -1;
  45693. }
  45694. else {
  45695. // No record of previous, set to be positive
  45696. sign = 1;
  45697. }
  45698. }
  45699. data.setItemLayout(idx, {
  45700. chartLayout: chartLayout,
  45701. sign: sign,
  45702. initBaseline: openVal > closeVal
  45703. ? ocHighPoint[constDim] : ocLowPoint[constDim], // open point.
  45704. bodyEnds: bodyEnds,
  45705. whiskerEnds: whiskerEnds,
  45706. brushRect: makeBrushRect()
  45707. });
  45708. ++dataIndex;
  45709. function getPoint(val) {
  45710. var p = [];
  45711. p[variableDim] = axisDimVal;
  45712. p[constDim] = val;
  45713. return (isNaN(axisDimVal) || isNaN(val))
  45714. ? [NaN, NaN]
  45715. : coordSys.dataToPoint(p);
  45716. }
  45717. function addBodyEnd(point, start) {
  45718. var point1 = point.slice();
  45719. var point2 = point.slice();
  45720. point1[variableDim] = subPixelOptimize(
  45721. point1[variableDim] + candleWidth / 2, 1, false
  45722. );
  45723. point2[variableDim] = subPixelOptimize(
  45724. point2[variableDim] - candleWidth / 2, 1, true
  45725. );
  45726. start
  45727. ? bodyEnds.push(point1, point2)
  45728. : bodyEnds.push(point2, point1);
  45729. }
  45730. function makeBrushRect() {
  45731. var pmin = getPoint(Math.min(openVal, closeVal, lowestVal, highestVal));
  45732. var pmax = getPoint(Math.max(openVal, closeVal, lowestVal, highestVal));
  45733. pmin[variableDim] -= candleWidth / 2;
  45734. pmax[variableDim] -= candleWidth / 2;
  45735. return {
  45736. x: pmin[0],
  45737. y: pmin[1],
  45738. width: constDim ? candleWidth : pmax[0] - pmin[0],
  45739. height: constDim ? pmax[1] - pmin[1] : candleWidth
  45740. };
  45741. }
  45742. function subPixelOptimizePoint(point) {
  45743. point[variableDim] = subPixelOptimize(point[variableDim], 1);
  45744. return point;
  45745. }
  45746. }, true);
  45747. });
  45748. };
  45749. function calculateCandleWidth(seriesModel, data) {
  45750. var baseAxis = seriesModel.getBaseAxis();
  45751. var extent;
  45752. var bandWidth = baseAxis.type === 'category'
  45753. ? baseAxis.getBandWidth()
  45754. : (
  45755. extent = baseAxis.getExtent(),
  45756. Math.abs(extent[1] - extent[0]) / data.count()
  45757. );
  45758. var barMaxWidth = parsePercent$1(
  45759. retrieve2$1(seriesModel.get('barMaxWidth'), bandWidth),
  45760. bandWidth
  45761. );
  45762. var barMinWidth = parsePercent$1(
  45763. retrieve2$1(seriesModel.get('barMinWidth'), 1),
  45764. bandWidth
  45765. );
  45766. var barWidth = seriesModel.get('barWidth');
  45767. return barWidth != null
  45768. ? parsePercent$1(barWidth, bandWidth)
  45769. // Put max outer to ensure bar visible in spite of overlap.
  45770. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  45771. }
  45772. registerPreprocessor(preprocessor);
  45773. registerVisual(candlestickVisual);
  45774. registerLayout(candlestickLayout);
  45775. SeriesModel.extend({
  45776. type: 'series.effectScatter',
  45777. dependencies: ['grid', 'polar'],
  45778. getInitialData: function (option, ecModel) {
  45779. return createListFromArray(this.getSource(), this);
  45780. },
  45781. brushSelector: 'point',
  45782. defaultOption: {
  45783. coordinateSystem: 'cartesian2d',
  45784. zlevel: 0,
  45785. z: 2,
  45786. legendHoverLink: true,
  45787. effectType: 'ripple',
  45788. progressive: 0,
  45789. // When to show the effect, option: 'render'|'emphasis'
  45790. showEffectOn: 'render',
  45791. // Ripple effect config
  45792. rippleEffect: {
  45793. period: 4,
  45794. // Scale of ripple
  45795. scale: 2.5,
  45796. // Brush type can be fill or stroke
  45797. brushType: 'fill'
  45798. },
  45799. // Cartesian coordinate system
  45800. // xAxisIndex: 0,
  45801. // yAxisIndex: 0,
  45802. // Polar coordinate system
  45803. // polarIndex: 0,
  45804. // Geo coordinate system
  45805. // geoIndex: 0,
  45806. // symbol: null, // 图形类型
  45807. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  45808. // symbolRotate: null, // 图形旋转控制
  45809. // large: false,
  45810. // Available when large is true
  45811. // largeThreshold: 2000,
  45812. // itemStyle: {
  45813. // opacity: 1
  45814. // }
  45815. }
  45816. });
  45817. /**
  45818. * Symbol with ripple effect
  45819. * @module echarts/chart/helper/EffectSymbol
  45820. */
  45821. var EFFECT_RIPPLE_NUMBER = 3;
  45822. function normalizeSymbolSize$1(symbolSize) {
  45823. if (!isArray(symbolSize)) {
  45824. symbolSize = [+symbolSize, +symbolSize];
  45825. }
  45826. return symbolSize;
  45827. }
  45828. function updateRipplePath(rippleGroup, effectCfg) {
  45829. rippleGroup.eachChild(function (ripplePath) {
  45830. ripplePath.attr({
  45831. z: effectCfg.z,
  45832. zlevel: effectCfg.zlevel,
  45833. style: {
  45834. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  45835. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  45836. }
  45837. });
  45838. });
  45839. }
  45840. /**
  45841. * @constructor
  45842. * @param {module:echarts/data/List} data
  45843. * @param {number} idx
  45844. * @extends {module:zrender/graphic/Group}
  45845. */
  45846. function EffectSymbol(data, idx) {
  45847. Group.call(this);
  45848. var symbol = new SymbolClz$1(data, idx);
  45849. var rippleGroup = new Group();
  45850. this.add(symbol);
  45851. this.add(rippleGroup);
  45852. rippleGroup.beforeUpdate = function () {
  45853. this.attr(symbol.getScale());
  45854. };
  45855. this.updateData(data, idx);
  45856. }
  45857. var effectSymbolProto = EffectSymbol.prototype;
  45858. effectSymbolProto.stopEffectAnimation = function () {
  45859. this.childAt(1).removeAll();
  45860. };
  45861. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  45862. var symbolType = effectCfg.symbolType;
  45863. var color = effectCfg.color;
  45864. var rippleGroup = this.childAt(1);
  45865. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  45866. // var ripplePath = createSymbol(
  45867. // symbolType, -0.5, -0.5, 1, 1, color
  45868. // );
  45869. // If width/height are set too small (e.g., set to 1) on ios10
  45870. // and macOS Sierra, a circle stroke become a rect, no matter what
  45871. // the scale is set. So we set width/height as 2. See #4136.
  45872. var ripplePath = createSymbol(
  45873. symbolType, -1, -1, 2, 2, color
  45874. );
  45875. ripplePath.attr({
  45876. style: {
  45877. strokeNoScale: true
  45878. },
  45879. z2: 99,
  45880. silent: true,
  45881. scale: [0.5, 0.5]
  45882. });
  45883. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  45884. // TODO Configurable effectCfg.period
  45885. ripplePath.animate('', true)
  45886. .when(effectCfg.period, {
  45887. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  45888. })
  45889. .delay(delay)
  45890. .start();
  45891. ripplePath.animateStyle(true)
  45892. .when(effectCfg.period, {
  45893. opacity: 0
  45894. })
  45895. .delay(delay)
  45896. .start();
  45897. rippleGroup.add(ripplePath);
  45898. }
  45899. updateRipplePath(rippleGroup, effectCfg);
  45900. };
  45901. /**
  45902. * Update effect symbol
  45903. */
  45904. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  45905. var oldEffectCfg = this._effectCfg;
  45906. var rippleGroup = this.childAt(1);
  45907. // Must reinitialize effect if following configuration changed
  45908. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  45909. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  45910. var propName = DIFFICULT_PROPS[i];
  45911. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  45912. this.stopEffectAnimation();
  45913. this.startEffectAnimation(effectCfg);
  45914. return;
  45915. }
  45916. }
  45917. updateRipplePath(rippleGroup, effectCfg);
  45918. };
  45919. /**
  45920. * Highlight symbol
  45921. */
  45922. effectSymbolProto.highlight = function () {
  45923. this.trigger('emphasis');
  45924. };
  45925. /**
  45926. * Downplay symbol
  45927. */
  45928. effectSymbolProto.downplay = function () {
  45929. this.trigger('normal');
  45930. };
  45931. /**
  45932. * Update symbol properties
  45933. * @param {module:echarts/data/List} data
  45934. * @param {number} idx
  45935. */
  45936. effectSymbolProto.updateData = function (data, idx) {
  45937. var seriesModel = data.hostModel;
  45938. this.childAt(0).updateData(data, idx);
  45939. var rippleGroup = this.childAt(1);
  45940. var itemModel = data.getItemModel(idx);
  45941. var symbolType = data.getItemVisual(idx, 'symbol');
  45942. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  45943. var color = data.getItemVisual(idx, 'color');
  45944. rippleGroup.attr('scale', symbolSize);
  45945. rippleGroup.traverse(function (ripplePath) {
  45946. ripplePath.attr({
  45947. fill: color
  45948. });
  45949. });
  45950. var symbolOffset = itemModel.getShallow('symbolOffset');
  45951. if (symbolOffset) {
  45952. var pos = rippleGroup.position;
  45953. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  45954. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  45955. }
  45956. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  45957. var effectCfg = {};
  45958. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  45959. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  45960. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  45961. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  45962. effectCfg.effectOffset = idx / data.count();
  45963. effectCfg.z = itemModel.getShallow('z') || 0;
  45964. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  45965. effectCfg.symbolType = symbolType;
  45966. effectCfg.color = color;
  45967. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  45968. if (effectCfg.showEffectOn === 'render') {
  45969. this._effectCfg
  45970. ? this.updateEffectAnimation(effectCfg)
  45971. : this.startEffectAnimation(effectCfg);
  45972. this._effectCfg = effectCfg;
  45973. }
  45974. else {
  45975. // Not keep old effect config
  45976. this._effectCfg = null;
  45977. this.stopEffectAnimation();
  45978. var symbol = this.childAt(0);
  45979. var onEmphasis = function () {
  45980. symbol.highlight();
  45981. if (effectCfg.showEffectOn !== 'render') {
  45982. this.startEffectAnimation(effectCfg);
  45983. }
  45984. };
  45985. var onNormal = function () {
  45986. symbol.downplay();
  45987. if (effectCfg.showEffectOn !== 'render') {
  45988. this.stopEffectAnimation();
  45989. }
  45990. };
  45991. this.on('mouseover', onEmphasis, this)
  45992. .on('mouseout', onNormal, this)
  45993. .on('emphasis', onEmphasis, this)
  45994. .on('normal', onNormal, this);
  45995. }
  45996. this._effectCfg = effectCfg;
  45997. };
  45998. effectSymbolProto.fadeOut = function (cb) {
  45999. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  46000. cb && cb();
  46001. };
  46002. inherits(EffectSymbol, Group);
  46003. extendChartView({
  46004. type: 'effectScatter',
  46005. init: function () {
  46006. this._symbolDraw = new SymbolDraw(EffectSymbol);
  46007. },
  46008. render: function (seriesModel, ecModel, api) {
  46009. var data = seriesModel.getData();
  46010. var effectSymbolDraw = this._symbolDraw;
  46011. effectSymbolDraw.updateData(data);
  46012. this.group.add(effectSymbolDraw.group);
  46013. },
  46014. updateTransform: function (seriesModel, ecModel, api) {
  46015. var data = seriesModel.getData();
  46016. this.group.dirty();
  46017. var res = pointsLayout().reset(seriesModel);
  46018. if (res.progress) {
  46019. res.progress({ start: 0, end: data.count() }, data);
  46020. }
  46021. this._symbolDraw.updateLayout(data);
  46022. },
  46023. _updateGroupTransform: function (seriesModel) {
  46024. var coordSys = seriesModel.coordinateSystem;
  46025. if (coordSys && coordSys.getRoamTransform) {
  46026. this.group.transform = clone$2(coordSys.getRoamTransform());
  46027. this.group.decomposeTransform();
  46028. }
  46029. },
  46030. remove: function (ecModel, api) {
  46031. this._symbolDraw && this._symbolDraw.remove(api);
  46032. },
  46033. dispose: function () {}
  46034. });
  46035. registerVisual(visualSymbol('effectScatter', 'circle'));
  46036. registerLayout(pointsLayout('effectScatter'));
  46037. var globalObj$1 = typeof window === 'undefined' ? global : window;
  46038. var Uint32Arr = globalObj$1.Uint32Array || Array;
  46039. var Float64Arr = globalObj$1.Float64Array || Array;
  46040. function compatEc2(seriesOpt) {
  46041. var data = seriesOpt.data;
  46042. if (data && data[0] && data[0][0] && data[0][0].coord) {
  46043. if (__DEV__) {
  46044. console.warn('Lines data configuration has been changed to'
  46045. + ' { coords:[[1,2],[2,3]] }');
  46046. }
  46047. seriesOpt.data = map(data, function (itemOpt) {
  46048. var coords = [
  46049. itemOpt[0].coord, itemOpt[1].coord
  46050. ];
  46051. var target = {
  46052. coords: coords
  46053. };
  46054. if (itemOpt[0].name) {
  46055. target.fromName = itemOpt[0].name;
  46056. }
  46057. if (itemOpt[1].name) {
  46058. target.toName = itemOpt[1].name;
  46059. }
  46060. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  46061. });
  46062. }
  46063. }
  46064. var LinesSeries = SeriesModel.extend({
  46065. type: 'series.lines',
  46066. dependencies: ['grid', 'polar'],
  46067. visualColorAccessPath: 'lineStyle.color',
  46068. init: function (option) {
  46069. // Not using preprocessor because mergeOption may not have series.type
  46070. compatEc2(option);
  46071. var result = this._processFlatCoordsArray(option.data);
  46072. this._flatCoords = result.flatCoords;
  46073. this._flatCoordsOffset = result.flatCoordsOffset;
  46074. if (result.flatCoords) {
  46075. option.data = new Float32Array(result.count);
  46076. }
  46077. LinesSeries.superApply(this, 'init', arguments);
  46078. },
  46079. mergeOption: function (option) {
  46080. compatEc2(option);
  46081. if (option.data) {
  46082. // Only update when have option data to merge.
  46083. var result = this._processFlatCoordsArray(option.data);
  46084. this._flatCoords = result.flatCoords;
  46085. this._flatCoordsOffset = result.flatCoordsOffset;
  46086. if (result.flatCoords) {
  46087. option.data = new Float32Array(result.count);
  46088. }
  46089. }
  46090. LinesSeries.superApply(this, 'mergeOption', arguments);
  46091. },
  46092. appendData: function (params) {
  46093. var result = this._processFlatCoordsArray(params.data);
  46094. if (result.flatCoords) {
  46095. if (!this._flatCoords) {
  46096. this._flatCoords = result.flatCoords;
  46097. this._flatCoordsOffset = result.flatCoordsOffset;
  46098. }
  46099. else {
  46100. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  46101. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  46102. }
  46103. params.data = new Float32Array(result.count);
  46104. }
  46105. this.getRawData().appendData(params.data);
  46106. },
  46107. _getCoordsFromItemModel: function (idx) {
  46108. var itemModel = this.getData().getItemModel(idx);
  46109. var coords = (itemModel.option instanceof Array)
  46110. ? itemModel.option : itemModel.getShallow('coords');
  46111. if (__DEV__) {
  46112. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  46113. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  46114. }
  46115. }
  46116. return coords;
  46117. },
  46118. getLineCoordsCount: function (idx) {
  46119. if (this._flatCoordsOffset) {
  46120. return this._flatCoordsOffset[idx * 2 + 1];
  46121. }
  46122. else {
  46123. return this._getCoordsFromItemModel(idx).length;
  46124. }
  46125. },
  46126. getLineCoords: function (idx, out) {
  46127. if (this._flatCoordsOffset) {
  46128. var offset = this._flatCoordsOffset[idx * 2];
  46129. var len = this._flatCoordsOffset[idx * 2 + 1];
  46130. for (var i = 0; i < len; i++) {
  46131. out[i] = out[i] || [];
  46132. out[i][0] = this._flatCoords[offset + i * 2];
  46133. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  46134. }
  46135. return len;
  46136. }
  46137. else {
  46138. var coords = this._getCoordsFromItemModel(idx);
  46139. for (var i = 0; i < coords.length; i++) {
  46140. out[i] = out[i] || [];
  46141. out[i][0] = coords[i][0];
  46142. out[i][1] = coords[i][1];
  46143. }
  46144. return coords.length;
  46145. }
  46146. },
  46147. _processFlatCoordsArray: function (data) {
  46148. var startOffset = 0;
  46149. if (this._flatCoords) {
  46150. startOffset = this._flatCoords.length;
  46151. }
  46152. // Stored as a typed array. In format
  46153. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  46154. if (typeof data[0] === 'number') {
  46155. var len = data.length;
  46156. // Store offset and len of each segment
  46157. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  46158. var coordsStorage = new Float64Arr(len);
  46159. var coordsCursor = 0;
  46160. var offsetCursor = 0;
  46161. var dataCount = 0;
  46162. for (var i = 0; i < len;) {
  46163. dataCount++;
  46164. var count = data[i++];
  46165. // Offset
  46166. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  46167. // Len
  46168. coordsOffsetAndLenStorage[offsetCursor++] = count;
  46169. for (var k = 0; k < count; k++) {
  46170. var x = data[i++];
  46171. var y = data[i++];
  46172. coordsStorage[coordsCursor++] = x;
  46173. coordsStorage[coordsCursor++] = y;
  46174. if (i > len) {
  46175. if (__DEV__) {
  46176. throw new Error('Invalid data format.');
  46177. }
  46178. }
  46179. }
  46180. }
  46181. return {
  46182. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  46183. flatCoords: coordsStorage,
  46184. count: dataCount
  46185. };
  46186. }
  46187. return {
  46188. flatCoordsOffset: null,
  46189. flatCoords: null,
  46190. count: data.length
  46191. };
  46192. },
  46193. getInitialData: function (option, ecModel) {
  46194. if (__DEV__) {
  46195. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  46196. if (!CoordSys) {
  46197. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  46198. }
  46199. }
  46200. var lineData = new List(['value'], this);
  46201. lineData.hasItemOption = false;
  46202. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  46203. // dataItem is simply coords
  46204. if (dataItem instanceof Array) {
  46205. return NaN;
  46206. }
  46207. else {
  46208. lineData.hasItemOption = true;
  46209. var value = dataItem.value;
  46210. if (value != null) {
  46211. return value instanceof Array ? value[dimIndex] : value;
  46212. }
  46213. }
  46214. });
  46215. return lineData;
  46216. },
  46217. formatTooltip: function (dataIndex) {
  46218. var data = this.getData();
  46219. var itemModel = data.getItemModel(dataIndex);
  46220. var name = itemModel.get('name');
  46221. if (name) {
  46222. return name;
  46223. }
  46224. var fromName = itemModel.get('fromName');
  46225. var toName = itemModel.get('toName');
  46226. var html = [];
  46227. fromName != null && html.push(fromName);
  46228. toName != null && html.push(toName);
  46229. return encodeHTML(html.join(' > '));
  46230. },
  46231. preventIncremental: function () {
  46232. return !!this.get('effect.show');
  46233. },
  46234. getProgressive: function () {
  46235. var progressive = this.option.progressive;
  46236. if (progressive == null) {
  46237. return this.option.large ? 1e4 : this.get('progressive');
  46238. }
  46239. return progressive;
  46240. },
  46241. getProgressiveThreshold: function () {
  46242. var progressiveThreshold = this.option.progressiveThreshold;
  46243. if (progressiveThreshold == null) {
  46244. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  46245. }
  46246. return progressiveThreshold;
  46247. },
  46248. defaultOption: {
  46249. coordinateSystem: 'geo',
  46250. zlevel: 0,
  46251. z: 2,
  46252. legendHoverLink: true,
  46253. hoverAnimation: true,
  46254. // Cartesian coordinate system
  46255. xAxisIndex: 0,
  46256. yAxisIndex: 0,
  46257. symbol: ['none', 'none'],
  46258. symbolSize: [10, 10],
  46259. // Geo coordinate system
  46260. geoIndex: 0,
  46261. effect: {
  46262. show: false,
  46263. period: 4,
  46264. // Animation delay. support callback
  46265. // delay: 0,
  46266. // If move with constant speed px/sec
  46267. // period will be ignored if this property is > 0,
  46268. constantSpeed: 0,
  46269. symbol: 'circle',
  46270. symbolSize: 3,
  46271. loop: true,
  46272. // Length of trail, 0 - 1
  46273. trailLength: 0.2
  46274. // Same with lineStyle.color
  46275. // color
  46276. },
  46277. large: false,
  46278. // Available when large is true
  46279. largeThreshold: 2000,
  46280. incremental: false,
  46281. incrementalThreshold: 3000,
  46282. // If lines are polyline
  46283. // polyline not support curveness, label, animation
  46284. polyline: false,
  46285. label: {
  46286. show: false,
  46287. position: 'end'
  46288. // distance: 5,
  46289. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  46290. },
  46291. lineStyle: {
  46292. opacity: 0.5
  46293. }
  46294. }
  46295. });
  46296. /**
  46297. * Provide effect for line
  46298. * @module echarts/chart/helper/EffectLine
  46299. */
  46300. /**
  46301. * @constructor
  46302. * @extends {module:zrender/graphic/Group}
  46303. * @alias {module:echarts/chart/helper/Line}
  46304. */
  46305. function EffectLine(lineData, idx, seriesScope) {
  46306. Group.call(this);
  46307. this.add(this.createLine(lineData, idx, seriesScope));
  46308. this._updateEffectSymbol(lineData, idx);
  46309. }
  46310. var effectLineProto = EffectLine.prototype;
  46311. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  46312. return new Line$1(lineData, idx, seriesScope);
  46313. };
  46314. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  46315. var itemModel = lineData.getItemModel(idx);
  46316. var effectModel = itemModel.getModel('effect');
  46317. var size = effectModel.get('symbolSize');
  46318. var symbolType = effectModel.get('symbol');
  46319. if (!isArray(size)) {
  46320. size = [size, size];
  46321. }
  46322. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  46323. var symbol = this.childAt(1);
  46324. if (this._symbolType !== symbolType) {
  46325. // Remove previous
  46326. this.remove(symbol);
  46327. symbol = createSymbol(
  46328. symbolType, -0.5, -0.5, 1, 1, color
  46329. );
  46330. symbol.z2 = 100;
  46331. symbol.culling = true;
  46332. this.add(symbol);
  46333. }
  46334. // Symbol may be removed if loop is false
  46335. if (!symbol) {
  46336. return;
  46337. }
  46338. // Shadow color is same with color in default
  46339. symbol.setStyle('shadowColor', color);
  46340. symbol.setStyle(effectModel.getItemStyle(['color']));
  46341. symbol.attr('scale', size);
  46342. symbol.setColor(color);
  46343. symbol.attr('scale', size);
  46344. this._symbolType = symbolType;
  46345. this._updateEffectAnimation(lineData, effectModel, idx);
  46346. };
  46347. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  46348. var symbol = this.childAt(1);
  46349. if (!symbol) {
  46350. return;
  46351. }
  46352. var self = this;
  46353. var points = lineData.getItemLayout(idx);
  46354. var period = effectModel.get('period') * 1000;
  46355. var loop = effectModel.get('loop');
  46356. var constantSpeed = effectModel.get('constantSpeed');
  46357. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  46358. return idx / lineData.count() * period / 3;
  46359. });
  46360. var isDelayFunc = typeof delayExpr === 'function';
  46361. // Ignore when updating
  46362. symbol.ignore = true;
  46363. this.updateAnimationPoints(symbol, points);
  46364. if (constantSpeed > 0) {
  46365. period = this.getLineLength(symbol) / constantSpeed * 1000;
  46366. }
  46367. if (period !== this._period || loop !== this._loop) {
  46368. symbol.stopAnimation();
  46369. var delay = delayExpr;
  46370. if (isDelayFunc) {
  46371. delay = delayExpr(idx);
  46372. }
  46373. if (symbol.__t > 0) {
  46374. delay = -period * symbol.__t;
  46375. }
  46376. symbol.__t = 0;
  46377. var animator = symbol.animate('', loop)
  46378. .when(period, {
  46379. __t: 1
  46380. })
  46381. .delay(delay)
  46382. .during(function () {
  46383. self.updateSymbolPosition(symbol);
  46384. });
  46385. if (!loop) {
  46386. animator.done(function () {
  46387. self.remove(symbol);
  46388. });
  46389. }
  46390. animator.start();
  46391. }
  46392. this._period = period;
  46393. this._loop = loop;
  46394. };
  46395. effectLineProto.getLineLength = function (symbol) {
  46396. // Not so accurate
  46397. return (dist(symbol.__p1, symbol.__cp1)
  46398. + dist(symbol.__cp1, symbol.__p2));
  46399. };
  46400. effectLineProto.updateAnimationPoints = function (symbol, points) {
  46401. symbol.__p1 = points[0];
  46402. symbol.__p2 = points[1];
  46403. symbol.__cp1 = points[2] || [
  46404. (points[0][0] + points[1][0]) / 2,
  46405. (points[0][1] + points[1][1]) / 2
  46406. ];
  46407. };
  46408. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  46409. this.childAt(0).updateData(lineData, idx, seriesScope);
  46410. this._updateEffectSymbol(lineData, idx);
  46411. };
  46412. effectLineProto.updateSymbolPosition = function (symbol) {
  46413. var p1 = symbol.__p1;
  46414. var p2 = symbol.__p2;
  46415. var cp1 = symbol.__cp1;
  46416. var t = symbol.__t;
  46417. var pos = symbol.position;
  46418. var quadraticAt$$1 = quadraticAt;
  46419. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  46420. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  46421. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  46422. // Tangent
  46423. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  46424. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  46425. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  46426. symbol.ignore = false;
  46427. };
  46428. effectLineProto.updateLayout = function (lineData, idx) {
  46429. this.childAt(0).updateLayout(lineData, idx);
  46430. var effectModel = lineData.getItemModel(idx).getModel('effect');
  46431. this._updateEffectAnimation(lineData, effectModel, idx);
  46432. };
  46433. inherits(EffectLine, Group);
  46434. /**
  46435. * @module echarts/chart/helper/Line
  46436. */
  46437. /**
  46438. * @constructor
  46439. * @extends {module:zrender/graphic/Group}
  46440. * @alias {module:echarts/chart/helper/Polyline}
  46441. */
  46442. function Polyline$2(lineData, idx, seriesScope) {
  46443. Group.call(this);
  46444. this._createPolyline(lineData, idx, seriesScope);
  46445. }
  46446. var polylineProto = Polyline$2.prototype;
  46447. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  46448. // var seriesModel = lineData.hostModel;
  46449. var points = lineData.getItemLayout(idx);
  46450. var line = new Polyline({
  46451. shape: {
  46452. points: points
  46453. }
  46454. });
  46455. this.add(line);
  46456. this._updateCommonStl(lineData, idx, seriesScope);
  46457. };
  46458. polylineProto.updateData = function (lineData, idx, seriesScope) {
  46459. var seriesModel = lineData.hostModel;
  46460. var line = this.childAt(0);
  46461. var target = {
  46462. shape: {
  46463. points: lineData.getItemLayout(idx)
  46464. }
  46465. };
  46466. updateProps(line, target, seriesModel, idx);
  46467. this._updateCommonStl(lineData, idx, seriesScope);
  46468. };
  46469. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  46470. var line = this.childAt(0);
  46471. var itemModel = lineData.getItemModel(idx);
  46472. var visualColor = lineData.getItemVisual(idx, 'color');
  46473. var lineStyle = seriesScope && seriesScope.lineStyle;
  46474. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  46475. if (!seriesScope || lineData.hasItemOption) {
  46476. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  46477. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  46478. }
  46479. line.useStyle(defaults(
  46480. {
  46481. strokeNoScale: true,
  46482. fill: 'none',
  46483. stroke: visualColor
  46484. },
  46485. lineStyle
  46486. ));
  46487. line.hoverStyle = hoverLineStyle;
  46488. setHoverStyle(this);
  46489. };
  46490. polylineProto.updateLayout = function (lineData, idx) {
  46491. var polyline = this.childAt(0);
  46492. polyline.setShape('points', lineData.getItemLayout(idx));
  46493. };
  46494. inherits(Polyline$2, Group);
  46495. /**
  46496. * Provide effect for line
  46497. * @module echarts/chart/helper/EffectLine
  46498. */
  46499. /**
  46500. * @constructor
  46501. * @extends {module:echarts/chart/helper/EffectLine}
  46502. * @alias {module:echarts/chart/helper/Polyline}
  46503. */
  46504. function EffectPolyline(lineData, idx, seriesScope) {
  46505. EffectLine.call(this, lineData, idx, seriesScope);
  46506. this._lastFrame = 0;
  46507. this._lastFramePercent = 0;
  46508. }
  46509. var effectPolylineProto = EffectPolyline.prototype;
  46510. // Overwrite
  46511. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  46512. return new Polyline$2(lineData, idx, seriesScope);
  46513. };
  46514. // Overwrite
  46515. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  46516. this._points = points;
  46517. var accLenArr = [0];
  46518. var len$$1 = 0;
  46519. for (var i = 1; i < points.length; i++) {
  46520. var p1 = points[i - 1];
  46521. var p2 = points[i];
  46522. len$$1 += dist(p1, p2);
  46523. accLenArr.push(len$$1);
  46524. }
  46525. if (len$$1 === 0) {
  46526. return;
  46527. }
  46528. for (var i = 0; i < accLenArr.length; i++) {
  46529. accLenArr[i] /= len$$1;
  46530. }
  46531. this._offsets = accLenArr;
  46532. this._length = len$$1;
  46533. };
  46534. // Overwrite
  46535. effectPolylineProto.getLineLength = function (symbol) {
  46536. return this._length;
  46537. };
  46538. // Overwrite
  46539. effectPolylineProto.updateSymbolPosition = function (symbol) {
  46540. var t = symbol.__t;
  46541. var points = this._points;
  46542. var offsets = this._offsets;
  46543. var len$$1 = points.length;
  46544. if (!offsets) {
  46545. // Has length 0
  46546. return;
  46547. }
  46548. var lastFrame = this._lastFrame;
  46549. var frame;
  46550. if (t < this._lastFramePercent) {
  46551. // Start from the next frame
  46552. // PENDING start from lastFrame ?
  46553. var start = Math.min(lastFrame + 1, len$$1 - 1);
  46554. for (frame = start; frame >= 0; frame--) {
  46555. if (offsets[frame] <= t) {
  46556. break;
  46557. }
  46558. }
  46559. // PENDING really need to do this ?
  46560. frame = Math.min(frame, len$$1 - 2);
  46561. }
  46562. else {
  46563. for (var frame = lastFrame; frame < len$$1; frame++) {
  46564. if (offsets[frame] > t) {
  46565. break;
  46566. }
  46567. }
  46568. frame = Math.min(frame - 1, len$$1 - 2);
  46569. }
  46570. lerp(
  46571. symbol.position, points[frame], points[frame + 1],
  46572. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  46573. );
  46574. var tx = points[frame + 1][0] - points[frame][0];
  46575. var ty = points[frame + 1][1] - points[frame][1];
  46576. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  46577. this._lastFrame = frame;
  46578. this._lastFramePercent = t;
  46579. symbol.ignore = false;
  46580. };
  46581. inherits(EffectPolyline, EffectLine);
  46582. // TODO Batch by color
  46583. var LargeLineShape = extendShape({
  46584. shape: {
  46585. polyline: false,
  46586. curveness: 0,
  46587. segs: []
  46588. },
  46589. buildPath: function (path, shape) {
  46590. var segs = shape.segs;
  46591. var curveness = shape.curveness;
  46592. if (shape.polyline) {
  46593. for (var i = 0; i < segs.length;) {
  46594. var count = segs[i++];
  46595. if (count > 0) {
  46596. path.moveTo(segs[i++], segs[i++]);
  46597. for (var k = 1; k < count; k++) {
  46598. path.lineTo(segs[i++], segs[i++]);
  46599. }
  46600. }
  46601. }
  46602. }
  46603. else {
  46604. for (var i = 0; i < segs.length;) {
  46605. var x0 = segs[i++];
  46606. var y0 = segs[i++];
  46607. var x1 = segs[i++];
  46608. var y1 = segs[i++];
  46609. path.moveTo(x0, y0);
  46610. if (curveness > 0) {
  46611. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  46612. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  46613. path.quadraticCurveTo(x2, y2, x1, y1);
  46614. }
  46615. else {
  46616. path.lineTo(x1, y1);
  46617. }
  46618. }
  46619. }
  46620. },
  46621. findDataIndex: function (x, y) {
  46622. var shape = this.shape;
  46623. var segs = shape.segs;
  46624. var curveness = shape.curveness;
  46625. if (shape.polyline) {
  46626. var dataIndex = 0;
  46627. for (var i = 0; i < segs.length;) {
  46628. var count = segs[i++];
  46629. if (count > 0) {
  46630. var x0 = segs[i++];
  46631. var y0 = segs[i++];
  46632. for (var k = 1; k < count; k++) {
  46633. var x1 = segs[i++];
  46634. var y1 = segs[i++];
  46635. if (containStroke$1(x0, y0, x1, y1)) {
  46636. return dataIndex;
  46637. }
  46638. }
  46639. }
  46640. dataIndex++;
  46641. }
  46642. }
  46643. else {
  46644. var dataIndex = 0;
  46645. for (var i = 0; i < segs.length;) {
  46646. var x0 = segs[i++];
  46647. var y0 = segs[i++];
  46648. var x1 = segs[i++];
  46649. var y1 = segs[i++];
  46650. if (curveness > 0) {
  46651. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  46652. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  46653. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  46654. return dataIndex;
  46655. }
  46656. }
  46657. else {
  46658. if (containStroke$1(x0, y0, x1, y1)) {
  46659. return dataIndex;
  46660. }
  46661. }
  46662. dataIndex++;
  46663. }
  46664. }
  46665. return -1;
  46666. }
  46667. });
  46668. function LargeLineDraw() {
  46669. this.group = new Group();
  46670. }
  46671. var largeLineProto = LargeLineDraw.prototype;
  46672. largeLineProto.isPersistent = function () {
  46673. return !this._incremental;
  46674. };
  46675. /**
  46676. * Update symbols draw by new data
  46677. * @param {module:echarts/data/List} data
  46678. */
  46679. largeLineProto.updateData = function (data) {
  46680. this.group.removeAll();
  46681. var lineEl = new LargeLineShape({
  46682. rectHover: true,
  46683. cursor: 'default'
  46684. });
  46685. lineEl.setShape({
  46686. segs: data.getLayout('linesPoints')
  46687. });
  46688. this._setCommon(lineEl, data);
  46689. // Add back
  46690. this.group.add(lineEl);
  46691. this._incremental = null;
  46692. };
  46693. /**
  46694. * @override
  46695. */
  46696. largeLineProto.incrementalPrepareUpdate = function (data) {
  46697. this.group.removeAll();
  46698. this._clearIncremental();
  46699. if (data.count() > 5e5) {
  46700. if (!this._incremental) {
  46701. this._incremental = new IncrementalDisplayble({
  46702. silent: true
  46703. });
  46704. }
  46705. this.group.add(this._incremental);
  46706. }
  46707. else {
  46708. this._incremental = null;
  46709. }
  46710. };
  46711. /**
  46712. * @override
  46713. */
  46714. largeLineProto.incrementalUpdate = function (taskParams, data) {
  46715. var lineEl = new LargeLineShape();
  46716. lineEl.setShape({
  46717. segs: data.getLayout('linesPoints')
  46718. });
  46719. this._setCommon(lineEl, data, !!this._incremental);
  46720. if (!this._incremental) {
  46721. lineEl.rectHover = true;
  46722. lineEl.cursor = 'default';
  46723. lineEl.__startIndex = taskParams.start;
  46724. this.group.add(lineEl);
  46725. }
  46726. else {
  46727. this._incremental.addDisplayable(lineEl, true);
  46728. }
  46729. };
  46730. /**
  46731. * @override
  46732. */
  46733. largeLineProto.remove = function () {
  46734. this._clearIncremental();
  46735. this._incremental = null;
  46736. this.group.removeAll();
  46737. };
  46738. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  46739. var hostModel = data.hostModel;
  46740. lineEl.setShape({
  46741. polyline: hostModel.get('polyline'),
  46742. curveness: hostModel.get('lineStyle.curveness')
  46743. });
  46744. lineEl.useStyle(
  46745. hostModel.getModel('lineStyle').getLineStyle()
  46746. );
  46747. lineEl.style.strokeNoScale = true;
  46748. var visualColor = data.getVisual('color');
  46749. if (visualColor) {
  46750. lineEl.setStyle('stroke', visualColor);
  46751. }
  46752. lineEl.setStyle('fill');
  46753. if (!isIncremental) {
  46754. // Enable tooltip
  46755. // PENDING May have performance issue when path is extremely large
  46756. lineEl.seriesIndex = hostModel.seriesIndex;
  46757. lineEl.on('mousemove', function (e) {
  46758. lineEl.dataIndex = null;
  46759. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  46760. if (dataIndex > 0) {
  46761. // Provide dataIndex for tooltip
  46762. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  46763. }
  46764. });
  46765. }
  46766. };
  46767. largeLineProto._clearIncremental = function () {
  46768. var incremental = this._incremental;
  46769. if (incremental) {
  46770. incremental.clearDisplaybles();
  46771. }
  46772. };
  46773. var linesLayout = {
  46774. seriesType: 'lines',
  46775. plan: createRenderPlanner(),
  46776. reset: function (seriesModel) {
  46777. var coordSys = seriesModel.coordinateSystem;
  46778. var isPolyline = seriesModel.get('polyline');
  46779. var isLarge = seriesModel.pipelineContext.large;
  46780. function progress(params, lineData) {
  46781. var lineCoords = [];
  46782. if (isLarge) {
  46783. var points;
  46784. var segCount = params.end - params.start;
  46785. if (isPolyline) {
  46786. var totalCoordsCount = 0;
  46787. for (var i = params.start; i < params.end; i++) {
  46788. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  46789. }
  46790. points = new Float32Array(segCount + totalCoordsCount * 2);
  46791. }
  46792. else {
  46793. points = new Float32Array(segCount * 2);
  46794. }
  46795. var offset = 0;
  46796. var pt = [];
  46797. for (var i = params.start; i < params.end; i++) {
  46798. var len = seriesModel.getLineCoords(i, lineCoords);
  46799. if (isPolyline) {
  46800. points[offset++] = len;
  46801. }
  46802. for (var k = 0; k < len; k++) {
  46803. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  46804. points[offset++] = pt[0];
  46805. points[offset++] = pt[1];
  46806. }
  46807. }
  46808. lineData.setLayout('linesPoints', points);
  46809. }
  46810. else {
  46811. for (var i = params.start; i < params.end; i++) {
  46812. var itemModel = lineData.getItemModel(i);
  46813. var len = seriesModel.getLineCoords(i, lineCoords);
  46814. var pts = [];
  46815. if (isPolyline) {
  46816. for (var j = 0; j < len; j++) {
  46817. pts.push(coordSys.dataToPoint(lineCoords[j]));
  46818. }
  46819. }
  46820. else {
  46821. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  46822. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  46823. var curveness = itemModel.get('lineStyle.curveness');
  46824. if (+curveness) {
  46825. pts[2] = [
  46826. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  46827. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  46828. ];
  46829. }
  46830. }
  46831. lineData.setItemLayout(i, pts);
  46832. }
  46833. }
  46834. }
  46835. return { progress: progress };
  46836. }
  46837. };
  46838. extendChartView({
  46839. type: 'lines',
  46840. init: function () {},
  46841. render: function (seriesModel, ecModel, api) {
  46842. var data = seriesModel.getData();
  46843. var lineDraw = this._updateLineDraw(data, seriesModel);
  46844. var zlevel = seriesModel.get('zlevel');
  46845. var trailLength = seriesModel.get('effect.trailLength');
  46846. var zr = api.getZr();
  46847. // Avoid the drag cause ghost shadow
  46848. // FIXME Better way ?
  46849. // SVG doesn't support
  46850. var isSvg = zr.painter.getType() === 'svg';
  46851. if (!isSvg) {
  46852. zr.painter.getLayer(zlevel).clear(true);
  46853. }
  46854. // Config layer with motion blur
  46855. if (this._lastZlevel != null && !isSvg) {
  46856. zr.configLayer(this._lastZlevel, {
  46857. motionBlur: false
  46858. });
  46859. }
  46860. if (this._showEffect(seriesModel) && trailLength) {
  46861. if (__DEV__) {
  46862. var notInIndividual = false;
  46863. ecModel.eachSeries(function (otherSeriesModel) {
  46864. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  46865. notInIndividual = true;
  46866. }
  46867. });
  46868. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  46869. }
  46870. if (!isSvg) {
  46871. zr.configLayer(zlevel, {
  46872. motionBlur: true,
  46873. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  46874. });
  46875. }
  46876. }
  46877. lineDraw.updateData(data);
  46878. this._lastZlevel = zlevel;
  46879. this._finished = true;
  46880. },
  46881. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  46882. var data = seriesModel.getData();
  46883. var lineDraw = this._updateLineDraw(data, seriesModel);
  46884. lineDraw.incrementalPrepareUpdate(data);
  46885. this._clearLayer(api);
  46886. this._finished = false;
  46887. },
  46888. incrementalRender: function (taskParams, seriesModel, ecModel) {
  46889. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  46890. this._finished = taskParams.end === seriesModel.getData().count();
  46891. },
  46892. updateTransform: function (seriesModel, ecModel, api) {
  46893. var data = seriesModel.getData();
  46894. if (!this._finished || seriesModel.pipelineContext.large) {
  46895. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  46896. return {
  46897. update: true
  46898. };
  46899. }
  46900. else {
  46901. // TODO Use same logic with ScatterView.
  46902. // Manually update layout
  46903. var res = linesLayout.reset(seriesModel);
  46904. if (res.progress) {
  46905. res.progress({ start: 0, end: data.count() }, data);
  46906. }
  46907. this._lineDraw.updateLayout();
  46908. this._clearLayer(api);
  46909. }
  46910. },
  46911. _updateLineDraw: function (data, seriesModel) {
  46912. var lineDraw = this._lineDraw;
  46913. var hasEffect = this._showEffect(seriesModel);
  46914. var isPolyline = !!seriesModel.get('polyline');
  46915. var pipelineContext = seriesModel.pipelineContext;
  46916. var isLargeDraw = pipelineContext.large;
  46917. if (__DEV__) {
  46918. if (hasEffect && isLargeDraw) {
  46919. console.warn('Large lines not support effect');
  46920. }
  46921. }
  46922. if (!lineDraw
  46923. || hasEffect !== this._hasEffet
  46924. || isPolyline !== this._isPolyline
  46925. || isLargeDraw !== this._isLargeDraw
  46926. ) {
  46927. if (lineDraw) {
  46928. lineDraw.remove();
  46929. }
  46930. lineDraw = this._lineDraw = isLargeDraw
  46931. ? new LargeLineDraw()
  46932. : new LineDraw(
  46933. isPolyline
  46934. ? (hasEffect ? EffectPolyline : Polyline$2)
  46935. : (hasEffect ? EffectLine : Line$1)
  46936. );
  46937. this._hasEffet = hasEffect;
  46938. this._isPolyline = isPolyline;
  46939. this._isLargeDraw = isLargeDraw;
  46940. this.group.removeAll();
  46941. }
  46942. this.group.add(lineDraw.group);
  46943. return lineDraw;
  46944. },
  46945. _showEffect: function (seriesModel) {
  46946. return !!seriesModel.get('effect.show');
  46947. },
  46948. _clearLayer: function (api) {
  46949. // Not use motion when dragging or zooming
  46950. var zr = api.getZr();
  46951. var isSvg = zr.painter.getType() === 'svg';
  46952. if (!isSvg && this._lastZlevel != null) {
  46953. zr.painter.getLayer(this._lastZlevel).clear(true);
  46954. }
  46955. },
  46956. remove: function (ecModel, api) {
  46957. this._lineDraw && this._lineDraw.remove();
  46958. this._lineDraw = null;
  46959. // Clear motion when lineDraw is removed
  46960. this._clearLayer(api);
  46961. },
  46962. dispose: function () {}
  46963. });
  46964. function normalize$2(a) {
  46965. if (!(a instanceof Array)) {
  46966. a = [a, a];
  46967. }
  46968. return a;
  46969. }
  46970. var opacityQuery = 'lineStyle.opacity'.split('.');
  46971. var linesVisual = {
  46972. seriesType: 'lines',
  46973. reset: function (seriesModel, ecModel, api) {
  46974. var symbolType = normalize$2(seriesModel.get('symbol'));
  46975. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  46976. var data = seriesModel.getData();
  46977. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  46978. data.setVisual('toSymbol', symbolType && symbolType[1]);
  46979. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  46980. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  46981. data.setVisual('opacity', seriesModel.get(opacityQuery));
  46982. function dataEach(data, idx) {
  46983. var itemModel = data.getItemModel(idx);
  46984. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  46985. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  46986. var opacity = itemModel.get(opacityQuery);
  46987. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  46988. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  46989. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  46990. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  46991. data.setItemVisual(idx, 'opacity', opacity);
  46992. }
  46993. return {dataEach: data.hasItemOption ? dataEach : null};
  46994. }
  46995. };
  46996. registerLayout(linesLayout);
  46997. registerVisual(linesVisual);
  46998. SeriesModel.extend({
  46999. type: 'series.heatmap',
  47000. getInitialData: function (option, ecModel) {
  47001. return createListFromArray(this.getSource(), this);
  47002. },
  47003. preventIncremental: function () {
  47004. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  47005. if (coordSysCreator && coordSysCreator.dimensions) {
  47006. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  47007. }
  47008. },
  47009. defaultOption: {
  47010. // Cartesian2D or geo
  47011. coordinateSystem: 'cartesian2d',
  47012. zlevel: 0,
  47013. z: 2,
  47014. // Cartesian coordinate system
  47015. // xAxisIndex: 0,
  47016. // yAxisIndex: 0,
  47017. // Geo coordinate system
  47018. geoIndex: 0,
  47019. blurSize: 30,
  47020. pointSize: 20,
  47021. maxOpacity: 1,
  47022. minOpacity: 0
  47023. }
  47024. });
  47025. /**
  47026. * @file defines echarts Heatmap Chart
  47027. * @author Ovilia (me@zhangwenli.com)
  47028. * Inspired by https://github.com/mourner/simpleheat
  47029. *
  47030. * @module
  47031. */
  47032. var GRADIENT_LEVELS = 256;
  47033. /**
  47034. * Heatmap Chart
  47035. *
  47036. * @class
  47037. */
  47038. function Heatmap() {
  47039. var canvas = createCanvas();
  47040. this.canvas = canvas;
  47041. this.blurSize = 30;
  47042. this.pointSize = 20;
  47043. this.maxOpacity = 1;
  47044. this.minOpacity = 0;
  47045. this._gradientPixels = {};
  47046. }
  47047. Heatmap.prototype = {
  47048. /**
  47049. * Renders Heatmap and returns the rendered canvas
  47050. * @param {Array} data array of data, each has x, y, value
  47051. * @param {number} width canvas width
  47052. * @param {number} height canvas height
  47053. */
  47054. update: function(data, width, height, normalize, colorFunc, isInRange) {
  47055. var brush = this._getBrush();
  47056. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  47057. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  47058. var r = this.pointSize + this.blurSize;
  47059. var canvas = this.canvas;
  47060. var ctx = canvas.getContext('2d');
  47061. var len = data.length;
  47062. canvas.width = width;
  47063. canvas.height = height;
  47064. for (var i = 0; i < len; ++i) {
  47065. var p = data[i];
  47066. var x = p[0];
  47067. var y = p[1];
  47068. var value = p[2];
  47069. // calculate alpha using value
  47070. var alpha = normalize(value);
  47071. // draw with the circle brush with alpha
  47072. ctx.globalAlpha = alpha;
  47073. ctx.drawImage(brush, x - r, y - r);
  47074. }
  47075. if (!canvas.width || !canvas.height) {
  47076. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  47077. // 'CanvasRenderingContext2D': The source height is 0."
  47078. return canvas;
  47079. }
  47080. // colorize the canvas using alpha value and set with gradient
  47081. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  47082. var pixels = imageData.data;
  47083. var offset = 0;
  47084. var pixelLen = pixels.length;
  47085. var minOpacity = this.minOpacity;
  47086. var maxOpacity = this.maxOpacity;
  47087. var diffOpacity = maxOpacity - minOpacity;
  47088. while(offset < pixelLen) {
  47089. var alpha = pixels[offset + 3] / 256;
  47090. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  47091. // Simple optimize to ignore the empty data
  47092. if (alpha > 0) {
  47093. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  47094. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  47095. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  47096. pixels[offset++] = gradient[gradientOffset];
  47097. pixels[offset++] = gradient[gradientOffset + 1];
  47098. pixels[offset++] = gradient[gradientOffset + 2];
  47099. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  47100. }
  47101. else {
  47102. offset += 4;
  47103. }
  47104. }
  47105. ctx.putImageData(imageData, 0, 0);
  47106. return canvas;
  47107. },
  47108. /**
  47109. * get canvas of a black circle brush used for canvas to draw later
  47110. * @private
  47111. * @returns {Object} circle brush canvas
  47112. */
  47113. _getBrush: function() {
  47114. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  47115. // set brush size
  47116. var r = this.pointSize + this.blurSize;
  47117. var d = r * 2;
  47118. brushCanvas.width = d;
  47119. brushCanvas.height = d;
  47120. var ctx = brushCanvas.getContext('2d');
  47121. ctx.clearRect(0, 0, d, d);
  47122. // in order to render shadow without the distinct circle,
  47123. // draw the distinct circle in an invisible place,
  47124. // and use shadowOffset to draw shadow in the center of the canvas
  47125. ctx.shadowOffsetX = d;
  47126. ctx.shadowBlur = this.blurSize;
  47127. // draw the shadow in black, and use alpha and shadow blur to generate
  47128. // color in color map
  47129. ctx.shadowColor = '#000';
  47130. // draw circle in the left to the canvas
  47131. ctx.beginPath();
  47132. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  47133. ctx.closePath();
  47134. ctx.fill();
  47135. return brushCanvas;
  47136. },
  47137. /**
  47138. * get gradient color map
  47139. * @private
  47140. */
  47141. _getGradient: function (data, colorFunc, state) {
  47142. var gradientPixels = this._gradientPixels;
  47143. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  47144. var color = [0, 0, 0, 0];
  47145. var off = 0;
  47146. for (var i = 0; i < 256; i++) {
  47147. colorFunc[state](i / 255, true, color);
  47148. pixelsSingleState[off++] = color[0];
  47149. pixelsSingleState[off++] = color[1];
  47150. pixelsSingleState[off++] = color[2];
  47151. pixelsSingleState[off++] = color[3];
  47152. }
  47153. return pixelsSingleState;
  47154. }
  47155. };
  47156. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  47157. var dataSpan = dataExtent[1] - dataExtent[0];
  47158. pieceList = map(pieceList, function (piece) {
  47159. return {
  47160. interval: [
  47161. (piece.interval[0] - dataExtent[0]) / dataSpan,
  47162. (piece.interval[1] - dataExtent[0]) / dataSpan
  47163. ]
  47164. };
  47165. });
  47166. var len = pieceList.length;
  47167. var lastIndex = 0;
  47168. return function (val) {
  47169. // Try to find in the location of the last found
  47170. for (var i = lastIndex; i < len; i++) {
  47171. var interval = pieceList[i].interval;
  47172. if (interval[0] <= val && val <= interval[1]) {
  47173. lastIndex = i;
  47174. break;
  47175. }
  47176. }
  47177. if (i === len) { // Not found, back interation
  47178. for (var i = lastIndex - 1; i >= 0; i--) {
  47179. var interval = pieceList[i].interval;
  47180. if (interval[0] <= val && val <= interval[1]) {
  47181. lastIndex = i;
  47182. break;
  47183. }
  47184. }
  47185. }
  47186. return i >= 0 && i < len && selected[i];
  47187. };
  47188. }
  47189. function getIsInContinuousRange(dataExtent, range) {
  47190. var dataSpan = dataExtent[1] - dataExtent[0];
  47191. range = [
  47192. (range[0] - dataExtent[0]) / dataSpan,
  47193. (range[1] - dataExtent[0]) / dataSpan
  47194. ];
  47195. return function (val) {
  47196. return val >= range[0] && val <= range[1];
  47197. };
  47198. }
  47199. function isGeoCoordSys(coordSys) {
  47200. var dimensions = coordSys.dimensions;
  47201. // Not use coorSys.type === 'geo' because coordSys maybe extended
  47202. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  47203. }
  47204. extendChartView({
  47205. type: 'heatmap',
  47206. render: function (seriesModel, ecModel, api) {
  47207. var visualMapOfThisSeries;
  47208. ecModel.eachComponent('visualMap', function (visualMap) {
  47209. visualMap.eachTargetSeries(function (targetSeries) {
  47210. if (targetSeries === seriesModel) {
  47211. visualMapOfThisSeries = visualMap;
  47212. }
  47213. });
  47214. });
  47215. if (__DEV__) {
  47216. if (!visualMapOfThisSeries) {
  47217. throw new Error('Heatmap must use with visualMap');
  47218. }
  47219. }
  47220. this.group.removeAll();
  47221. this._incrementalDisplayable = null;
  47222. var coordSys = seriesModel.coordinateSystem;
  47223. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  47224. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  47225. }
  47226. else if (isGeoCoordSys(coordSys)) {
  47227. this._renderOnGeo(
  47228. coordSys, seriesModel, visualMapOfThisSeries, api
  47229. );
  47230. }
  47231. },
  47232. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  47233. this.group.removeAll();
  47234. },
  47235. incrementalRender: function (params, seriesModel, ecModel, api) {
  47236. var coordSys = seriesModel.coordinateSystem;
  47237. if (coordSys) {
  47238. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  47239. }
  47240. },
  47241. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  47242. var coordSys = seriesModel.coordinateSystem;
  47243. var width;
  47244. var height;
  47245. if (coordSys.type === 'cartesian2d') {
  47246. var xAxis = coordSys.getAxis('x');
  47247. var yAxis = coordSys.getAxis('y');
  47248. if (__DEV__) {
  47249. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  47250. throw new Error('Heatmap on cartesian must have two category axes');
  47251. }
  47252. if (!(xAxis.onBand && yAxis.onBand)) {
  47253. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  47254. }
  47255. }
  47256. width = xAxis.getBandWidth();
  47257. height = yAxis.getBandWidth();
  47258. }
  47259. var group = this.group;
  47260. var data = seriesModel.getData();
  47261. var itemStyleQuery = 'itemStyle';
  47262. var hoverItemStyleQuery = 'emphasis.itemStyle';
  47263. var labelQuery = 'label';
  47264. var hoverLabelQuery = 'emphasis.label';
  47265. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  47266. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  47267. var labelModel = seriesModel.getModel(labelQuery);
  47268. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  47269. var coordSysType = coordSys.type;
  47270. var dataDims = coordSysType === 'cartesian2d'
  47271. ? [
  47272. data.mapDimension('x'),
  47273. data.mapDimension('y'),
  47274. data.mapDimension('value')
  47275. ]
  47276. : [
  47277. data.mapDimension('time'),
  47278. data.mapDimension('value')
  47279. ];
  47280. for (var idx = start; idx < end; idx++) {
  47281. var rect;
  47282. if (coordSysType === 'cartesian2d') {
  47283. // Ignore empty data
  47284. if (isNaN(data.get(dataDims[2], idx))) {
  47285. continue;
  47286. }
  47287. var point = coordSys.dataToPoint([
  47288. data.get(dataDims[0], idx),
  47289. data.get(dataDims[1], idx)
  47290. ]);
  47291. rect = new Rect({
  47292. shape: {
  47293. x: point[0] - width / 2,
  47294. y: point[1] - height / 2,
  47295. width: width,
  47296. height: height
  47297. },
  47298. style: {
  47299. fill: data.getItemVisual(idx, 'color'),
  47300. opacity: data.getItemVisual(idx, 'opacity')
  47301. }
  47302. });
  47303. }
  47304. else {
  47305. // Ignore empty data
  47306. if (isNaN(data.get(dataDims[1], idx))) {
  47307. continue;
  47308. }
  47309. rect = new Rect({
  47310. z2: 1,
  47311. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  47312. style: {
  47313. fill: data.getItemVisual(idx, 'color'),
  47314. opacity: data.getItemVisual(idx, 'opacity')
  47315. }
  47316. });
  47317. }
  47318. var itemModel = data.getItemModel(idx);
  47319. // Optimization for large datset
  47320. if (data.hasItemOption) {
  47321. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  47322. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  47323. labelModel = itemModel.getModel(labelQuery);
  47324. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  47325. }
  47326. var rawValue = seriesModel.getRawValue(idx);
  47327. var defaultText = '-';
  47328. if (rawValue && rawValue[2] != null) {
  47329. defaultText = rawValue[2];
  47330. }
  47331. setLabelStyle(
  47332. style, hoverStl, labelModel, hoverLabelModel,
  47333. {
  47334. labelFetcher: seriesModel,
  47335. labelDataIndex: idx,
  47336. defaultText: defaultText,
  47337. isRectText: true
  47338. }
  47339. );
  47340. rect.setStyle(style);
  47341. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  47342. rect.incremental = incremental;
  47343. // PENDING
  47344. if (incremental) {
  47345. // Rect must use hover layer if it's incremental.
  47346. rect.useHoverLayer = true;
  47347. }
  47348. group.add(rect);
  47349. data.setItemGraphicEl(idx, rect);
  47350. }
  47351. },
  47352. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  47353. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  47354. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  47355. // if (!visualMapping) {
  47356. // throw new Error('Data range must have color visuals');
  47357. // }
  47358. var data = seriesModel.getData();
  47359. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  47360. hmLayer.blurSize = seriesModel.get('blurSize');
  47361. hmLayer.pointSize = seriesModel.get('pointSize');
  47362. hmLayer.minOpacity = seriesModel.get('minOpacity');
  47363. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  47364. var rect = geo.getViewRect().clone();
  47365. var roamTransform = geo.getRoamTransform();
  47366. rect.applyTransform(roamTransform);
  47367. // Clamp on viewport
  47368. var x = Math.max(rect.x, 0);
  47369. var y = Math.max(rect.y, 0);
  47370. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  47371. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  47372. var width = x2 - x;
  47373. var height = y2 - y;
  47374. var dims = [
  47375. data.mapDimension('lng'),
  47376. data.mapDimension('lat'),
  47377. data.mapDimension('value')
  47378. ];
  47379. var points = data.mapArray(dims, function (lng, lat, value) {
  47380. var pt = geo.dataToPoint([lng, lat]);
  47381. pt[0] -= x;
  47382. pt[1] -= y;
  47383. pt.push(value);
  47384. return pt;
  47385. });
  47386. var dataExtent = visualMapModel.getExtent();
  47387. var isInRange = visualMapModel.type === 'visualMap.continuous'
  47388. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  47389. : getIsInPiecewiseRange(
  47390. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  47391. );
  47392. hmLayer.update(
  47393. points, width, height,
  47394. inRangeVisuals.color.getNormalizer(),
  47395. {
  47396. inRange: inRangeVisuals.color.getColorMapper(),
  47397. outOfRange: outOfRangeVisuals.color.getColorMapper()
  47398. },
  47399. isInRange
  47400. );
  47401. var img = new ZImage({
  47402. style: {
  47403. width: width,
  47404. height: height,
  47405. x: x,
  47406. y: y,
  47407. image: hmLayer.canvas
  47408. },
  47409. silent: true
  47410. });
  47411. this.group.add(img);
  47412. },
  47413. dispose: function () {}
  47414. });
  47415. var PictorialBarSeries = BaseBarSeries.extend({
  47416. type: 'series.pictorialBar',
  47417. dependencies: ['grid'],
  47418. defaultOption: {
  47419. symbol: 'circle', // Customized bar shape
  47420. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  47421. symbolRotate: null,
  47422. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  47423. symbolOffset: null,
  47424. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  47425. // Auto margin by defualt.
  47426. symbolRepeat: false, // false/null/undefined, means no repeat.
  47427. // Can be true, means auto calculate repeat times and cut by data.
  47428. // Can be a number, specifies repeat times, and do not cut by data.
  47429. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  47430. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  47431. symbolClip: false,
  47432. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  47433. symbolPatternSize: 400, // 400 * 400 px
  47434. barGap: '-100%', // In most case, overlap is needed.
  47435. // z can be set in data item, which is z2 actually.
  47436. // Disable progressive
  47437. progressive: 0,
  47438. hoverAnimation: false // Open only when needed.
  47439. },
  47440. getInitialData: function (option) {
  47441. // Disable stack.
  47442. option.stack = null;
  47443. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  47444. }
  47445. });
  47446. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  47447. // index: +isHorizontal
  47448. var LAYOUT_ATTRS = [
  47449. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  47450. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  47451. ];
  47452. var pathForLineWidth = new Circle();
  47453. var BarView$1 = extendChartView({
  47454. type: 'pictorialBar',
  47455. render: function (seriesModel, ecModel, api) {
  47456. var group = this.group;
  47457. var data = seriesModel.getData();
  47458. var oldData = this._data;
  47459. var cartesian = seriesModel.coordinateSystem;
  47460. var baseAxis = cartesian.getBaseAxis();
  47461. var isHorizontal = !!baseAxis.isHorizontal();
  47462. var coordSysRect = cartesian.grid.getRect();
  47463. var opt = {
  47464. ecSize: {width: api.getWidth(), height: api.getHeight()},
  47465. seriesModel: seriesModel,
  47466. coordSys: cartesian,
  47467. coordSysExtent: [
  47468. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  47469. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  47470. ],
  47471. isHorizontal: isHorizontal,
  47472. valueDim: LAYOUT_ATTRS[+isHorizontal],
  47473. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  47474. };
  47475. data.diff(oldData)
  47476. .add(function (dataIndex) {
  47477. if (!data.hasValue(dataIndex)) {
  47478. return;
  47479. }
  47480. var itemModel = getItemModel(data, dataIndex);
  47481. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  47482. var bar = createBar(data, opt, symbolMeta);
  47483. data.setItemGraphicEl(dataIndex, bar);
  47484. group.add(bar);
  47485. updateCommon$1(bar, opt, symbolMeta);
  47486. })
  47487. .update(function (newIndex, oldIndex) {
  47488. var bar = oldData.getItemGraphicEl(oldIndex);
  47489. if (!data.hasValue(newIndex)) {
  47490. group.remove(bar);
  47491. return;
  47492. }
  47493. var itemModel = getItemModel(data, newIndex);
  47494. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  47495. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  47496. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  47497. group.remove(bar);
  47498. data.setItemGraphicEl(newIndex, null);
  47499. bar = null;
  47500. }
  47501. if (bar) {
  47502. updateBar(bar, opt, symbolMeta);
  47503. }
  47504. else {
  47505. bar = createBar(data, opt, symbolMeta, true);
  47506. }
  47507. data.setItemGraphicEl(newIndex, bar);
  47508. bar.__pictorialSymbolMeta = symbolMeta;
  47509. // Add back
  47510. group.add(bar);
  47511. updateCommon$1(bar, opt, symbolMeta);
  47512. })
  47513. .remove(function (dataIndex) {
  47514. var bar = oldData.getItemGraphicEl(dataIndex);
  47515. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  47516. })
  47517. .execute();
  47518. this._data = data;
  47519. return this.group;
  47520. },
  47521. dispose: noop,
  47522. remove: function (ecModel, api) {
  47523. var group = this.group;
  47524. var data = this._data;
  47525. if (ecModel.get('animation')) {
  47526. if (data) {
  47527. data.eachItemGraphicEl(function (bar) {
  47528. removeBar(data, bar.dataIndex, ecModel, bar);
  47529. });
  47530. }
  47531. }
  47532. else {
  47533. group.removeAll();
  47534. }
  47535. }
  47536. });
  47537. // Set or calculate default value about symbol, and calculate layout info.
  47538. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  47539. var layout = data.getItemLayout(dataIndex);
  47540. var symbolRepeat = itemModel.get('symbolRepeat');
  47541. var symbolClip = itemModel.get('symbolClip');
  47542. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  47543. var symbolRotate = itemModel.get('symbolRotate');
  47544. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  47545. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  47546. var isAnimationEnabled = itemModel.isAnimationEnabled();
  47547. var symbolMeta = {
  47548. dataIndex: dataIndex,
  47549. layout: layout,
  47550. itemModel: itemModel,
  47551. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  47552. color: data.getItemVisual(dataIndex, 'color'),
  47553. symbolClip: symbolClip,
  47554. symbolRepeat: symbolRepeat,
  47555. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  47556. symbolPatternSize: symbolPatternSize,
  47557. rotation: rotation,
  47558. animationModel: isAnimationEnabled ? itemModel : null,
  47559. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  47560. z2: itemModel.getShallow('z', true) || 0
  47561. };
  47562. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  47563. prepareSymbolSize(
  47564. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  47565. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  47566. );
  47567. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  47568. var symbolSize = symbolMeta.symbolSize;
  47569. var symbolOffset = itemModel.get('symbolOffset');
  47570. if (isArray(symbolOffset)) {
  47571. symbolOffset = [
  47572. parsePercent$1(symbolOffset[0], symbolSize[0]),
  47573. parsePercent$1(symbolOffset[1], symbolSize[1])
  47574. ];
  47575. }
  47576. prepareLayoutInfo(
  47577. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  47578. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  47579. opt, symbolMeta
  47580. );
  47581. return symbolMeta;
  47582. }
  47583. // bar length can be negative.
  47584. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  47585. var valueDim = opt.valueDim;
  47586. var symbolBoundingData = itemModel.get('symbolBoundingData');
  47587. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  47588. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  47589. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  47590. var boundingLength;
  47591. if (isArray(symbolBoundingData)) {
  47592. var symbolBoundingExtent = [
  47593. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  47594. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  47595. ];
  47596. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  47597. boundingLength = symbolBoundingExtent[pxSignIdx];
  47598. }
  47599. else if (symbolBoundingData != null) {
  47600. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  47601. }
  47602. else if (symbolRepeat) {
  47603. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  47604. }
  47605. else {
  47606. boundingLength = layout[valueDim.wh];
  47607. }
  47608. output.boundingLength = boundingLength;
  47609. if (symbolRepeat) {
  47610. output.repeatCutLength = layout[valueDim.wh];
  47611. }
  47612. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  47613. }
  47614. function convertToCoordOnAxis(axis, value) {
  47615. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  47616. }
  47617. // Support ['100%', '100%']
  47618. function prepareSymbolSize(
  47619. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  47620. pxSign, symbolPatternSize, opt, output
  47621. ) {
  47622. var valueDim = opt.valueDim;
  47623. var categoryDim = opt.categoryDim;
  47624. var categorySize = Math.abs(layout[categoryDim.wh]);
  47625. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  47626. if (isArray(symbolSize)) {
  47627. symbolSize = symbolSize.slice();
  47628. }
  47629. else {
  47630. if (symbolSize == null) {
  47631. symbolSize = '100%';
  47632. }
  47633. symbolSize = [symbolSize, symbolSize];
  47634. }
  47635. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  47636. // to complicated to calculate real percent value if considering scaled lineWidth.
  47637. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  47638. // which can be tolerated in pictorial chart.
  47639. symbolSize[categoryDim.index] = parsePercent$1(
  47640. symbolSize[categoryDim.index],
  47641. categorySize
  47642. );
  47643. symbolSize[valueDim.index] = parsePercent$1(
  47644. symbolSize[valueDim.index],
  47645. symbolRepeat ? categorySize : Math.abs(boundingLength)
  47646. );
  47647. output.symbolSize = symbolSize;
  47648. // If x or y is less than zero, show reversed shape.
  47649. var symbolScale = output.symbolScale = [
  47650. symbolSize[0] / symbolPatternSize,
  47651. symbolSize[1] / symbolPatternSize
  47652. ];
  47653. // Follow convention, 'right' and 'top' is the normal scale.
  47654. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  47655. }
  47656. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  47657. // In symbols are drawn with scale, so do not need to care about the case that width
  47658. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  47659. // be calculated.
  47660. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  47661. if (valueLineWidth) {
  47662. pathForLineWidth.attr({
  47663. scale: symbolScale.slice(),
  47664. rotation: rotation
  47665. });
  47666. pathForLineWidth.updateTransform();
  47667. valueLineWidth /= pathForLineWidth.getLineScale();
  47668. valueLineWidth *= symbolScale[opt.valueDim.index];
  47669. }
  47670. output.valueLineWidth = valueLineWidth;
  47671. }
  47672. function prepareLayoutInfo(
  47673. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  47674. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  47675. ) {
  47676. var categoryDim = opt.categoryDim;
  47677. var valueDim = opt.valueDim;
  47678. var pxSign = output.pxSign;
  47679. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  47680. var pathLen = unitLength;
  47681. // Note: rotation will not effect the layout of symbols, because user may
  47682. // want symbols to rotate on its center, which should not be translated
  47683. // when rotating.
  47684. if (symbolRepeat) {
  47685. var absBoundingLength = Math.abs(boundingLength);
  47686. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  47687. var hasEndGap = false;
  47688. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  47689. hasEndGap = true;
  47690. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  47691. }
  47692. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  47693. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  47694. // When symbol margin is less than 0, margin at both ends will be subtracted
  47695. // to ensure that all of the symbols will not be overflow the given area.
  47696. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  47697. // Both final repeatTimes and final symbolMargin area calculated based on
  47698. // boundingLength.
  47699. var repeatSpecified = isNumeric(symbolRepeat);
  47700. var repeatTimes = repeatSpecified
  47701. ? symbolRepeat
  47702. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  47703. // Adjust calculate margin, to ensure each symbol is displayed
  47704. // entirely in the given layout area.
  47705. var mDiff = absBoundingLength - repeatTimes * unitLength;
  47706. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  47707. uLenWithMargin = unitLength + symbolMargin * 2;
  47708. endFix = hasEndGap ? 0 : symbolMargin * 2;
  47709. // Update repeatTimes when not all symbol will be shown.
  47710. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  47711. repeatTimes = repeatCutLength
  47712. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  47713. : 0;
  47714. }
  47715. pathLen = repeatTimes * uLenWithMargin - endFix;
  47716. output.repeatTimes = repeatTimes;
  47717. output.symbolMargin = symbolMargin;
  47718. }
  47719. var sizeFix = pxSign * (pathLen / 2);
  47720. var pathPosition = output.pathPosition = [];
  47721. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  47722. pathPosition[valueDim.index] = symbolPosition === 'start'
  47723. ? sizeFix
  47724. : symbolPosition === 'end'
  47725. ? boundingLength - sizeFix
  47726. : boundingLength / 2; // 'center'
  47727. if (symbolOffset) {
  47728. pathPosition[0] += symbolOffset[0];
  47729. pathPosition[1] += symbolOffset[1];
  47730. }
  47731. var bundlePosition = output.bundlePosition = [];
  47732. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  47733. bundlePosition[valueDim.index] = layout[valueDim.xy];
  47734. var barRectShape = output.barRectShape = extend({}, layout);
  47735. barRectShape[valueDim.wh] = pxSign * Math.max(
  47736. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  47737. );
  47738. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  47739. var clipShape = output.clipShape = {};
  47740. // Consider that symbol may be overflow layout rect.
  47741. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  47742. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  47743. clipShape[valueDim.xy] = 0;
  47744. clipShape[valueDim.wh] = layout[valueDim.wh];
  47745. }
  47746. function createPath(symbolMeta) {
  47747. var symbolPatternSize = symbolMeta.symbolPatternSize;
  47748. var path = createSymbol(
  47749. // Consider texture img, make a big size.
  47750. symbolMeta.symbolType,
  47751. -symbolPatternSize / 2,
  47752. -symbolPatternSize / 2,
  47753. symbolPatternSize,
  47754. symbolPatternSize,
  47755. symbolMeta.color
  47756. );
  47757. path.attr({
  47758. culling: true
  47759. });
  47760. path.type !== 'image' && path.setStyle({
  47761. strokeNoScale: true
  47762. });
  47763. return path;
  47764. }
  47765. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  47766. var bundle = bar.__pictorialBundle;
  47767. var symbolSize = symbolMeta.symbolSize;
  47768. var valueLineWidth = symbolMeta.valueLineWidth;
  47769. var pathPosition = symbolMeta.pathPosition;
  47770. var valueDim = opt.valueDim;
  47771. var repeatTimes = symbolMeta.repeatTimes || 0;
  47772. var index = 0;
  47773. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  47774. eachPath(bar, function (path) {
  47775. path.__pictorialAnimationIndex = index;
  47776. path.__pictorialRepeatTimes = repeatTimes;
  47777. if (index < repeatTimes) {
  47778. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  47779. }
  47780. else {
  47781. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  47782. bundle.remove(path);
  47783. });
  47784. }
  47785. updateHoverAnimation(path, symbolMeta);
  47786. index++;
  47787. });
  47788. for (; index < repeatTimes; index++) {
  47789. var path = createPath(symbolMeta);
  47790. path.__pictorialAnimationIndex = index;
  47791. path.__pictorialRepeatTimes = repeatTimes;
  47792. bundle.add(path);
  47793. var target = makeTarget(index);
  47794. updateAttr(
  47795. path,
  47796. {
  47797. position: target.position,
  47798. scale: [0, 0]
  47799. },
  47800. {
  47801. scale: target.scale,
  47802. rotation: target.rotation
  47803. },
  47804. symbolMeta,
  47805. isUpdate
  47806. );
  47807. // FIXME
  47808. // If all emphasis/normal through action.
  47809. path
  47810. .on('mouseover', onMouseOver)
  47811. .on('mouseout', onMouseOut);
  47812. updateHoverAnimation(path, symbolMeta);
  47813. }
  47814. function makeTarget(index) {
  47815. var position = pathPosition.slice();
  47816. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  47817. // Otherwise: i = index;
  47818. var pxSign = symbolMeta.pxSign;
  47819. var i = index;
  47820. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  47821. i = repeatTimes - 1 - index;
  47822. }
  47823. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  47824. return {
  47825. position: position,
  47826. scale: symbolMeta.symbolScale.slice(),
  47827. rotation: symbolMeta.rotation
  47828. };
  47829. }
  47830. function onMouseOver() {
  47831. eachPath(bar, function (path) {
  47832. path.trigger('emphasis');
  47833. });
  47834. }
  47835. function onMouseOut() {
  47836. eachPath(bar, function (path) {
  47837. path.trigger('normal');
  47838. });
  47839. }
  47840. }
  47841. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  47842. var bundle = bar.__pictorialBundle;
  47843. var mainPath = bar.__pictorialMainPath;
  47844. if (!mainPath) {
  47845. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  47846. bundle.add(mainPath);
  47847. updateAttr(
  47848. mainPath,
  47849. {
  47850. position: symbolMeta.pathPosition.slice(),
  47851. scale: [0, 0],
  47852. rotation: symbolMeta.rotation
  47853. },
  47854. {
  47855. scale: symbolMeta.symbolScale.slice()
  47856. },
  47857. symbolMeta,
  47858. isUpdate
  47859. );
  47860. mainPath
  47861. .on('mouseover', onMouseOver)
  47862. .on('mouseout', onMouseOut);
  47863. }
  47864. else {
  47865. updateAttr(
  47866. mainPath,
  47867. null,
  47868. {
  47869. position: symbolMeta.pathPosition.slice(),
  47870. scale: symbolMeta.symbolScale.slice(),
  47871. rotation: symbolMeta.rotation
  47872. },
  47873. symbolMeta,
  47874. isUpdate
  47875. );
  47876. }
  47877. updateHoverAnimation(mainPath, symbolMeta);
  47878. function onMouseOver() {
  47879. this.trigger('emphasis');
  47880. }
  47881. function onMouseOut() {
  47882. this.trigger('normal');
  47883. }
  47884. }
  47885. // bar rect is used for label.
  47886. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  47887. var rectShape = extend({}, symbolMeta.barRectShape);
  47888. var barRect = bar.__pictorialBarRect;
  47889. if (!barRect) {
  47890. barRect = bar.__pictorialBarRect = new Rect({
  47891. z2: 2,
  47892. shape: rectShape,
  47893. silent: true,
  47894. style: {
  47895. stroke: 'transparent',
  47896. fill: 'transparent',
  47897. lineWidth: 0
  47898. }
  47899. });
  47900. bar.add(barRect);
  47901. }
  47902. else {
  47903. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  47904. }
  47905. }
  47906. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  47907. // If not clip, symbol will be remove and rebuilt.
  47908. if (symbolMeta.symbolClip) {
  47909. var clipPath = bar.__pictorialClipPath;
  47910. var clipShape = extend({}, symbolMeta.clipShape);
  47911. var valueDim = opt.valueDim;
  47912. var animationModel = symbolMeta.animationModel;
  47913. var dataIndex = symbolMeta.dataIndex;
  47914. if (clipPath) {
  47915. updateProps(
  47916. clipPath, {shape: clipShape}, animationModel, dataIndex
  47917. );
  47918. }
  47919. else {
  47920. clipShape[valueDim.wh] = 0;
  47921. clipPath = new Rect({shape: clipShape});
  47922. bar.__pictorialBundle.setClipPath(clipPath);
  47923. bar.__pictorialClipPath = clipPath;
  47924. var target = {};
  47925. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  47926. graphic[isUpdate ? 'updateProps' : 'initProps'](
  47927. clipPath, {shape: target}, animationModel, dataIndex
  47928. );
  47929. }
  47930. }
  47931. }
  47932. function getItemModel(data, dataIndex) {
  47933. var itemModel = data.getItemModel(dataIndex);
  47934. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  47935. itemModel.isAnimationEnabled = isAnimationEnabled;
  47936. return itemModel;
  47937. }
  47938. function getAnimationDelayParams(path) {
  47939. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  47940. return {
  47941. index: path.__pictorialAnimationIndex,
  47942. count: path.__pictorialRepeatTimes
  47943. };
  47944. }
  47945. function isAnimationEnabled() {
  47946. // `animation` prop can be set on itemModel in pictorial bar chart.
  47947. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  47948. }
  47949. function updateHoverAnimation(path, symbolMeta) {
  47950. path.off('emphasis').off('normal');
  47951. var scale = symbolMeta.symbolScale.slice();
  47952. symbolMeta.hoverAnimation && path
  47953. .on('emphasis', function() {
  47954. this.animateTo({
  47955. scale: [scale[0] * 1.1, scale[1] * 1.1]
  47956. }, 400, 'elasticOut');
  47957. })
  47958. .on('normal', function() {
  47959. this.animateTo({
  47960. scale: scale.slice()
  47961. }, 400, 'elasticOut');
  47962. });
  47963. }
  47964. function createBar(data, opt, symbolMeta, isUpdate) {
  47965. // bar is the main element for each data.
  47966. var bar = new Group();
  47967. // bundle is used for location and clip.
  47968. var bundle = new Group();
  47969. bar.add(bundle);
  47970. bar.__pictorialBundle = bundle;
  47971. bundle.attr('position', symbolMeta.bundlePosition.slice());
  47972. if (symbolMeta.symbolRepeat) {
  47973. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  47974. }
  47975. else {
  47976. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  47977. }
  47978. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  47979. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  47980. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  47981. bar.__pictorialSymbolMeta = symbolMeta;
  47982. return bar;
  47983. }
  47984. function updateBar(bar, opt, symbolMeta) {
  47985. var animationModel = symbolMeta.animationModel;
  47986. var dataIndex = symbolMeta.dataIndex;
  47987. var bundle = bar.__pictorialBundle;
  47988. updateProps(
  47989. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  47990. );
  47991. if (symbolMeta.symbolRepeat) {
  47992. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  47993. }
  47994. else {
  47995. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  47996. }
  47997. createOrUpdateBarRect(bar, symbolMeta, true);
  47998. createOrUpdateClip(bar, opt, symbolMeta, true);
  47999. }
  48000. function removeBar(data, dataIndex, animationModel, bar) {
  48001. // Not show text when animating
  48002. var labelRect = bar.__pictorialBarRect;
  48003. labelRect && (labelRect.style.text = null);
  48004. var pathes = [];
  48005. eachPath(bar, function (path) {
  48006. pathes.push(path);
  48007. });
  48008. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  48009. // I do not find proper remove animation for clip yet.
  48010. bar.__pictorialClipPath && (animationModel = null);
  48011. each$1(pathes, function (path) {
  48012. updateProps(
  48013. path, {scale: [0, 0]}, animationModel, dataIndex,
  48014. function () {
  48015. bar.parent && bar.parent.remove(bar);
  48016. }
  48017. );
  48018. });
  48019. data.setItemGraphicEl(dataIndex, null);
  48020. }
  48021. function getShapeStr(data, symbolMeta) {
  48022. return [
  48023. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  48024. !!symbolMeta.symbolRepeat,
  48025. !!symbolMeta.symbolClip
  48026. ].join(':');
  48027. }
  48028. function eachPath(bar, cb, context) {
  48029. // Do not use Group#eachChild, because it do not support remove.
  48030. each$1(bar.__pictorialBundle.children(), function (el) {
  48031. el !== bar.__pictorialBarRect && cb.call(context, el);
  48032. });
  48033. }
  48034. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  48035. immediateAttrs && el.attr(immediateAttrs);
  48036. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  48037. if (symbolMeta.symbolClip && !isUpdate) {
  48038. animationAttrs && el.attr(animationAttrs);
  48039. }
  48040. else {
  48041. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  48042. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  48043. );
  48044. }
  48045. }
  48046. function updateCommon$1(bar, opt, symbolMeta) {
  48047. var color = symbolMeta.color;
  48048. var dataIndex = symbolMeta.dataIndex;
  48049. var itemModel = symbolMeta.itemModel;
  48050. // Color must be excluded.
  48051. // Because symbol provide setColor individually to set fill and stroke
  48052. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  48053. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  48054. var cursorStyle = itemModel.getShallow('cursor');
  48055. eachPath(bar, function (path) {
  48056. // PENDING setColor should be before setStyle!!!
  48057. path.setColor(color);
  48058. path.setStyle(defaults(
  48059. {
  48060. fill: color,
  48061. opacity: symbolMeta.opacity
  48062. },
  48063. normalStyle
  48064. ));
  48065. setHoverStyle(path, hoverStyle);
  48066. cursorStyle && (path.cursor = cursorStyle);
  48067. path.z2 = symbolMeta.z2;
  48068. });
  48069. var barRectHoverStyle = {};
  48070. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  48071. var barRect = bar.__pictorialBarRect;
  48072. setLabel(
  48073. barRect.style, barRectHoverStyle, itemModel,
  48074. color, opt.seriesModel, dataIndex, barPositionOutside
  48075. );
  48076. setHoverStyle(barRect, barRectHoverStyle);
  48077. }
  48078. function toIntTimes(times) {
  48079. var roundedTimes = Math.round(times);
  48080. // Escapse accurate error
  48081. return Math.abs(times - roundedTimes) < 1e-4
  48082. ? roundedTimes
  48083. : Math.ceil(times);
  48084. }
  48085. // In case developer forget to include grid component
  48086. registerLayout(curry(
  48087. layout, 'pictorialBar'
  48088. ));
  48089. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  48090. /**
  48091. * @constructor module:echarts/coord/single/SingleAxis
  48092. * @extends {module:echarts/coord/Axis}
  48093. * @param {string} dim
  48094. * @param {*} scale
  48095. * @param {Array.<number>} coordExtent
  48096. * @param {string} axisType
  48097. * @param {string} position
  48098. */
  48099. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  48100. Axis.call(this, dim, scale, coordExtent);
  48101. /**
  48102. * Axis type
  48103. * - 'category'
  48104. * - 'value'
  48105. * - 'time'
  48106. * - 'log'
  48107. * @type {string}
  48108. */
  48109. this.type = axisType || 'value';
  48110. /**
  48111. * Axis position
  48112. * - 'top'
  48113. * - 'bottom'
  48114. * - 'left'
  48115. * - 'right'
  48116. * @type {string}
  48117. */
  48118. this.position = position || 'bottom';
  48119. /**
  48120. * Axis orient
  48121. * - 'horizontal'
  48122. * - 'vertical'
  48123. * @type {[type]}
  48124. */
  48125. this.orient = null;
  48126. /**
  48127. * @type {number}
  48128. */
  48129. this._labelInterval = null;
  48130. };
  48131. SingleAxis.prototype = {
  48132. constructor: SingleAxis,
  48133. /**
  48134. * Axis model
  48135. * @type {module:echarts/coord/single/AxisModel}
  48136. */
  48137. model: null,
  48138. /**
  48139. * Judge the orient of the axis.
  48140. * @return {boolean}
  48141. */
  48142. isHorizontal: function () {
  48143. var position = this.position;
  48144. return position === 'top' || position === 'bottom';
  48145. },
  48146. /**
  48147. * @override
  48148. */
  48149. pointToData: function (point, clamp) {
  48150. return this.coordinateSystem.pointToData(point, clamp)[0];
  48151. },
  48152. /**
  48153. * Convert the local coord(processed by dataToCoord())
  48154. * to global coord(concrete pixel coord).
  48155. * designated by module:echarts/coord/single/Single.
  48156. * @type {Function}
  48157. */
  48158. toGlobalCoord: null,
  48159. /**
  48160. * Convert the global coord to local coord.
  48161. * designated by module:echarts/coord/single/Single.
  48162. * @type {Function}
  48163. */
  48164. toLocalCoord: null
  48165. };
  48166. inherits(SingleAxis, Axis);
  48167. /**
  48168. * Single coordinates system.
  48169. */
  48170. /**
  48171. * Create a single coordinates system.
  48172. *
  48173. * @param {module:echarts/coord/single/AxisModel} axisModel
  48174. * @param {module:echarts/model/Global} ecModel
  48175. * @param {module:echarts/ExtensionAPI} api
  48176. */
  48177. function Single(axisModel, ecModel, api) {
  48178. /**
  48179. * @type {string}
  48180. * @readOnly
  48181. */
  48182. this.dimension = 'single';
  48183. /**
  48184. * Add it just for draw tooltip.
  48185. *
  48186. * @type {Array.<string>}
  48187. * @readOnly
  48188. */
  48189. this.dimensions = ['single'];
  48190. /**
  48191. * @private
  48192. * @type {module:echarts/coord/single/SingleAxis}.
  48193. */
  48194. this._axis = null;
  48195. /**
  48196. * @private
  48197. * @type {module:zrender/core/BoundingRect}
  48198. */
  48199. this._rect;
  48200. this._init(axisModel, ecModel, api);
  48201. /**
  48202. * @type {module:echarts/coord/single/AxisModel}
  48203. */
  48204. this.model = axisModel;
  48205. }
  48206. Single.prototype = {
  48207. type: 'singleAxis',
  48208. axisPointerEnabled: true,
  48209. constructor: Single,
  48210. /**
  48211. * Initialize single coordinate system.
  48212. *
  48213. * @param {module:echarts/coord/single/AxisModel} axisModel
  48214. * @param {module:echarts/model/Global} ecModel
  48215. * @param {module:echarts/ExtensionAPI} api
  48216. * @private
  48217. */
  48218. _init: function (axisModel, ecModel, api) {
  48219. var dim = this.dimension;
  48220. var axis = new SingleAxis(
  48221. dim,
  48222. createScaleByModel(axisModel),
  48223. [0, 0],
  48224. axisModel.get('type'),
  48225. axisModel.get('position')
  48226. );
  48227. var isCategory = axis.type === 'category';
  48228. axis.onBand = isCategory && axisModel.get('boundaryGap');
  48229. axis.inverse = axisModel.get('inverse');
  48230. axis.orient = axisModel.get('orient');
  48231. axisModel.axis = axis;
  48232. axis.model = axisModel;
  48233. axis.coordinateSystem = this;
  48234. this._axis = axis;
  48235. },
  48236. /**
  48237. * Update axis scale after data processed
  48238. * @param {module:echarts/model/Global} ecModel
  48239. * @param {module:echarts/ExtensionAPI} api
  48240. */
  48241. update: function (ecModel, api) {
  48242. ecModel.eachSeries(function (seriesModel) {
  48243. if (seriesModel.coordinateSystem === this) {
  48244. var data = seriesModel.getData();
  48245. each$1(data.mapDimension(this.dimension, true), function (dim) {
  48246. this._axis.scale.unionExtentFromData(data, dim);
  48247. }, this);
  48248. niceScaleExtent(this._axis.scale, this._axis.model);
  48249. }
  48250. }, this);
  48251. },
  48252. /**
  48253. * Resize the single coordinate system.
  48254. *
  48255. * @param {module:echarts/coord/single/AxisModel} axisModel
  48256. * @param {module:echarts/ExtensionAPI} api
  48257. */
  48258. resize: function (axisModel, api) {
  48259. this._rect = getLayoutRect(
  48260. {
  48261. left: axisModel.get('left'),
  48262. top: axisModel.get('top'),
  48263. right: axisModel.get('right'),
  48264. bottom: axisModel.get('bottom'),
  48265. width: axisModel.get('width'),
  48266. height: axisModel.get('height')
  48267. },
  48268. {
  48269. width: api.getWidth(),
  48270. height: api.getHeight()
  48271. }
  48272. );
  48273. this._adjustAxis();
  48274. },
  48275. /**
  48276. * @return {module:zrender/core/BoundingRect}
  48277. */
  48278. getRect: function () {
  48279. return this._rect;
  48280. },
  48281. /**
  48282. * @private
  48283. */
  48284. _adjustAxis: function () {
  48285. var rect = this._rect;
  48286. var axis = this._axis;
  48287. var isHorizontal = axis.isHorizontal();
  48288. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  48289. var idx = axis.reverse ? 1 : 0;
  48290. axis.setExtent(extent[idx], extent[1 - idx]);
  48291. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  48292. },
  48293. /**
  48294. * @param {module:echarts/coord/single/SingleAxis} axis
  48295. * @param {number} coordBase
  48296. */
  48297. _updateAxisTransform: function (axis, coordBase) {
  48298. var axisExtent = axis.getExtent();
  48299. var extentSum = axisExtent[0] + axisExtent[1];
  48300. var isHorizontal = axis.isHorizontal();
  48301. axis.toGlobalCoord = isHorizontal
  48302. ? function (coord) {
  48303. return coord + coordBase;
  48304. }
  48305. : function (coord) {
  48306. return extentSum - coord + coordBase;
  48307. };
  48308. axis.toLocalCoord = isHorizontal
  48309. ? function (coord) {
  48310. return coord - coordBase;
  48311. }
  48312. : function (coord) {
  48313. return extentSum - coord + coordBase;
  48314. };
  48315. },
  48316. /**
  48317. * Get axis.
  48318. *
  48319. * @return {module:echarts/coord/single/SingleAxis}
  48320. */
  48321. getAxis: function () {
  48322. return this._axis;
  48323. },
  48324. /**
  48325. * Get axis, add it just for draw tooltip.
  48326. *
  48327. * @return {[type]} [description]
  48328. */
  48329. getBaseAxis: function () {
  48330. return this._axis;
  48331. },
  48332. /**
  48333. * @return {Array.<module:echarts/coord/Axis>}
  48334. */
  48335. getAxes: function () {
  48336. return [this._axis];
  48337. },
  48338. /**
  48339. * @return {Object} {baseAxes: [], otherAxes: []}
  48340. */
  48341. getTooltipAxes: function () {
  48342. return {baseAxes: [this.getAxis()]};
  48343. },
  48344. /**
  48345. * If contain point.
  48346. *
  48347. * @param {Array.<number>} point
  48348. * @return {boolean}
  48349. */
  48350. containPoint: function (point) {
  48351. var rect = this.getRect();
  48352. var axis = this.getAxis();
  48353. var orient = axis.orient;
  48354. if (orient === 'horizontal') {
  48355. return axis.contain(axis.toLocalCoord(point[0]))
  48356. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  48357. }
  48358. else {
  48359. return axis.contain(axis.toLocalCoord(point[1]))
  48360. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  48361. }
  48362. },
  48363. /**
  48364. * @param {Array.<number>} point
  48365. * @return {Array.<number>}
  48366. */
  48367. pointToData: function (point) {
  48368. var axis = this.getAxis();
  48369. return [axis.coordToData(axis.toLocalCoord(
  48370. point[axis.orient === 'horizontal' ? 0 : 1]
  48371. ))];
  48372. },
  48373. /**
  48374. * Convert the series data to concrete point.
  48375. *
  48376. * @param {number|Array.<number>} val
  48377. * @return {Array.<number>}
  48378. */
  48379. dataToPoint: function (val) {
  48380. var axis = this.getAxis();
  48381. var rect = this.getRect();
  48382. var pt = [];
  48383. var idx = axis.orient === 'horizontal' ? 0 : 1;
  48384. if (val instanceof Array) {
  48385. val = val[0];
  48386. }
  48387. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  48388. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  48389. return pt;
  48390. }
  48391. };
  48392. /**
  48393. * Single coordinate system creator.
  48394. */
  48395. /**
  48396. * Create single coordinate system and inject it into seriesModel.
  48397. *
  48398. * @param {module:echarts/model/Global} ecModel
  48399. * @param {module:echarts/ExtensionAPI} api
  48400. * @return {Array.<module:echarts/coord/single/Single>}
  48401. */
  48402. function create$3(ecModel, api) {
  48403. var singles = [];
  48404. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  48405. var single = new Single(axisModel, ecModel, api);
  48406. single.name = 'single_' + idx;
  48407. single.resize(axisModel, api);
  48408. axisModel.coordinateSystem = single;
  48409. singles.push(single);
  48410. });
  48411. ecModel.eachSeries(function (seriesModel) {
  48412. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  48413. var singleAxisModel = ecModel.queryComponents({
  48414. mainType: 'singleAxis',
  48415. index: seriesModel.get('singleAxisIndex'),
  48416. id: seriesModel.get('singleAxisId')
  48417. })[0];
  48418. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  48419. }
  48420. });
  48421. return singles;
  48422. }
  48423. CoordinateSystemManager.register('single', {
  48424. create: create$3,
  48425. dimensions: Single.prototype.dimensions
  48426. });
  48427. /**
  48428. * @param {Object} opt {labelInside}
  48429. * @return {Object} {
  48430. * position, rotation, labelDirection, labelOffset,
  48431. * tickDirection, labelRotate, labelInterval, z2
  48432. * }
  48433. */
  48434. function layout$2 (axisModel, opt) {
  48435. opt = opt || {};
  48436. var single = axisModel.coordinateSystem;
  48437. var axis = axisModel.axis;
  48438. var layout = {};
  48439. var axisPosition = axis.position;
  48440. var orient = axis.orient;
  48441. var rect = single.getRect();
  48442. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  48443. var positionMap = {
  48444. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  48445. vertical: {left: rectBound[0], right: rectBound[1]}
  48446. };
  48447. layout.position = [
  48448. orient === 'vertical'
  48449. ? positionMap.vertical[axisPosition]
  48450. : rectBound[0],
  48451. orient === 'horizontal'
  48452. ? positionMap.horizontal[axisPosition]
  48453. : rectBound[3]
  48454. ];
  48455. var r = {horizontal: 0, vertical: 1};
  48456. layout.rotation = Math.PI / 2 * r[orient];
  48457. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  48458. layout.labelDirection = layout.tickDirection
  48459. = layout.nameDirection
  48460. = directionMap[axisPosition];
  48461. if (axisModel.get('axisTick.inside')) {
  48462. layout.tickDirection = -layout.tickDirection;
  48463. }
  48464. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  48465. layout.labelDirection = -layout.labelDirection;
  48466. }
  48467. var labelRotation = opt.rotate;
  48468. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  48469. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  48470. layout.labelInterval = axis.getLabelInterval();
  48471. layout.z2 = 1;
  48472. return layout;
  48473. }
  48474. var getInterval$2 = AxisBuilder.getInterval;
  48475. var ifIgnoreOnTick$2 = AxisBuilder.ifIgnoreOnTick;
  48476. var axisBuilderAttrs$2 = [
  48477. 'axisLine', 'axisTickLabel', 'axisName'
  48478. ];
  48479. var selfBuilderAttr = 'splitLine';
  48480. var SingleAxisView = AxisView.extend({
  48481. type: 'singleAxis',
  48482. axisPointerClass: 'SingleAxisPointer',
  48483. render: function (axisModel, ecModel, api, payload) {
  48484. var group = this.group;
  48485. group.removeAll();
  48486. var layout = layout$2(axisModel);
  48487. var axisBuilder = new AxisBuilder(axisModel, layout);
  48488. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  48489. group.add(axisBuilder.getGroup());
  48490. if (axisModel.get(selfBuilderAttr + '.show')) {
  48491. this['_' + selfBuilderAttr](axisModel, layout.labelInterval);
  48492. }
  48493. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  48494. },
  48495. _splitLine: function(axisModel, labelInterval) {
  48496. var axis = axisModel.axis;
  48497. if (axis.scale.isBlank()) {
  48498. return;
  48499. }
  48500. var splitLineModel = axisModel.getModel('splitLine');
  48501. var lineStyleModel = splitLineModel.getModel('lineStyle');
  48502. var lineWidth = lineStyleModel.get('width');
  48503. var lineColors = lineStyleModel.get('color');
  48504. var lineInterval = getInterval$2(splitLineModel, labelInterval);
  48505. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  48506. var gridRect = axisModel.coordinateSystem.getRect();
  48507. var isHorizontal = axis.isHorizontal();
  48508. var splitLines = [];
  48509. var lineCount = 0;
  48510. var ticksCoords = axis.getTicksCoords();
  48511. var p1 = [];
  48512. var p2 = [];
  48513. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  48514. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  48515. for (var i = 0; i < ticksCoords.length; ++i) {
  48516. if (ifIgnoreOnTick$2(
  48517. axis, i, lineInterval, ticksCoords.length,
  48518. showMinLabel, showMaxLabel
  48519. )) {
  48520. continue;
  48521. }
  48522. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  48523. if (isHorizontal) {
  48524. p1[0] = tickCoord;
  48525. p1[1] = gridRect.y;
  48526. p2[0] = tickCoord;
  48527. p2[1] = gridRect.y + gridRect.height;
  48528. }
  48529. else {
  48530. p1[0] = gridRect.x;
  48531. p1[1] = tickCoord;
  48532. p2[0] = gridRect.x + gridRect.width;
  48533. p2[1] = tickCoord;
  48534. }
  48535. var colorIndex = (lineCount++) % lineColors.length;
  48536. splitLines[colorIndex] = splitLines[colorIndex] || [];
  48537. splitLines[colorIndex].push(new Line(
  48538. subPixelOptimizeLine({
  48539. shape: {
  48540. x1: p1[0],
  48541. y1: p1[1],
  48542. x2: p2[0],
  48543. y2: p2[1]
  48544. },
  48545. style: {
  48546. lineWidth: lineWidth
  48547. },
  48548. silent: true
  48549. })));
  48550. }
  48551. for (var i = 0; i < splitLines.length; ++i) {
  48552. this.group.add(mergePath(splitLines[i], {
  48553. style: {
  48554. stroke: lineColors[i % lineColors.length],
  48555. lineDash: lineStyleModel.getLineDash(lineWidth),
  48556. lineWidth: lineWidth
  48557. },
  48558. silent: true
  48559. }));
  48560. }
  48561. }
  48562. });
  48563. var AxisModel$4 = ComponentModel.extend({
  48564. type: 'singleAxis',
  48565. layoutMode: 'box',
  48566. /**
  48567. * @type {module:echarts/coord/single/SingleAxis}
  48568. */
  48569. axis: null,
  48570. /**
  48571. * @type {module:echarts/coord/single/Single}
  48572. */
  48573. coordinateSystem: null,
  48574. /**
  48575. * @override
  48576. */
  48577. getCoordSysModel: function () {
  48578. return this;
  48579. }
  48580. });
  48581. var defaultOption$2 = {
  48582. left: '5%',
  48583. top: '5%',
  48584. right: '5%',
  48585. bottom: '5%',
  48586. type: 'value',
  48587. position: 'bottom',
  48588. orient: 'horizontal',
  48589. axisLine: {
  48590. show: true,
  48591. lineStyle: {
  48592. width: 2,
  48593. type: 'solid'
  48594. }
  48595. },
  48596. // Single coordinate system and single axis is the,
  48597. // which is used as the parent tooltip model.
  48598. // same model, so we set default tooltip show as true.
  48599. tooltip: {
  48600. show: true
  48601. },
  48602. axisTick: {
  48603. show: true,
  48604. length: 6,
  48605. lineStyle: {
  48606. width: 2
  48607. }
  48608. },
  48609. axisLabel: {
  48610. show: true,
  48611. interval: 'auto'
  48612. },
  48613. splitLine: {
  48614. show: true,
  48615. lineStyle: {
  48616. type: 'dashed',
  48617. opacity: 0.2
  48618. }
  48619. }
  48620. };
  48621. function getAxisType$2(axisName, option) {
  48622. return option.type || (option.data ? 'category' : 'value');
  48623. }
  48624. merge(AxisModel$4.prototype, axisModelCommonMixin);
  48625. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  48626. /**
  48627. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  48628. * @param {module:echarts/model/Global} ecModel
  48629. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  48630. */
  48631. var findPointFromSeries = function (finder, ecModel) {
  48632. var point = [];
  48633. var seriesIndex = finder.seriesIndex;
  48634. var seriesModel;
  48635. if (seriesIndex == null || !(
  48636. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  48637. )) {
  48638. return {point: []};
  48639. }
  48640. var data = seriesModel.getData();
  48641. var dataIndex = queryDataIndex(data, finder);
  48642. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  48643. return {point: []};
  48644. }
  48645. var el = data.getItemGraphicEl(dataIndex);
  48646. var coordSys = seriesModel.coordinateSystem;
  48647. if (seriesModel.getTooltipPosition) {
  48648. point = seriesModel.getTooltipPosition(dataIndex) || [];
  48649. }
  48650. else if (coordSys && coordSys.dataToPoint) {
  48651. point = coordSys.dataToPoint(
  48652. data.getValues(
  48653. map(coordSys.dimensions, function (dim) {
  48654. return data.mapDimension(dim);
  48655. }), dataIndex, true
  48656. )
  48657. ) || [];
  48658. }
  48659. else if (el) {
  48660. // Use graphic bounding rect
  48661. var rect = el.getBoundingRect().clone();
  48662. rect.applyTransform(el.transform);
  48663. point = [
  48664. rect.x + rect.width / 2,
  48665. rect.y + rect.height / 2
  48666. ];
  48667. }
  48668. return {point: point, el: el};
  48669. };
  48670. var each$15 = each$1;
  48671. var curry$3 = curry;
  48672. var inner$6 = makeInner();
  48673. /**
  48674. * Basic logic: check all axis, if they do not demand show/highlight,
  48675. * then hide/downplay them.
  48676. *
  48677. * @param {Object} coordSysAxesInfo
  48678. * @param {Object} payload
  48679. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  48680. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  48681. * trigger axisPointer and tooltip.
  48682. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  48683. * trigger axisPointer and tooltip.
  48684. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  48685. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  48686. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  48687. * [{
  48688. * axisDim: 'x'|'y'|'angle'|...,
  48689. * axisIndex: ...,
  48690. * value: ...
  48691. * }, ...]
  48692. * @param {Function} [payload.dispatchAction]
  48693. * @param {Object} [payload.tooltipOption]
  48694. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  48695. * which can be specified in dispatchAction
  48696. * @param {module:echarts/model/Global} ecModel
  48697. * @param {module:echarts/ExtensionAPI} api
  48698. * @return {Object} content of event obj for echarts.connect.
  48699. */
  48700. var axisTrigger = function (payload, ecModel, api) {
  48701. var currTrigger = payload.currTrigger;
  48702. var point = [payload.x, payload.y];
  48703. var finder = payload;
  48704. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  48705. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  48706. // Pending
  48707. // See #6121. But we are not able to reproduce it yet.
  48708. if (!coordSysAxesInfo) {
  48709. return;
  48710. }
  48711. if (illegalPoint(point)) {
  48712. // Used in the default behavior of `connection`: use the sample seriesIndex
  48713. // and dataIndex. And also used in the tooltipView trigger.
  48714. point = findPointFromSeries({
  48715. seriesIndex: finder.seriesIndex,
  48716. // Do not use dataIndexInside from other ec instance.
  48717. // FIXME: auto detect it?
  48718. dataIndex: finder.dataIndex
  48719. }, ecModel).point;
  48720. }
  48721. var isIllegalPoint = illegalPoint(point);
  48722. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  48723. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  48724. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  48725. // and dataIndex.
  48726. var inputAxesInfo = finder.axesInfo;
  48727. var axesInfo = coordSysAxesInfo.axesInfo;
  48728. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  48729. var outputFinder = {};
  48730. var showValueMap = {};
  48731. var dataByCoordSys = {list: [], map: {}};
  48732. var updaters = {
  48733. showPointer: curry$3(showPointer, showValueMap),
  48734. showTooltip: curry$3(showTooltip, dataByCoordSys)
  48735. };
  48736. // Process for triggered axes.
  48737. each$15(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  48738. // If a point given, it must be contained by the coordinate system.
  48739. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  48740. each$15(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  48741. var axis = axisInfo.axis;
  48742. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  48743. // If no inputAxesInfo, no axis is restricted.
  48744. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  48745. var val = inputAxisInfo && inputAxisInfo.value;
  48746. if (val == null && !isIllegalPoint) {
  48747. val = axis.pointToData(point);
  48748. }
  48749. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  48750. }
  48751. });
  48752. });
  48753. // Process for linked axes.
  48754. var linkTriggers = {};
  48755. each$15(axesInfo, function (tarAxisInfo, tarKey) {
  48756. var linkGroup = tarAxisInfo.linkGroup;
  48757. // If axis has been triggered in the previous stage, it should not be triggered by link.
  48758. if (linkGroup && !showValueMap[tarKey]) {
  48759. each$15(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  48760. var srcValItem = showValueMap[srcKey];
  48761. // If srcValItem exist, source axis is triggered, so link to target axis.
  48762. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  48763. var val = srcValItem.value;
  48764. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  48765. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  48766. )));
  48767. linkTriggers[tarAxisInfo.key] = val;
  48768. }
  48769. });
  48770. }
  48771. });
  48772. each$15(linkTriggers, function (val, tarKey) {
  48773. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  48774. });
  48775. updateModelActually(showValueMap, axesInfo, outputFinder);
  48776. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  48777. dispatchHighDownActually(axesInfo, dispatchAction, api);
  48778. return outputFinder;
  48779. };
  48780. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  48781. var axis = axisInfo.axis;
  48782. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  48783. return;
  48784. }
  48785. if (!axisInfo.involveSeries) {
  48786. updaters.showPointer(axisInfo, newValue);
  48787. return;
  48788. }
  48789. // Heavy calculation. So put it after axis.containData checking.
  48790. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  48791. var payloadBatch = payloadInfo.payloadBatch;
  48792. var snapToValue = payloadInfo.snapToValue;
  48793. // Fill content of event obj for echarts.connect.
  48794. // By defualt use the first involved series data as a sample to connect.
  48795. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  48796. extend(outputFinder, payloadBatch[0]);
  48797. }
  48798. // If no linkSource input, this process is for collecting link
  48799. // target, where snap should not be accepted.
  48800. if (!dontSnap && axisInfo.snap) {
  48801. if (axis.containData(snapToValue) && snapToValue != null) {
  48802. newValue = snapToValue;
  48803. }
  48804. }
  48805. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  48806. // Tooltip should always be snapToValue, otherwise there will be
  48807. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  48808. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  48809. }
  48810. function buildPayloadsBySeries(value, axisInfo) {
  48811. var axis = axisInfo.axis;
  48812. var dim = axis.dim;
  48813. var snapToValue = value;
  48814. var payloadBatch = [];
  48815. var minDist = Number.MAX_VALUE;
  48816. var minDiff = -1;
  48817. each$15(axisInfo.seriesModels, function (series, idx) {
  48818. var dataDim = series.getData().mapDimension(dim, true);
  48819. var seriesNestestValue;
  48820. var dataIndices;
  48821. if (series.getAxisTooltipData) {
  48822. var result = series.getAxisTooltipData(dataDim, value, axis);
  48823. dataIndices = result.dataIndices;
  48824. seriesNestestValue = result.nestestValue;
  48825. }
  48826. else {
  48827. dataIndices = series.getData().indicesOfNearest(
  48828. dataDim[0],
  48829. value,
  48830. // Add a threshold to avoid find the wrong dataIndex
  48831. // when data length is not same.
  48832. false, axis.type === 'category' ? 0.5 : null
  48833. );
  48834. if (!dataIndices.length) {
  48835. return;
  48836. }
  48837. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  48838. }
  48839. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  48840. return;
  48841. }
  48842. var diff = value - seriesNestestValue;
  48843. var dist = Math.abs(diff);
  48844. // Consider category case
  48845. if (dist <= minDist) {
  48846. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  48847. minDist = dist;
  48848. minDiff = diff;
  48849. snapToValue = seriesNestestValue;
  48850. payloadBatch.length = 0;
  48851. }
  48852. each$15(dataIndices, function (dataIndex) {
  48853. payloadBatch.push({
  48854. seriesIndex: series.seriesIndex,
  48855. dataIndexInside: dataIndex,
  48856. dataIndex: series.getData().getRawIndex(dataIndex)
  48857. });
  48858. });
  48859. }
  48860. });
  48861. return {
  48862. payloadBatch: payloadBatch,
  48863. snapToValue: snapToValue
  48864. };
  48865. }
  48866. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  48867. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  48868. }
  48869. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  48870. var payloadBatch = payloadInfo.payloadBatch;
  48871. var axis = axisInfo.axis;
  48872. var axisModel = axis.model;
  48873. var axisPointerModel = axisInfo.axisPointerModel;
  48874. // If no data, do not create anything in dataByCoordSys,
  48875. // whose length will be used to judge whether dispatch action.
  48876. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  48877. return;
  48878. }
  48879. var coordSysModel = axisInfo.coordSys.model;
  48880. var coordSysKey = makeKey(coordSysModel);
  48881. var coordSysItem = dataByCoordSys.map[coordSysKey];
  48882. if (!coordSysItem) {
  48883. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  48884. coordSysId: coordSysModel.id,
  48885. coordSysIndex: coordSysModel.componentIndex,
  48886. coordSysType: coordSysModel.type,
  48887. coordSysMainType: coordSysModel.mainType,
  48888. dataByAxis: []
  48889. };
  48890. dataByCoordSys.list.push(coordSysItem);
  48891. }
  48892. coordSysItem.dataByAxis.push({
  48893. axisDim: axis.dim,
  48894. axisIndex: axisModel.componentIndex,
  48895. axisType: axisModel.type,
  48896. axisId: axisModel.id,
  48897. value: value,
  48898. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  48899. // depends that all models have been updated. So it should not be performed
  48900. // here. Considering axisPointerModel used here is volatile, which is hard
  48901. // to be retrieve in TooltipView, we prepare parameters here.
  48902. valueLabelOpt: {
  48903. precision: axisPointerModel.get('label.precision'),
  48904. formatter: axisPointerModel.get('label.formatter')
  48905. },
  48906. seriesDataIndices: payloadBatch.slice()
  48907. });
  48908. }
  48909. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  48910. var outputAxesInfo = outputFinder.axesInfo = [];
  48911. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  48912. each$15(axesInfo, function (axisInfo, key) {
  48913. var option = axisInfo.axisPointerModel.option;
  48914. var valItem = showValueMap[key];
  48915. if (valItem) {
  48916. !axisInfo.useHandle && (option.status = 'show');
  48917. option.value = valItem.value;
  48918. // For label formatter param and highlight.
  48919. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  48920. }
  48921. // When always show (e.g., handle used), remain
  48922. // original value and status.
  48923. else {
  48924. // If hide, value still need to be set, consider
  48925. // click legend to toggle axis blank.
  48926. !axisInfo.useHandle && (option.status = 'hide');
  48927. }
  48928. // If status is 'hide', should be no info in payload.
  48929. option.status === 'show' && outputAxesInfo.push({
  48930. axisDim: axisInfo.axis.dim,
  48931. axisIndex: axisInfo.axis.model.componentIndex,
  48932. value: option.value
  48933. });
  48934. });
  48935. }
  48936. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  48937. // Basic logic: If no showTip required, hideTip will be dispatched.
  48938. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  48939. dispatchAction({type: 'hideTip'});
  48940. return;
  48941. }
  48942. // In most case only one axis (or event one series is used). It is
  48943. // convinient to fetch payload.seriesIndex and payload.dataIndex
  48944. // dirtectly. So put the first seriesIndex and dataIndex of the first
  48945. // axis on the payload.
  48946. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  48947. dispatchAction({
  48948. type: 'showTip',
  48949. escapeConnect: true,
  48950. x: point[0],
  48951. y: point[1],
  48952. tooltipOption: payload.tooltipOption,
  48953. position: payload.position,
  48954. dataIndexInside: sampleItem.dataIndexInside,
  48955. dataIndex: sampleItem.dataIndex,
  48956. seriesIndex: sampleItem.seriesIndex,
  48957. dataByCoordSys: dataByCoordSys.list
  48958. });
  48959. }
  48960. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  48961. // FIXME
  48962. // highlight status modification shoule be a stage of main process?
  48963. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  48964. var zr = api.getZr();
  48965. var highDownKey = 'axisPointerLastHighlights';
  48966. var lastHighlights = inner$6(zr)[highDownKey] || {};
  48967. var newHighlights = inner$6(zr)[highDownKey] = {};
  48968. // Update highlight/downplay status according to axisPointer model.
  48969. // Build hash map and remove duplicate incidentally.
  48970. each$15(axesInfo, function (axisInfo, key) {
  48971. var option = axisInfo.axisPointerModel.option;
  48972. option.status === 'show' && each$15(option.seriesDataIndices, function (batchItem) {
  48973. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  48974. newHighlights[key] = batchItem;
  48975. });
  48976. });
  48977. // Diff.
  48978. var toHighlight = [];
  48979. var toDownplay = [];
  48980. each$1(lastHighlights, function (batchItem, key) {
  48981. !newHighlights[key] && toDownplay.push(batchItem);
  48982. });
  48983. each$1(newHighlights, function (batchItem, key) {
  48984. !lastHighlights[key] && toHighlight.push(batchItem);
  48985. });
  48986. toDownplay.length && api.dispatchAction({
  48987. type: 'downplay', escapeConnect: true, batch: toDownplay
  48988. });
  48989. toHighlight.length && api.dispatchAction({
  48990. type: 'highlight', escapeConnect: true, batch: toHighlight
  48991. });
  48992. }
  48993. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  48994. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  48995. var inputAxisInfo = inputAxesInfo[i];
  48996. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  48997. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  48998. ) {
  48999. return inputAxisInfo;
  49000. }
  49001. }
  49002. }
  49003. function makeMapperParam(axisInfo) {
  49004. var axisModel = axisInfo.axis.model;
  49005. var item = {};
  49006. var dim = item.axisDim = axisInfo.axis.dim;
  49007. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  49008. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  49009. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  49010. return item;
  49011. }
  49012. function illegalPoint(point) {
  49013. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  49014. }
  49015. var AxisPointerModel = extendComponentModel({
  49016. type: 'axisPointer',
  49017. coordSysAxesInfo: null,
  49018. defaultOption: {
  49019. // 'auto' means that show when triggered by tooltip or handle.
  49020. show: 'auto',
  49021. // 'click' | 'mousemove' | 'none'
  49022. triggerOn: null, // set default in AxisPonterView.js
  49023. zlevel: 0,
  49024. z: 50,
  49025. type: 'line',
  49026. // axispointer triggered by tootip determine snap automatically,
  49027. // see `modelHelper`.
  49028. snap: false,
  49029. triggerTooltip: true,
  49030. value: null,
  49031. status: null, // Init value depends on whether handle is used.
  49032. // [group0, group1, ...]
  49033. // Each group can be: {
  49034. // mapper: function () {},
  49035. // singleTooltip: 'multiple', // 'multiple' or 'single'
  49036. // xAxisId: ...,
  49037. // yAxisName: ...,
  49038. // angleAxisIndex: ...
  49039. // }
  49040. // mapper: can be ignored.
  49041. // input: {axisInfo, value}
  49042. // output: {axisInfo, value}
  49043. link: [],
  49044. // Do not set 'auto' here, otherwise global animation: false
  49045. // will not effect at this axispointer.
  49046. animation: null,
  49047. animationDurationUpdate: 200,
  49048. lineStyle: {
  49049. color: '#aaa',
  49050. width: 1,
  49051. type: 'solid'
  49052. },
  49053. shadowStyle: {
  49054. color: 'rgba(150,150,150,0.3)'
  49055. },
  49056. label: {
  49057. show: true,
  49058. formatter: null, // string | Function
  49059. precision: 'auto', // Or a number like 0, 1, 2 ...
  49060. margin: 3,
  49061. color: '#fff',
  49062. padding: [5, 7, 5, 7],
  49063. backgroundColor: 'auto', // default: axis line color
  49064. borderColor: null,
  49065. borderWidth: 0,
  49066. shadowBlur: 3,
  49067. shadowColor: '#aaa'
  49068. // Considering applicability, common style should
  49069. // better not have shadowOffset.
  49070. // shadowOffsetX: 0,
  49071. // shadowOffsetY: 2
  49072. },
  49073. handle: {
  49074. show: false,
  49075. 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', // jshint ignore:line
  49076. size: 45,
  49077. // handle margin is from symbol center to axis, which is stable when circular move.
  49078. margin: 50,
  49079. // color: '#1b8bbd'
  49080. // color: '#2f4554'
  49081. color: '#333',
  49082. shadowBlur: 3,
  49083. shadowColor: '#aaa',
  49084. shadowOffsetX: 0,
  49085. shadowOffsetY: 2,
  49086. // For mobile performance
  49087. throttle: 40
  49088. }
  49089. }
  49090. });
  49091. var inner$7 = makeInner();
  49092. var each$16 = each$1;
  49093. /**
  49094. * @param {string} key
  49095. * @param {module:echarts/ExtensionAPI} api
  49096. * @param {Function} handler
  49097. * param: {string} currTrigger
  49098. * param: {Array.<number>} point
  49099. */
  49100. function register(key, api, handler) {
  49101. if (env$1.node) {
  49102. return;
  49103. }
  49104. var zr = api.getZr();
  49105. inner$7(zr).records || (inner$7(zr).records = {});
  49106. initGlobalListeners(zr, api);
  49107. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  49108. record.handler = handler;
  49109. }
  49110. function initGlobalListeners(zr, api) {
  49111. if (inner$7(zr).initialized) {
  49112. return;
  49113. }
  49114. inner$7(zr).initialized = true;
  49115. useHandler('click', curry(doEnter, 'click'));
  49116. useHandler('mousemove', curry(doEnter, 'mousemove'));
  49117. // useHandler('mouseout', onLeave);
  49118. useHandler('globalout', onLeave);
  49119. function useHandler(eventType, cb) {
  49120. zr.on(eventType, function (e) {
  49121. var dis = makeDispatchAction(api);
  49122. each$16(inner$7(zr).records, function (record) {
  49123. record && cb(record, e, dis.dispatchAction);
  49124. });
  49125. dispatchTooltipFinally(dis.pendings, api);
  49126. });
  49127. }
  49128. }
  49129. function dispatchTooltipFinally(pendings, api) {
  49130. var showLen = pendings.showTip.length;
  49131. var hideLen = pendings.hideTip.length;
  49132. var actuallyPayload;
  49133. if (showLen) {
  49134. actuallyPayload = pendings.showTip[showLen - 1];
  49135. }
  49136. else if (hideLen) {
  49137. actuallyPayload = pendings.hideTip[hideLen - 1];
  49138. }
  49139. if (actuallyPayload) {
  49140. actuallyPayload.dispatchAction = null;
  49141. api.dispatchAction(actuallyPayload);
  49142. }
  49143. }
  49144. function onLeave(record, e, dispatchAction) {
  49145. record.handler('leave', null, dispatchAction);
  49146. }
  49147. function doEnter(currTrigger, record, e, dispatchAction) {
  49148. record.handler(currTrigger, e, dispatchAction);
  49149. }
  49150. function makeDispatchAction(api) {
  49151. var pendings = {
  49152. showTip: [],
  49153. hideTip: []
  49154. };
  49155. // FIXME
  49156. // better approach?
  49157. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  49158. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  49159. // So we have to add "final stage" to merge those dispatched actions.
  49160. var dispatchAction = function (payload) {
  49161. var pendingList = pendings[payload.type];
  49162. if (pendingList) {
  49163. pendingList.push(payload);
  49164. }
  49165. else {
  49166. payload.dispatchAction = dispatchAction;
  49167. api.dispatchAction(payload);
  49168. }
  49169. };
  49170. return {
  49171. dispatchAction: dispatchAction,
  49172. pendings: pendings
  49173. };
  49174. }
  49175. /**
  49176. * @param {string} key
  49177. * @param {module:echarts/ExtensionAPI} api
  49178. */
  49179. function unregister(key, api) {
  49180. if (env$1.node) {
  49181. return;
  49182. }
  49183. var zr = api.getZr();
  49184. var record = (inner$7(zr).records || {})[key];
  49185. if (record) {
  49186. inner$7(zr).records[key] = null;
  49187. }
  49188. }
  49189. var AxisPointerView = extendComponentView({
  49190. type: 'axisPointer',
  49191. render: function (globalAxisPointerModel, ecModel, api) {
  49192. var globalTooltipModel = ecModel.getComponent('tooltip');
  49193. var triggerOn = globalAxisPointerModel.get('triggerOn')
  49194. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  49195. // Register global listener in AxisPointerView to enable
  49196. // AxisPointerView to be independent to Tooltip.
  49197. register(
  49198. 'axisPointer',
  49199. api,
  49200. function (currTrigger, e, dispatchAction) {
  49201. // If 'none', it is not controlled by mouse totally.
  49202. if (triggerOn !== 'none'
  49203. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  49204. ) {
  49205. dispatchAction({
  49206. type: 'updateAxisPointer',
  49207. currTrigger: currTrigger,
  49208. x: e && e.offsetX,
  49209. y: e && e.offsetY
  49210. });
  49211. }
  49212. }
  49213. );
  49214. },
  49215. /**
  49216. * @override
  49217. */
  49218. remove: function (ecModel, api) {
  49219. unregister(api.getZr(), 'axisPointer');
  49220. AxisPointerView.superApply(this._model, 'remove', arguments);
  49221. },
  49222. /**
  49223. * @override
  49224. */
  49225. dispose: function (ecModel, api) {
  49226. unregister('axisPointer', api);
  49227. AxisPointerView.superApply(this._model, 'dispose', arguments);
  49228. }
  49229. });
  49230. var inner$8 = makeInner();
  49231. var clone$4 = clone;
  49232. var bind$2 = bind;
  49233. /**
  49234. * Base axis pointer class in 2D.
  49235. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  49236. */
  49237. function BaseAxisPointer () {
  49238. }
  49239. BaseAxisPointer.prototype = {
  49240. /**
  49241. * @private
  49242. */
  49243. _group: null,
  49244. /**
  49245. * @private
  49246. */
  49247. _lastGraphicKey: null,
  49248. /**
  49249. * @private
  49250. */
  49251. _handle: null,
  49252. /**
  49253. * @private
  49254. */
  49255. _dragging: false,
  49256. /**
  49257. * @private
  49258. */
  49259. _lastValue: null,
  49260. /**
  49261. * @private
  49262. */
  49263. _lastStatus: null,
  49264. /**
  49265. * @private
  49266. */
  49267. _payloadInfo: null,
  49268. /**
  49269. * In px, arbitrary value. Do not set too small,
  49270. * no animation is ok for most cases.
  49271. * @protected
  49272. */
  49273. animationThreshold: 15,
  49274. /**
  49275. * @implement
  49276. */
  49277. render: function (axisModel, axisPointerModel, api, forceRender) {
  49278. var value = axisPointerModel.get('value');
  49279. var status = axisPointerModel.get('status');
  49280. // Bind them to `this`, not in closure, otherwise they will not
  49281. // be replaced when user calling setOption in not merge mode.
  49282. this._axisModel = axisModel;
  49283. this._axisPointerModel = axisPointerModel;
  49284. this._api = api;
  49285. // Optimize: `render` will be called repeatly during mouse move.
  49286. // So it is power consuming if performing `render` each time,
  49287. // especially on mobile device.
  49288. if (!forceRender
  49289. && this._lastValue === value
  49290. && this._lastStatus === status
  49291. ) {
  49292. return;
  49293. }
  49294. this._lastValue = value;
  49295. this._lastStatus = status;
  49296. var group = this._group;
  49297. var handle = this._handle;
  49298. if (!status || status === 'hide') {
  49299. // Do not clear here, for animation better.
  49300. group && group.hide();
  49301. handle && handle.hide();
  49302. return;
  49303. }
  49304. group && group.show();
  49305. handle && handle.show();
  49306. // Otherwise status is 'show'
  49307. var elOption = {};
  49308. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  49309. // Enable change axis pointer type.
  49310. var graphicKey = elOption.graphicKey;
  49311. if (graphicKey !== this._lastGraphicKey) {
  49312. this.clear(api);
  49313. }
  49314. this._lastGraphicKey = graphicKey;
  49315. var moveAnimation = this._moveAnimation =
  49316. this.determineAnimation(axisModel, axisPointerModel);
  49317. if (!group) {
  49318. group = this._group = new Group();
  49319. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  49320. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  49321. api.getZr().add(group);
  49322. }
  49323. else {
  49324. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  49325. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  49326. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  49327. }
  49328. updateMandatoryProps(group, axisPointerModel, true);
  49329. this._renderHandle(value);
  49330. },
  49331. /**
  49332. * @implement
  49333. */
  49334. remove: function (api) {
  49335. this.clear(api);
  49336. },
  49337. /**
  49338. * @implement
  49339. */
  49340. dispose: function (api) {
  49341. this.clear(api);
  49342. },
  49343. /**
  49344. * @protected
  49345. */
  49346. determineAnimation: function (axisModel, axisPointerModel) {
  49347. var animation = axisPointerModel.get('animation');
  49348. var axis = axisModel.axis;
  49349. var isCategoryAxis = axis.type === 'category';
  49350. var useSnap = axisPointerModel.get('snap');
  49351. // Value axis without snap always do not snap.
  49352. if (!useSnap && !isCategoryAxis) {
  49353. return false;
  49354. }
  49355. if (animation === 'auto' || animation == null) {
  49356. var animationThreshold = this.animationThreshold;
  49357. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  49358. return true;
  49359. }
  49360. // It is important to auto animation when snap used. Consider if there is
  49361. // a dataZoom, animation will be disabled when too many points exist, while
  49362. // it will be enabled for better visual effect when little points exist.
  49363. if (useSnap) {
  49364. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  49365. var axisExtent = axis.getExtent();
  49366. // Approximate band width
  49367. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  49368. }
  49369. return false;
  49370. }
  49371. return animation === true;
  49372. },
  49373. /**
  49374. * add {pointer, label, graphicKey} to elOption
  49375. * @protected
  49376. */
  49377. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  49378. // Shoule be implemenented by sub-class.
  49379. },
  49380. /**
  49381. * @protected
  49382. */
  49383. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  49384. var pointerOption = elOption.pointer;
  49385. if (pointerOption) {
  49386. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  49387. clone$4(elOption.pointer)
  49388. );
  49389. group.add(pointerEl);
  49390. }
  49391. },
  49392. /**
  49393. * @protected
  49394. */
  49395. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  49396. if (elOption.label) {
  49397. var labelEl = inner$8(group).labelEl = new Rect(
  49398. clone$4(elOption.label)
  49399. );
  49400. group.add(labelEl);
  49401. updateLabelShowHide(labelEl, axisPointerModel);
  49402. }
  49403. },
  49404. /**
  49405. * @protected
  49406. */
  49407. updatePointerEl: function (group, elOption, updateProps$$1) {
  49408. var pointerEl = inner$8(group).pointerEl;
  49409. if (pointerEl) {
  49410. pointerEl.setStyle(elOption.pointer.style);
  49411. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  49412. }
  49413. },
  49414. /**
  49415. * @protected
  49416. */
  49417. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  49418. var labelEl = inner$8(group).labelEl;
  49419. if (labelEl) {
  49420. labelEl.setStyle(elOption.label.style);
  49421. updateProps$$1(labelEl, {
  49422. // Consider text length change in vertical axis, animation should
  49423. // be used on shape, otherwise the effect will be weird.
  49424. shape: elOption.label.shape,
  49425. position: elOption.label.position
  49426. });
  49427. updateLabelShowHide(labelEl, axisPointerModel);
  49428. }
  49429. },
  49430. /**
  49431. * @private
  49432. */
  49433. _renderHandle: function (value) {
  49434. if (this._dragging || !this.updateHandleTransform) {
  49435. return;
  49436. }
  49437. var axisPointerModel = this._axisPointerModel;
  49438. var zr = this._api.getZr();
  49439. var handle = this._handle;
  49440. var handleModel = axisPointerModel.getModel('handle');
  49441. var status = axisPointerModel.get('status');
  49442. if (!handleModel.get('show') || !status || status === 'hide') {
  49443. handle && zr.remove(handle);
  49444. this._handle = null;
  49445. return;
  49446. }
  49447. var isInit;
  49448. if (!this._handle) {
  49449. isInit = true;
  49450. handle = this._handle = createIcon(
  49451. handleModel.get('icon'),
  49452. {
  49453. cursor: 'move',
  49454. draggable: true,
  49455. onmousemove: function (e) {
  49456. // Fot mobile devicem, prevent screen slider on the button.
  49457. stop(e.event);
  49458. },
  49459. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  49460. drift: bind$2(this._onHandleDragMove, this),
  49461. ondragend: bind$2(this._onHandleDragEnd, this)
  49462. }
  49463. );
  49464. zr.add(handle);
  49465. }
  49466. updateMandatoryProps(handle, axisPointerModel, false);
  49467. // update style
  49468. var includeStyles = [
  49469. 'color', 'borderColor', 'borderWidth', 'opacity',
  49470. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  49471. ];
  49472. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  49473. // update position
  49474. var handleSize = handleModel.get('size');
  49475. if (!isArray(handleSize)) {
  49476. handleSize = [handleSize, handleSize];
  49477. }
  49478. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  49479. createOrUpdate(
  49480. this,
  49481. '_doDispatchAxisPointer',
  49482. handleModel.get('throttle') || 0,
  49483. 'fixRate'
  49484. );
  49485. this._moveHandleToValue(value, isInit);
  49486. },
  49487. /**
  49488. * @private
  49489. */
  49490. _moveHandleToValue: function (value, isInit) {
  49491. updateProps$1(
  49492. this._axisPointerModel,
  49493. !isInit && this._moveAnimation,
  49494. this._handle,
  49495. getHandleTransProps(this.getHandleTransform(
  49496. value, this._axisModel, this._axisPointerModel
  49497. ))
  49498. );
  49499. },
  49500. /**
  49501. * @private
  49502. */
  49503. _onHandleDragMove: function (dx, dy) {
  49504. var handle = this._handle;
  49505. if (!handle) {
  49506. return;
  49507. }
  49508. this._dragging = true;
  49509. // Persistent for throttle.
  49510. var trans = this.updateHandleTransform(
  49511. getHandleTransProps(handle),
  49512. [dx, dy],
  49513. this._axisModel,
  49514. this._axisPointerModel
  49515. );
  49516. this._payloadInfo = trans;
  49517. handle.stopAnimation();
  49518. handle.attr(getHandleTransProps(trans));
  49519. inner$8(handle).lastProp = null;
  49520. this._doDispatchAxisPointer();
  49521. },
  49522. /**
  49523. * Throttled method.
  49524. * @private
  49525. */
  49526. _doDispatchAxisPointer: function () {
  49527. var handle = this._handle;
  49528. if (!handle) {
  49529. return;
  49530. }
  49531. var payloadInfo = this._payloadInfo;
  49532. var axisModel = this._axisModel;
  49533. this._api.dispatchAction({
  49534. type: 'updateAxisPointer',
  49535. x: payloadInfo.cursorPoint[0],
  49536. y: payloadInfo.cursorPoint[1],
  49537. tooltipOption: payloadInfo.tooltipOption,
  49538. axesInfo: [{
  49539. axisDim: axisModel.axis.dim,
  49540. axisIndex: axisModel.componentIndex
  49541. }]
  49542. });
  49543. },
  49544. /**
  49545. * @private
  49546. */
  49547. _onHandleDragEnd: function (moveAnimation) {
  49548. this._dragging = false;
  49549. var handle = this._handle;
  49550. if (!handle) {
  49551. return;
  49552. }
  49553. var value = this._axisPointerModel.get('value');
  49554. // Consider snap or categroy axis, handle may be not consistent with
  49555. // axisPointer. So move handle to align the exact value position when
  49556. // drag ended.
  49557. this._moveHandleToValue(value);
  49558. // For the effect: tooltip will be shown when finger holding on handle
  49559. // button, and will be hidden after finger left handle button.
  49560. this._api.dispatchAction({
  49561. type: 'hideTip'
  49562. });
  49563. },
  49564. /**
  49565. * Should be implemenented by sub-class if support `handle`.
  49566. * @protected
  49567. * @param {number} value
  49568. * @param {module:echarts/model/Model} axisModel
  49569. * @param {module:echarts/model/Model} axisPointerModel
  49570. * @return {Object} {position: [x, y], rotation: 0}
  49571. */
  49572. getHandleTransform: null,
  49573. /**
  49574. * * Should be implemenented by sub-class if support `handle`.
  49575. * @protected
  49576. * @param {Object} transform {position, rotation}
  49577. * @param {Array.<number>} delta [dx, dy]
  49578. * @param {module:echarts/model/Model} axisModel
  49579. * @param {module:echarts/model/Model} axisPointerModel
  49580. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  49581. */
  49582. updateHandleTransform: null,
  49583. /**
  49584. * @private
  49585. */
  49586. clear: function (api) {
  49587. this._lastValue = null;
  49588. this._lastStatus = null;
  49589. var zr = api.getZr();
  49590. var group = this._group;
  49591. var handle = this._handle;
  49592. if (zr && group) {
  49593. this._lastGraphicKey = null;
  49594. group && zr.remove(group);
  49595. handle && zr.remove(handle);
  49596. this._group = null;
  49597. this._handle = null;
  49598. this._payloadInfo = null;
  49599. }
  49600. },
  49601. /**
  49602. * @protected
  49603. */
  49604. doClear: function () {
  49605. // Implemented by sub-class if necessary.
  49606. },
  49607. /**
  49608. * @protected
  49609. * @param {Array.<number>} xy
  49610. * @param {Array.<number>} wh
  49611. * @param {number} [xDimIndex=0] or 1
  49612. */
  49613. buildLabel: function (xy, wh, xDimIndex) {
  49614. xDimIndex = xDimIndex || 0;
  49615. return {
  49616. x: xy[xDimIndex],
  49617. y: xy[1 - xDimIndex],
  49618. width: wh[xDimIndex],
  49619. height: wh[1 - xDimIndex]
  49620. };
  49621. }
  49622. };
  49623. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  49624. function updateProps$1(animationModel, moveAnimation, el, props) {
  49625. // Animation optimize.
  49626. if (!propsEqual(inner$8(el).lastProp, props)) {
  49627. inner$8(el).lastProp = props;
  49628. moveAnimation
  49629. ? updateProps(el, props, animationModel)
  49630. : (el.stopAnimation(), el.attr(props));
  49631. }
  49632. }
  49633. function propsEqual(lastProps, newProps) {
  49634. if (isObject$1(lastProps) && isObject$1(newProps)) {
  49635. var equals = true;
  49636. each$1(newProps, function (item, key) {
  49637. equals = equals && propsEqual(lastProps[key], item);
  49638. });
  49639. return !!equals;
  49640. }
  49641. else {
  49642. return lastProps === newProps;
  49643. }
  49644. }
  49645. function updateLabelShowHide(labelEl, axisPointerModel) {
  49646. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  49647. }
  49648. function getHandleTransProps(trans) {
  49649. return {
  49650. position: trans.position.slice(),
  49651. rotation: trans.rotation || 0
  49652. };
  49653. }
  49654. function updateMandatoryProps(group, axisPointerModel, silent) {
  49655. var z = axisPointerModel.get('z');
  49656. var zlevel = axisPointerModel.get('zlevel');
  49657. group && group.traverse(function (el) {
  49658. if (el.type !== 'group') {
  49659. z != null && (el.z = z);
  49660. zlevel != null && (el.zlevel = zlevel);
  49661. el.silent = silent;
  49662. }
  49663. });
  49664. }
  49665. enableClassExtend(BaseAxisPointer);
  49666. /**
  49667. * @param {module:echarts/model/Model} axisPointerModel
  49668. */
  49669. function buildElStyle(axisPointerModel) {
  49670. var axisPointerType = axisPointerModel.get('type');
  49671. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  49672. var style;
  49673. if (axisPointerType === 'line') {
  49674. style = styleModel.getLineStyle();
  49675. style.fill = null;
  49676. }
  49677. else if (axisPointerType === 'shadow') {
  49678. style = styleModel.getAreaStyle();
  49679. style.stroke = null;
  49680. }
  49681. return style;
  49682. }
  49683. /**
  49684. * @param {Function} labelPos {align, verticalAlign, position}
  49685. */
  49686. function buildLabelElOption(
  49687. elOption, axisModel, axisPointerModel, api, labelPos
  49688. ) {
  49689. var value = axisPointerModel.get('value');
  49690. var text = getValueLabel(
  49691. value, axisModel.axis, axisModel.ecModel,
  49692. axisPointerModel.get('seriesDataIndices'),
  49693. {
  49694. precision: axisPointerModel.get('label.precision'),
  49695. formatter: axisPointerModel.get('label.formatter')
  49696. }
  49697. );
  49698. var labelModel = axisPointerModel.getModel('label');
  49699. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  49700. var font = labelModel.getFont();
  49701. var textRect = getBoundingRect(text, font);
  49702. var position = labelPos.position;
  49703. var width = textRect.width + paddings[1] + paddings[3];
  49704. var height = textRect.height + paddings[0] + paddings[2];
  49705. // Adjust by align.
  49706. var align = labelPos.align;
  49707. align === 'right' && (position[0] -= width);
  49708. align === 'center' && (position[0] -= width / 2);
  49709. var verticalAlign = labelPos.verticalAlign;
  49710. verticalAlign === 'bottom' && (position[1] -= height);
  49711. verticalAlign === 'middle' && (position[1] -= height / 2);
  49712. // Not overflow ec container
  49713. confineInContainer(position, width, height, api);
  49714. var bgColor = labelModel.get('backgroundColor');
  49715. if (!bgColor || bgColor === 'auto') {
  49716. bgColor = axisModel.get('axisLine.lineStyle.color');
  49717. }
  49718. elOption.label = {
  49719. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  49720. position: position.slice(),
  49721. // TODO: rich
  49722. style: {
  49723. text: text,
  49724. textFont: font,
  49725. textFill: labelModel.getTextColor(),
  49726. textPosition: 'inside',
  49727. fill: bgColor,
  49728. stroke: labelModel.get('borderColor') || 'transparent',
  49729. lineWidth: labelModel.get('borderWidth') || 0,
  49730. shadowBlur: labelModel.get('shadowBlur'),
  49731. shadowColor: labelModel.get('shadowColor'),
  49732. shadowOffsetX: labelModel.get('shadowOffsetX'),
  49733. shadowOffsetY: labelModel.get('shadowOffsetY')
  49734. },
  49735. // Lable should be over axisPointer.
  49736. z2: 10
  49737. };
  49738. }
  49739. // Do not overflow ec container
  49740. function confineInContainer(position, width, height, api) {
  49741. var viewWidth = api.getWidth();
  49742. var viewHeight = api.getHeight();
  49743. position[0] = Math.min(position[0] + width, viewWidth) - width;
  49744. position[1] = Math.min(position[1] + height, viewHeight) - height;
  49745. position[0] = Math.max(position[0], 0);
  49746. position[1] = Math.max(position[1], 0);
  49747. }
  49748. /**
  49749. * @param {number} value
  49750. * @param {module:echarts/coord/Axis} axis
  49751. * @param {module:echarts/model/Global} ecModel
  49752. * @param {Object} opt
  49753. * @param {Array.<Object>} seriesDataIndices
  49754. * @param {number|string} opt.precision 'auto' or a number
  49755. * @param {string|Function} opt.formatter label formatter
  49756. */
  49757. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  49758. var text = axis.scale.getLabel(
  49759. // If `precision` is set, width can be fixed (like '12.00500'), which
  49760. // helps to debounce when when moving label.
  49761. value, {precision: opt.precision}
  49762. );
  49763. var formatter = opt.formatter;
  49764. if (formatter) {
  49765. var params = {
  49766. value: getAxisRawValue(axis, value),
  49767. seriesData: []
  49768. };
  49769. each$1(seriesDataIndices, function (idxItem) {
  49770. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  49771. var dataIndex = idxItem.dataIndexInside;
  49772. var dataParams = series && series.getDataParams(dataIndex);
  49773. dataParams && params.seriesData.push(dataParams);
  49774. });
  49775. if (isString(formatter)) {
  49776. text = formatter.replace('{value}', text);
  49777. }
  49778. else if (isFunction$1(formatter)) {
  49779. text = formatter(params);
  49780. }
  49781. }
  49782. return text;
  49783. }
  49784. /**
  49785. * @param {module:echarts/coord/Axis} axis
  49786. * @param {number} value
  49787. * @param {Object} layoutInfo {
  49788. * rotation, position, labelOffset, labelDirection, labelMargin
  49789. * }
  49790. */
  49791. function getTransformedPosition (axis, value, layoutInfo) {
  49792. var transform = create$1();
  49793. rotate(transform, transform, layoutInfo.rotation);
  49794. translate(transform, transform, layoutInfo.position);
  49795. return applyTransform$1([
  49796. axis.dataToCoord(value),
  49797. (layoutInfo.labelOffset || 0)
  49798. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  49799. ], transform);
  49800. }
  49801. function buildCartesianSingleLabelElOption(
  49802. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  49803. ) {
  49804. var textLayout = AxisBuilder.innerTextLayout(
  49805. layoutInfo.rotation, 0, layoutInfo.labelDirection
  49806. );
  49807. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  49808. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  49809. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  49810. align: textLayout.textAlign,
  49811. verticalAlign: textLayout.textVerticalAlign
  49812. });
  49813. }
  49814. /**
  49815. * @param {Array.<number>} p1
  49816. * @param {Array.<number>} p2
  49817. * @param {number} [xDimIndex=0] or 1
  49818. */
  49819. function makeLineShape(p1, p2, xDimIndex) {
  49820. xDimIndex = xDimIndex || 0;
  49821. return {
  49822. x1: p1[xDimIndex],
  49823. y1: p1[1 - xDimIndex],
  49824. x2: p2[xDimIndex],
  49825. y2: p2[1 - xDimIndex]
  49826. };
  49827. }
  49828. /**
  49829. * @param {Array.<number>} xy
  49830. * @param {Array.<number>} wh
  49831. * @param {number} [xDimIndex=0] or 1
  49832. */
  49833. function makeRectShape(xy, wh, xDimIndex) {
  49834. xDimIndex = xDimIndex || 0;
  49835. return {
  49836. x: xy[xDimIndex],
  49837. y: xy[1 - xDimIndex],
  49838. width: wh[xDimIndex],
  49839. height: wh[1 - xDimIndex]
  49840. };
  49841. }
  49842. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  49843. return {
  49844. cx: cx,
  49845. cy: cy,
  49846. r0: r0,
  49847. r: r,
  49848. startAngle: startAngle,
  49849. endAngle: endAngle,
  49850. clockwise: true
  49851. };
  49852. }
  49853. var CartesianAxisPointer = BaseAxisPointer.extend({
  49854. /**
  49855. * @override
  49856. */
  49857. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  49858. var axis = axisModel.axis;
  49859. var grid = axis.grid;
  49860. var axisPointerType = axisPointerModel.get('type');
  49861. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  49862. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  49863. if (axisPointerType && axisPointerType !== 'none') {
  49864. var elStyle = buildElStyle(axisPointerModel);
  49865. var pointerOption = pointerShapeBuilder[axisPointerType](
  49866. axis, pixelValue, otherExtent, elStyle
  49867. );
  49868. pointerOption.style = elStyle;
  49869. elOption.graphicKey = pointerOption.type;
  49870. elOption.pointer = pointerOption;
  49871. }
  49872. var layoutInfo = layout$1(grid.model, axisModel);
  49873. buildCartesianSingleLabelElOption(
  49874. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  49875. );
  49876. },
  49877. /**
  49878. * @override
  49879. */
  49880. getHandleTransform: function (value, axisModel, axisPointerModel) {
  49881. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  49882. labelInside: false
  49883. });
  49884. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  49885. return {
  49886. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  49887. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  49888. };
  49889. },
  49890. /**
  49891. * @override
  49892. */
  49893. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  49894. var axis = axisModel.axis;
  49895. var grid = axis.grid;
  49896. var axisExtent = axis.getGlobalExtent(true);
  49897. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  49898. var dimIndex = axis.dim === 'x' ? 0 : 1;
  49899. var currPosition = transform.position;
  49900. currPosition[dimIndex] += delta[dimIndex];
  49901. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  49902. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  49903. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  49904. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  49905. cursorPoint[dimIndex] = currPosition[dimIndex];
  49906. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  49907. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  49908. return {
  49909. position: currPosition,
  49910. rotation: transform.rotation,
  49911. cursorPoint: cursorPoint,
  49912. tooltipOption: tooltipOptions[dimIndex]
  49913. };
  49914. }
  49915. });
  49916. function getCartesian(grid, axis) {
  49917. var opt = {};
  49918. opt[axis.dim + 'AxisIndex'] = axis.index;
  49919. return grid.getCartesian(opt);
  49920. }
  49921. var pointerShapeBuilder = {
  49922. line: function (axis, pixelValue, otherExtent, elStyle) {
  49923. var targetShape = makeLineShape(
  49924. [pixelValue, otherExtent[0]],
  49925. [pixelValue, otherExtent[1]],
  49926. getAxisDimIndex(axis)
  49927. );
  49928. subPixelOptimizeLine({
  49929. shape: targetShape,
  49930. style: elStyle
  49931. });
  49932. return {
  49933. type: 'Line',
  49934. shape: targetShape
  49935. };
  49936. },
  49937. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  49938. var bandWidth = axis.getBandWidth();
  49939. var span = otherExtent[1] - otherExtent[0];
  49940. return {
  49941. type: 'Rect',
  49942. shape: makeRectShape(
  49943. [pixelValue - bandWidth / 2, otherExtent[0]],
  49944. [bandWidth, span],
  49945. getAxisDimIndex(axis)
  49946. )
  49947. };
  49948. }
  49949. };
  49950. function getAxisDimIndex(axis) {
  49951. return axis.dim === 'x' ? 0 : 1;
  49952. }
  49953. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  49954. // CartesianAxisPointer is not supposed to be required here. But consider
  49955. // echarts.simple.js and online build tooltip, which only require gridSimple,
  49956. // CartesianAxisPointer should be able to required somewhere.
  49957. registerPreprocessor(function (option) {
  49958. // Always has a global axisPointerModel for default setting.
  49959. if (option) {
  49960. (!option.axisPointer || option.axisPointer.length === 0)
  49961. && (option.axisPointer = {});
  49962. var link = option.axisPointer.link;
  49963. // Normalize to array to avoid object mergin. But if link
  49964. // is not set, remain null/undefined, otherwise it will
  49965. // override existent link setting.
  49966. if (link && !isArray(link)) {
  49967. option.axisPointer.link = [link];
  49968. }
  49969. }
  49970. });
  49971. // This process should proformed after coordinate systems created
  49972. // and series data processed. So put it on statistic processing stage.
  49973. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  49974. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  49975. // allAxesInfo should be updated when setOption performed.
  49976. ecModel.getComponent('axisPointer').coordSysAxesInfo
  49977. = collect(ecModel, api);
  49978. });
  49979. // Broadcast to all views.
  49980. registerAction({
  49981. type: 'updateAxisPointer',
  49982. event: 'updateAxisPointer',
  49983. update: ':updateAxisPointer'
  49984. }, axisTrigger);
  49985. var XY = ['x', 'y'];
  49986. var WH = ['width', 'height'];
  49987. var SingleAxisPointer = BaseAxisPointer.extend({
  49988. /**
  49989. * @override
  49990. */
  49991. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  49992. var axis = axisModel.axis;
  49993. var coordSys = axis.coordinateSystem;
  49994. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  49995. var pixelValue = coordSys.dataToPoint(value)[0];
  49996. var axisPointerType = axisPointerModel.get('type');
  49997. if (axisPointerType && axisPointerType !== 'none') {
  49998. var elStyle = buildElStyle(axisPointerModel);
  49999. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  50000. axis, pixelValue, otherExtent, elStyle
  50001. );
  50002. pointerOption.style = elStyle;
  50003. elOption.graphicKey = pointerOption.type;
  50004. elOption.pointer = pointerOption;
  50005. }
  50006. var layoutInfo = layout$2(axisModel);
  50007. buildCartesianSingleLabelElOption(
  50008. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50009. );
  50010. },
  50011. /**
  50012. * @override
  50013. */
  50014. getHandleTransform: function (value, axisModel, axisPointerModel) {
  50015. var layoutInfo = layout$2(axisModel, {labelInside: false});
  50016. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  50017. return {
  50018. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50019. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  50020. };
  50021. },
  50022. /**
  50023. * @override
  50024. */
  50025. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  50026. var axis = axisModel.axis;
  50027. var coordSys = axis.coordinateSystem;
  50028. var dimIndex = getPointDimIndex(axis);
  50029. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  50030. var currPosition = transform.position;
  50031. currPosition[dimIndex] += delta[dimIndex];
  50032. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  50033. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  50034. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  50035. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  50036. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  50037. cursorPoint[dimIndex] = currPosition[dimIndex];
  50038. return {
  50039. position: currPosition,
  50040. rotation: transform.rotation,
  50041. cursorPoint: cursorPoint,
  50042. tooltipOption: {
  50043. verticalAlign: 'middle'
  50044. }
  50045. };
  50046. }
  50047. });
  50048. var pointerShapeBuilder$1 = {
  50049. line: function (axis, pixelValue, otherExtent, elStyle) {
  50050. var targetShape = makeLineShape(
  50051. [pixelValue, otherExtent[0]],
  50052. [pixelValue, otherExtent[1]],
  50053. getPointDimIndex(axis)
  50054. );
  50055. subPixelOptimizeLine({
  50056. shape: targetShape,
  50057. style: elStyle
  50058. });
  50059. return {
  50060. type: 'Line',
  50061. shape: targetShape
  50062. };
  50063. },
  50064. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  50065. var bandWidth = axis.getBandWidth();
  50066. var span = otherExtent[1] - otherExtent[0];
  50067. return {
  50068. type: 'Rect',
  50069. shape: makeRectShape(
  50070. [pixelValue - bandWidth / 2, otherExtent[0]],
  50071. [bandWidth, span],
  50072. getPointDimIndex(axis)
  50073. )
  50074. };
  50075. }
  50076. };
  50077. function getPointDimIndex(axis) {
  50078. return axis.isHorizontal() ? 0 : 1;
  50079. }
  50080. function getGlobalExtent(coordSys, dimIndex) {
  50081. var rect = coordSys.getRect();
  50082. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  50083. }
  50084. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  50085. extendComponentView({
  50086. type: 'single'
  50087. });
  50088. /**
  50089. * @file Define the themeRiver view's series model
  50090. * @author Deqing Li(annong035@gmail.com)
  50091. */
  50092. var DATA_NAME_INDEX = 2;
  50093. var ThemeRiverSeries = SeriesModel.extend({
  50094. type: 'series.themeRiver',
  50095. dependencies: ['singleAxis'],
  50096. /**
  50097. * @readOnly
  50098. * @type {module:zrender/core/util#HashMap}
  50099. */
  50100. nameMap: null,
  50101. /**
  50102. * @override
  50103. */
  50104. init: function (option) {
  50105. ThemeRiverSeries.superApply(this, 'init', arguments);
  50106. // Put this function here is for the sake of consistency of code style.
  50107. // Enable legend selection for each data item
  50108. // Use a function instead of direct access because data reference may changed
  50109. this.legendDataProvider = function () {
  50110. return this.getRawData();
  50111. };
  50112. },
  50113. /**
  50114. * If there is no value of a certain point in the time for some event,set it value to 0.
  50115. *
  50116. * @param {Array} data initial data in the option
  50117. * @return {Array}
  50118. */
  50119. fixData: function (data) {
  50120. var rawDataLength = data.length;
  50121. // grouped data by name
  50122. var dataByName = nest()
  50123. .key(function (dataItem) {
  50124. return dataItem[2];
  50125. })
  50126. .entries(data);
  50127. // data group in each layer
  50128. var layData = map(dataByName, function (d) {
  50129. return {
  50130. name: d.key,
  50131. dataList: d.values
  50132. };
  50133. });
  50134. var layerNum = layData.length;
  50135. var largestLayer = -1;
  50136. var index = -1;
  50137. for (var i = 0; i < layerNum; ++i) {
  50138. var len = layData[i].dataList.length;
  50139. if (len > largestLayer) {
  50140. largestLayer = len;
  50141. index = i;
  50142. }
  50143. }
  50144. for (var k = 0; k < layerNum; ++k) {
  50145. if (k === index) {
  50146. continue;
  50147. }
  50148. var name = layData[k].name;
  50149. for (var j = 0; j < largestLayer; ++j) {
  50150. var timeValue = layData[index].dataList[j][0];
  50151. var length = layData[k].dataList.length;
  50152. var keyIndex = -1;
  50153. for (var l = 0; l < length; ++l) {
  50154. var value = layData[k].dataList[l][0];
  50155. if (value === timeValue) {
  50156. keyIndex = l;
  50157. break;
  50158. }
  50159. }
  50160. if (keyIndex === -1) {
  50161. data[rawDataLength] = [];
  50162. data[rawDataLength][0] = timeValue;
  50163. data[rawDataLength][1] = 0;
  50164. data[rawDataLength][2] = name;
  50165. rawDataLength++;
  50166. }
  50167. }
  50168. }
  50169. return data;
  50170. },
  50171. /**
  50172. * @override
  50173. * @param {Object} option the initial option that user gived
  50174. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  50175. * @return {module:echarts/data/List}
  50176. */
  50177. getInitialData: function (option, ecModel) {
  50178. var singleAxisModel = ecModel.queryComponents({
  50179. mainType: 'singleAxis',
  50180. index: this.get('singleAxisIndex'),
  50181. id: this.get('singleAxisId')
  50182. })[0];
  50183. var axisType = singleAxisModel.get('type');
  50184. // filter the data item with the value of label is undefined
  50185. var filterData = filter(option.data, function (dataItem) {
  50186. return dataItem[2] !== undefined;
  50187. });
  50188. // ??? TODO design a stage to transfer data for themeRiver and lines?
  50189. var data = this.fixData(filterData || []);
  50190. var nameList = [];
  50191. var nameMap = this.nameMap = createHashMap();
  50192. var count = 0;
  50193. for (var i = 0; i < data.length; ++i) {
  50194. nameList.push(data[i][DATA_NAME_INDEX]);
  50195. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  50196. nameMap.set(data[i][DATA_NAME_INDEX], count);
  50197. count++;
  50198. }
  50199. }
  50200. var dimensionsInfo = createDimensions(data, {
  50201. coordDimensions: ['single'],
  50202. dimensionsDefine: [
  50203. {
  50204. name: 'time',
  50205. type: getDimensionTypeByAxis(axisType)
  50206. },
  50207. {
  50208. name: 'value',
  50209. type: 'float'
  50210. },
  50211. {
  50212. name: 'name',
  50213. type: 'ordinal'
  50214. }
  50215. ],
  50216. encodeDefine: {
  50217. single: 0,
  50218. value: 1,
  50219. itemName: 2
  50220. }
  50221. });
  50222. var list = new List(dimensionsInfo, this);
  50223. list.initData(data);
  50224. return list;
  50225. },
  50226. /**
  50227. * The raw data is divided into multiple layers and each layer
  50228. * has same name.
  50229. *
  50230. * @return {Array.<Array.<number>>}
  50231. */
  50232. getLayerSeries: function () {
  50233. var data = this.getData();
  50234. var lenCount = data.count();
  50235. var indexArr = [];
  50236. for (var i = 0; i < lenCount; ++i) {
  50237. indexArr[i] = i;
  50238. }
  50239. // data group by name
  50240. var dataByName = nest()
  50241. .key(function (index) {
  50242. return data.get('name', index);
  50243. })
  50244. .entries(indexArr);
  50245. var layerSeries = map(dataByName, function (d) {
  50246. return {
  50247. name: d.key,
  50248. indices: d.values
  50249. };
  50250. });
  50251. var timeDim = data.mapDimension('single');
  50252. for (var j = 0; j < layerSeries.length; ++j) {
  50253. layerSeries[j].indices.sort(comparer);
  50254. }
  50255. function comparer(index1, index2) {
  50256. return data.get(timeDim, index1) - data.get(timeDim, index2);
  50257. }
  50258. return layerSeries;
  50259. },
  50260. /**
  50261. * Get data indices for show tooltip content
  50262. *
  50263. * @param {Array.<string>|string} dim single coordinate dimension
  50264. * @param {number} value axis value
  50265. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  50266. * the themeRiver.
  50267. * @return {Object} {dataIndices, nestestValue}
  50268. */
  50269. getAxisTooltipData: function (dim, value, baseAxis) {
  50270. if (!isArray(dim)) {
  50271. dim = dim ? [dim] : [];
  50272. }
  50273. var data = this.getData();
  50274. var layerSeries = this.getLayerSeries();
  50275. var indices = [];
  50276. var layerNum = layerSeries.length;
  50277. var nestestValue;
  50278. for (var i = 0; i < layerNum; ++i) {
  50279. var minDist = Number.MAX_VALUE;
  50280. var nearestIdx = -1;
  50281. var pointNum = layerSeries[i].indices.length;
  50282. for (var j = 0; j < pointNum; ++j) {
  50283. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  50284. var dist = Math.abs(theValue - value);
  50285. if (dist <= minDist) {
  50286. nestestValue = theValue;
  50287. minDist = dist;
  50288. nearestIdx = layerSeries[i].indices[j];
  50289. }
  50290. }
  50291. indices.push(nearestIdx);
  50292. }
  50293. return {dataIndices: indices, nestestValue: nestestValue};
  50294. },
  50295. /**
  50296. * @override
  50297. * @param {number} dataIndex index of data
  50298. */
  50299. formatTooltip: function (dataIndex) {
  50300. var data = this.getData();
  50301. var htmlName = data.getName(dataIndex);
  50302. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  50303. if (isNaN(htmlValue) || htmlValue == null) {
  50304. htmlValue = '-';
  50305. }
  50306. return encodeHTML(htmlName + ' : ' + htmlValue);
  50307. },
  50308. defaultOption: {
  50309. zlevel: 0,
  50310. z: 2,
  50311. coordinateSystem: 'singleAxis',
  50312. // gap in axis's orthogonal orientation
  50313. boundaryGap: ['10%', '10%'],
  50314. // legendHoverLink: true,
  50315. singleAxisIndex: 0,
  50316. animationEasing: 'linear',
  50317. label: {
  50318. margin: 4,
  50319. textAlign: 'right',
  50320. show: true,
  50321. position: 'left',
  50322. color: '#000',
  50323. fontSize: 11
  50324. },
  50325. emphasis: {
  50326. label: {
  50327. show: true
  50328. }
  50329. }
  50330. }
  50331. });
  50332. /**
  50333. * @file The file used to draw themeRiver view
  50334. * @author Deqing Li(annong035@gmail.com)
  50335. */
  50336. extendChartView({
  50337. type: 'themeRiver',
  50338. init: function () {
  50339. this._layers = [];
  50340. },
  50341. render: function (seriesModel, ecModel, api) {
  50342. var data = seriesModel.getData();
  50343. var group = this.group;
  50344. var layerSeries = seriesModel.getLayerSeries();
  50345. var layoutInfo = data.getLayout('layoutInfo');
  50346. var rect = layoutInfo.rect;
  50347. var boundaryGap = layoutInfo.boundaryGap;
  50348. group.attr('position', [0, rect.y + boundaryGap[0]]);
  50349. function keyGetter(item) {
  50350. return item.name;
  50351. }
  50352. var dataDiffer = new DataDiffer(
  50353. this._layersSeries || [], layerSeries,
  50354. keyGetter, keyGetter
  50355. );
  50356. var newLayersGroups = {};
  50357. dataDiffer
  50358. .add(bind(process, this, 'add'))
  50359. .update(bind(process, this, 'update'))
  50360. .remove(bind(process, this, 'remove'))
  50361. .execute();
  50362. function process(status, idx, oldIdx) {
  50363. var oldLayersGroups = this._layers;
  50364. if (status === 'remove') {
  50365. group.remove(oldLayersGroups[idx]);
  50366. return;
  50367. }
  50368. var points0 = [];
  50369. var points1 = [];
  50370. var color;
  50371. var indices = layerSeries[idx].indices;
  50372. for (var j = 0; j < indices.length; j++) {
  50373. var layout = data.getItemLayout(indices[j]);
  50374. var x = layout.x;
  50375. var y0 = layout.y0;
  50376. var y = layout.y;
  50377. points0.push([x, y0]);
  50378. points1.push([x, y0 + y]);
  50379. color = data.getItemVisual(indices[j], 'color');
  50380. }
  50381. var polygon;
  50382. var text;
  50383. var textLayout = data.getItemLayout(indices[0]);
  50384. var itemModel = data.getItemModel(indices[j - 1]);
  50385. var labelModel = itemModel.getModel('label');
  50386. var margin = labelModel.get('margin');
  50387. if (status === 'add') {
  50388. var layerGroup = newLayersGroups[idx] = new Group();
  50389. polygon = new Polygon$1({
  50390. shape: {
  50391. points: points0,
  50392. stackedOnPoints: points1,
  50393. smooth: 0.4,
  50394. stackedOnSmooth: 0.4,
  50395. smoothConstraint: false
  50396. },
  50397. z2: 0
  50398. });
  50399. text = new Text({
  50400. style: {
  50401. x: textLayout.x - margin,
  50402. y: textLayout.y0 + textLayout.y / 2
  50403. }
  50404. });
  50405. layerGroup.add(polygon);
  50406. layerGroup.add(text);
  50407. group.add(layerGroup);
  50408. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  50409. polygon.removeClipPath();
  50410. }));
  50411. }
  50412. else {
  50413. var layerGroup = oldLayersGroups[oldIdx];
  50414. polygon = layerGroup.childAt(0);
  50415. text = layerGroup.childAt(1);
  50416. group.add(layerGroup);
  50417. newLayersGroups[idx] = layerGroup;
  50418. updateProps(polygon, {
  50419. shape: {
  50420. points: points0,
  50421. stackedOnPoints: points1
  50422. }
  50423. }, seriesModel);
  50424. updateProps(text, {
  50425. style: {
  50426. x: textLayout.x - margin,
  50427. y: textLayout.y0 + textLayout.y / 2
  50428. }
  50429. }, seriesModel);
  50430. }
  50431. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  50432. var itemStyleModel = itemModel.getModel('itemStyle');
  50433. setTextStyle(text.style, labelModel, {
  50434. text: labelModel.get('show')
  50435. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  50436. || data.getName(indices[j - 1])
  50437. : null,
  50438. textVerticalAlign: 'middle'
  50439. });
  50440. polygon.setStyle(extend({
  50441. fill: color
  50442. }, itemStyleModel.getItemStyle(['color'])));
  50443. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  50444. }
  50445. this._layersSeries = layerSeries;
  50446. this._layers = newLayersGroups;
  50447. },
  50448. dispose: function () {}
  50449. });
  50450. // add animation to the view
  50451. function createGridClipShape$3(rect, seriesModel, cb) {
  50452. var rectEl = new Rect({
  50453. shape: {
  50454. x: rect.x - 10,
  50455. y: rect.y - 10,
  50456. width: 0,
  50457. height: rect.height + 20
  50458. }
  50459. });
  50460. initProps(rectEl, {
  50461. shape: {
  50462. width: rect.width + 20,
  50463. height: rect.height + 20
  50464. }
  50465. }, seriesModel, cb);
  50466. return rectEl;
  50467. }
  50468. /**
  50469. * @file Using layout algorithm transform the raw data to layout information.
  50470. * @author Deqing Li(annong035@gmail.com)
  50471. */
  50472. var themeRiverLayout = function (ecModel, api) {
  50473. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  50474. var data = seriesModel.getData();
  50475. var single = seriesModel.coordinateSystem;
  50476. var layoutInfo = {};
  50477. // use the axis boundingRect for view
  50478. var rect = single.getRect();
  50479. layoutInfo.rect = rect;
  50480. var boundaryGap = seriesModel.get('boundaryGap');
  50481. var axis = single.getAxis();
  50482. layoutInfo.boundaryGap = boundaryGap;
  50483. if (axis.orient === 'horizontal') {
  50484. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  50485. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  50486. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  50487. themeRiverLayout$1(data, seriesModel, height);
  50488. }
  50489. else {
  50490. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  50491. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  50492. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  50493. themeRiverLayout$1(data, seriesModel, width);
  50494. }
  50495. data.setLayout('layoutInfo', layoutInfo);
  50496. });
  50497. };
  50498. /**
  50499. * The layout information about themeriver
  50500. *
  50501. * @param {module:echarts/data/List} data data in the series
  50502. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  50503. * @param {number} height value used to compute every series height
  50504. */
  50505. function themeRiverLayout$1(data, seriesModel, height) {
  50506. if (!data.count()) {
  50507. return;
  50508. }
  50509. var coordSys = seriesModel.coordinateSystem;
  50510. // the data in each layer are organized into a series.
  50511. var layerSeries = seriesModel.getLayerSeries();
  50512. // the points in each layer.
  50513. var timeDim = data.mapDimension('single');
  50514. var valueDim = data.mapDimension('value');
  50515. var layerPoints = map(layerSeries, function (singleLayer) {
  50516. return map(singleLayer.indices, function (idx) {
  50517. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  50518. pt[1] = data.get(valueDim, idx);
  50519. return pt;
  50520. });
  50521. });
  50522. var base = computeBaseline(layerPoints);
  50523. var baseLine = base.y0;
  50524. var ky = height / base.max;
  50525. // set layout information for each item.
  50526. var n = layerSeries.length;
  50527. var m = layerSeries[0].indices.length;
  50528. var baseY0;
  50529. for (var j = 0; j < m; ++j) {
  50530. baseY0 = baseLine[j] * ky;
  50531. data.setItemLayout(layerSeries[0].indices[j], {
  50532. layerIndex: 0,
  50533. x: layerPoints[0][j][0],
  50534. y0: baseY0,
  50535. y: layerPoints[0][j][1] * ky
  50536. });
  50537. for (var i = 1; i < n; ++i) {
  50538. baseY0 += layerPoints[i - 1][j][1] * ky;
  50539. data.setItemLayout(layerSeries[i].indices[j], {
  50540. layerIndex: i,
  50541. x: layerPoints[i][j][0],
  50542. y0: baseY0,
  50543. y: layerPoints[i][j][1] * ky
  50544. });
  50545. }
  50546. }
  50547. }
  50548. /**
  50549. * Compute the baseLine of the rawdata
  50550. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  50551. *
  50552. * @param {Array.<Array>} data the points in each layer
  50553. * @return {Object}
  50554. */
  50555. function computeBaseline(data) {
  50556. var layerNum = data.length;
  50557. var pointNum = data[0].length;
  50558. var sums = [];
  50559. var y0 = [];
  50560. var max = 0;
  50561. var temp;
  50562. var base = {};
  50563. for (var i = 0; i < pointNum; ++i) {
  50564. for (var j = 0, temp = 0; j < layerNum; ++j) {
  50565. temp += data[j][i][1];
  50566. }
  50567. if (temp > max) {
  50568. max = temp;
  50569. }
  50570. sums.push(temp);
  50571. }
  50572. for (var k = 0; k < pointNum; ++k) {
  50573. y0[k] = (max - sums[k]) / 2;
  50574. }
  50575. max = 0;
  50576. for (var l = 0; l < pointNum; ++l) {
  50577. var sum = sums[l] + y0[l];
  50578. if (sum > max) {
  50579. max = sum;
  50580. }
  50581. }
  50582. base.y0 = y0;
  50583. base.max = max;
  50584. return base;
  50585. }
  50586. /**
  50587. * @file Visual encoding for themeRiver view
  50588. * @author Deqing Li(annong035@gmail.com)
  50589. */
  50590. var themeRiverVisual = function (ecModel) {
  50591. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  50592. var data = seriesModel.getData();
  50593. var rawData = seriesModel.getRawData();
  50594. var colorList = seriesModel.get('color');
  50595. var idxMap = createHashMap();
  50596. data.each(function (idx) {
  50597. idxMap.set(data.getRawIndex(idx), idx);
  50598. });
  50599. rawData.each(function (rawIndex) {
  50600. var name = rawData.getName(rawIndex);
  50601. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  50602. rawData.setItemVisual(rawIndex, 'color', color);
  50603. var idx = idxMap.get(rawIndex);
  50604. if (idx != null) {
  50605. data.setItemVisual(idx, 'color', color);
  50606. }
  50607. });
  50608. });
  50609. };
  50610. registerLayout(themeRiverLayout);
  50611. registerVisual(themeRiverVisual);
  50612. registerProcessor(dataFilter('themeRiver'));
  50613. SeriesModel.extend({
  50614. type: 'series.sunburst',
  50615. /**
  50616. * @type {module:echarts/data/Tree~Node}
  50617. */
  50618. _viewRoot: null,
  50619. getInitialData: function (option, ecModel) {
  50620. // Create a virtual root.
  50621. var root = { name: option.name, children: option.data };
  50622. completeTreeValue$1(root);
  50623. var levels = option.levels || [];
  50624. // levels = option.levels = setDefault(levels, ecModel);
  50625. var treeOption = {};
  50626. treeOption.levels = levels;
  50627. // Make sure always a new tree is created when setOption,
  50628. // in TreemapView, we check whether oldTree === newTree
  50629. // to choose mappings approach among old shapes and new shapes.
  50630. return Tree.createTree(root, this, treeOption).data;
  50631. },
  50632. optionUpdated: function () {
  50633. this.resetViewRoot();
  50634. },
  50635. /*
  50636. * @override
  50637. */
  50638. getDataParams: function (dataIndex) {
  50639. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  50640. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  50641. params.treePathInfo = wrapTreePathInfo(node, this);
  50642. return params;
  50643. },
  50644. defaultOption: {
  50645. zlevel: 0,
  50646. z: 2,
  50647. // 默认全局居中
  50648. center: ['50%', '50%'],
  50649. radius: [0, '75%'],
  50650. // 默认顺时针
  50651. clockwise: true,
  50652. startAngle: 90,
  50653. // 最小角度改为0
  50654. minAngle: 0,
  50655. percentPrecision: 2,
  50656. // If still show when all data zero.
  50657. stillShowZeroSum: true,
  50658. // Policy of highlighting pieces when hover on one
  50659. // Valid values: 'none' (for not downplay others), 'descendant',
  50660. // 'ancestor', 'self'
  50661. highlightPolicy: 'descendant',
  50662. // 'rootToNode', 'link', or false
  50663. nodeClick: 'rootToNode',
  50664. renderLabelForZeroData: false,
  50665. label: {
  50666. // could be: 'radial', 'tangential', or 'none'
  50667. rotate: 'radial',
  50668. show: true,
  50669. opacity: 1,
  50670. // 'left' is for inner side of inside, and 'right' is for outter
  50671. // side for inside
  50672. align: 'center',
  50673. position: 'inside',
  50674. distance: 5,
  50675. silent: true,
  50676. emphasis: {}
  50677. },
  50678. itemStyle: {
  50679. borderWidth: 1,
  50680. borderColor: 'white',
  50681. opacity: 1,
  50682. emphasis: {},
  50683. highlight: {
  50684. opacity: 1
  50685. },
  50686. downplay: {
  50687. opacity: 0.9
  50688. }
  50689. },
  50690. // Animation type canbe expansion, scale
  50691. animationType: 'expansion',
  50692. animationDuration: 1000,
  50693. animationDurationUpdate: 500,
  50694. animationEasing: 'cubicOut',
  50695. data: [],
  50696. levels: [],
  50697. /**
  50698. * Sort order.
  50699. *
  50700. * Valid values: 'desc', 'asc', null, or callback function.
  50701. * 'desc' and 'asc' for descend and ascendant order;
  50702. * null for not sorting;
  50703. * example of callback function:
  50704. * function(nodeA, nodeB) {
  50705. * return nodeA.getValue() - nodeB.getValue();
  50706. * }
  50707. */
  50708. sort: 'desc'
  50709. },
  50710. getViewRoot: function () {
  50711. return this._viewRoot;
  50712. },
  50713. /**
  50714. * @param {module:echarts/data/Tree~Node} [viewRoot]
  50715. */
  50716. resetViewRoot: function (viewRoot) {
  50717. viewRoot
  50718. ? (this._viewRoot = viewRoot)
  50719. : (viewRoot = this._viewRoot);
  50720. var root = this.getRawData().tree.root;
  50721. if (!viewRoot
  50722. || (viewRoot !== root && !root.contains(viewRoot))
  50723. ) {
  50724. this._viewRoot = root;
  50725. }
  50726. }
  50727. });
  50728. /**
  50729. * @param {Object} dataNode
  50730. */
  50731. function completeTreeValue$1(dataNode) {
  50732. // Postorder travel tree.
  50733. // If value of none-leaf node is not set,
  50734. // calculate it by suming up the value of all children.
  50735. var sum = 0;
  50736. each$1(dataNode.children, function (child) {
  50737. completeTreeValue$1(child);
  50738. var childValue = child.value;
  50739. isArray(childValue) && (childValue = childValue[0]);
  50740. sum += childValue;
  50741. });
  50742. var thisValue = dataNode.value;
  50743. if (isArray(thisValue)) {
  50744. thisValue = thisValue[0];
  50745. }
  50746. if (thisValue == null || isNaN(thisValue)) {
  50747. thisValue = sum;
  50748. }
  50749. // Value should not less than 0.
  50750. if (thisValue < 0) {
  50751. thisValue = 0;
  50752. }
  50753. isArray(dataNode.value)
  50754. ? (dataNode.value[0] = thisValue)
  50755. : (dataNode.value = thisValue);
  50756. }
  50757. var NodeHighlightPolicy = {
  50758. NONE: 'none', // not downplay others
  50759. DESCENDANT: 'descendant',
  50760. ANCESTOR: 'ancestor',
  50761. SELF: 'self'
  50762. };
  50763. var DEFAULT_SECTOR_Z = 2;
  50764. var DEFAULT_TEXT_Z = 4;
  50765. /**
  50766. * Sunburstce of Sunburst including Sector, Label, LabelLine
  50767. * @constructor
  50768. * @extends {module:zrender/graphic/Group}
  50769. */
  50770. function SunburstPiece(node, seriesModel, ecModel) {
  50771. Group.call(this);
  50772. var sector = new Sector({
  50773. z2: DEFAULT_SECTOR_Z
  50774. });
  50775. var text = new Text({
  50776. z2: DEFAULT_TEXT_Z,
  50777. silent: node.getModel('label').get('silent')
  50778. });
  50779. this.add(sector);
  50780. this.add(text);
  50781. this.updateData(true, node, 'normal', seriesModel, ecModel);
  50782. // Hover to change label and labelLine
  50783. function onEmphasis() {
  50784. text.ignore = text.hoverIgnore;
  50785. }
  50786. function onNormal() {
  50787. text.ignore = text.normalIgnore;
  50788. }
  50789. this.on('emphasis', onEmphasis)
  50790. .on('normal', onNormal)
  50791. .on('mouseover', onEmphasis)
  50792. .on('mouseout', onNormal);
  50793. }
  50794. var SunburstPieceProto = SunburstPiece.prototype;
  50795. SunburstPieceProto.updateData = function (
  50796. firstCreate,
  50797. node,
  50798. state,
  50799. seriesModel,
  50800. ecModel
  50801. ) {
  50802. this.node = node;
  50803. node.piece = this;
  50804. seriesModel = seriesModel || this._seriesModel;
  50805. ecModel = ecModel || this._ecModel;
  50806. var sector = this.childAt(0);
  50807. sector.dataIndex = node.dataIndex;
  50808. var itemModel = node.getModel();
  50809. var layout = node.getLayout();
  50810. var sectorShape = extend({}, layout);
  50811. sectorShape.label = null;
  50812. var visualColor = getNodeColor(node, seriesModel, ecModel);
  50813. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  50814. var style;
  50815. if (state === 'normal') {
  50816. style = normalStyle;
  50817. }
  50818. else {
  50819. var stateStyle = itemModel.getModel(state + '.itemStyle')
  50820. .getItemStyle();
  50821. style = merge(stateStyle, normalStyle);
  50822. }
  50823. style = defaults(
  50824. {
  50825. lineJoin: 'bevel',
  50826. fill: style.fill || visualColor
  50827. },
  50828. style
  50829. );
  50830. if (firstCreate) {
  50831. sector.setShape(sectorShape);
  50832. sector.shape.r = layout.r0;
  50833. updateProps(
  50834. sector,
  50835. {
  50836. shape: {
  50837. r: layout.r
  50838. }
  50839. },
  50840. seriesModel,
  50841. node.dataIndex
  50842. );
  50843. sector.useStyle(style);
  50844. }
  50845. else {
  50846. updateProps(sector, {
  50847. shape: sectorShape,
  50848. style: style
  50849. }, seriesModel);
  50850. }
  50851. if (state === 'normal') {
  50852. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle')
  50853. .getItemStyle();
  50854. setHoverStyle(this);
  50855. }
  50856. this._updateLabel(seriesModel, ecModel, visualColor);
  50857. var cursorStyle = itemModel.getShallow('cursor');
  50858. cursorStyle && sector.attr('cursor', cursorStyle);
  50859. if (firstCreate) {
  50860. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  50861. this._initEvents(sector, node, seriesModel, highlightPolicy);
  50862. }
  50863. this._seriesModel = seriesModel || this._seriesModel;
  50864. this._ecModel = ecModel || this._ecModel;
  50865. };
  50866. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  50867. var that = this;
  50868. this.node.hostTree.root.eachNode(function (n) {
  50869. if (n.piece) {
  50870. if (that.node === n) {
  50871. n.piece.updateData(false, n, 'emphasis');
  50872. }
  50873. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  50874. n.piece.childAt(0).trigger('highlight');
  50875. }
  50876. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  50877. n.piece.childAt(0).trigger('downplay');
  50878. }
  50879. }
  50880. });
  50881. };
  50882. SunburstPieceProto.onNormal = function () {
  50883. this.node.hostTree.root.eachNode(function (n) {
  50884. if (n.piece) {
  50885. n.piece.updateData(false, n, 'normal');
  50886. }
  50887. });
  50888. };
  50889. SunburstPieceProto.onHighlight = function () {
  50890. this.updateData(false, this.node, 'highlight');
  50891. };
  50892. SunburstPieceProto.onDownplay = function () {
  50893. this.updateData(false, this.node, 'downplay');
  50894. };
  50895. SunburstPieceProto._updateLabel = function (seriesModel, ecModel, visualColor) {
  50896. var itemModel = this.node.getModel();
  50897. var labelModel = itemModel.getModel('label');
  50898. var labelHoverModel = itemModel.getModel('label.emphasis');
  50899. var text = retrieve(
  50900. seriesModel.getFormattedLabel(
  50901. this.node.dataIndex, 'normal', null, null, 'label'
  50902. ),
  50903. this.node.name
  50904. );
  50905. if (!labelModel.get('show')) {
  50906. text = '';
  50907. }
  50908. var label = this.childAt(1);
  50909. setLabelStyle(
  50910. label.style, label.hoverStyle = {}, labelModel, labelHoverModel,
  50911. {
  50912. defaultText: labelModel.getShallow('show') ? text : null,
  50913. autoColor: visualColor,
  50914. useInsideStyle: true
  50915. }
  50916. );
  50917. var layout = this.node.getLayout();
  50918. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  50919. var dx = Math.cos(midAngle);
  50920. var dy = Math.sin(midAngle);
  50921. var r;
  50922. var labelPosition = labelModel.get('position');
  50923. var labelPadding = labelModel.get('distance') || 0;
  50924. var textAlign = labelModel.get('align');
  50925. if (labelPosition === 'outside') {
  50926. r = layout.r + labelPadding;
  50927. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  50928. }
  50929. else {
  50930. if (!textAlign || textAlign === 'center') {
  50931. r = (layout.r + layout.r0) / 2;
  50932. textAlign = 'center';
  50933. }
  50934. else if (textAlign === 'left') {
  50935. r = layout.r0 + labelPadding;
  50936. if (midAngle > Math.PI / 2) {
  50937. textAlign = 'right';
  50938. }
  50939. }
  50940. else if (textAlign === 'right') {
  50941. r = layout.r - labelPadding;
  50942. if (midAngle > Math.PI / 2) {
  50943. textAlign = 'left';
  50944. }
  50945. }
  50946. }
  50947. label.attr('style', {
  50948. text: text,
  50949. textAlign: textAlign,
  50950. textVerticalAlign: labelModel.get('verticalAlign') || 'middle',
  50951. opacity: labelModel.get('opacity')
  50952. });
  50953. var textX = r * dx + layout.cx;
  50954. var textY = r * dy + layout.cy;
  50955. label.attr('position', [textX, textY]);
  50956. var rotateType = labelModel.getShallow('rotate');
  50957. var rotate = 0;
  50958. if (rotateType === 'radial') {
  50959. rotate = -midAngle;
  50960. if (rotate < -Math.PI / 2) {
  50961. rotate += Math.PI;
  50962. }
  50963. }
  50964. else if (rotateType === 'tangential') {
  50965. rotate = Math.PI / 2 - midAngle;
  50966. if (rotate > Math.PI / 2) {
  50967. rotate -= Math.PI;
  50968. }
  50969. else if (rotate < -Math.PI / 2) {
  50970. rotate += Math.PI;
  50971. }
  50972. } else if (typeof rotateType === 'number') {
  50973. rotate = rotateType * Math.PI / 180;
  50974. }
  50975. label.attr('rotation', rotate);
  50976. };
  50977. SunburstPieceProto._initEvents = function (
  50978. sector,
  50979. node,
  50980. seriesModel,
  50981. highlightPolicy
  50982. ) {
  50983. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  50984. var that = this;
  50985. var onEmphasis = function () {
  50986. that.onEmphasis(highlightPolicy);
  50987. };
  50988. var onNormal = function () {
  50989. that.onNormal();
  50990. };
  50991. var onDownplay = function () {
  50992. that.onDownplay();
  50993. };
  50994. var onHighlight = function () {
  50995. that.onHighlight();
  50996. };
  50997. if (seriesModel.isAnimationEnabled()) {
  50998. sector
  50999. .on('mouseover', onEmphasis)
  51000. .on('mouseout', onNormal)
  51001. .on('emphasis', onEmphasis)
  51002. .on('normal', onNormal)
  51003. .on('downplay', onDownplay)
  51004. .on('highlight', onHighlight);
  51005. }
  51006. };
  51007. inherits(SunburstPiece, Group);
  51008. /**
  51009. * Get node color
  51010. *
  51011. * @param {TreeNode} node the node to get color
  51012. * @param {module:echarts/model/Series} seriesModel series
  51013. * @param {module:echarts/model/Global} ecModel echarts defaults
  51014. */
  51015. function getNodeColor(node, seriesModel, ecModel) {
  51016. // Color from visualMap
  51017. var visualColor = node.getVisual('color');
  51018. var visualMetaList = node.getVisual('visualMeta');
  51019. if (visualMetaList.length === 0) {
  51020. // Use first-generation color if has no visualMap
  51021. visualColor = null;
  51022. }
  51023. // Self color or level color
  51024. var color = node.getModel('itemStyle').get('color');
  51025. if (color) {
  51026. return color;
  51027. }
  51028. else if (visualColor) {
  51029. // Color mapping
  51030. return visualColor;
  51031. }
  51032. else if (node.depth === 0) {
  51033. // Virtual root node
  51034. return ecModel.option.color[0];
  51035. }
  51036. else {
  51037. // First-generation color
  51038. var length = ecModel.option.color.length;
  51039. color = ecModel.option.color[getRootId(node) % length];
  51040. }
  51041. return color;
  51042. }
  51043. /**
  51044. * Get index of root in sorted order
  51045. *
  51046. * @param {TreeNode} node current node
  51047. * @return {number} index in root
  51048. */
  51049. function getRootId(node) {
  51050. var ancestor = node;
  51051. while (ancestor.depth > 1) {
  51052. ancestor = ancestor.parentNode;
  51053. }
  51054. var virtualRoot = node.getAncestors()[0];
  51055. return indexOf(virtualRoot.children, ancestor);
  51056. }
  51057. function isNodeHighlighted(node, activeNode, policy) {
  51058. if (policy === NodeHighlightPolicy.NONE) {
  51059. return false;
  51060. }
  51061. else if (policy === NodeHighlightPolicy.SELF) {
  51062. return node === activeNode;
  51063. }
  51064. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  51065. return node === activeNode || node.isAncestorOf(activeNode);
  51066. }
  51067. else {
  51068. return node === activeNode || node.isDescendantOf(activeNode);
  51069. }
  51070. }
  51071. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  51072. var SunburstView = Chart.extend({
  51073. type: 'sunburst',
  51074. init: function () {
  51075. },
  51076. render: function (seriesModel, ecModel, api, payload) {
  51077. var that = this;
  51078. this.seriesModel = seriesModel;
  51079. this.api = api;
  51080. this.ecModel = ecModel;
  51081. var virtualRoot = seriesModel.getData().tree.root;
  51082. var newRoot = seriesModel.getViewRoot();
  51083. var group = this.group;
  51084. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  51085. var newChildren = [];
  51086. newRoot.eachNode(function (node) {
  51087. newChildren.push(node);
  51088. });
  51089. var oldChildren = this._oldChildren || [];
  51090. dualTravel(newChildren, oldChildren);
  51091. renderRollUp(virtualRoot, newRoot);
  51092. if (payload && payload.highlight && payload.highlight.piece) {
  51093. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  51094. payload.highlight.piece.onEmphasis(highlightPolicy);
  51095. }
  51096. else if (payload && payload.unhighlight) {
  51097. var piece = virtualRoot.piece;
  51098. if (!piece && virtualRoot.children.length) {
  51099. piece = virtualRoot.children[0].piece;
  51100. }
  51101. if (piece) {
  51102. piece.onNormal();
  51103. }
  51104. }
  51105. this._initEvents();
  51106. this._oldChildren = newChildren;
  51107. function dualTravel(newChildren, oldChildren) {
  51108. if (newChildren.length === 0 && oldChildren.length === 0) {
  51109. return;
  51110. }
  51111. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  51112. .add(processNode)
  51113. .update(processNode)
  51114. .remove(curry(processNode, null))
  51115. .execute();
  51116. function getKey(node) {
  51117. return node.getId();
  51118. }
  51119. function processNode(newId, oldId) {
  51120. var newNode = newId == null ? null : newChildren[newId];
  51121. var oldNode = oldId == null ? null : oldChildren[oldId];
  51122. doRenderNode(newNode, oldNode);
  51123. }
  51124. }
  51125. function doRenderNode(newNode, oldNode) {
  51126. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  51127. // Not render data with value 0
  51128. newNode = null;
  51129. }
  51130. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  51131. if (oldNode && oldNode.piece) {
  51132. if (newNode) {
  51133. // Update
  51134. oldNode.piece.updateData(
  51135. false, newNode, 'normal', seriesModel, ecModel);
  51136. }
  51137. else {
  51138. // Remove
  51139. removeNode(oldNode);
  51140. }
  51141. }
  51142. else if (newNode) {
  51143. // Add
  51144. var piece = new SunburstPiece(
  51145. newNode,
  51146. seriesModel,
  51147. ecModel
  51148. );
  51149. group.add(piece);
  51150. }
  51151. }
  51152. }
  51153. function removeNode(node) {
  51154. if (!node) {
  51155. return;
  51156. }
  51157. if (node.piece) {
  51158. group.remove(node.piece);
  51159. node.piece = null;
  51160. }
  51161. }
  51162. function renderRollUp(virtualRoot, viewRoot) {
  51163. if (viewRoot.depth > 0) {
  51164. // Render
  51165. if (virtualRoot.piece) {
  51166. // Update
  51167. virtualRoot.piece.updateData(
  51168. false, virtualRoot, 'normal', seriesModel, ecModel);
  51169. }
  51170. else {
  51171. // Add
  51172. virtualRoot.piece = new SunburstPiece(
  51173. virtualRoot,
  51174. seriesModel,
  51175. ecModel
  51176. );
  51177. group.add(virtualRoot.piece);
  51178. }
  51179. if (viewRoot.piece._onclickEvent) {
  51180. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  51181. }
  51182. var event = function (e) {
  51183. that._rootToNode(viewRoot.parentNode);
  51184. };
  51185. viewRoot.piece._onclickEvent = event;
  51186. virtualRoot.piece.on('click', event);
  51187. }
  51188. else if (virtualRoot.piece) {
  51189. // Remove
  51190. group.remove(virtualRoot.piece);
  51191. virtualRoot.piece = null;
  51192. }
  51193. }
  51194. },
  51195. dispose: function () {
  51196. },
  51197. /**
  51198. * @private
  51199. */
  51200. _initEvents: function () {
  51201. var that = this;
  51202. var event = function (e) {
  51203. var nodeClick = that.seriesModel.get('nodeClick', true);
  51204. if (!nodeClick) {
  51205. return;
  51206. }
  51207. var targetFound = false;
  51208. var viewRoot = that.seriesModel.getViewRoot();
  51209. viewRoot.eachNode(function (node) {
  51210. if (!targetFound
  51211. && node.piece && node.piece.childAt(0) === e.target
  51212. ) {
  51213. if (nodeClick === 'rootToNode') {
  51214. that._rootToNode(node);
  51215. }
  51216. else if (nodeClick === 'link') {
  51217. var itemModel = node.getModel();
  51218. var link = itemModel.get('link', true);
  51219. if (link) {
  51220. var linkTarget = itemModel.get('target', true)
  51221. || '_blank';
  51222. link && window.open(link, linkTarget);
  51223. }
  51224. }
  51225. targetFound = true;
  51226. }
  51227. });
  51228. };
  51229. if (this.group._onclickEvent) {
  51230. this.group.off('click', this.group._onclickEvent);
  51231. }
  51232. this.group.on('click', event);
  51233. this.group._onclickEvent = event;
  51234. },
  51235. /**
  51236. * @private
  51237. */
  51238. _rootToNode: function (node) {
  51239. if (node !== this.seriesModel.getViewRoot()) {
  51240. this.api.dispatchAction({
  51241. type: ROOT_TO_NODE_ACTION,
  51242. from: this.uid,
  51243. seriesId: this.seriesModel.id,
  51244. targetNode: node
  51245. });
  51246. }
  51247. },
  51248. /**
  51249. * @implement
  51250. */
  51251. containPoint: function (point, seriesModel) {
  51252. var treeRoot = seriesModel.getData();
  51253. var itemLayout = treeRoot.getItemLayout(0);
  51254. if (itemLayout) {
  51255. var dx = point[0] - itemLayout.cx;
  51256. var dy = point[1] - itemLayout.cy;
  51257. var radius = Math.sqrt(dx * dx + dy * dy);
  51258. return radius <= itemLayout.r && radius >= itemLayout.r0;
  51259. }
  51260. }
  51261. });
  51262. /**
  51263. * @file Sunburst action
  51264. */
  51265. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  51266. registerAction(
  51267. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  51268. function (payload, ecModel) {
  51269. ecModel.eachComponent(
  51270. {mainType: 'series', subType: 'sunburst', query: payload},
  51271. handleRootToNode
  51272. );
  51273. function handleRootToNode(model, index) {
  51274. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  51275. if (targetInfo) {
  51276. var originViewRoot = model.getViewRoot();
  51277. if (originViewRoot) {
  51278. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  51279. ? 'rollUp' : 'drillDown';
  51280. }
  51281. model.resetViewRoot(targetInfo.node);
  51282. }
  51283. }
  51284. }
  51285. );
  51286. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  51287. registerAction(
  51288. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  51289. function (payload, ecModel) {
  51290. ecModel.eachComponent(
  51291. {mainType: 'series', subType: 'sunburst', query: payload},
  51292. handleHighlight
  51293. );
  51294. function handleHighlight(model, index) {
  51295. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  51296. if (targetInfo) {
  51297. payload.highlight = targetInfo.node;
  51298. }
  51299. }
  51300. }
  51301. );
  51302. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  51303. registerAction(
  51304. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  51305. function (payload, ecModel) {
  51306. ecModel.eachComponent(
  51307. {mainType: 'series', subType: 'sunburst', query: payload},
  51308. handleUnhighlight
  51309. );
  51310. function handleUnhighlight(model, index) {
  51311. payload.unhighlight = true;
  51312. }
  51313. }
  51314. );
  51315. var RADIAN$1 = Math.PI / 180;
  51316. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  51317. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  51318. var center = seriesModel.get('center');
  51319. var radius = seriesModel.get('radius');
  51320. if (!isArray(radius)) {
  51321. radius = [0, radius];
  51322. }
  51323. if (!isArray(center)) {
  51324. center = [center, center];
  51325. }
  51326. var width = api.getWidth();
  51327. var height = api.getHeight();
  51328. var size = Math.min(width, height);
  51329. var cx = parsePercent$1(center[0], width);
  51330. var cy = parsePercent$1(center[1], height);
  51331. var r0 = parsePercent$1(radius[0], size / 2);
  51332. var r = parsePercent$1(radius[1], size / 2);
  51333. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  51334. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  51335. var virtualRoot = seriesModel.getData().tree.root;
  51336. var treeRoot = seriesModel.getViewRoot();
  51337. var rootDepth = treeRoot.depth;
  51338. var sort = seriesModel.get('sort');
  51339. if (sort != null) {
  51340. initChildren$1(treeRoot, sort);
  51341. }
  51342. var validDataCount = 0;
  51343. each$1(treeRoot.children, function (child) {
  51344. !isNaN(child.getValue()) && validDataCount++;
  51345. });
  51346. var sum = treeRoot.getValue();
  51347. // Sum may be 0
  51348. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  51349. var renderRollupNode = treeRoot.depth > 0;
  51350. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  51351. var rPerLevel = (r - r0) / (levels || 1);
  51352. var clockwise = seriesModel.get('clockwise');
  51353. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  51354. // In the case some sector angle is smaller than minAngle
  51355. var dir = clockwise ? 1 : -1;
  51356. /**
  51357. * Render a tree
  51358. * @return increased angle
  51359. */
  51360. var renderNode = function (node, startAngle) {
  51361. if (!node) {
  51362. return;
  51363. }
  51364. var endAngle = startAngle;
  51365. // Render self
  51366. if (node !== virtualRoot) {
  51367. // Tree node is virtual, so it doesn't need to be drawn
  51368. var value = node.getValue();
  51369. var angle = (sum === 0 && stillShowZeroSum)
  51370. ? unitRadian : (value * unitRadian);
  51371. if (angle < minAngle) {
  51372. angle = minAngle;
  51373. }
  51374. else {
  51375. }
  51376. endAngle = startAngle + dir * angle;
  51377. var depth = node.depth - rootDepth
  51378. - (renderRollupNode ? -1 : 1);
  51379. var rStart = r0 + rPerLevel * depth;
  51380. var rEnd = r0 + rPerLevel * (depth + 1);
  51381. var itemModel = node.getModel();
  51382. if (itemModel.get('r0') != null) {
  51383. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  51384. }
  51385. if (itemModel.get('r') != null) {
  51386. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  51387. }
  51388. node.setLayout({
  51389. angle: angle,
  51390. startAngle: startAngle,
  51391. endAngle: endAngle,
  51392. clockwise: clockwise,
  51393. cx: cx,
  51394. cy: cy,
  51395. r0: rStart,
  51396. r: rEnd
  51397. });
  51398. }
  51399. // Render children
  51400. if (node.children && node.children.length) {
  51401. // currentAngle = startAngle;
  51402. var siblingAngle = 0;
  51403. each$1(node.children, function (node) {
  51404. siblingAngle += renderNode(node, startAngle + siblingAngle);
  51405. });
  51406. }
  51407. return endAngle - startAngle;
  51408. };
  51409. // Virtual root node for roll up
  51410. if (renderRollupNode) {
  51411. var rStart = r0;
  51412. var rEnd = r0 + rPerLevel;
  51413. var angle = Math.PI * 2;
  51414. virtualRoot.setLayout({
  51415. angle: angle,
  51416. startAngle: startAngle,
  51417. endAngle: startAngle + angle,
  51418. clockwise: clockwise,
  51419. cx: cx,
  51420. cy: cy,
  51421. r0: rStart,
  51422. r: rEnd
  51423. });
  51424. }
  51425. renderNode(treeRoot, startAngle);
  51426. });
  51427. };
  51428. /**
  51429. * Init node children by order and update visual
  51430. *
  51431. * @param {TreeNode} node root node
  51432. * @param {boolean} isAsc if is in ascendant order
  51433. */
  51434. function initChildren$1(node, isAsc) {
  51435. var children = node.children || [];
  51436. node.children = sort$2(children, isAsc);
  51437. // Init children recursively
  51438. if (children.length) {
  51439. each$1(node.children, function (child) {
  51440. initChildren$1(child, isAsc);
  51441. });
  51442. }
  51443. }
  51444. /**
  51445. * Sort children nodes
  51446. *
  51447. * @param {TreeNode[]} children children of node to be sorted
  51448. * @param {string | function | null} sort sort method
  51449. * See SunburstSeries.js for details.
  51450. */
  51451. function sort$2(children, sortOrder) {
  51452. if (typeof sortOrder === 'function') {
  51453. return children.sort(sortOrder);
  51454. }
  51455. else {
  51456. var isAsc = sortOrder === 'asc';
  51457. return children.sort(function (a, b) {
  51458. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  51459. return diff === 0
  51460. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  51461. : diff;
  51462. });
  51463. }
  51464. }
  51465. registerVisual(curry(dataColor, 'sunburst'));
  51466. registerLayout(curry(sunburstLayout, 'sunburst'));
  51467. registerProcessor(curry(dataFilter, 'sunburst'));
  51468. function dataToCoordSize(dataSize, dataItem) {
  51469. // dataItem is necessary in log axis.
  51470. dataItem = dataItem || [0, 0];
  51471. return map(['x', 'y'], function (dim, dimIdx) {
  51472. var axis = this.getAxis(dim);
  51473. var val = dataItem[dimIdx];
  51474. var halfSize = dataSize[dimIdx] / 2;
  51475. return axis.type === 'category'
  51476. ? axis.getBandWidth()
  51477. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  51478. }, this);
  51479. }
  51480. var prepareCartesian2d = function (coordSys) {
  51481. var rect = coordSys.grid.getRect();
  51482. return {
  51483. coordSys: {
  51484. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  51485. type: 'cartesian2d',
  51486. x: rect.x,
  51487. y: rect.y,
  51488. width: rect.width,
  51489. height: rect.height
  51490. },
  51491. api: {
  51492. coord: function (data) {
  51493. // do not provide "out" param
  51494. return coordSys.dataToPoint(data);
  51495. },
  51496. size: bind(dataToCoordSize, coordSys)
  51497. }
  51498. };
  51499. };
  51500. function dataToCoordSize$1(dataSize, dataItem) {
  51501. dataItem = dataItem || [0, 0];
  51502. return map([0, 1], function (dimIdx) {
  51503. var val = dataItem[dimIdx];
  51504. var halfSize = dataSize[dimIdx] / 2;
  51505. var p1 = [];
  51506. var p2 = [];
  51507. p1[dimIdx] = val - halfSize;
  51508. p2[dimIdx] = val + halfSize;
  51509. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  51510. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  51511. }, this);
  51512. }
  51513. var prepareGeo = function (coordSys) {
  51514. var rect = coordSys.getBoundingRect();
  51515. return {
  51516. coordSys: {
  51517. type: 'geo',
  51518. x: rect.x,
  51519. y: rect.y,
  51520. width: rect.width,
  51521. height: rect.height
  51522. },
  51523. api: {
  51524. coord: function (data, noRoam) {
  51525. // do not provide "out" param
  51526. return coordSys.dataToPoint(data, noRoam);
  51527. },
  51528. size: bind(dataToCoordSize$1, coordSys)
  51529. }
  51530. };
  51531. };
  51532. function dataToCoordSize$2(dataSize, dataItem) {
  51533. // dataItem is necessary in log axis.
  51534. var axis = this.getAxis();
  51535. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  51536. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  51537. return axis.type === 'category'
  51538. ? axis.getBandWidth()
  51539. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  51540. }
  51541. var prepareSingleAxis = function (coordSys) {
  51542. var rect = coordSys.getRect();
  51543. return {
  51544. coordSys: {
  51545. type: 'singleAxis',
  51546. x: rect.x,
  51547. y: rect.y,
  51548. width: rect.width,
  51549. height: rect.height
  51550. },
  51551. api: {
  51552. coord: function (val) {
  51553. // do not provide "out" param
  51554. return coordSys.dataToPoint(val);
  51555. },
  51556. size: bind(dataToCoordSize$2, coordSys)
  51557. }
  51558. };
  51559. };
  51560. function dataToCoordSize$3(dataSize, dataItem) {
  51561. // dataItem is necessary in log axis.
  51562. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  51563. var axis = this['get' + dim + 'Axis']();
  51564. var val = dataItem[dimIdx];
  51565. var halfSize = dataSize[dimIdx] / 2;
  51566. var method = 'dataTo' + dim;
  51567. var result = axis.type === 'category'
  51568. ? axis.getBandWidth()
  51569. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  51570. if (dim === 'Angle') {
  51571. result = result * Math.PI / 180;
  51572. }
  51573. return result;
  51574. }, this);
  51575. }
  51576. var preparePolar = function (coordSys) {
  51577. var radiusAxis = coordSys.getRadiusAxis();
  51578. var angleAxis = coordSys.getAngleAxis();
  51579. var radius = radiusAxis.getExtent();
  51580. radius[0] > radius[1] && radius.reverse();
  51581. return {
  51582. coordSys: {
  51583. type: 'polar',
  51584. cx: coordSys.cx,
  51585. cy: coordSys.cy,
  51586. r: radius[1],
  51587. r0: radius[0]
  51588. },
  51589. api: {
  51590. coord: bind(function (data) {
  51591. var radius = radiusAxis.dataToRadius(data[0]);
  51592. var angle = angleAxis.dataToAngle(data[1]);
  51593. var coord = coordSys.coordToPoint([radius, angle]);
  51594. coord.push(radius, angle * Math.PI / 180);
  51595. return coord;
  51596. }),
  51597. size: bind(dataToCoordSize$3, coordSys)
  51598. }
  51599. };
  51600. };
  51601. var prepareCalendar = function (coordSys) {
  51602. var rect = coordSys.getRect();
  51603. var rangeInfo = coordSys.getRangeInfo();
  51604. return {
  51605. coordSys: {
  51606. type: 'calendar',
  51607. x: rect.x,
  51608. y: rect.y,
  51609. width: rect.width,
  51610. height: rect.height,
  51611. cellWidth: coordSys.getCellWidth(),
  51612. cellHeight: coordSys.getCellHeight(),
  51613. rangeInfo: {
  51614. start: rangeInfo.start,
  51615. end: rangeInfo.end,
  51616. weeks: rangeInfo.weeks,
  51617. dayCount: rangeInfo.allDay
  51618. }
  51619. },
  51620. api: {
  51621. coord: function (data, clamp) {
  51622. return coordSys.dataToPoint(data, clamp);
  51623. },
  51624. }
  51625. };
  51626. };
  51627. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  51628. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  51629. var LABEL_NORMAL = ['label'];
  51630. var LABEL_EMPHASIS = ['emphasis', 'label'];
  51631. // Use prefix to avoid index to be the same as el.name,
  51632. // which will cause weird udpate animation.
  51633. var GROUP_DIFF_PREFIX = 'e\0\0';
  51634. /**
  51635. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  51636. * of each coordinate systems are not required by each coordinate systems directly, but
  51637. * required by the module `custom`.
  51638. *
  51639. * prepareInfoForCustomSeries {Function}: optional
  51640. * @return {Object} {coordSys: {...}, api: {
  51641. * coord: function (data, clamp) {}, // return point in global.
  51642. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  51643. * }}
  51644. */
  51645. var prepareCustoms = {
  51646. cartesian2d: prepareCartesian2d,
  51647. geo: prepareGeo,
  51648. singleAxis: prepareSingleAxis,
  51649. polar: preparePolar,
  51650. calendar: prepareCalendar
  51651. };
  51652. // ------
  51653. // Model
  51654. // ------
  51655. extendSeriesModel({
  51656. type: 'series.custom',
  51657. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  51658. defaultOption: {
  51659. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  51660. zlevel: 0,
  51661. z: 2,
  51662. legendHoverLink: true
  51663. // Cartesian coordinate system
  51664. // xAxisIndex: 0,
  51665. // yAxisIndex: 0,
  51666. // Polar coordinate system
  51667. // polarIndex: 0,
  51668. // Geo coordinate system
  51669. // geoIndex: 0,
  51670. // label: {}
  51671. // itemStyle: {}
  51672. },
  51673. getInitialData: function (option, ecModel) {
  51674. return createListFromArray(this.getSource(), this);
  51675. }
  51676. });
  51677. // -----
  51678. // View
  51679. // -----
  51680. extendChartView({
  51681. type: 'custom',
  51682. /**
  51683. * @private
  51684. * @type {module:echarts/data/List}
  51685. */
  51686. _data: null,
  51687. /**
  51688. * @override
  51689. */
  51690. render: function (customSeries, ecModel, api) {
  51691. var oldData = this._data;
  51692. var data = customSeries.getData();
  51693. var group = this.group;
  51694. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  51695. this.group.removeAll();
  51696. data.diff(oldData)
  51697. .add(function (newIdx) {
  51698. data.hasValue(newIdx) && createOrUpdate$1(
  51699. null, newIdx, renderItem(newIdx), customSeries, group, data
  51700. );
  51701. })
  51702. .update(function (newIdx, oldIdx) {
  51703. var el = oldData.getItemGraphicEl(oldIdx);
  51704. data.hasValue(newIdx)
  51705. ? createOrUpdate$1(
  51706. el, newIdx, renderItem(newIdx), customSeries, group, data
  51707. )
  51708. : (el && group.remove(el));
  51709. })
  51710. .remove(function (oldIdx) {
  51711. var el = oldData.getItemGraphicEl(oldIdx);
  51712. el && group.remove(el);
  51713. })
  51714. .execute();
  51715. this._data = data;
  51716. },
  51717. incrementalPrepareRender: function (customSeries, ecModel, api) {
  51718. this.group.removeAll();
  51719. this._data = null;
  51720. },
  51721. incrementalRender: function (params, customSeries, ecModel, api) {
  51722. var data = customSeries.getData();
  51723. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  51724. function setIncrementalAndHoverLayer(el) {
  51725. if (!el.isGroup) {
  51726. el.incremental = true;
  51727. el.useHoverLayer = true;
  51728. }
  51729. }
  51730. for (var idx = params.start; idx < params.end; idx++) {
  51731. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  51732. el.traverse(setIncrementalAndHoverLayer);
  51733. }
  51734. },
  51735. /**
  51736. * @override
  51737. */
  51738. dispose: noop
  51739. });
  51740. function createEl(elOption) {
  51741. var graphicType = elOption.type;
  51742. var el;
  51743. if (graphicType === 'path') {
  51744. var shape = elOption.shape;
  51745. el = makePath(
  51746. shape.pathData,
  51747. null,
  51748. {
  51749. x: shape.x || 0,
  51750. y: shape.y || 0,
  51751. width: shape.width || 0,
  51752. height: shape.height || 0
  51753. },
  51754. 'center'
  51755. );
  51756. el.__customPathData = elOption.pathData;
  51757. }
  51758. else if (graphicType === 'image') {
  51759. el = new ZImage({
  51760. });
  51761. el.__customImagePath = elOption.style.image;
  51762. }
  51763. else if (graphicType === 'text') {
  51764. el = new Text({
  51765. });
  51766. el.__customText = elOption.style.text;
  51767. }
  51768. else {
  51769. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  51770. if (__DEV__) {
  51771. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  51772. }
  51773. el = new Clz();
  51774. }
  51775. el.__customGraphicType = graphicType;
  51776. el.name = elOption.name;
  51777. return el;
  51778. }
  51779. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  51780. var targetProps = {};
  51781. var elOptionStyle = elOption.style || {};
  51782. elOption.shape && (targetProps.shape = clone(elOption.shape));
  51783. elOption.position && (targetProps.position = elOption.position.slice());
  51784. elOption.scale && (targetProps.scale = elOption.scale.slice());
  51785. elOption.origin && (targetProps.origin = elOption.origin.slice());
  51786. elOption.rotation && (targetProps.rotation = elOption.rotation);
  51787. if (el.type === 'image' && elOption.style) {
  51788. var targetStyle = targetProps.style = {};
  51789. each$1(['x', 'y', 'width', 'height'], function (prop) {
  51790. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  51791. });
  51792. }
  51793. if (el.type === 'text' && elOption.style) {
  51794. var targetStyle = targetProps.style = {};
  51795. each$1(['x', 'y'], function (prop) {
  51796. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  51797. });
  51798. // Compatible with previous: both support
  51799. // textFill and fill, textStroke and stroke in 'text' element.
  51800. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  51801. elOptionStyle.textFill = elOptionStyle.fill
  51802. );
  51803. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  51804. elOptionStyle.textStroke = elOptionStyle.stroke
  51805. );
  51806. }
  51807. if (el.type !== 'group') {
  51808. el.useStyle(elOptionStyle);
  51809. // Init animation.
  51810. if (isInit) {
  51811. el.style.opacity = 0;
  51812. var targetOpacity = elOptionStyle.opacity;
  51813. targetOpacity == null && (targetOpacity = 1);
  51814. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  51815. }
  51816. }
  51817. if (isInit) {
  51818. el.attr(targetProps);
  51819. }
  51820. else {
  51821. updateProps(el, targetProps, animatableModel, dataIndex);
  51822. }
  51823. // z2 must not be null/undefined, otherwise sort error may occur.
  51824. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  51825. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  51826. }
  51827. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  51828. if (elOptionStyle[prop] != null && !isInit) {
  51829. targetStyle[prop] = elOptionStyle[prop];
  51830. elOptionStyle[prop] = oldElStyle[prop];
  51831. }
  51832. }
  51833. function makeRenderItem(customSeries, data, ecModel, api) {
  51834. var renderItem = customSeries.get('renderItem');
  51835. var coordSys = customSeries.coordinateSystem;
  51836. var prepareResult = {};
  51837. if (coordSys) {
  51838. if (__DEV__) {
  51839. assert$1(renderItem, 'series.render is required.');
  51840. assert$1(
  51841. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  51842. 'This coordSys does not support custom series.'
  51843. );
  51844. }
  51845. prepareResult = coordSys.prepareCustoms
  51846. ? coordSys.prepareCustoms()
  51847. : prepareCustoms[coordSys.type](coordSys);
  51848. }
  51849. var userAPI = defaults({
  51850. getWidth: api.getWidth,
  51851. getHeight: api.getHeight,
  51852. getZr: api.getZr,
  51853. getDevicePixelRatio: api.getDevicePixelRatio,
  51854. value: value,
  51855. style: style,
  51856. styleEmphasis: styleEmphasis,
  51857. visual: visual,
  51858. barLayout: barLayout,
  51859. currentSeriesIndices: currentSeriesIndices,
  51860. font: font
  51861. }, prepareResult.api || {});
  51862. var userParams = {
  51863. context: {},
  51864. seriesId: customSeries.id,
  51865. seriesName: customSeries.name,
  51866. seriesIndex: customSeries.seriesIndex,
  51867. coordSys: prepareResult.coordSys,
  51868. dataInsideLength: data.count(),
  51869. encode: wrapEncodeDef(customSeries.getData())
  51870. };
  51871. // Do not support call `api` asynchronously without dataIndexInside input.
  51872. var currDataIndexInside;
  51873. var currDirty = true;
  51874. var currItemModel;
  51875. var currLabelNormalModel;
  51876. var currLabelEmphasisModel;
  51877. var currVisualColor;
  51878. return function (dataIndexInside) {
  51879. currDataIndexInside = dataIndexInside;
  51880. currDirty = true;
  51881. return renderItem && renderItem(
  51882. defaults({
  51883. dataIndexInside: dataIndexInside,
  51884. dataIndex: data.getRawIndex(dataIndexInside)
  51885. }, userParams),
  51886. userAPI
  51887. ) || {};
  51888. };
  51889. // Do not update cache until api called.
  51890. function updateCache(dataIndexInside) {
  51891. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  51892. if (currDirty) {
  51893. currItemModel = data.getItemModel(dataIndexInside);
  51894. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  51895. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  51896. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  51897. currDirty = false;
  51898. }
  51899. }
  51900. /**
  51901. * @public
  51902. * @param {number|string} dim
  51903. * @param {number} [dataIndexInside=currDataIndexInside]
  51904. * @return {number|string} value
  51905. */
  51906. function value(dim, dataIndexInside) {
  51907. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  51908. return data.get(data.getDimension(dim || 0), dataIndexInside);
  51909. }
  51910. /**
  51911. * By default, `visual` is applied to style (to support visualMap).
  51912. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  51913. * it can be implemented as:
  51914. * `api.style({stroke: api.visual('color'), fill: null})`;
  51915. * @public
  51916. * @param {Object} [extra]
  51917. * @param {number} [dataIndexInside=currDataIndexInside]
  51918. */
  51919. function style(extra, dataIndexInside) {
  51920. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  51921. updateCache(dataIndexInside);
  51922. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  51923. currVisualColor != null && (itemStyle.fill = currVisualColor);
  51924. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  51925. opacity != null && (itemStyle.opacity = opacity);
  51926. setTextStyle(itemStyle, currLabelNormalModel, null, {
  51927. autoColor: currVisualColor,
  51928. isRectText: true
  51929. });
  51930. itemStyle.text = currLabelNormalModel.getShallow('show')
  51931. ? retrieve2(
  51932. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  51933. getDefaultLabel(data, dataIndexInside)
  51934. )
  51935. : null;
  51936. extra && extend(itemStyle, extra);
  51937. return itemStyle;
  51938. }
  51939. /**
  51940. * @public
  51941. * @param {Object} [extra]
  51942. * @param {number} [dataIndexInside=currDataIndexInside]
  51943. */
  51944. function styleEmphasis(extra, dataIndexInside) {
  51945. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  51946. updateCache(dataIndexInside);
  51947. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  51948. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  51949. isRectText: true
  51950. }, true);
  51951. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  51952. ? retrieve3(
  51953. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  51954. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  51955. getDefaultLabel(data, dataIndexInside)
  51956. )
  51957. : null;
  51958. extra && extend(itemStyle, extra);
  51959. return itemStyle;
  51960. }
  51961. /**
  51962. * @public
  51963. * @param {string} visualType
  51964. * @param {number} [dataIndexInside=currDataIndexInside]
  51965. */
  51966. function visual(visualType, dataIndexInside) {
  51967. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  51968. return data.getItemVisual(dataIndexInside, visualType);
  51969. }
  51970. /**
  51971. * @public
  51972. * @param {number} opt.count Positive interger.
  51973. * @param {number} [opt.barWidth]
  51974. * @param {number} [opt.barMaxWidth]
  51975. * @param {number} [opt.barGap]
  51976. * @param {number} [opt.barCategoryGap]
  51977. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  51978. */
  51979. function barLayout(opt) {
  51980. if (coordSys.getBaseAxis) {
  51981. var baseAxis = coordSys.getBaseAxis();
  51982. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  51983. }
  51984. }
  51985. /**
  51986. * @public
  51987. * @return {Array.<number>}
  51988. */
  51989. function currentSeriesIndices() {
  51990. return ecModel.getCurrentSeriesIndices();
  51991. }
  51992. /**
  51993. * @public
  51994. * @param {Object} opt
  51995. * @param {string} [opt.fontStyle]
  51996. * @param {number} [opt.fontWeight]
  51997. * @param {number} [opt.fontSize]
  51998. * @param {string} [opt.fontFamily]
  51999. * @return {string} font string
  52000. */
  52001. function font(opt) {
  52002. return getFont(opt, ecModel);
  52003. }
  52004. }
  52005. function wrapEncodeDef(data) {
  52006. var encodeDef = {};
  52007. each$1(data.dimensions, function (dimName, dataDimIndex) {
  52008. var dimInfo = data.getDimensionInfo(dimName);
  52009. if (!dimInfo.isExtraCoord) {
  52010. var coordDim = dimInfo.coordDim;
  52011. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  52012. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  52013. }
  52014. });
  52015. return encodeDef;
  52016. }
  52017. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  52018. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  52019. el && data.setItemGraphicEl(dataIndex, el);
  52020. return el;
  52021. }
  52022. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  52023. var elOptionType = elOption.type;
  52024. if (el
  52025. && elOptionType !== el.__customGraphicType
  52026. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  52027. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  52028. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  52029. ) {
  52030. group.remove(el);
  52031. el = null;
  52032. }
  52033. // `elOption.type` is undefined when `renderItem` returns nothing.
  52034. if (elOptionType == null) {
  52035. return;
  52036. }
  52037. var isInit = !el;
  52038. !el && (el = createEl(elOption));
  52039. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  52040. if (elOptionType === 'group') {
  52041. var oldChildren = el.children() || [];
  52042. var newChildren = elOption.children || [];
  52043. if (elOption.diffChildrenByName) {
  52044. // lower performance.
  52045. diffGroupChildren({
  52046. oldChildren: oldChildren,
  52047. newChildren: newChildren,
  52048. dataIndex: dataIndex,
  52049. animatableModel: animatableModel,
  52050. group: el,
  52051. data: data
  52052. });
  52053. }
  52054. else {
  52055. // better performance.
  52056. var index = 0;
  52057. for (; index < newChildren.length; index++) {
  52058. doCreateOrUpdate(
  52059. el.childAt(index),
  52060. dataIndex,
  52061. newChildren[index],
  52062. animatableModel,
  52063. el,
  52064. data
  52065. );
  52066. }
  52067. for (; index < oldChildren.length; index++) {
  52068. oldChildren[index] && el.remove(oldChildren[index]);
  52069. }
  52070. }
  52071. }
  52072. group.add(el);
  52073. return el;
  52074. }
  52075. function diffGroupChildren(context) {
  52076. (new DataDiffer(
  52077. context.oldChildren,
  52078. context.newChildren,
  52079. getKey,
  52080. getKey,
  52081. context
  52082. ))
  52083. .add(processAddUpdate)
  52084. .update(processAddUpdate)
  52085. .remove(processRemove)
  52086. .execute();
  52087. }
  52088. function getKey(item, idx) {
  52089. var name = item && item.name;
  52090. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  52091. }
  52092. function processAddUpdate(newIndex, oldIndex) {
  52093. var context = this.context;
  52094. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  52095. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  52096. doCreateOrUpdate(
  52097. child,
  52098. context.dataIndex,
  52099. childOption,
  52100. context.animatableModel,
  52101. context.group,
  52102. context.data
  52103. );
  52104. }
  52105. function processRemove(oldIndex) {
  52106. var context = this.context;
  52107. var child = context.oldChildren[oldIndex];
  52108. child && context.group.remove(child);
  52109. }
  52110. // -------------
  52111. // Preprocessor
  52112. // -------------
  52113. registerPreprocessor(function (option) {
  52114. var graphicOption = option.graphic;
  52115. // Convert
  52116. // {graphic: [{left: 10, type: 'circle'}, ...]}
  52117. // or
  52118. // {graphic: {left: 10, type: 'circle'}}
  52119. // to
  52120. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  52121. if (isArray(graphicOption)) {
  52122. if (!graphicOption[0] || !graphicOption[0].elements) {
  52123. option.graphic = [{elements: graphicOption}];
  52124. }
  52125. else {
  52126. // Only one graphic instance can be instantiated. (We dont
  52127. // want that too many views are created in echarts._viewMap)
  52128. option.graphic = [option.graphic[0]];
  52129. }
  52130. }
  52131. else if (graphicOption && !graphicOption.elements) {
  52132. option.graphic = [{elements: [graphicOption]}];
  52133. }
  52134. });
  52135. // ------
  52136. // Model
  52137. // ------
  52138. var GraphicModel = extendComponentModel({
  52139. type: 'graphic',
  52140. defaultOption: {
  52141. // Extra properties for each elements:
  52142. //
  52143. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  52144. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  52145. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  52146. // This mechanism is useful when you want to position a group/element
  52147. // against the right side or the center of this container.
  52148. //
  52149. // width/height: (can only be pixel value, default 0)
  52150. // Only be used to specify contianer(group) size, if needed. And
  52151. // can not be percentage value (like '33%'). See the reason in the
  52152. // layout algorithm below.
  52153. //
  52154. // bounding: (enum: 'all' (default) | 'raw')
  52155. // Specify how to calculate boundingRect when locating.
  52156. // 'all': Get uioned and transformed boundingRect
  52157. // from both itself and its descendants.
  52158. // This mode simplies confining a group of elements in the bounding
  52159. // of their ancester container (e.g., using 'right: 0').
  52160. // 'raw': Only use the boundingRect of itself and before transformed.
  52161. // This mode is similar to css behavior, which is useful when you
  52162. // want an element to be able to overflow its container. (Consider
  52163. // a rotated circle needs to be located in a corner.)
  52164. // Note: elements is always behind its ancestors in this elements array.
  52165. elements: [],
  52166. parentId: null
  52167. },
  52168. /**
  52169. * Save el options for the sake of the performance (only update modified graphics).
  52170. * The order is the same as those in option. (ancesters -> descendants)
  52171. *
  52172. * @private
  52173. * @type {Array.<Object>}
  52174. */
  52175. _elOptionsToUpdate: null,
  52176. /**
  52177. * @override
  52178. */
  52179. mergeOption: function (option) {
  52180. // Prevent default merge to elements
  52181. var elements = this.option.elements;
  52182. this.option.elements = null;
  52183. GraphicModel.superApply(this, 'mergeOption', arguments);
  52184. this.option.elements = elements;
  52185. },
  52186. /**
  52187. * @override
  52188. */
  52189. optionUpdated: function (newOption, isInit) {
  52190. var thisOption = this.option;
  52191. var newList = (isInit ? thisOption : newOption).elements;
  52192. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  52193. var flattenedList = [];
  52194. this._flatten(newList, flattenedList);
  52195. var mappingResult = mappingToExists(existList, flattenedList);
  52196. makeIdAndName(mappingResult);
  52197. // Clear elOptionsToUpdate
  52198. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  52199. each$1(mappingResult, function (resultItem, index) {
  52200. var newElOption = resultItem.option;
  52201. if (__DEV__) {
  52202. assert$1(
  52203. isObject$1(newElOption) || resultItem.exist,
  52204. 'Empty graphic option definition'
  52205. );
  52206. }
  52207. if (!newElOption) {
  52208. return;
  52209. }
  52210. elOptionsToUpdate.push(newElOption);
  52211. setKeyInfoToNewElOption(resultItem, newElOption);
  52212. mergeNewElOptionToExist(existList, index, newElOption);
  52213. setLayoutInfoToExist(existList[index], newElOption);
  52214. }, this);
  52215. // Clean
  52216. for (var i = existList.length - 1; i >= 0; i--) {
  52217. if (existList[i] == null) {
  52218. existList.splice(i, 1);
  52219. }
  52220. else {
  52221. // $action should be volatile, otherwise option gotten from
  52222. // `getOption` will contain unexpected $action.
  52223. delete existList[i].$action;
  52224. }
  52225. }
  52226. },
  52227. /**
  52228. * Convert
  52229. * [{
  52230. * type: 'group',
  52231. * id: 'xx',
  52232. * children: [{type: 'circle'}, {type: 'polygon'}]
  52233. * }]
  52234. * to
  52235. * [
  52236. * {type: 'group', id: 'xx'},
  52237. * {type: 'circle', parentId: 'xx'},
  52238. * {type: 'polygon', parentId: 'xx'}
  52239. * ]
  52240. *
  52241. * @private
  52242. * @param {Array.<Object>} optionList option list
  52243. * @param {Array.<Object>} result result of flatten
  52244. * @param {Object} parentOption parent option
  52245. */
  52246. _flatten: function (optionList, result, parentOption) {
  52247. each$1(optionList, function (option) {
  52248. if (!option) {
  52249. return;
  52250. }
  52251. if (parentOption) {
  52252. option.parentOption = parentOption;
  52253. }
  52254. result.push(option);
  52255. var children = option.children;
  52256. if (option.type === 'group' && children) {
  52257. this._flatten(children, result, option);
  52258. }
  52259. // Deleting for JSON output, and for not affecting group creation.
  52260. delete option.children;
  52261. }, this);
  52262. },
  52263. // FIXME
  52264. // Pass to view using payload? setOption has a payload?
  52265. useElOptionsToUpdate: function () {
  52266. var els = this._elOptionsToUpdate;
  52267. // Clear to avoid render duplicately when zooming.
  52268. this._elOptionsToUpdate = null;
  52269. return els;
  52270. }
  52271. });
  52272. // -----
  52273. // View
  52274. // -----
  52275. extendComponentView({
  52276. type: 'graphic',
  52277. /**
  52278. * @override
  52279. */
  52280. init: function (ecModel, api) {
  52281. /**
  52282. * @private
  52283. * @type {module:zrender/core/util.HashMap}
  52284. */
  52285. this._elMap = createHashMap();
  52286. /**
  52287. * @private
  52288. * @type {module:echarts/graphic/GraphicModel}
  52289. */
  52290. this._lastGraphicModel;
  52291. },
  52292. /**
  52293. * @override
  52294. */
  52295. render: function (graphicModel, ecModel, api) {
  52296. // Having leveraged between use cases and algorithm complexity, a very
  52297. // simple layout mechanism is used:
  52298. // The size(width/height) can be determined by itself or its parent (not
  52299. // implemented yet), but can not by its children. (Top-down travel)
  52300. // The location(x/y) can be determined by the bounding rect of itself
  52301. // (can including its descendants or not) and the size of its parent.
  52302. // (Bottom-up travel)
  52303. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  52304. // view will be reused.
  52305. if (graphicModel !== this._lastGraphicModel) {
  52306. this._clear();
  52307. }
  52308. this._lastGraphicModel = graphicModel;
  52309. this._updateElements(graphicModel, api);
  52310. this._relocate(graphicModel, api);
  52311. },
  52312. /**
  52313. * Update graphic elements.
  52314. *
  52315. * @private
  52316. * @param {Object} graphicModel graphic model
  52317. * @param {module:echarts/ExtensionAPI} api extension API
  52318. */
  52319. _updateElements: function (graphicModel, api) {
  52320. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  52321. if (!elOptionsToUpdate) {
  52322. return;
  52323. }
  52324. var elMap = this._elMap;
  52325. var rootGroup = this.group;
  52326. // Top-down tranverse to assign graphic settings to each elements.
  52327. each$1(elOptionsToUpdate, function (elOption) {
  52328. var $action = elOption.$action;
  52329. var id = elOption.id;
  52330. var existEl = elMap.get(id);
  52331. var parentId = elOption.parentId;
  52332. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  52333. if (elOption.type === 'text') {
  52334. var elOptionStyle = elOption.style;
  52335. // In top/bottom mode, textVerticalAlign should not be used, which cause
  52336. // inaccurately locating.
  52337. if (elOption.hv && elOption.hv[1]) {
  52338. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  52339. }
  52340. // Compatible with previous setting: both support fill and textFill,
  52341. // stroke and textStroke.
  52342. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  52343. elOptionStyle.textFill = elOptionStyle.fill
  52344. );
  52345. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  52346. elOptionStyle.textStroke = elOptionStyle.stroke
  52347. );
  52348. }
  52349. // Remove unnecessary props to avoid potential problems.
  52350. var elOptionCleaned = getCleanedElOption(elOption);
  52351. // For simple, do not support parent change, otherwise reorder is needed.
  52352. if (__DEV__) {
  52353. existEl && assert$1(
  52354. targetElParent === existEl.parent,
  52355. 'Changing parent is not supported.'
  52356. );
  52357. }
  52358. if (!$action || $action === 'merge') {
  52359. existEl
  52360. ? existEl.attr(elOptionCleaned)
  52361. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  52362. }
  52363. else if ($action === 'replace') {
  52364. removeEl(existEl, elMap);
  52365. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  52366. }
  52367. else if ($action === 'remove') {
  52368. removeEl(existEl, elMap);
  52369. }
  52370. var el = elMap.get(id);
  52371. if (el) {
  52372. el.__ecGraphicWidth = elOption.width;
  52373. el.__ecGraphicHeight = elOption.height;
  52374. }
  52375. });
  52376. },
  52377. /**
  52378. * Locate graphic elements.
  52379. *
  52380. * @private
  52381. * @param {Object} graphicModel graphic model
  52382. * @param {module:echarts/ExtensionAPI} api extension API
  52383. */
  52384. _relocate: function (graphicModel, api) {
  52385. var elOptions = graphicModel.option.elements;
  52386. var rootGroup = this.group;
  52387. var elMap = this._elMap;
  52388. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  52389. for (var i = elOptions.length - 1; i >= 0; i--) {
  52390. var elOption = elOptions[i];
  52391. var el = elMap.get(elOption.id);
  52392. if (!el) {
  52393. continue;
  52394. }
  52395. var parentEl = el.parent;
  52396. var containerInfo = parentEl === rootGroup
  52397. ? {
  52398. width: api.getWidth(),
  52399. height: api.getHeight()
  52400. }
  52401. : { // Like 'position:absolut' in css, default 0.
  52402. width: parentEl.__ecGraphicWidth || 0,
  52403. height: parentEl.__ecGraphicHeight || 0
  52404. };
  52405. positionElement(
  52406. el, elOption, containerInfo, null,
  52407. {hv: elOption.hv, boundingMode: elOption.bounding}
  52408. );
  52409. }
  52410. },
  52411. /**
  52412. * Clear all elements.
  52413. *
  52414. * @private
  52415. */
  52416. _clear: function () {
  52417. var elMap = this._elMap;
  52418. elMap.each(function (el) {
  52419. removeEl(el, elMap);
  52420. });
  52421. this._elMap = createHashMap();
  52422. },
  52423. /**
  52424. * @override
  52425. */
  52426. dispose: function () {
  52427. this._clear();
  52428. }
  52429. });
  52430. function createEl$1(id, targetElParent, elOption, elMap) {
  52431. var graphicType = elOption.type;
  52432. if (__DEV__) {
  52433. assert$1(graphicType, 'graphic type MUST be set');
  52434. }
  52435. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  52436. if (__DEV__) {
  52437. assert$1(Clz, 'graphic type can not be found');
  52438. }
  52439. var el = new Clz(elOption);
  52440. targetElParent.add(el);
  52441. elMap.set(id, el);
  52442. el.__ecGraphicId = id;
  52443. }
  52444. function removeEl(existEl, elMap) {
  52445. var existElParent = existEl && existEl.parent;
  52446. if (existElParent) {
  52447. existEl.type === 'group' && existEl.traverse(function (el) {
  52448. removeEl(el, elMap);
  52449. });
  52450. elMap.removeKey(existEl.__ecGraphicId);
  52451. existElParent.remove(existEl);
  52452. }
  52453. }
  52454. // Remove unnecessary props to avoid potential problems.
  52455. function getCleanedElOption(elOption) {
  52456. elOption = extend({}, elOption);
  52457. each$1(
  52458. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  52459. function (name) {
  52460. delete elOption[name];
  52461. }
  52462. );
  52463. return elOption;
  52464. }
  52465. function isSetLoc(obj, props) {
  52466. var isSet;
  52467. each$1(props, function (prop) {
  52468. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  52469. });
  52470. return isSet;
  52471. }
  52472. function setKeyInfoToNewElOption(resultItem, newElOption) {
  52473. var existElOption = resultItem.exist;
  52474. // Set id and type after id assigned.
  52475. newElOption.id = resultItem.keyInfo.id;
  52476. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  52477. // Set parent id if not specified
  52478. if (newElOption.parentId == null) {
  52479. var newElParentOption = newElOption.parentOption;
  52480. if (newElParentOption) {
  52481. newElOption.parentId = newElParentOption.id;
  52482. }
  52483. else if (existElOption) {
  52484. newElOption.parentId = existElOption.parentId;
  52485. }
  52486. }
  52487. // Clear
  52488. newElOption.parentOption = null;
  52489. }
  52490. function mergeNewElOptionToExist(existList, index, newElOption) {
  52491. // Update existing options, for `getOption` feature.
  52492. var newElOptCopy = extend({}, newElOption);
  52493. var existElOption = existList[index];
  52494. var $action = newElOption.$action || 'merge';
  52495. if ($action === 'merge') {
  52496. if (existElOption) {
  52497. if (__DEV__) {
  52498. var newType = newElOption.type;
  52499. assert$1(
  52500. !newType || existElOption.type === newType,
  52501. 'Please set $action: "replace" to change `type`'
  52502. );
  52503. }
  52504. // We can ensure that newElOptCopy and existElOption are not
  52505. // the same object, so `merge` will not change newElOptCopy.
  52506. merge(existElOption, newElOptCopy, true);
  52507. // Rigid body, use ignoreSize.
  52508. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  52509. // Will be used in render.
  52510. copyLayoutParams(newElOption, existElOption);
  52511. }
  52512. else {
  52513. existList[index] = newElOptCopy;
  52514. }
  52515. }
  52516. else if ($action === 'replace') {
  52517. existList[index] = newElOptCopy;
  52518. }
  52519. else if ($action === 'remove') {
  52520. // null will be cleaned later.
  52521. existElOption && (existList[index] = null);
  52522. }
  52523. }
  52524. function setLayoutInfoToExist(existItem, newElOption) {
  52525. if (!existItem) {
  52526. return;
  52527. }
  52528. existItem.hv = newElOption.hv = [
  52529. // Rigid body, dont care `width`.
  52530. isSetLoc(newElOption, ['left', 'right']),
  52531. // Rigid body, dont care `height`.
  52532. isSetLoc(newElOption, ['top', 'bottom'])
  52533. ];
  52534. // Give default group size. Otherwise layout error may occur.
  52535. if (existItem.type === 'group') {
  52536. existItem.width == null && (existItem.width = newElOption.width = 0);
  52537. existItem.height == null && (existItem.height = newElOption.height = 0);
  52538. }
  52539. }
  52540. var LegendModel = extendComponentModel({
  52541. type: 'legend.plain',
  52542. dependencies: ['series'],
  52543. layoutMode: {
  52544. type: 'box',
  52545. // legend.width/height are maxWidth/maxHeight actually,
  52546. // whereas realy width/height is calculated by its content.
  52547. // (Setting {left: 10, right: 10} does not make sense).
  52548. // So consider the case:
  52549. // `setOption({legend: {left: 10});`
  52550. // then `setOption({legend: {right: 10});`
  52551. // The previous `left` should be cleared by setting `ignoreSize`.
  52552. ignoreSize: true
  52553. },
  52554. init: function (option, parentModel, ecModel) {
  52555. this.mergeDefaultAndTheme(option, ecModel);
  52556. option.selected = option.selected || {};
  52557. },
  52558. mergeOption: function (option) {
  52559. LegendModel.superCall(this, 'mergeOption', option);
  52560. },
  52561. optionUpdated: function () {
  52562. this._updateData(this.ecModel);
  52563. var legendData = this._data;
  52564. // If selectedMode is single, try to select one
  52565. if (legendData[0] && this.get('selectedMode') === 'single') {
  52566. var hasSelected = false;
  52567. // If has any selected in option.selected
  52568. for (var i = 0; i < legendData.length; i++) {
  52569. var name = legendData[i].get('name');
  52570. if (this.isSelected(name)) {
  52571. // Force to unselect others
  52572. this.select(name);
  52573. hasSelected = true;
  52574. break;
  52575. }
  52576. }
  52577. // Try select the first if selectedMode is single
  52578. !hasSelected && this.select(legendData[0].get('name'));
  52579. }
  52580. },
  52581. _updateData: function (ecModel) {
  52582. var potentialData = [];
  52583. var availableNames = [];
  52584. ecModel.eachRawSeries(function (seriesModel) {
  52585. var seriesName = seriesModel.name;
  52586. availableNames.push(seriesName);
  52587. var potentialSeriesName;
  52588. if (seriesModel.legendDataProvider) {
  52589. var data = seriesModel.legendDataProvider();
  52590. var names = data.mapArray(data.getName);
  52591. if (!ecModel.isSeriesFiltered(seriesModel)) {
  52592. availableNames = availableNames.concat(names);
  52593. }
  52594. if (names.length) {
  52595. potentialData = potentialData.concat(names);
  52596. }
  52597. else {
  52598. potentialSeriesName = seriesName;
  52599. }
  52600. }
  52601. else {
  52602. potentialSeriesName = seriesName;
  52603. }
  52604. if (potentialSeriesName && potentialSeriesName !== DEFAULT_COMPONENT_NAME) {
  52605. potentialData.push(potentialSeriesName);
  52606. }
  52607. });
  52608. /**
  52609. * @type {Array.<string>}
  52610. * @private
  52611. */
  52612. this._availableNames = availableNames;
  52613. // If legend.data not specified in option, use availableNames as data,
  52614. // which is convinient for user preparing option.
  52615. var rawData = this.get('data') || potentialData;
  52616. var legendData = map(rawData, function (dataItem) {
  52617. // Can be string or number
  52618. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  52619. dataItem = {
  52620. name: dataItem
  52621. };
  52622. }
  52623. return new Model(dataItem, this, this.ecModel);
  52624. }, this);
  52625. /**
  52626. * @type {Array.<module:echarts/model/Model>}
  52627. * @private
  52628. */
  52629. this._data = legendData;
  52630. },
  52631. /**
  52632. * @return {Array.<module:echarts/model/Model>}
  52633. */
  52634. getData: function () {
  52635. return this._data;
  52636. },
  52637. /**
  52638. * @param {string} name
  52639. */
  52640. select: function (name) {
  52641. var selected = this.option.selected;
  52642. var selectedMode = this.get('selectedMode');
  52643. if (selectedMode === 'single') {
  52644. var data = this._data;
  52645. each$1(data, function (dataItem) {
  52646. selected[dataItem.get('name')] = false;
  52647. });
  52648. }
  52649. selected[name] = true;
  52650. },
  52651. /**
  52652. * @param {string} name
  52653. */
  52654. unSelect: function (name) {
  52655. if (this.get('selectedMode') !== 'single') {
  52656. this.option.selected[name] = false;
  52657. }
  52658. },
  52659. /**
  52660. * @param {string} name
  52661. */
  52662. toggleSelected: function (name) {
  52663. var selected = this.option.selected;
  52664. // Default is true
  52665. if (!selected.hasOwnProperty(name)) {
  52666. selected[name] = true;
  52667. }
  52668. this[selected[name] ? 'unSelect' : 'select'](name);
  52669. },
  52670. /**
  52671. * @param {string} name
  52672. */
  52673. isSelected: function (name) {
  52674. var selected = this.option.selected;
  52675. return !(selected.hasOwnProperty(name) && !selected[name])
  52676. && indexOf(this._availableNames, name) >= 0;
  52677. },
  52678. defaultOption: {
  52679. // 一级层叠
  52680. zlevel: 0,
  52681. // 二级层叠
  52682. z: 4,
  52683. show: true,
  52684. // 布局方式,默认为水平布局,可选为:
  52685. // 'horizontal' | 'vertical'
  52686. orient: 'horizontal',
  52687. left: 'center',
  52688. // right: 'center',
  52689. top: 0,
  52690. // bottom: null,
  52691. // 水平对齐
  52692. // 'auto' | 'left' | 'right'
  52693. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  52694. align: 'auto',
  52695. backgroundColor: 'rgba(0,0,0,0)',
  52696. // 图例边框颜色
  52697. borderColor: '#ccc',
  52698. borderRadius: 0,
  52699. // 图例边框线宽,单位px,默认为0(无边框)
  52700. borderWidth: 0,
  52701. // 图例内边距,单位px,默认各方向内边距为5,
  52702. // 接受数组分别设定上右下左边距,同css
  52703. padding: 5,
  52704. // 各个item之间的间隔,单位px,默认为10,
  52705. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  52706. itemGap: 10,
  52707. // 图例图形宽度
  52708. itemWidth: 25,
  52709. // 图例图形高度
  52710. itemHeight: 14,
  52711. // 图例关闭时候的颜色
  52712. inactiveColor: '#ccc',
  52713. textStyle: {
  52714. // 图例文字颜色
  52715. color: '#333'
  52716. },
  52717. // formatter: '',
  52718. // 选择模式,默认开启图例开关
  52719. selectedMode: true,
  52720. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  52721. // selected: null,
  52722. // 图例内容(详见legend.data,数组中每一项代表一个item
  52723. // data: [],
  52724. // Tooltip 相关配置
  52725. tooltip: {
  52726. show: false
  52727. }
  52728. }
  52729. });
  52730. function legendSelectActionHandler(methodName, payload, ecModel) {
  52731. var selectedMap = {};
  52732. var isToggleSelect = methodName === 'toggleSelected';
  52733. var isSelected;
  52734. // Update all legend components
  52735. ecModel.eachComponent('legend', function (legendModel) {
  52736. if (isToggleSelect && isSelected != null) {
  52737. // Force other legend has same selected status
  52738. // Or the first is toggled to true and other are toggled to false
  52739. // In the case one legend has some item unSelected in option. And if other legend
  52740. // doesn't has the item, they will assume it is selected.
  52741. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  52742. }
  52743. else {
  52744. legendModel[methodName](payload.name);
  52745. isSelected = legendModel.isSelected(payload.name);
  52746. }
  52747. var legendData = legendModel.getData();
  52748. each$1(legendData, function (model) {
  52749. var name = model.get('name');
  52750. // Wrap element
  52751. if (name === '\n' || name === '') {
  52752. return;
  52753. }
  52754. var isItemSelected = legendModel.isSelected(name);
  52755. if (selectedMap.hasOwnProperty(name)) {
  52756. // Unselected if any legend is unselected
  52757. selectedMap[name] = selectedMap[name] && isItemSelected;
  52758. }
  52759. else {
  52760. selectedMap[name] = isItemSelected;
  52761. }
  52762. });
  52763. });
  52764. // Return the event explicitly
  52765. return {
  52766. name: payload.name,
  52767. selected: selectedMap
  52768. };
  52769. }
  52770. /**
  52771. * @event legendToggleSelect
  52772. * @type {Object}
  52773. * @property {string} type 'legendToggleSelect'
  52774. * @property {string} [from]
  52775. * @property {string} name Series name or data item name
  52776. */
  52777. registerAction(
  52778. 'legendToggleSelect', 'legendselectchanged',
  52779. curry(legendSelectActionHandler, 'toggleSelected')
  52780. );
  52781. /**
  52782. * @event legendSelect
  52783. * @type {Object}
  52784. * @property {string} type 'legendSelect'
  52785. * @property {string} name Series name or data item name
  52786. */
  52787. registerAction(
  52788. 'legendSelect', 'legendselected',
  52789. curry(legendSelectActionHandler, 'select')
  52790. );
  52791. /**
  52792. * @event legendUnSelect
  52793. * @type {Object}
  52794. * @property {string} type 'legendUnSelect'
  52795. * @property {string} name Series name or data item name
  52796. */
  52797. registerAction(
  52798. 'legendUnSelect', 'legendunselected',
  52799. curry(legendSelectActionHandler, 'unSelect')
  52800. );
  52801. /**
  52802. * Layout list like component.
  52803. * It will box layout each items in group of component and then position the whole group in the viewport
  52804. * @param {module:zrender/group/Group} group
  52805. * @param {module:echarts/model/Component} componentModel
  52806. * @param {module:echarts/ExtensionAPI}
  52807. */
  52808. function layout$3(group, componentModel, api) {
  52809. var boxLayoutParams = componentModel.getBoxLayoutParams();
  52810. var padding = componentModel.get('padding');
  52811. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  52812. var rect = getLayoutRect(
  52813. boxLayoutParams,
  52814. viewportSize,
  52815. padding
  52816. );
  52817. box(
  52818. componentModel.get('orient'),
  52819. group,
  52820. componentModel.get('itemGap'),
  52821. rect.width,
  52822. rect.height
  52823. );
  52824. positionElement(
  52825. group,
  52826. boxLayoutParams,
  52827. viewportSize,
  52828. padding
  52829. );
  52830. }
  52831. function makeBackground(rect, componentModel) {
  52832. var padding = normalizeCssArray$1(
  52833. componentModel.get('padding')
  52834. );
  52835. var style = componentModel.getItemStyle(['color', 'opacity']);
  52836. style.fill = componentModel.get('backgroundColor');
  52837. var rect = new Rect({
  52838. shape: {
  52839. x: rect.x - padding[3],
  52840. y: rect.y - padding[0],
  52841. width: rect.width + padding[1] + padding[3],
  52842. height: rect.height + padding[0] + padding[2],
  52843. r: componentModel.get('borderRadius')
  52844. },
  52845. style: style,
  52846. silent: true,
  52847. z2: -1
  52848. });
  52849. // FIXME
  52850. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  52851. // and background rect when setting like `left: 0`, `top: 0`.
  52852. // graphic.subPixelOptimizeRect(rect);
  52853. return rect;
  52854. }
  52855. var curry$4 = curry;
  52856. var each$17 = each$1;
  52857. var Group$3 = Group;
  52858. var LegendView = extendComponentView({
  52859. type: 'legend.plain',
  52860. newlineDisabled: false,
  52861. /**
  52862. * @override
  52863. */
  52864. init: function () {
  52865. /**
  52866. * @private
  52867. * @type {module:zrender/container/Group}
  52868. */
  52869. this.group.add(this._contentGroup = new Group$3());
  52870. /**
  52871. * @private
  52872. * @type {module:zrender/Element}
  52873. */
  52874. this._backgroundEl;
  52875. },
  52876. /**
  52877. * @protected
  52878. */
  52879. getContentGroup: function () {
  52880. return this._contentGroup;
  52881. },
  52882. /**
  52883. * @override
  52884. */
  52885. render: function (legendModel, ecModel, api) {
  52886. this.resetInner();
  52887. if (!legendModel.get('show', true)) {
  52888. return;
  52889. }
  52890. var itemAlign = legendModel.get('align');
  52891. if (!itemAlign || itemAlign === 'auto') {
  52892. itemAlign = (
  52893. legendModel.get('left') === 'right'
  52894. && legendModel.get('orient') === 'vertical'
  52895. ) ? 'right' : 'left';
  52896. }
  52897. this.renderInner(itemAlign, legendModel, ecModel, api);
  52898. // Perform layout.
  52899. var positionInfo = legendModel.getBoxLayoutParams();
  52900. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  52901. var padding = legendModel.get('padding');
  52902. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  52903. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  52904. // Place mainGroup, based on the calculated `mainRect`.
  52905. var layoutRect = getLayoutRect(
  52906. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  52907. viewportSize,
  52908. padding
  52909. );
  52910. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  52911. // Render background after group is layout.
  52912. this.group.add(
  52913. this._backgroundEl = makeBackground(mainRect, legendModel)
  52914. );
  52915. },
  52916. /**
  52917. * @protected
  52918. */
  52919. resetInner: function () {
  52920. this.getContentGroup().removeAll();
  52921. this._backgroundEl && this.group.remove(this._backgroundEl);
  52922. },
  52923. /**
  52924. * @protected
  52925. */
  52926. renderInner: function (itemAlign, legendModel, ecModel, api) {
  52927. var contentGroup = this.getContentGroup();
  52928. var legendDrawnMap = createHashMap();
  52929. var selectMode = legendModel.get('selectedMode');
  52930. each$17(legendModel.getData(), function (itemModel, dataIndex) {
  52931. var name = itemModel.get('name');
  52932. // Use empty string or \n as a newline string
  52933. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  52934. contentGroup.add(new Group$3({
  52935. newline: true
  52936. }));
  52937. return;
  52938. }
  52939. var seriesModel = ecModel.getSeriesByName(name)[0];
  52940. if (legendDrawnMap.get(name)) {
  52941. // Have been drawed
  52942. return;
  52943. }
  52944. // Series legend
  52945. if (seriesModel) {
  52946. var data = seriesModel.getData();
  52947. var color = data.getVisual('color');
  52948. // If color is a callback function
  52949. if (typeof color === 'function') {
  52950. // Use the first data
  52951. color = color(seriesModel.getDataParams(0));
  52952. }
  52953. // Using rect symbol defaultly
  52954. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  52955. var symbolType = data.getVisual('symbol');
  52956. var itemGroup = this._createItem(
  52957. name, dataIndex, itemModel, legendModel,
  52958. legendSymbolType, symbolType,
  52959. itemAlign, color,
  52960. selectMode
  52961. );
  52962. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  52963. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api))
  52964. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api));
  52965. legendDrawnMap.set(name, true);
  52966. }
  52967. else {
  52968. // Data legend of pie, funnel
  52969. ecModel.eachRawSeries(function (seriesModel) {
  52970. // In case multiple series has same data name
  52971. if (legendDrawnMap.get(name)) {
  52972. return;
  52973. }
  52974. if (seriesModel.legendDataProvider) {
  52975. var data = seriesModel.legendDataProvider();
  52976. var idx = data.indexOfName(name);
  52977. if (idx < 0) {
  52978. return;
  52979. }
  52980. var color = data.getItemVisual(idx, 'color');
  52981. var legendSymbolType = 'roundRect';
  52982. var itemGroup = this._createItem(
  52983. name, dataIndex, itemModel, legendModel,
  52984. legendSymbolType, null,
  52985. itemAlign, color,
  52986. selectMode
  52987. );
  52988. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  52989. // FIXME Should not specify the series name
  52990. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api))
  52991. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api));
  52992. legendDrawnMap.set(name, true);
  52993. }
  52994. }, this);
  52995. }
  52996. if (__DEV__) {
  52997. if (!legendDrawnMap.get(name)) {
  52998. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  52999. }
  53000. }
  53001. }, this);
  53002. },
  53003. _createItem: function (
  53004. name, dataIndex, itemModel, legendModel,
  53005. legendSymbolType, symbolType,
  53006. itemAlign, color, selectMode
  53007. ) {
  53008. var itemWidth = legendModel.get('itemWidth');
  53009. var itemHeight = legendModel.get('itemHeight');
  53010. var inactiveColor = legendModel.get('inactiveColor');
  53011. var isSelected = legendModel.isSelected(name);
  53012. var itemGroup = new Group$3();
  53013. var textStyleModel = itemModel.getModel('textStyle');
  53014. var itemIcon = itemModel.get('icon');
  53015. var tooltipModel = itemModel.getModel('tooltip');
  53016. var legendGlobalTooltipModel = tooltipModel.parentModel;
  53017. // Use user given icon first
  53018. legendSymbolType = itemIcon || legendSymbolType;
  53019. itemGroup.add(createSymbol(
  53020. legendSymbolType,
  53021. 0,
  53022. 0,
  53023. itemWidth,
  53024. itemHeight,
  53025. isSelected ? color : inactiveColor,
  53026. true
  53027. ));
  53028. // Compose symbols
  53029. // PENDING
  53030. if (!itemIcon && symbolType
  53031. // At least show one symbol, can't be all none
  53032. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  53033. ) {
  53034. var size = itemHeight * 0.8;
  53035. if (symbolType === 'none') {
  53036. symbolType = 'circle';
  53037. }
  53038. // Put symbol in the center
  53039. itemGroup.add(createSymbol(
  53040. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  53041. isSelected ? color : inactiveColor
  53042. ));
  53043. }
  53044. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  53045. var textAlign = itemAlign;
  53046. var formatter = legendModel.get('formatter');
  53047. var content = name;
  53048. if (typeof formatter === 'string' && formatter) {
  53049. content = formatter.replace('{name}', name != null ? name : '');
  53050. }
  53051. else if (typeof formatter === 'function') {
  53052. content = formatter(name);
  53053. }
  53054. itemGroup.add(new Text({
  53055. style: setTextStyle({}, textStyleModel, {
  53056. text: content,
  53057. x: textX,
  53058. y: itemHeight / 2,
  53059. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  53060. textAlign: textAlign,
  53061. textVerticalAlign: 'middle'
  53062. })
  53063. }));
  53064. // Add a invisible rect to increase the area of mouse hover
  53065. var hitRect = new Rect({
  53066. shape: itemGroup.getBoundingRect(),
  53067. invisible: true,
  53068. tooltip: tooltipModel.get('show') ? extend({
  53069. content: name,
  53070. // Defaul formatter
  53071. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  53072. return name;
  53073. },
  53074. formatterParams: {
  53075. componentType: 'legend',
  53076. legendIndex: legendModel.componentIndex,
  53077. name: name,
  53078. $vars: ['name']
  53079. }
  53080. }, tooltipModel.option) : null
  53081. });
  53082. itemGroup.add(hitRect);
  53083. itemGroup.eachChild(function (child) {
  53084. child.silent = true;
  53085. });
  53086. hitRect.silent = !selectMode;
  53087. this.getContentGroup().add(itemGroup);
  53088. setHoverStyle(itemGroup);
  53089. itemGroup.__legendDataIndex = dataIndex;
  53090. return itemGroup;
  53091. },
  53092. /**
  53093. * @protected
  53094. */
  53095. layoutInner: function (legendModel, itemAlign, maxSize) {
  53096. var contentGroup = this.getContentGroup();
  53097. // Place items in contentGroup.
  53098. box(
  53099. legendModel.get('orient'),
  53100. contentGroup,
  53101. legendModel.get('itemGap'),
  53102. maxSize.width,
  53103. maxSize.height
  53104. );
  53105. var contentRect = contentGroup.getBoundingRect();
  53106. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  53107. return this.group.getBoundingRect();
  53108. }
  53109. });
  53110. function dispatchSelectAction(name, api) {
  53111. api.dispatchAction({
  53112. type: 'legendToggleSelect',
  53113. name: name
  53114. });
  53115. }
  53116. function dispatchHighlightAction(seriesModel, dataName, api) {
  53117. // If element hover will move to a hoverLayer.
  53118. var el = api.getZr().storage.getDisplayList()[0];
  53119. if (!(el && el.useHoverLayer)) {
  53120. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53121. type: 'highlight',
  53122. seriesName: seriesModel.name,
  53123. name: dataName
  53124. });
  53125. }
  53126. }
  53127. function dispatchDownplayAction(seriesModel, dataName, api) {
  53128. // If element hover will move to a hoverLayer.
  53129. var el = api.getZr().storage.getDisplayList()[0];
  53130. if (!(el && el.useHoverLayer)) {
  53131. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53132. type: 'downplay',
  53133. seriesName: seriesModel.name,
  53134. name: dataName
  53135. });
  53136. }
  53137. }
  53138. var legendFilter = function (ecModel) {
  53139. var legendModels = ecModel.findComponents({
  53140. mainType: 'legend'
  53141. });
  53142. if (legendModels && legendModels.length) {
  53143. ecModel.filterSeries(function (series) {
  53144. // If in any legend component the status is not selected.
  53145. // Because in legend series is assumed selected when it is not in the legend data.
  53146. for (var i = 0; i < legendModels.length; i++) {
  53147. if (!legendModels[i].isSelected(series.name)) {
  53148. return false;
  53149. }
  53150. }
  53151. return true;
  53152. });
  53153. }
  53154. };
  53155. // Do not contain scrollable legend, for sake of file size.
  53156. // Series Filter
  53157. registerProcessor(legendFilter);
  53158. ComponentModel.registerSubTypeDefaulter('legend', function () {
  53159. // Default 'plain' when no type specified.
  53160. return 'plain';
  53161. });
  53162. var ScrollableLegendModel = LegendModel.extend({
  53163. type: 'legend.scroll',
  53164. /**
  53165. * @param {number} scrollDataIndex
  53166. */
  53167. setScrollDataIndex: function (scrollDataIndex) {
  53168. this.option.scrollDataIndex = scrollDataIndex;
  53169. },
  53170. defaultOption: {
  53171. scrollDataIndex: 0,
  53172. pageButtonItemGap: 5,
  53173. pageButtonGap: null,
  53174. pageButtonPosition: 'end', // 'start' or 'end'
  53175. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  53176. pageIcons: {
  53177. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  53178. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  53179. },
  53180. pageIconColor: '#2f4554',
  53181. pageIconInactiveColor: '#aaa',
  53182. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  53183. pageTextStyle: {
  53184. color: '#333'
  53185. },
  53186. animationDurationUpdate: 800
  53187. },
  53188. /**
  53189. * @override
  53190. */
  53191. init: function (option, parentModel, ecModel, extraOpt) {
  53192. var inputPositionParams = getLayoutParams(option);
  53193. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  53194. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  53195. },
  53196. /**
  53197. * @override
  53198. */
  53199. mergeOption: function (option, extraOpt) {
  53200. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  53201. mergeAndNormalizeLayoutParams(this, this.option, option);
  53202. },
  53203. getOrient: function () {
  53204. return this.get('orient') === 'vertical'
  53205. ? {index: 1, name: 'vertical'}
  53206. : {index: 0, name: 'horizontal'};
  53207. }
  53208. });
  53209. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  53210. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  53211. var orient = legendModel.getOrient();
  53212. var ignoreSize = [1, 1];
  53213. ignoreSize[orient.index] = 0;
  53214. mergeLayoutParam(target, raw, {
  53215. type: 'box', ignoreSize: ignoreSize
  53216. });
  53217. }
  53218. /**
  53219. * Separate legend and scrollable legend to reduce package size.
  53220. */
  53221. var Group$4 = Group;
  53222. var WH$1 = ['width', 'height'];
  53223. var XY$1 = ['x', 'y'];
  53224. var ScrollableLegendView = LegendView.extend({
  53225. type: 'legend.scroll',
  53226. newlineDisabled: true,
  53227. init: function () {
  53228. ScrollableLegendView.superCall(this, 'init');
  53229. /**
  53230. * @private
  53231. * @type {number} For `scroll`.
  53232. */
  53233. this._currentIndex = 0;
  53234. /**
  53235. * @private
  53236. * @type {module:zrender/container/Group}
  53237. */
  53238. this.group.add(this._containerGroup = new Group$4());
  53239. this._containerGroup.add(this.getContentGroup());
  53240. /**
  53241. * @private
  53242. * @type {module:zrender/container/Group}
  53243. */
  53244. this.group.add(this._controllerGroup = new Group$4());
  53245. /**
  53246. *
  53247. * @private
  53248. */
  53249. this._showController;
  53250. },
  53251. /**
  53252. * @override
  53253. */
  53254. resetInner: function () {
  53255. ScrollableLegendView.superCall(this, 'resetInner');
  53256. this._controllerGroup.removeAll();
  53257. this._containerGroup.removeClipPath();
  53258. this._containerGroup.__rectSize = null;
  53259. },
  53260. /**
  53261. * @override
  53262. */
  53263. renderInner: function (itemAlign, legendModel, ecModel, api) {
  53264. var me = this;
  53265. // Render content items.
  53266. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  53267. var controllerGroup = this._controllerGroup;
  53268. var pageIconSize = legendModel.get('pageIconSize', true);
  53269. if (!isArray(pageIconSize)) {
  53270. pageIconSize = [pageIconSize, pageIconSize];
  53271. }
  53272. createPageButton('pagePrev', 0);
  53273. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  53274. controllerGroup.add(new Text({
  53275. name: 'pageText',
  53276. style: {
  53277. textFill: pageTextStyleModel.getTextColor(),
  53278. font: pageTextStyleModel.getFont(),
  53279. textVerticalAlign: 'middle',
  53280. textAlign: 'center'
  53281. },
  53282. silent: true
  53283. }));
  53284. createPageButton('pageNext', 1);
  53285. function createPageButton(name, iconIdx) {
  53286. var pageDataIndexName = name + 'DataIndex';
  53287. var icon = createIcon(
  53288. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  53289. {
  53290. // Buttons will be created in each render, so we do not need
  53291. // to worry about avoiding using legendModel kept in scope.
  53292. onclick: bind(
  53293. me._pageGo, me, pageDataIndexName, legendModel, api
  53294. )
  53295. },
  53296. {
  53297. x: -pageIconSize[0] / 2,
  53298. y: -pageIconSize[1] / 2,
  53299. width: pageIconSize[0],
  53300. height: pageIconSize[1]
  53301. }
  53302. );
  53303. icon.name = name;
  53304. controllerGroup.add(icon);
  53305. }
  53306. },
  53307. /**
  53308. * @override
  53309. */
  53310. layoutInner: function (legendModel, itemAlign, maxSize) {
  53311. var contentGroup = this.getContentGroup();
  53312. var containerGroup = this._containerGroup;
  53313. var controllerGroup = this._controllerGroup;
  53314. var orientIdx = legendModel.getOrient().index;
  53315. var wh = WH$1[orientIdx];
  53316. var hw = WH$1[1 - orientIdx];
  53317. var yx = XY$1[1 - orientIdx];
  53318. // Place items in contentGroup.
  53319. box(
  53320. legendModel.get('orient'),
  53321. contentGroup,
  53322. legendModel.get('itemGap'),
  53323. !orientIdx ? null : maxSize.width,
  53324. orientIdx ? null : maxSize.height
  53325. );
  53326. box(
  53327. // Buttons in controller are layout always horizontally.
  53328. 'horizontal',
  53329. controllerGroup,
  53330. legendModel.get('pageButtonItemGap', true)
  53331. );
  53332. var contentRect = contentGroup.getBoundingRect();
  53333. var controllerRect = controllerGroup.getBoundingRect();
  53334. var showController = this._showController = contentRect[wh] > maxSize[wh];
  53335. var contentPos = [-contentRect.x, -contentRect.y];
  53336. // Remain contentPos when scroll animation perfroming.
  53337. contentPos[orientIdx] = contentGroup.position[orientIdx];
  53338. // Layout container group based on 0.
  53339. var containerPos = [0, 0];
  53340. var controllerPos = [-controllerRect.x, -controllerRect.y];
  53341. var pageButtonGap = retrieve2(
  53342. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  53343. );
  53344. // Place containerGroup and controllerGroup and contentGroup.
  53345. if (showController) {
  53346. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  53347. // controller is on the right / bottom.
  53348. if (pageButtonPosition === 'end') {
  53349. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  53350. }
  53351. // controller is on the left / top.
  53352. else {
  53353. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  53354. }
  53355. }
  53356. // Always align controller to content as 'middle'.
  53357. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  53358. contentGroup.attr('position', contentPos);
  53359. containerGroup.attr('position', containerPos);
  53360. controllerGroup.attr('position', controllerPos);
  53361. // Calculate `mainRect` and set `clipPath`.
  53362. // mainRect should not be calculated by `this.group.getBoundingRect()`
  53363. // for sake of the overflow.
  53364. var mainRect = this.group.getBoundingRect();
  53365. var mainRect = {x: 0, y: 0};
  53366. // Consider content may be overflow (should be clipped).
  53367. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  53368. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  53369. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  53370. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  53371. containerGroup.__rectSize = maxSize[wh];
  53372. if (showController) {
  53373. var clipShape = {x: 0, y: 0};
  53374. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  53375. clipShape[hw] = mainRect[hw];
  53376. containerGroup.setClipPath(new Rect({shape: clipShape}));
  53377. // Consider content may be larger than container, container rect
  53378. // can not be obtained from `containerGroup.getBoundingRect()`.
  53379. containerGroup.__rectSize = clipShape[wh];
  53380. }
  53381. else {
  53382. // Do not remove or ignore controller. Keep them set as place holders.
  53383. controllerGroup.eachChild(function (child) {
  53384. child.attr({invisible: true, silent: true});
  53385. });
  53386. }
  53387. // Content translate animation.
  53388. var pageInfo = this._getPageInfo(legendModel);
  53389. pageInfo.pageIndex != null && updateProps(
  53390. contentGroup,
  53391. {position: pageInfo.contentPosition},
  53392. // When switch from "show controller" to "not show controller", view should be
  53393. // updated immediately without animation, otherwise causes weird efffect.
  53394. showController ? legendModel : false
  53395. );
  53396. this._updatePageInfoView(legendModel, pageInfo);
  53397. return mainRect;
  53398. },
  53399. _pageGo: function (to, legendModel, api) {
  53400. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  53401. scrollDataIndex != null && api.dispatchAction({
  53402. type: 'legendScroll',
  53403. scrollDataIndex: scrollDataIndex,
  53404. legendId: legendModel.id
  53405. });
  53406. },
  53407. _updatePageInfoView: function (legendModel, pageInfo) {
  53408. var controllerGroup = this._controllerGroup;
  53409. each$1(['pagePrev', 'pageNext'], function (name) {
  53410. var canJump = pageInfo[name + 'DataIndex'] != null;
  53411. var icon = controllerGroup.childOfName(name);
  53412. if (icon) {
  53413. icon.setStyle(
  53414. 'fill',
  53415. canJump
  53416. ? legendModel.get('pageIconColor', true)
  53417. : legendModel.get('pageIconInactiveColor', true)
  53418. );
  53419. icon.cursor = canJump ? 'pointer' : 'default';
  53420. }
  53421. });
  53422. var pageText = controllerGroup.childOfName('pageText');
  53423. var pageFormatter = legendModel.get('pageFormatter');
  53424. var pageIndex = pageInfo.pageIndex;
  53425. var current = pageIndex != null ? pageIndex + 1 : 0;
  53426. var total = pageInfo.pageCount;
  53427. pageText && pageFormatter && pageText.setStyle(
  53428. 'text',
  53429. isString(pageFormatter)
  53430. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  53431. : pageFormatter({current: current, total: total})
  53432. );
  53433. },
  53434. /**
  53435. * @param {module:echarts/model/Model} legendModel
  53436. * @return {Object} {
  53437. * contentPosition: Array.<number>, null when data item not found.
  53438. * pageIndex: number, null when data item not found.
  53439. * pageCount: number, always be a number, can be 0.
  53440. * pagePrevDataIndex: number, null when no next page.
  53441. * pageNextDataIndex: number, null when no previous page.
  53442. * }
  53443. */
  53444. _getPageInfo: function (legendModel) {
  53445. // Align left or top by the current dataIndex.
  53446. var currDataIndex = legendModel.get('scrollDataIndex', true);
  53447. var contentGroup = this.getContentGroup();
  53448. var contentRect = contentGroup.getBoundingRect();
  53449. var containerRectSize = this._containerGroup.__rectSize;
  53450. var orientIdx = legendModel.getOrient().index;
  53451. var wh = WH$1[orientIdx];
  53452. var hw = WH$1[1 - orientIdx];
  53453. var xy = XY$1[orientIdx];
  53454. var contentPos = contentGroup.position.slice();
  53455. var pageIndex;
  53456. var pagePrevDataIndex;
  53457. var pageNextDataIndex;
  53458. var targetItemGroup;
  53459. if (this._showController) {
  53460. contentGroup.eachChild(function (child) {
  53461. if (child.__legendDataIndex === currDataIndex) {
  53462. targetItemGroup = child;
  53463. }
  53464. });
  53465. }
  53466. else {
  53467. targetItemGroup = contentGroup.childAt(0);
  53468. }
  53469. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  53470. if (targetItemGroup) {
  53471. var itemRect = targetItemGroup.getBoundingRect();
  53472. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  53473. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  53474. pageIndex = Math.floor(
  53475. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  53476. );
  53477. pageIndex = (contentRect[wh] && pageCount)
  53478. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  53479. : -1;
  53480. var winRect = {x: 0, y: 0};
  53481. winRect[wh] = containerRectSize;
  53482. winRect[hw] = contentRect[hw];
  53483. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  53484. var startIdx;
  53485. var children = contentGroup.children();
  53486. contentGroup.eachChild(function (child, index) {
  53487. var itemRect = getItemRect(child);
  53488. if (itemRect.intersect(winRect)) {
  53489. startIdx == null && (startIdx = index);
  53490. // It is user-friendly that the last item shown in the
  53491. // current window is shown at the begining of next window.
  53492. pageNextDataIndex = child.__legendDataIndex;
  53493. }
  53494. // If the last item is shown entirely, no next page.
  53495. if (index === children.length - 1
  53496. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  53497. ) {
  53498. pageNextDataIndex = null;
  53499. }
  53500. });
  53501. // Always align based on the left/top most item, so the left/top most
  53502. // item in the previous window is needed to be found here.
  53503. if (startIdx != null) {
  53504. var startItem = children[startIdx];
  53505. var startRect = getItemRect(startItem);
  53506. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  53507. // If the first item is shown entirely, no previous page.
  53508. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  53509. pagePrevDataIndex = null;
  53510. }
  53511. else {
  53512. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  53513. startIdx--;
  53514. }
  53515. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  53516. }
  53517. }
  53518. }
  53519. return {
  53520. contentPosition: contentPos,
  53521. pageIndex: pageIndex,
  53522. pageCount: pageCount,
  53523. pagePrevDataIndex: pagePrevDataIndex,
  53524. pageNextDataIndex: pageNextDataIndex
  53525. };
  53526. function getItemRect(el) {
  53527. var itemRect = el.getBoundingRect().clone();
  53528. itemRect[xy] += el.position[orientIdx];
  53529. return itemRect;
  53530. }
  53531. }
  53532. });
  53533. /**
  53534. * @event legendScroll
  53535. * @type {Object}
  53536. * @property {string} type 'legendScroll'
  53537. * @property {string} scrollDataIndex
  53538. */
  53539. registerAction(
  53540. 'legendScroll', 'legendscroll',
  53541. function (payload, ecModel) {
  53542. var scrollDataIndex = payload.scrollDataIndex;
  53543. scrollDataIndex != null && ecModel.eachComponent(
  53544. {mainType: 'legend', subType: 'scroll', query: payload},
  53545. function (legendModel) {
  53546. legendModel.setScrollDataIndex(scrollDataIndex);
  53547. }
  53548. );
  53549. }
  53550. );
  53551. /**
  53552. * Legend component entry file8
  53553. */
  53554. extendComponentModel({
  53555. type: 'tooltip',
  53556. dependencies: ['axisPointer'],
  53557. defaultOption: {
  53558. zlevel: 0,
  53559. z: 8,
  53560. show: true,
  53561. // tooltip主体内容
  53562. showContent: true,
  53563. // 'trigger' only works on coordinate system.
  53564. // 'item' | 'axis' | 'none'
  53565. trigger: 'item',
  53566. // 'click' | 'mousemove' | 'none'
  53567. triggerOn: 'mousemove|click',
  53568. alwaysShowContent: false,
  53569. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  53570. // 位置 {Array} | {Function}
  53571. // position: null
  53572. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  53573. // align: null,
  53574. // verticalAlign: null,
  53575. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  53576. confine: false,
  53577. // 内容格式器:{string}(Template) ¦ {Function}
  53578. // formatter: null
  53579. showDelay: 0,
  53580. // 隐藏延迟,单位ms
  53581. hideDelay: 100,
  53582. // 动画变换时间,单位s
  53583. transitionDuration: 0.4,
  53584. enterable: false,
  53585. // 提示背景颜色,默认为透明度为0.7的黑色
  53586. backgroundColor: 'rgba(50,50,50,0.7)',
  53587. // 提示边框颜色
  53588. borderColor: '#333',
  53589. // 提示边框圆角,单位px,默认为4
  53590. borderRadius: 4,
  53591. // 提示边框线宽,单位px,默认为0(无边框)
  53592. borderWidth: 0,
  53593. // 提示内边距,单位px,默认各方向内边距为5,
  53594. // 接受数组分别设定上右下左边距,同css
  53595. padding: 5,
  53596. // Extra css text
  53597. extraCssText: '',
  53598. // 坐标轴指示器,坐标轴触发有效
  53599. axisPointer: {
  53600. // 默认为直线
  53601. // 可选为:'line' | 'shadow' | 'cross'
  53602. type: 'line',
  53603. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  53604. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  53605. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  53606. // 极坐标系会默认选择 angle 轴
  53607. axis: 'auto',
  53608. animation: 'auto',
  53609. animationDurationUpdate: 200,
  53610. animationEasingUpdate: 'exponentialOut',
  53611. crossStyle: {
  53612. color: '#999',
  53613. width: 1,
  53614. type: 'dashed',
  53615. // TODO formatter
  53616. textStyle: {}
  53617. }
  53618. // lineStyle and shadowStyle should not be specified here,
  53619. // otherwise it will always override those styles on option.axisPointer.
  53620. },
  53621. textStyle: {
  53622. color: '#fff',
  53623. fontSize: 14
  53624. }
  53625. }
  53626. });
  53627. var each$19 = each$1;
  53628. var toCamelCase$1 = toCamelCase;
  53629. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  53630. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  53631. /**
  53632. * @param {number} duration
  53633. * @return {string}
  53634. * @inner
  53635. */
  53636. function assembleTransition(duration) {
  53637. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  53638. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  53639. + 'top ' + duration + 's ' + transitionCurve;
  53640. return map(vendors, function (vendorPrefix) {
  53641. return vendorPrefix + 'transition:' + transitionText;
  53642. }).join(';');
  53643. }
  53644. /**
  53645. * @param {Object} textStyle
  53646. * @return {string}
  53647. * @inner
  53648. */
  53649. function assembleFont(textStyleModel) {
  53650. var cssText = [];
  53651. var fontSize = textStyleModel.get('fontSize');
  53652. var color = textStyleModel.getTextColor();
  53653. color && cssText.push('color:' + color);
  53654. cssText.push('font:' + textStyleModel.getFont());
  53655. fontSize &&
  53656. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  53657. each$19(['decoration', 'align'], function (name) {
  53658. var val = textStyleModel.get(name);
  53659. val && cssText.push('text-' + name + ':' + val);
  53660. });
  53661. return cssText.join(';');
  53662. }
  53663. /**
  53664. * @param {Object} tooltipModel
  53665. * @return {string}
  53666. * @inner
  53667. */
  53668. function assembleCssText(tooltipModel) {
  53669. var cssText = [];
  53670. var transitionDuration = tooltipModel.get('transitionDuration');
  53671. var backgroundColor = tooltipModel.get('backgroundColor');
  53672. var textStyleModel = tooltipModel.getModel('textStyle');
  53673. var padding = tooltipModel.get('padding');
  53674. // Animation transition. Do not animate when transitionDuration is 0.
  53675. transitionDuration &&
  53676. cssText.push(assembleTransition(transitionDuration));
  53677. if (backgroundColor) {
  53678. if (env$1.canvasSupported) {
  53679. cssText.push('background-Color:' + backgroundColor);
  53680. }
  53681. else {
  53682. // for ie
  53683. cssText.push(
  53684. 'background-Color:#' + toHex(backgroundColor)
  53685. );
  53686. cssText.push('filter:alpha(opacity=70)');
  53687. }
  53688. }
  53689. // Border style
  53690. each$19(['width', 'color', 'radius'], function (name) {
  53691. var borderName = 'border-' + name;
  53692. var camelCase = toCamelCase$1(borderName);
  53693. var val = tooltipModel.get(camelCase);
  53694. val != null &&
  53695. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  53696. });
  53697. // Text style
  53698. cssText.push(assembleFont(textStyleModel));
  53699. // Padding
  53700. if (padding != null) {
  53701. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  53702. }
  53703. return cssText.join(';') + ';';
  53704. }
  53705. /**
  53706. * @alias module:echarts/component/tooltip/TooltipContent
  53707. * @constructor
  53708. */
  53709. function TooltipContent(container, api) {
  53710. if (env$1.wxa) {
  53711. return null;
  53712. }
  53713. var el = document.createElement('div');
  53714. var zr = this._zr = api.getZr();
  53715. this.el = el;
  53716. this._x = api.getWidth() / 2;
  53717. this._y = api.getHeight() / 2;
  53718. container.appendChild(el);
  53719. this._container = container;
  53720. this._show = false;
  53721. /**
  53722. * @private
  53723. */
  53724. this._hideTimeout;
  53725. var self = this;
  53726. el.onmouseenter = function () {
  53727. // clear the timeout in hideLater and keep showing tooltip
  53728. if (self._enterable) {
  53729. clearTimeout(self._hideTimeout);
  53730. self._show = true;
  53731. }
  53732. self._inContent = true;
  53733. };
  53734. el.onmousemove = function (e) {
  53735. e = e || window.event;
  53736. if (!self._enterable) {
  53737. // Try trigger zrender event to avoid mouse
  53738. // in and out shape too frequently
  53739. var handler = zr.handler;
  53740. normalizeEvent(container, e, true);
  53741. handler.dispatch('mousemove', e);
  53742. }
  53743. };
  53744. el.onmouseleave = function () {
  53745. if (self._enterable) {
  53746. if (self._show) {
  53747. self.hideLater(self._hideDelay);
  53748. }
  53749. }
  53750. self._inContent = false;
  53751. };
  53752. }
  53753. TooltipContent.prototype = {
  53754. constructor: TooltipContent,
  53755. /**
  53756. * @private
  53757. * @type {boolean}
  53758. */
  53759. _enterable: true,
  53760. /**
  53761. * Update when tooltip is rendered
  53762. */
  53763. update: function () {
  53764. // FIXME
  53765. // Move this logic to ec main?
  53766. var container = this._container;
  53767. var stl = container.currentStyle
  53768. || document.defaultView.getComputedStyle(container);
  53769. var domStyle = container.style;
  53770. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  53771. domStyle.position = 'relative';
  53772. }
  53773. // Hide the tooltip
  53774. // PENDING
  53775. // this.hide();
  53776. },
  53777. show: function (tooltipModel) {
  53778. clearTimeout(this._hideTimeout);
  53779. var el = this.el;
  53780. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  53781. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  53782. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  53783. + (tooltipModel.get('extraCssText') || '');
  53784. el.style.display = el.innerHTML ? 'block' : 'none';
  53785. this._show = true;
  53786. },
  53787. setContent: function (content) {
  53788. this.el.innerHTML = content == null ? '' : content;
  53789. },
  53790. setEnterable: function (enterable) {
  53791. this._enterable = enterable;
  53792. },
  53793. getSize: function () {
  53794. var el = this.el;
  53795. return [el.clientWidth, el.clientHeight];
  53796. },
  53797. moveTo: function (x, y) {
  53798. // xy should be based on canvas root. But tooltipContent is
  53799. // the sibling of canvas root. So padding of ec container
  53800. // should be considered here.
  53801. var zr = this._zr;
  53802. var viewportRootOffset;
  53803. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  53804. x += viewportRootOffset.offsetLeft;
  53805. y += viewportRootOffset.offsetTop;
  53806. }
  53807. var style = this.el.style;
  53808. style.left = x + 'px';
  53809. style.top = y + 'px';
  53810. this._x = x;
  53811. this._y = y;
  53812. },
  53813. hide: function () {
  53814. this.el.style.display = 'none';
  53815. this._show = false;
  53816. },
  53817. hideLater: function (time) {
  53818. if (this._show && !(this._inContent && this._enterable)) {
  53819. if (time) {
  53820. this._hideDelay = time;
  53821. // Set show false to avoid invoke hideLater mutiple times
  53822. this._show = false;
  53823. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  53824. }
  53825. else {
  53826. this.hide();
  53827. }
  53828. }
  53829. },
  53830. isShow: function () {
  53831. return this._show;
  53832. }
  53833. };
  53834. var bind$3 = bind;
  53835. var each$18 = each$1;
  53836. var parsePercent$2 = parsePercent$1;
  53837. var proxyRect = new Rect({
  53838. shape: {x: -1, y: -1, width: 2, height: 2}
  53839. });
  53840. extendComponentView({
  53841. type: 'tooltip',
  53842. init: function (ecModel, api) {
  53843. if (env$1.node) {
  53844. return;
  53845. }
  53846. var tooltipContent = new TooltipContent(api.getDom(), api);
  53847. this._tooltipContent = tooltipContent;
  53848. },
  53849. render: function (tooltipModel, ecModel, api) {
  53850. if (env$1.node || env$1.wxa) {
  53851. return;
  53852. }
  53853. // Reset
  53854. this.group.removeAll();
  53855. /**
  53856. * @private
  53857. * @type {module:echarts/component/tooltip/TooltipModel}
  53858. */
  53859. this._tooltipModel = tooltipModel;
  53860. /**
  53861. * @private
  53862. * @type {module:echarts/model/Global}
  53863. */
  53864. this._ecModel = ecModel;
  53865. /**
  53866. * @private
  53867. * @type {module:echarts/ExtensionAPI}
  53868. */
  53869. this._api = api;
  53870. /**
  53871. * Should be cleaned when render.
  53872. * @private
  53873. * @type {Array.<Array.<Object>>}
  53874. */
  53875. this._lastDataByCoordSys = null;
  53876. /**
  53877. * @private
  53878. * @type {boolean}
  53879. */
  53880. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  53881. var tooltipContent = this._tooltipContent;
  53882. tooltipContent.update();
  53883. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  53884. this._initGlobalListener();
  53885. this._keepShow();
  53886. },
  53887. _initGlobalListener: function () {
  53888. var tooltipModel = this._tooltipModel;
  53889. var triggerOn = tooltipModel.get('triggerOn');
  53890. register(
  53891. 'itemTooltip',
  53892. this._api,
  53893. bind$3(function (currTrigger, e, dispatchAction) {
  53894. // If 'none', it is not controlled by mouse totally.
  53895. if (triggerOn !== 'none') {
  53896. if (triggerOn.indexOf(currTrigger) >= 0) {
  53897. this._tryShow(e, dispatchAction);
  53898. }
  53899. else if (currTrigger === 'leave') {
  53900. this._hide(dispatchAction);
  53901. }
  53902. }
  53903. }, this)
  53904. );
  53905. },
  53906. _keepShow: function () {
  53907. var tooltipModel = this._tooltipModel;
  53908. var ecModel = this._ecModel;
  53909. var api = this._api;
  53910. // Try to keep the tooltip show when refreshing
  53911. if (this._lastX != null
  53912. && this._lastY != null
  53913. // When user is willing to control tooltip totally using API,
  53914. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  53915. // which is not expected.
  53916. && tooltipModel.get('triggerOn') !== 'none'
  53917. ) {
  53918. var self = this;
  53919. clearTimeout(this._refreshUpdateTimeout);
  53920. this._refreshUpdateTimeout = setTimeout(function () {
  53921. // Show tip next tick after other charts are rendered
  53922. // In case highlight action has wrong result
  53923. // FIXME
  53924. self.manuallyShowTip(tooltipModel, ecModel, api, {
  53925. x: self._lastX,
  53926. y: self._lastY
  53927. });
  53928. });
  53929. }
  53930. },
  53931. /**
  53932. * Show tip manually by
  53933. * dispatchAction({
  53934. * type: 'showTip',
  53935. * x: 10,
  53936. * y: 10
  53937. * });
  53938. * Or
  53939. * dispatchAction({
  53940. * type: 'showTip',
  53941. * seriesIndex: 0,
  53942. * dataIndex or dataIndexInside or name
  53943. * });
  53944. *
  53945. * TODO Batch
  53946. */
  53947. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  53948. if (payload.from === this.uid || env$1.node) {
  53949. return;
  53950. }
  53951. var dispatchAction = makeDispatchAction$1(payload, api);
  53952. // Reset ticket
  53953. this._ticket = '';
  53954. // When triggered from axisPointer.
  53955. var dataByCoordSys = payload.dataByCoordSys;
  53956. if (payload.tooltip && payload.x != null && payload.y != null) {
  53957. var el = proxyRect;
  53958. el.position = [payload.x, payload.y];
  53959. el.update();
  53960. el.tooltip = payload.tooltip;
  53961. // Manually show tooltip while view is not using zrender elements.
  53962. this._tryShow({
  53963. offsetX: payload.x,
  53964. offsetY: payload.y,
  53965. target: el
  53966. }, dispatchAction);
  53967. }
  53968. else if (dataByCoordSys) {
  53969. this._tryShow({
  53970. offsetX: payload.x,
  53971. offsetY: payload.y,
  53972. position: payload.position,
  53973. event: {},
  53974. dataByCoordSys: payload.dataByCoordSys,
  53975. tooltipOption: payload.tooltipOption
  53976. }, dispatchAction);
  53977. }
  53978. else if (payload.seriesIndex != null) {
  53979. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  53980. return;
  53981. }
  53982. var pointInfo = findPointFromSeries(payload, ecModel);
  53983. var cx = pointInfo.point[0];
  53984. var cy = pointInfo.point[1];
  53985. if (cx != null && cy != null) {
  53986. this._tryShow({
  53987. offsetX: cx,
  53988. offsetY: cy,
  53989. position: payload.position,
  53990. target: pointInfo.el,
  53991. event: {}
  53992. }, dispatchAction);
  53993. }
  53994. }
  53995. else if (payload.x != null && payload.y != null) {
  53996. // FIXME
  53997. // should wrap dispatchAction like `axisPointer/globalListener` ?
  53998. api.dispatchAction({
  53999. type: 'updateAxisPointer',
  54000. x: payload.x,
  54001. y: payload.y
  54002. });
  54003. this._tryShow({
  54004. offsetX: payload.x,
  54005. offsetY: payload.y,
  54006. position: payload.position,
  54007. target: api.getZr().findHover(payload.x, payload.y).target,
  54008. event: {}
  54009. }, dispatchAction);
  54010. }
  54011. },
  54012. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  54013. var tooltipContent = this._tooltipContent;
  54014. if (!this._alwaysShowContent && this._tooltipModel) {
  54015. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  54016. }
  54017. this._lastX = this._lastY = null;
  54018. if (payload.from !== this.uid) {
  54019. this._hide(makeDispatchAction$1(payload, api));
  54020. }
  54021. },
  54022. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  54023. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  54024. // and tooltip.
  54025. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  54026. var seriesIndex = payload.seriesIndex;
  54027. var dataIndex = payload.dataIndex;
  54028. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  54029. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  54030. return;
  54031. }
  54032. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  54033. if (!seriesModel) {
  54034. return;
  54035. }
  54036. var data = seriesModel.getData();
  54037. var tooltipModel = buildTooltipModel([
  54038. data.getItemModel(dataIndex),
  54039. seriesModel,
  54040. (seriesModel.coordinateSystem || {}).model,
  54041. tooltipModel
  54042. ]);
  54043. if (tooltipModel.get('trigger') !== 'axis') {
  54044. return;
  54045. }
  54046. api.dispatchAction({
  54047. type: 'updateAxisPointer',
  54048. seriesIndex: seriesIndex,
  54049. dataIndex: dataIndex,
  54050. position: payload.position
  54051. });
  54052. return true;
  54053. },
  54054. _tryShow: function (e, dispatchAction) {
  54055. var el = e.target;
  54056. var tooltipModel = this._tooltipModel;
  54057. if (!tooltipModel) {
  54058. return;
  54059. }
  54060. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  54061. this._lastX = e.offsetX;
  54062. this._lastY = e.offsetY;
  54063. var dataByCoordSys = e.dataByCoordSys;
  54064. if (dataByCoordSys && dataByCoordSys.length) {
  54065. this._showAxisTooltip(dataByCoordSys, e);
  54066. }
  54067. // Always show item tooltip if mouse is on the element with dataIndex
  54068. else if (el && el.dataIndex != null) {
  54069. this._lastDataByCoordSys = null;
  54070. this._showSeriesItemTooltip(e, el, dispatchAction);
  54071. }
  54072. // Tooltip provided directly. Like legend.
  54073. else if (el && el.tooltip) {
  54074. this._lastDataByCoordSys = null;
  54075. this._showComponentItemTooltip(e, el, dispatchAction);
  54076. }
  54077. else {
  54078. this._lastDataByCoordSys = null;
  54079. this._hide(dispatchAction);
  54080. }
  54081. },
  54082. _showOrMove: function (tooltipModel, cb) {
  54083. // showDelay is used in this case: tooltip.enterable is set
  54084. // as true. User intent to move mouse into tooltip and click
  54085. // something. `showDelay` makes it easyer to enter the content
  54086. // but tooltip do not move immediately.
  54087. var delay = tooltipModel.get('showDelay');
  54088. cb = bind(cb, this);
  54089. clearTimeout(this._showTimout);
  54090. delay > 0
  54091. ? (this._showTimout = setTimeout(cb, delay))
  54092. : cb();
  54093. },
  54094. _showAxisTooltip: function (dataByCoordSys, e) {
  54095. var ecModel = this._ecModel;
  54096. var globalTooltipModel = this._tooltipModel;
  54097. var point = [e.offsetX, e.offsetY];
  54098. var singleDefaultHTML = [];
  54099. var singleParamsList = [];
  54100. var singleTooltipModel = buildTooltipModel([
  54101. e.tooltipOption,
  54102. globalTooltipModel
  54103. ]);
  54104. each$18(dataByCoordSys, function (itemCoordSys) {
  54105. // var coordParamList = [];
  54106. // var coordDefaultHTML = [];
  54107. // var coordTooltipModel = buildTooltipModel([
  54108. // e.tooltipOption,
  54109. // itemCoordSys.tooltipOption,
  54110. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  54111. // globalTooltipModel
  54112. // ]);
  54113. // var displayMode = coordTooltipModel.get('displayMode');
  54114. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  54115. each$18(itemCoordSys.dataByAxis, function (item) {
  54116. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  54117. var axisValue = item.value;
  54118. var seriesDefaultHTML = [];
  54119. if (!axisModel || axisValue == null) {
  54120. return;
  54121. }
  54122. var valueLabel = getValueLabel(
  54123. axisValue, axisModel.axis, ecModel,
  54124. item.seriesDataIndices,
  54125. item.valueLabelOpt
  54126. );
  54127. each$1(item.seriesDataIndices, function (idxItem) {
  54128. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  54129. var dataIndex = idxItem.dataIndexInside;
  54130. var dataParams = series && series.getDataParams(dataIndex);
  54131. dataParams.axisDim = item.axisDim;
  54132. dataParams.axisIndex = item.axisIndex;
  54133. dataParams.axisType = item.axisType;
  54134. dataParams.axisId = item.axisId;
  54135. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  54136. dataParams.axisValueLabel = valueLabel;
  54137. if (dataParams) {
  54138. singleParamsList.push(dataParams);
  54139. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  54140. }
  54141. });
  54142. // Default tooltip content
  54143. // FIXME
  54144. // (1) shold be the first data which has name?
  54145. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  54146. var firstLine = valueLabel;
  54147. singleDefaultHTML.push(
  54148. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  54149. + seriesDefaultHTML.join('<br />')
  54150. );
  54151. });
  54152. }, this);
  54153. // In most case, the second axis is shown upper than the first one.
  54154. singleDefaultHTML.reverse();
  54155. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  54156. var positionExpr = e.position;
  54157. this._showOrMove(singleTooltipModel, function () {
  54158. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  54159. this._updatePosition(
  54160. singleTooltipModel,
  54161. positionExpr,
  54162. point[0], point[1],
  54163. this._tooltipContent,
  54164. singleParamsList
  54165. );
  54166. }
  54167. else {
  54168. this._showTooltipContent(
  54169. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  54170. point[0], point[1], positionExpr
  54171. );
  54172. }
  54173. });
  54174. // Do not trigger events here, because this branch only be entered
  54175. // from dispatchAction.
  54176. },
  54177. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  54178. var ecModel = this._ecModel;
  54179. // Use dataModel in element if possible
  54180. // Used when mouseover on a element like markPoint or edge
  54181. // In which case, the data is not main data in series.
  54182. var seriesIndex = el.seriesIndex;
  54183. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  54184. // For example, graph link.
  54185. var dataModel = el.dataModel || seriesModel;
  54186. var dataIndex = el.dataIndex;
  54187. var dataType = el.dataType;
  54188. var data = dataModel.getData();
  54189. var tooltipModel = buildTooltipModel([
  54190. data.getItemModel(dataIndex),
  54191. dataModel,
  54192. seriesModel && (seriesModel.coordinateSystem || {}).model,
  54193. this._tooltipModel
  54194. ]);
  54195. var tooltipTrigger = tooltipModel.get('trigger');
  54196. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  54197. return;
  54198. }
  54199. var params = dataModel.getDataParams(dataIndex, dataType);
  54200. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  54201. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  54202. this._showOrMove(tooltipModel, function () {
  54203. this._showTooltipContent(
  54204. tooltipModel, defaultHtml, params, asyncTicket,
  54205. e.offsetX, e.offsetY, e.position, e.target
  54206. );
  54207. });
  54208. // FIXME
  54209. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  54210. dispatchAction({
  54211. type: 'showTip',
  54212. dataIndexInside: dataIndex,
  54213. dataIndex: data.getRawIndex(dataIndex),
  54214. seriesIndex: seriesIndex,
  54215. from: this.uid
  54216. });
  54217. },
  54218. _showComponentItemTooltip: function (e, el, dispatchAction) {
  54219. var tooltipOpt = el.tooltip;
  54220. if (typeof tooltipOpt === 'string') {
  54221. var content = tooltipOpt;
  54222. tooltipOpt = {
  54223. content: content,
  54224. // Fixed formatter
  54225. formatter: content
  54226. };
  54227. }
  54228. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  54229. var defaultHtml = subTooltipModel.get('content');
  54230. var asyncTicket = Math.random();
  54231. // Do not check whether `trigger` is 'none' here, because `trigger`
  54232. // only works on cooridinate system. In fact, we have not found case
  54233. // that requires setting `trigger` nothing on component yet.
  54234. this._showOrMove(subTooltipModel, function () {
  54235. this._showTooltipContent(
  54236. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  54237. asyncTicket, e.offsetX, e.offsetY, e.position, el
  54238. );
  54239. });
  54240. // If not dispatch showTip, tip may be hide triggered by axis.
  54241. dispatchAction({
  54242. type: 'showTip',
  54243. from: this.uid
  54244. });
  54245. },
  54246. _showTooltipContent: function (
  54247. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  54248. ) {
  54249. // Reset ticket
  54250. this._ticket = '';
  54251. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  54252. return;
  54253. }
  54254. var tooltipContent = this._tooltipContent;
  54255. var formatter = tooltipModel.get('formatter');
  54256. positionExpr = positionExpr || tooltipModel.get('position');
  54257. var html = defaultHtml;
  54258. if (formatter && typeof formatter === 'string') {
  54259. html = formatTpl(formatter, params, true);
  54260. }
  54261. else if (typeof formatter === 'function') {
  54262. var callback = bind$3(function (cbTicket, html) {
  54263. if (cbTicket === this._ticket) {
  54264. tooltipContent.setContent(html);
  54265. this._updatePosition(
  54266. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  54267. );
  54268. }
  54269. }, this);
  54270. this._ticket = asyncTicket;
  54271. html = formatter(params, asyncTicket, callback);
  54272. }
  54273. tooltipContent.setContent(html);
  54274. tooltipContent.show(tooltipModel);
  54275. this._updatePosition(
  54276. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  54277. );
  54278. },
  54279. /**
  54280. * @param {string|Function|Array.<number>|Object} positionExpr
  54281. * @param {number} x Mouse x
  54282. * @param {number} y Mouse y
  54283. * @param {boolean} confine Whether confine tooltip content in view rect.
  54284. * @param {Object|<Array.<Object>} params
  54285. * @param {module:zrender/Element} el target element
  54286. * @param {module:echarts/ExtensionAPI} api
  54287. * @return {Array.<number>}
  54288. */
  54289. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  54290. var viewWidth = this._api.getWidth();
  54291. var viewHeight = this._api.getHeight();
  54292. positionExpr = positionExpr || tooltipModel.get('position');
  54293. var contentSize = content.getSize();
  54294. var align = tooltipModel.get('align');
  54295. var vAlign = tooltipModel.get('verticalAlign');
  54296. var rect = el && el.getBoundingRect().clone();
  54297. el && rect.applyTransform(el.transform);
  54298. if (typeof positionExpr === 'function') {
  54299. // Callback of position can be an array or a string specify the position
  54300. positionExpr = positionExpr([x, y], params, content.el, rect, {
  54301. viewSize: [viewWidth, viewHeight],
  54302. contentSize: contentSize.slice()
  54303. });
  54304. }
  54305. if (isArray(positionExpr)) {
  54306. x = parsePercent$2(positionExpr[0], viewWidth);
  54307. y = parsePercent$2(positionExpr[1], viewHeight);
  54308. }
  54309. else if (isObject$1(positionExpr)) {
  54310. positionExpr.width = contentSize[0];
  54311. positionExpr.height = contentSize[1];
  54312. var layoutRect = getLayoutRect(
  54313. positionExpr, {width: viewWidth, height: viewHeight}
  54314. );
  54315. x = layoutRect.x;
  54316. y = layoutRect.y;
  54317. align = null;
  54318. // When positionExpr is left/top/right/bottom,
  54319. // align and verticalAlign will not work.
  54320. vAlign = null;
  54321. }
  54322. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  54323. else if (typeof positionExpr === 'string' && el) {
  54324. var pos = calcTooltipPosition(
  54325. positionExpr, rect, contentSize
  54326. );
  54327. x = pos[0];
  54328. y = pos[1];
  54329. }
  54330. else {
  54331. var pos = refixTooltipPosition(
  54332. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  54333. );
  54334. x = pos[0];
  54335. y = pos[1];
  54336. }
  54337. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  54338. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  54339. if (tooltipModel.get('confine')) {
  54340. var pos = confineTooltipPosition(
  54341. x, y, content.el, viewWidth, viewHeight
  54342. );
  54343. x = pos[0];
  54344. y = pos[1];
  54345. }
  54346. content.moveTo(x, y);
  54347. },
  54348. // FIXME
  54349. // Should we remove this but leave this to user?
  54350. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  54351. var lastCoordSys = this._lastDataByCoordSys;
  54352. var contentNotChanged = !!lastCoordSys
  54353. && lastCoordSys.length === dataByCoordSys.length;
  54354. contentNotChanged && each$18(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  54355. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  54356. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  54357. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  54358. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  54359. contentNotChanged && each$18(lastDataByAxis, function (lastItem, indexAxis) {
  54360. var thisItem = thisDataByAxis[indexAxis] || {};
  54361. var lastIndices = lastItem.seriesDataIndices || [];
  54362. var newIndices = thisItem.seriesDataIndices || [];
  54363. contentNotChanged &=
  54364. lastItem.value === thisItem.value
  54365. && lastItem.axisType === thisItem.axisType
  54366. && lastItem.axisId === thisItem.axisId
  54367. && lastIndices.length === newIndices.length;
  54368. contentNotChanged && each$18(lastIndices, function (lastIdxItem, j) {
  54369. var newIdxItem = newIndices[j];
  54370. contentNotChanged &=
  54371. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  54372. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  54373. });
  54374. });
  54375. });
  54376. this._lastDataByCoordSys = dataByCoordSys;
  54377. return !!contentNotChanged;
  54378. },
  54379. _hide: function (dispatchAction) {
  54380. // Do not directly hideLater here, because this behavior may be prevented
  54381. // in dispatchAction when showTip is dispatched.
  54382. // FIXME
  54383. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  54384. this._lastDataByCoordSys = null;
  54385. dispatchAction({
  54386. type: 'hideTip',
  54387. from: this.uid
  54388. });
  54389. },
  54390. dispose: function (ecModel, api) {
  54391. if (env$1.node) {
  54392. return;
  54393. }
  54394. this._tooltipContent.hide();
  54395. unregister('itemTooltip', api);
  54396. }
  54397. });
  54398. /**
  54399. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  54400. * From top to bottom. (the last one should be globalTooltipModel);
  54401. */
  54402. function buildTooltipModel(modelCascade) {
  54403. var resultModel = modelCascade.pop();
  54404. while (modelCascade.length) {
  54405. var tooltipOpt = modelCascade.pop();
  54406. if (tooltipOpt) {
  54407. if (Model.isInstance(tooltipOpt)) {
  54408. tooltipOpt = tooltipOpt.get('tooltip', true);
  54409. }
  54410. // In each data item tooltip can be simply write:
  54411. // {
  54412. // value: 10,
  54413. // tooltip: 'Something you need to know'
  54414. // }
  54415. if (typeof tooltipOpt === 'string') {
  54416. tooltipOpt = {formatter: tooltipOpt};
  54417. }
  54418. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  54419. }
  54420. }
  54421. return resultModel;
  54422. }
  54423. function makeDispatchAction$1(payload, api) {
  54424. return payload.dispatchAction || bind(api.dispatchAction, api);
  54425. }
  54426. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  54427. var size = getOuterSize(el);
  54428. var width = size.width;
  54429. var height = size.height;
  54430. if (gapH != null) {
  54431. if (x + width + gapH > viewWidth) {
  54432. x -= width + gapH;
  54433. }
  54434. else {
  54435. x += gapH;
  54436. }
  54437. }
  54438. if (gapV != null) {
  54439. if (y + height + gapV > viewHeight) {
  54440. y -= height + gapV;
  54441. }
  54442. else {
  54443. y += gapV;
  54444. }
  54445. }
  54446. return [x, y];
  54447. }
  54448. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  54449. var size = getOuterSize(el);
  54450. var width = size.width;
  54451. var height = size.height;
  54452. x = Math.min(x + width, viewWidth) - width;
  54453. y = Math.min(y + height, viewHeight) - height;
  54454. x = Math.max(x, 0);
  54455. y = Math.max(y, 0);
  54456. return [x, y];
  54457. }
  54458. function getOuterSize(el) {
  54459. var width = el.clientWidth;
  54460. var height = el.clientHeight;
  54461. // Consider browser compatibility.
  54462. // IE8 does not support getComputedStyle.
  54463. if (document.defaultView && document.defaultView.getComputedStyle) {
  54464. var stl = document.defaultView.getComputedStyle(el);
  54465. if (stl) {
  54466. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  54467. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  54468. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  54469. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  54470. }
  54471. }
  54472. return {width: width, height: height};
  54473. }
  54474. function calcTooltipPosition(position, rect, contentSize) {
  54475. var domWidth = contentSize[0];
  54476. var domHeight = contentSize[1];
  54477. var gap = 5;
  54478. var x = 0;
  54479. var y = 0;
  54480. var rectWidth = rect.width;
  54481. var rectHeight = rect.height;
  54482. switch (position) {
  54483. case 'inside':
  54484. x = rect.x + rectWidth / 2 - domWidth / 2;
  54485. y = rect.y + rectHeight / 2 - domHeight / 2;
  54486. break;
  54487. case 'top':
  54488. x = rect.x + rectWidth / 2 - domWidth / 2;
  54489. y = rect.y - domHeight - gap;
  54490. break;
  54491. case 'bottom':
  54492. x = rect.x + rectWidth / 2 - domWidth / 2;
  54493. y = rect.y + rectHeight + gap;
  54494. break;
  54495. case 'left':
  54496. x = rect.x - domWidth - gap;
  54497. y = rect.y + rectHeight / 2 - domHeight / 2;
  54498. break;
  54499. case 'right':
  54500. x = rect.x + rectWidth + gap;
  54501. y = rect.y + rectHeight / 2 - domHeight / 2;
  54502. }
  54503. return [x, y];
  54504. }
  54505. function isCenterAlign(align) {
  54506. return align === 'center' || align === 'middle';
  54507. }
  54508. // FIXME Better way to pack data in graphic element
  54509. /**
  54510. * @action
  54511. * @property {string} type
  54512. * @property {number} seriesIndex
  54513. * @property {number} dataIndex
  54514. * @property {number} [x]
  54515. * @property {number} [y]
  54516. */
  54517. registerAction(
  54518. {
  54519. type: 'showTip',
  54520. event: 'showTip',
  54521. update: 'tooltip:manuallyShowTip'
  54522. },
  54523. // noop
  54524. function () {}
  54525. );
  54526. registerAction(
  54527. {
  54528. type: 'hideTip',
  54529. event: 'hideTip',
  54530. update: 'tooltip:manuallyHideTip'
  54531. },
  54532. // noop
  54533. function () {}
  54534. );
  54535. function getSeriesStackId$1(seriesModel) {
  54536. return seriesModel.get('stack')
  54537. || '__ec_stack_' + seriesModel.seriesIndex;
  54538. }
  54539. function getAxisKey$1(axis) {
  54540. return axis.dim;
  54541. }
  54542. /**
  54543. * @param {string} seriesType
  54544. * @param {module:echarts/model/Global} ecModel
  54545. * @param {module:echarts/ExtensionAPI} api
  54546. */
  54547. function barLayoutPolar(seriesType, ecModel, api) {
  54548. var width = api.getWidth();
  54549. var height = api.getHeight();
  54550. var lastStackCoords = {};
  54551. var lastStackCoordsOrigin = {};
  54552. var barWidthAndOffset = calRadialBar(
  54553. filter(
  54554. ecModel.getSeriesByType(seriesType),
  54555. function (seriesModel) {
  54556. return !ecModel.isSeriesFiltered(seriesModel)
  54557. && seriesModel.coordinateSystem
  54558. && seriesModel.coordinateSystem.type === 'polar';
  54559. }
  54560. )
  54561. );
  54562. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  54563. // Check series coordinate, do layout for polar only
  54564. if (seriesModel.coordinateSystem.type !== 'polar') {
  54565. return;
  54566. }
  54567. var data = seriesModel.getData();
  54568. var polar = seriesModel.coordinateSystem;
  54569. var angleAxis = polar.getAngleAxis();
  54570. var baseAxis = polar.getBaseAxis();
  54571. var stackId = getSeriesStackId$1(seriesModel);
  54572. var columnLayoutInfo
  54573. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  54574. var columnOffset = columnLayoutInfo.offset;
  54575. var columnWidth = columnLayoutInfo.width;
  54576. var valueAxis = polar.getOtherAxis(baseAxis);
  54577. var center = seriesModel.get('center') || ['50%', '50%'];
  54578. var cx = parsePercent$1(center[0], width);
  54579. var cy = parsePercent$1(center[1], height);
  54580. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  54581. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  54582. var valueAxisStart = valueAxis.getExtent()[0];
  54583. var valueMax = valueAxis.model.get('max');
  54584. var valueMin = valueAxis.model.get('min');
  54585. var coordDims = [
  54586. data.mapDimension('radius'),
  54587. data.mapDimension('angle')
  54588. ];
  54589. var coords = data.mapArray(coordDims, function (radius, angle) {
  54590. return polar.dataToPoint([radius, angle]);
  54591. }, true);
  54592. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  54593. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  54594. data.each(data.mapDimension(valueAxis.dim), function (value, idx) {
  54595. if (isNaN(value)) {
  54596. return;
  54597. }
  54598. if (!lastStackCoords[stackId][idx]) {
  54599. lastStackCoords[stackId][idx] = {
  54600. p: valueAxisStart, // Positive stack
  54601. n: valueAxisStart // Negative stack
  54602. };
  54603. lastStackCoordsOrigin[stackId][idx] = {
  54604. p: valueAxisStart, // Positive stack
  54605. n: valueAxisStart // Negative stack
  54606. };
  54607. }
  54608. var sign = value >= 0 ? 'p' : 'n';
  54609. var coord = polar.pointToCoord(coords[idx]);
  54610. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  54611. var r0;
  54612. var r;
  54613. var startAngle;
  54614. var endAngle;
  54615. if (valueAxis.dim === 'radius') {
  54616. // radial sector
  54617. r0 = lastCoordOrigin;
  54618. r = coord[0];
  54619. startAngle = (-coord[1] + columnOffset) * Math.PI / 180;
  54620. endAngle = startAngle + columnWidth * Math.PI / 180;
  54621. if (Math.abs(r) < barMinHeight) {
  54622. r = r0 + (r < 0 ? -1 : 1) * barMinHeight;
  54623. }
  54624. lastStackCoordsOrigin[stackId][idx][sign] = r;
  54625. }
  54626. else {
  54627. // tangential sector
  54628. r0 = coord[0] + columnOffset;
  54629. r = r0 + columnWidth;
  54630. // clamp data if min or max is defined for valueAxis
  54631. if (valueMax != null) {
  54632. value = Math.min(value, valueMax);
  54633. }
  54634. if (valueMin != null) {
  54635. value = Math.max(value, valueMin);
  54636. }
  54637. var angle = angleAxis.dataToAngle(value);
  54638. if (Math.abs(angle - lastCoordOrigin) < barMinAngle) {
  54639. angle = lastCoordOrigin - (value < 0 ? -1 : 1)
  54640. * barMinAngle;
  54641. }
  54642. startAngle = -lastCoordOrigin * Math.PI / 180;
  54643. endAngle = -angle * Math.PI / 180;
  54644. // if the previous stack is at the end of the ring,
  54645. // add a round to differentiate it from origin
  54646. var extent = angleAxis.getExtent();
  54647. var stackCoord = angle;
  54648. if (stackCoord === extent[0] && value > 0) {
  54649. stackCoord = extent[1];
  54650. }
  54651. else if (stackCoord === extent[1] && value < 0) {
  54652. stackCoord = extent[0];
  54653. }
  54654. lastStackCoordsOrigin[stackId][idx][sign] = stackCoord;
  54655. }
  54656. data.setItemLayout(idx, {
  54657. cx: cx,
  54658. cy: cy,
  54659. r0: r0,
  54660. r: r,
  54661. startAngle: startAngle,
  54662. endAngle: endAngle
  54663. });
  54664. }, true);
  54665. }, this);
  54666. }
  54667. /**
  54668. * Calculate bar width and offset for radial bar charts
  54669. */
  54670. function calRadialBar(barSeries, api) {
  54671. // Columns info on each category axis. Key is polar name
  54672. var columnsMap = {};
  54673. each$1(barSeries, function (seriesModel, idx) {
  54674. var data = seriesModel.getData();
  54675. var polar = seriesModel.coordinateSystem;
  54676. var baseAxis = polar.getBaseAxis();
  54677. var axisExtent = baseAxis.getExtent();
  54678. var bandWidth = baseAxis.type === 'category'
  54679. ? baseAxis.getBandWidth()
  54680. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  54681. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  54682. bandWidth: bandWidth,
  54683. remainedWidth: bandWidth,
  54684. autoWidthCount: 0,
  54685. categoryGap: '20%',
  54686. gap: '30%',
  54687. stacks: {}
  54688. };
  54689. var stacks = columnsOnAxis.stacks;
  54690. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  54691. var stackId = getSeriesStackId$1(seriesModel);
  54692. if (!stacks[stackId]) {
  54693. columnsOnAxis.autoWidthCount++;
  54694. }
  54695. stacks[stackId] = stacks[stackId] || {
  54696. width: 0,
  54697. maxWidth: 0
  54698. };
  54699. var barWidth = parsePercent$1(
  54700. seriesModel.get('barWidth'),
  54701. bandWidth
  54702. );
  54703. var barMaxWidth = parsePercent$1(
  54704. seriesModel.get('barMaxWidth'),
  54705. bandWidth
  54706. );
  54707. var barGap = seriesModel.get('barGap');
  54708. var barCategoryGap = seriesModel.get('barCategoryGap');
  54709. if (barWidth && !stacks[stackId].width) {
  54710. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  54711. stacks[stackId].width = barWidth;
  54712. columnsOnAxis.remainedWidth -= barWidth;
  54713. }
  54714. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  54715. (barGap != null) && (columnsOnAxis.gap = barGap);
  54716. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  54717. });
  54718. var result = {};
  54719. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  54720. result[coordSysName] = {};
  54721. var stacks = columnsOnAxis.stacks;
  54722. var bandWidth = columnsOnAxis.bandWidth;
  54723. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  54724. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  54725. var remainedWidth = columnsOnAxis.remainedWidth;
  54726. var autoWidthCount = columnsOnAxis.autoWidthCount;
  54727. var autoWidth = (remainedWidth - categoryGap)
  54728. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  54729. autoWidth = Math.max(autoWidth, 0);
  54730. // Find if any auto calculated bar exceeded maxBarWidth
  54731. each$1(stacks, function (column, stack) {
  54732. var maxWidth = column.maxWidth;
  54733. if (maxWidth && maxWidth < autoWidth) {
  54734. maxWidth = Math.min(maxWidth, remainedWidth);
  54735. if (column.width) {
  54736. maxWidth = Math.min(maxWidth, column.width);
  54737. }
  54738. remainedWidth -= maxWidth;
  54739. column.width = maxWidth;
  54740. autoWidthCount--;
  54741. }
  54742. });
  54743. // Recalculate width again
  54744. autoWidth = (remainedWidth - categoryGap)
  54745. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  54746. autoWidth = Math.max(autoWidth, 0);
  54747. var widthSum = 0;
  54748. var lastColumn;
  54749. each$1(stacks, function (column, idx) {
  54750. if (!column.width) {
  54751. column.width = autoWidth;
  54752. }
  54753. lastColumn = column;
  54754. widthSum += column.width * (1 + barGapPercent);
  54755. });
  54756. if (lastColumn) {
  54757. widthSum -= lastColumn.width * barGapPercent;
  54758. }
  54759. var offset = -widthSum / 2;
  54760. each$1(stacks, function (column, stackId) {
  54761. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  54762. offset: offset,
  54763. width: column.width
  54764. };
  54765. offset += column.width * (1 + barGapPercent);
  54766. });
  54767. });
  54768. return result;
  54769. }
  54770. function RadiusAxis(scale, radiusExtent) {
  54771. Axis.call(this, 'radius', scale, radiusExtent);
  54772. /**
  54773. * Axis type
  54774. * - 'category'
  54775. * - 'value'
  54776. * - 'time'
  54777. * - 'log'
  54778. * @type {string}
  54779. */
  54780. this.type = 'category';
  54781. }
  54782. RadiusAxis.prototype = {
  54783. constructor: RadiusAxis,
  54784. /**
  54785. * @override
  54786. */
  54787. pointToData: function (point, clamp) {
  54788. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  54789. },
  54790. dataToRadius: Axis.prototype.dataToCoord,
  54791. radiusToData: Axis.prototype.coordToData
  54792. };
  54793. inherits(RadiusAxis, Axis);
  54794. function AngleAxis(scale, angleExtent) {
  54795. angleExtent = angleExtent || [0, 360];
  54796. Axis.call(this, 'angle', scale, angleExtent);
  54797. /**
  54798. * Axis type
  54799. * - 'category'
  54800. * - 'value'
  54801. * - 'time'
  54802. * - 'log'
  54803. * @type {string}
  54804. */
  54805. this.type = 'category';
  54806. }
  54807. AngleAxis.prototype = {
  54808. constructor: AngleAxis,
  54809. /**
  54810. * @override
  54811. */
  54812. pointToData: function (point, clamp) {
  54813. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  54814. },
  54815. dataToAngle: Axis.prototype.dataToCoord,
  54816. angleToData: Axis.prototype.coordToData
  54817. };
  54818. inherits(AngleAxis, Axis);
  54819. /**
  54820. * @module echarts/coord/polar/Polar
  54821. */
  54822. /**
  54823. * @alias {module:echarts/coord/polar/Polar}
  54824. * @constructor
  54825. * @param {string} name
  54826. */
  54827. var Polar = function (name) {
  54828. /**
  54829. * @type {string}
  54830. */
  54831. this.name = name || '';
  54832. /**
  54833. * x of polar center
  54834. * @type {number}
  54835. */
  54836. this.cx = 0;
  54837. /**
  54838. * y of polar center
  54839. * @type {number}
  54840. */
  54841. this.cy = 0;
  54842. /**
  54843. * @type {module:echarts/coord/polar/RadiusAxis}
  54844. * @private
  54845. */
  54846. this._radiusAxis = new RadiusAxis();
  54847. /**
  54848. * @type {module:echarts/coord/polar/AngleAxis}
  54849. * @private
  54850. */
  54851. this._angleAxis = new AngleAxis();
  54852. this._radiusAxis.polar = this._angleAxis.polar = this;
  54853. };
  54854. Polar.prototype = {
  54855. type: 'polar',
  54856. axisPointerEnabled: true,
  54857. constructor: Polar,
  54858. /**
  54859. * @param {Array.<string>}
  54860. * @readOnly
  54861. */
  54862. dimensions: ['radius', 'angle'],
  54863. /**
  54864. * @type {module:echarts/coord/PolarModel}
  54865. */
  54866. model: null,
  54867. /**
  54868. * If contain coord
  54869. * @param {Array.<number>} point
  54870. * @return {boolean}
  54871. */
  54872. containPoint: function (point) {
  54873. var coord = this.pointToCoord(point);
  54874. return this._radiusAxis.contain(coord[0])
  54875. && this._angleAxis.contain(coord[1]);
  54876. },
  54877. /**
  54878. * If contain data
  54879. * @param {Array.<number>} data
  54880. * @return {boolean}
  54881. */
  54882. containData: function (data) {
  54883. return this._radiusAxis.containData(data[0])
  54884. && this._angleAxis.containData(data[1]);
  54885. },
  54886. /**
  54887. * @param {string} dim
  54888. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  54889. */
  54890. getAxis: function (dim) {
  54891. return this['_' + dim + 'Axis'];
  54892. },
  54893. /**
  54894. * @return {Array.<module:echarts/coord/Axis>}
  54895. */
  54896. getAxes: function () {
  54897. return [this._radiusAxis, this._angleAxis];
  54898. },
  54899. /**
  54900. * Get axes by type of scale
  54901. * @param {string} scaleType
  54902. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  54903. */
  54904. getAxesByScale: function (scaleType) {
  54905. var axes = [];
  54906. var angleAxis = this._angleAxis;
  54907. var radiusAxis = this._radiusAxis;
  54908. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  54909. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  54910. return axes;
  54911. },
  54912. /**
  54913. * @return {module:echarts/coord/polar/AngleAxis}
  54914. */
  54915. getAngleAxis: function () {
  54916. return this._angleAxis;
  54917. },
  54918. /**
  54919. * @return {module:echarts/coord/polar/RadiusAxis}
  54920. */
  54921. getRadiusAxis: function () {
  54922. return this._radiusAxis;
  54923. },
  54924. /**
  54925. * @param {module:echarts/coord/polar/Axis}
  54926. * @return {module:echarts/coord/polar/Axis}
  54927. */
  54928. getOtherAxis: function (axis) {
  54929. var angleAxis = this._angleAxis;
  54930. return axis === angleAxis ? this._radiusAxis : angleAxis;
  54931. },
  54932. /**
  54933. * Base axis will be used on stacking.
  54934. *
  54935. * @return {module:echarts/coord/polar/Axis}
  54936. */
  54937. getBaseAxis: function () {
  54938. return this.getAxesByScale('ordinal')[0]
  54939. || this.getAxesByScale('time')[0]
  54940. || this.getAngleAxis();
  54941. },
  54942. /**
  54943. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  54944. * @return {Object} {baseAxes: [], otherAxes: []}
  54945. */
  54946. getTooltipAxes: function (dim) {
  54947. var baseAxis = (dim != null && dim !== 'auto')
  54948. ? this.getAxis(dim) : this.getBaseAxis();
  54949. return {
  54950. baseAxes: [baseAxis],
  54951. otherAxes: [this.getOtherAxis(baseAxis)]
  54952. };
  54953. },
  54954. /**
  54955. * Convert a single data item to (x, y) point.
  54956. * Parameter data is an array which the first element is radius and the second is angle
  54957. * @param {Array.<number>} data
  54958. * @param {boolean} [clamp=false]
  54959. * @return {Array.<number>}
  54960. */
  54961. dataToPoint: function (data, clamp) {
  54962. return this.coordToPoint([
  54963. this._radiusAxis.dataToRadius(data[0], clamp),
  54964. this._angleAxis.dataToAngle(data[1], clamp)
  54965. ]);
  54966. },
  54967. /**
  54968. * Convert a (x, y) point to data
  54969. * @param {Array.<number>} point
  54970. * @param {boolean} [clamp=false]
  54971. * @return {Array.<number>}
  54972. */
  54973. pointToData: function (point, clamp) {
  54974. var coord = this.pointToCoord(point);
  54975. return [
  54976. this._radiusAxis.radiusToData(coord[0], clamp),
  54977. this._angleAxis.angleToData(coord[1], clamp)
  54978. ];
  54979. },
  54980. /**
  54981. * Convert a (x, y) point to (radius, angle) coord
  54982. * @param {Array.<number>} point
  54983. * @return {Array.<number>}
  54984. */
  54985. pointToCoord: function (point) {
  54986. var dx = point[0] - this.cx;
  54987. var dy = point[1] - this.cy;
  54988. var angleAxis = this.getAngleAxis();
  54989. var extent = angleAxis.getExtent();
  54990. var minAngle = Math.min(extent[0], extent[1]);
  54991. var maxAngle = Math.max(extent[0], extent[1]);
  54992. // Fix fixed extent in polarCreator
  54993. // FIXME
  54994. angleAxis.inverse
  54995. ? (minAngle = maxAngle - 360)
  54996. : (maxAngle = minAngle + 360);
  54997. var radius = Math.sqrt(dx * dx + dy * dy);
  54998. dx /= radius;
  54999. dy /= radius;
  55000. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  55001. // move to angleExtent
  55002. var dir = radian < minAngle ? 1 : -1;
  55003. while (radian < minAngle || radian > maxAngle) {
  55004. radian += dir * 360;
  55005. }
  55006. return [radius, radian];
  55007. },
  55008. /**
  55009. * Convert a (radius, angle) coord to (x, y) point
  55010. * @param {Array.<number>} coord
  55011. * @return {Array.<number>}
  55012. */
  55013. coordToPoint: function (coord) {
  55014. var radius = coord[0];
  55015. var radian = coord[1] / 180 * Math.PI;
  55016. var x = Math.cos(radian) * radius + this.cx;
  55017. // Inverse the y
  55018. var y = -Math.sin(radian) * radius + this.cy;
  55019. return [x, y];
  55020. }
  55021. };
  55022. var PolarAxisModel = ComponentModel.extend({
  55023. type: 'polarAxis',
  55024. /**
  55025. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55026. */
  55027. axis: null,
  55028. /**
  55029. * @override
  55030. */
  55031. getCoordSysModel: function () {
  55032. return this.ecModel.queryComponents({
  55033. mainType: 'polar',
  55034. index: this.option.polarIndex,
  55035. id: this.option.polarId
  55036. })[0];
  55037. }
  55038. });
  55039. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  55040. var polarAxisDefaultExtendedOption = {
  55041. angle: {
  55042. // polarIndex: 0,
  55043. // polarId: '',
  55044. startAngle: 90,
  55045. clockwise: true,
  55046. splitNumber: 12,
  55047. axisLabel: {
  55048. rotate: false
  55049. }
  55050. },
  55051. radius: {
  55052. // polarIndex: 0,
  55053. // polarId: '',
  55054. splitNumber: 5
  55055. }
  55056. };
  55057. function getAxisType$3(axisDim, option) {
  55058. // Default axis with data is category axis
  55059. return option.type || (option.data ? 'category' : 'value');
  55060. }
  55061. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  55062. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  55063. extendComponentModel({
  55064. type: 'polar',
  55065. dependencies: ['polarAxis', 'angleAxis'],
  55066. /**
  55067. * @type {module:echarts/coord/polar/Polar}
  55068. */
  55069. coordinateSystem: null,
  55070. /**
  55071. * @param {string} axisType
  55072. * @return {module:echarts/coord/polar/AxisModel}
  55073. */
  55074. findAxisModel: function (axisType) {
  55075. var foundAxisModel;
  55076. var ecModel = this.ecModel;
  55077. ecModel.eachComponent(axisType, function (axisModel) {
  55078. if (axisModel.getCoordSysModel() === this) {
  55079. foundAxisModel = axisModel;
  55080. }
  55081. }, this);
  55082. return foundAxisModel;
  55083. },
  55084. defaultOption: {
  55085. zlevel: 0,
  55086. z: 0,
  55087. center: ['50%', '50%'],
  55088. radius: '80%'
  55089. }
  55090. });
  55091. // TODO Axis scale
  55092. // 依赖 PolarModel 做预处理
  55093. /**
  55094. * Resize method bound to the polar
  55095. * @param {module:echarts/coord/polar/PolarModel} polarModel
  55096. * @param {module:echarts/ExtensionAPI} api
  55097. */
  55098. function resizePolar(polar, polarModel, api) {
  55099. var center = polarModel.get('center');
  55100. var width = api.getWidth();
  55101. var height = api.getHeight();
  55102. polar.cx = parsePercent$1(center[0], width);
  55103. polar.cy = parsePercent$1(center[1], height);
  55104. var radiusAxis = polar.getRadiusAxis();
  55105. var size = Math.min(width, height) / 2;
  55106. var radius = parsePercent$1(polarModel.get('radius'), size);
  55107. radiusAxis.inverse
  55108. ? radiusAxis.setExtent(radius, 0)
  55109. : radiusAxis.setExtent(0, radius);
  55110. }
  55111. /**
  55112. * Update polar
  55113. */
  55114. function updatePolarScale(ecModel, api) {
  55115. var polar = this;
  55116. var angleAxis = polar.getAngleAxis();
  55117. var radiusAxis = polar.getRadiusAxis();
  55118. // Reset scale
  55119. angleAxis.scale.setExtent(Infinity, -Infinity);
  55120. radiusAxis.scale.setExtent(Infinity, -Infinity);
  55121. ecModel.eachSeries(function (seriesModel) {
  55122. if (seriesModel.coordinateSystem === polar) {
  55123. var data = seriesModel.getData();
  55124. each$1(data.mapDimension('radius', true), function (dim) {
  55125. radiusAxis.scale.unionExtentFromData(data, dim);
  55126. });
  55127. each$1(data.mapDimension('angle', true), function (dim) {
  55128. angleAxis.scale.unionExtentFromData(data, dim);
  55129. });
  55130. }
  55131. });
  55132. niceScaleExtent(angleAxis.scale, angleAxis.model);
  55133. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  55134. // Fix extent of category angle axis
  55135. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  55136. var extent = angleAxis.getExtent();
  55137. var diff = 360 / angleAxis.scale.count();
  55138. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  55139. angleAxis.setExtent(extent[0], extent[1]);
  55140. }
  55141. }
  55142. /**
  55143. * Set common axis properties
  55144. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55145. * @param {module:echarts/coord/polar/AxisModel}
  55146. * @inner
  55147. */
  55148. function setAxis(axis, axisModel) {
  55149. axis.type = axisModel.get('type');
  55150. axis.scale = createScaleByModel(axisModel);
  55151. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  55152. axis.inverse = axisModel.get('inverse');
  55153. if (axisModel.mainType === 'angleAxis') {
  55154. axis.inverse ^= axisModel.get('clockwise');
  55155. var startAngle = axisModel.get('startAngle');
  55156. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  55157. }
  55158. // Inject axis instance
  55159. axisModel.axis = axis;
  55160. axis.model = axisModel;
  55161. }
  55162. var polarCreator = {
  55163. dimensions: Polar.prototype.dimensions,
  55164. create: function (ecModel, api) {
  55165. var polarList = [];
  55166. ecModel.eachComponent('polar', function (polarModel, idx) {
  55167. var polar = new Polar(idx);
  55168. // Inject resize and update method
  55169. polar.update = updatePolarScale;
  55170. var radiusAxis = polar.getRadiusAxis();
  55171. var angleAxis = polar.getAngleAxis();
  55172. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  55173. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  55174. setAxis(radiusAxis, radiusAxisModel);
  55175. setAxis(angleAxis, angleAxisModel);
  55176. resizePolar(polar, polarModel, api);
  55177. polarList.push(polar);
  55178. polarModel.coordinateSystem = polar;
  55179. polar.model = polarModel;
  55180. });
  55181. // Inject coordinateSystem to series
  55182. ecModel.eachSeries(function (seriesModel) {
  55183. if (seriesModel.get('coordinateSystem') === 'polar') {
  55184. var polarModel = ecModel.queryComponents({
  55185. mainType: 'polar',
  55186. index: seriesModel.get('polarIndex'),
  55187. id: seriesModel.get('polarId')
  55188. })[0];
  55189. if (__DEV__) {
  55190. if (!polarModel) {
  55191. throw new Error(
  55192. 'Polar "' + retrieve(
  55193. seriesModel.get('polarIndex'),
  55194. seriesModel.get('polarId'),
  55195. 0
  55196. ) + '" not found'
  55197. );
  55198. }
  55199. }
  55200. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  55201. }
  55202. });
  55203. return polarList;
  55204. }
  55205. };
  55206. CoordinateSystemManager.register('polar', polarCreator);
  55207. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  55208. function getAxisLineShape(polar, rExtent, angle) {
  55209. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  55210. var start = polar.coordToPoint([rExtent[0], angle]);
  55211. var end = polar.coordToPoint([rExtent[1], angle]);
  55212. return {
  55213. x1: start[0],
  55214. y1: start[1],
  55215. x2: end[0],
  55216. y2: end[1]
  55217. };
  55218. }
  55219. function getRadiusIdx(polar) {
  55220. var radiusAxis = polar.getRadiusAxis();
  55221. return radiusAxis.inverse ? 0 : 1;
  55222. }
  55223. AxisView.extend({
  55224. type: 'angleAxis',
  55225. axisPointerClass: 'PolarAxisPointer',
  55226. render: function (angleAxisModel, ecModel) {
  55227. this.group.removeAll();
  55228. if (!angleAxisModel.get('show')) {
  55229. return;
  55230. }
  55231. var angleAxis = angleAxisModel.axis;
  55232. var polar = angleAxis.polar;
  55233. var radiusExtent = polar.getRadiusAxis().getExtent();
  55234. var ticksAngles = angleAxis.getTicksCoords();
  55235. if (angleAxis.type !== 'category') {
  55236. // Remove the last tick which will overlap the first tick
  55237. ticksAngles.pop();
  55238. }
  55239. each$1(elementList$1, function (name) {
  55240. if (angleAxisModel.get(name +'.show')
  55241. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  55242. ) {
  55243. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent);
  55244. }
  55245. }, this);
  55246. },
  55247. /**
  55248. * @private
  55249. */
  55250. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  55251. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  55252. var circle = new Circle({
  55253. shape: {
  55254. cx: polar.cx,
  55255. cy: polar.cy,
  55256. r: radiusExtent[getRadiusIdx(polar)]
  55257. },
  55258. style: lineStyleModel.getLineStyle(),
  55259. z2: 1,
  55260. silent: true
  55261. });
  55262. circle.style.fill = null;
  55263. this.group.add(circle);
  55264. },
  55265. /**
  55266. * @private
  55267. */
  55268. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  55269. var tickModel = angleAxisModel.getModel('axisTick');
  55270. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  55271. var radius = radiusExtent[getRadiusIdx(polar)];
  55272. var lines = map(ticksAngles, function (tickAngle) {
  55273. return new Line({
  55274. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngle)
  55275. });
  55276. });
  55277. this.group.add(mergePath(
  55278. lines, {
  55279. style: defaults(
  55280. tickModel.getModel('lineStyle').getLineStyle(),
  55281. {
  55282. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  55283. }
  55284. )
  55285. }
  55286. ));
  55287. },
  55288. /**
  55289. * @private
  55290. */
  55291. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  55292. var axis = angleAxisModel.axis;
  55293. var categoryData = angleAxisModel.getCategories();
  55294. var labelModel = angleAxisModel.getModel('axisLabel');
  55295. var labels = angleAxisModel.getFormattedLabels();
  55296. var labelMargin = labelModel.get('margin');
  55297. var labelsAngles = axis.getLabelsCoords();
  55298. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  55299. for (var i = 0; i < ticksAngles.length; i++) {
  55300. var r = radiusExtent[getRadiusIdx(polar)];
  55301. var p = polar.coordToPoint([r + labelMargin, labelsAngles[i]]);
  55302. var cx = polar.cx;
  55303. var cy = polar.cy;
  55304. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  55305. ? 'center' : (p[0] > cx ? 'left' : 'right');
  55306. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  55307. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  55308. if (categoryData && categoryData[i] && categoryData[i].textStyle) {
  55309. labelModel = new Model(categoryData[i].textStyle, labelModel, labelModel.ecModel);
  55310. }
  55311. var textEl = new Text({silent: true});
  55312. this.group.add(textEl);
  55313. setTextStyle(textEl.style, labelModel, {
  55314. x: p[0],
  55315. y: p[1],
  55316. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  55317. text: labels[i],
  55318. textAlign: labelTextAlign,
  55319. textVerticalAlign: labelTextVerticalAlign
  55320. });
  55321. }
  55322. },
  55323. /**
  55324. * @private
  55325. */
  55326. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  55327. var splitLineModel = angleAxisModel.getModel('splitLine');
  55328. var lineStyleModel = splitLineModel.getModel('lineStyle');
  55329. var lineColors = lineStyleModel.get('color');
  55330. var lineCount = 0;
  55331. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  55332. var splitLines = [];
  55333. for (var i = 0; i < ticksAngles.length; i++) {
  55334. var colorIndex = (lineCount++) % lineColors.length;
  55335. splitLines[colorIndex] = splitLines[colorIndex] || [];
  55336. splitLines[colorIndex].push(new Line({
  55337. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i])
  55338. }));
  55339. }
  55340. // Simple optimization
  55341. // Batching the lines if color are the same
  55342. for (var i = 0; i < splitLines.length; i++) {
  55343. this.group.add(mergePath(splitLines[i], {
  55344. style: defaults({
  55345. stroke: lineColors[i % lineColors.length]
  55346. }, lineStyleModel.getLineStyle()),
  55347. silent: true,
  55348. z: angleAxisModel.get('z')
  55349. }));
  55350. }
  55351. },
  55352. /**
  55353. * @private
  55354. */
  55355. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  55356. var splitAreaModel = angleAxisModel.getModel('splitArea');
  55357. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  55358. var areaColors = areaStyleModel.get('color');
  55359. var lineCount = 0;
  55360. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  55361. var splitAreas = [];
  55362. var RADIAN = Math.PI / 180;
  55363. var prevAngle = -ticksAngles[0] * RADIAN;
  55364. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  55365. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  55366. var clockwise = angleAxisModel.get('clockwise');
  55367. for (var i = 1; i < ticksAngles.length; i++) {
  55368. var colorIndex = (lineCount++) % areaColors.length;
  55369. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  55370. splitAreas[colorIndex].push(new Sector({
  55371. shape: {
  55372. cx: polar.cx,
  55373. cy: polar.cy,
  55374. r0: r0,
  55375. r: r1,
  55376. startAngle: prevAngle,
  55377. endAngle: -ticksAngles[i] * RADIAN,
  55378. clockwise: clockwise
  55379. },
  55380. silent: true
  55381. }));
  55382. prevAngle = -ticksAngles[i] * RADIAN;
  55383. }
  55384. // Simple optimization
  55385. // Batching the lines if color are the same
  55386. for (var i = 0; i < splitAreas.length; i++) {
  55387. this.group.add(mergePath(splitAreas[i], {
  55388. style: defaults({
  55389. fill: areaColors[i % areaColors.length]
  55390. }, areaStyleModel.getAreaStyle()),
  55391. silent: true
  55392. }));
  55393. }
  55394. }
  55395. });
  55396. var axisBuilderAttrs$3 = [
  55397. 'axisLine', 'axisTickLabel', 'axisName'
  55398. ];
  55399. var selfBuilderAttrs$1 = [
  55400. 'splitLine', 'splitArea'
  55401. ];
  55402. AxisView.extend({
  55403. type: 'radiusAxis',
  55404. axisPointerClass: 'PolarAxisPointer',
  55405. render: function (radiusAxisModel, ecModel) {
  55406. this.group.removeAll();
  55407. if (!radiusAxisModel.get('show')) {
  55408. return;
  55409. }
  55410. var radiusAxis = radiusAxisModel.axis;
  55411. var polar = radiusAxis.polar;
  55412. var angleAxis = polar.getAngleAxis();
  55413. var ticksCoords = radiusAxis.getTicksCoords();
  55414. var axisAngle = angleAxis.getExtent()[0];
  55415. var radiusExtent = radiusAxis.getExtent();
  55416. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  55417. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  55418. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  55419. this.group.add(axisBuilder.getGroup());
  55420. each$1(selfBuilderAttrs$1, function (name) {
  55421. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  55422. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  55423. }
  55424. }, this);
  55425. },
  55426. /**
  55427. * @private
  55428. */
  55429. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  55430. var splitLineModel = radiusAxisModel.getModel('splitLine');
  55431. var lineStyleModel = splitLineModel.getModel('lineStyle');
  55432. var lineColors = lineStyleModel.get('color');
  55433. var lineCount = 0;
  55434. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  55435. var splitLines = [];
  55436. for (var i = 0; i < ticksCoords.length; i++) {
  55437. var colorIndex = (lineCount++) % lineColors.length;
  55438. splitLines[colorIndex] = splitLines[colorIndex] || [];
  55439. splitLines[colorIndex].push(new Circle({
  55440. shape: {
  55441. cx: polar.cx,
  55442. cy: polar.cy,
  55443. r: ticksCoords[i]
  55444. },
  55445. silent: true
  55446. }));
  55447. }
  55448. // Simple optimization
  55449. // Batching the lines if color are the same
  55450. for (var i = 0; i < splitLines.length; i++) {
  55451. this.group.add(mergePath(splitLines[i], {
  55452. style: defaults({
  55453. stroke: lineColors[i % lineColors.length],
  55454. fill: null
  55455. }, lineStyleModel.getLineStyle()),
  55456. silent: true
  55457. }));
  55458. }
  55459. },
  55460. /**
  55461. * @private
  55462. */
  55463. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  55464. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  55465. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  55466. var areaColors = areaStyleModel.get('color');
  55467. var lineCount = 0;
  55468. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  55469. var splitAreas = [];
  55470. var prevRadius = ticksCoords[0];
  55471. for (var i = 1; i < ticksCoords.length; i++) {
  55472. var colorIndex = (lineCount++) % areaColors.length;
  55473. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  55474. splitAreas[colorIndex].push(new Sector({
  55475. shape: {
  55476. cx: polar.cx,
  55477. cy: polar.cy,
  55478. r0: prevRadius,
  55479. r: ticksCoords[i],
  55480. startAngle: 0,
  55481. endAngle: Math.PI * 2
  55482. },
  55483. silent: true
  55484. }));
  55485. prevRadius = ticksCoords[i];
  55486. }
  55487. // Simple optimization
  55488. // Batching the lines if color are the same
  55489. for (var i = 0; i < splitAreas.length; i++) {
  55490. this.group.add(mergePath(splitAreas[i], {
  55491. style: defaults({
  55492. fill: areaColors[i % areaColors.length]
  55493. }, areaStyleModel.getAreaStyle()),
  55494. silent: true
  55495. }));
  55496. }
  55497. }
  55498. });
  55499. /**
  55500. * @inner
  55501. */
  55502. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  55503. return {
  55504. position: [polar.cx, polar.cy],
  55505. rotation: axisAngle / 180 * Math.PI,
  55506. labelDirection: -1,
  55507. tickDirection: -1,
  55508. nameDirection: 1,
  55509. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  55510. // Over splitLine and splitArea
  55511. z2: 1
  55512. };
  55513. }
  55514. var PolarAxisPointer = BaseAxisPointer.extend({
  55515. /**
  55516. * @override
  55517. */
  55518. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  55519. var axis = axisModel.axis;
  55520. if (axis.dim === 'angle') {
  55521. this.animationThreshold = Math.PI / 18;
  55522. }
  55523. var polar = axis.polar;
  55524. var otherAxis = polar.getOtherAxis(axis);
  55525. var otherExtent = otherAxis.getExtent();
  55526. var coordValue;
  55527. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  55528. var axisPointerType = axisPointerModel.get('type');
  55529. if (axisPointerType && axisPointerType !== 'none') {
  55530. var elStyle = buildElStyle(axisPointerModel);
  55531. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  55532. axis, polar, coordValue, otherExtent, elStyle
  55533. );
  55534. pointerOption.style = elStyle;
  55535. elOption.graphicKey = pointerOption.type;
  55536. elOption.pointer = pointerOption;
  55537. }
  55538. var labelMargin = axisPointerModel.get('label.margin');
  55539. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  55540. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  55541. }
  55542. // Do not support handle, utill any user requires it.
  55543. });
  55544. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  55545. var axis = axisModel.axis;
  55546. var coord = axis.dataToCoord(value);
  55547. var axisAngle = polar.getAngleAxis().getExtent()[0];
  55548. axisAngle = axisAngle / 180 * Math.PI;
  55549. var radiusExtent = polar.getRadiusAxis().getExtent();
  55550. var position;
  55551. var align;
  55552. var verticalAlign;
  55553. if (axis.dim === 'radius') {
  55554. var transform = create$1();
  55555. rotate(transform, transform, axisAngle);
  55556. translate(transform, transform, [polar.cx, polar.cy]);
  55557. position = applyTransform$1([coord, -labelMargin], transform);
  55558. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  55559. var labelLayout = AxisBuilder.innerTextLayout(
  55560. axisAngle, labelRotation * Math.PI / 180, -1
  55561. );
  55562. align = labelLayout.textAlign;
  55563. verticalAlign = labelLayout.textVerticalAlign;
  55564. }
  55565. else { // angle axis
  55566. var r = radiusExtent[1];
  55567. position = polar.coordToPoint([r + labelMargin, coord]);
  55568. var cx = polar.cx;
  55569. var cy = polar.cy;
  55570. align = Math.abs(position[0] - cx) / r < 0.3
  55571. ? 'center' : (position[0] > cx ? 'left' : 'right');
  55572. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  55573. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  55574. }
  55575. return {
  55576. position: position,
  55577. align: align,
  55578. verticalAlign: verticalAlign
  55579. };
  55580. }
  55581. var pointerShapeBuilder$2 = {
  55582. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  55583. return axis.dim === 'angle'
  55584. ? {
  55585. type: 'Line',
  55586. shape: makeLineShape(
  55587. polar.coordToPoint([otherExtent[0], coordValue]),
  55588. polar.coordToPoint([otherExtent[1], coordValue])
  55589. )
  55590. }
  55591. : {
  55592. type: 'Circle',
  55593. shape: {
  55594. cx: polar.cx,
  55595. cy: polar.cy,
  55596. r: coordValue
  55597. }
  55598. };
  55599. },
  55600. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  55601. var bandWidth = axis.getBandWidth();
  55602. var radian = Math.PI / 180;
  55603. return axis.dim === 'angle'
  55604. ? {
  55605. type: 'Sector',
  55606. shape: makeSectorShape(
  55607. polar.cx, polar.cy,
  55608. otherExtent[0], otherExtent[1],
  55609. // In ECharts y is negative if angle is positive
  55610. (-coordValue - bandWidth / 2) * radian,
  55611. (-coordValue + bandWidth / 2) * radian
  55612. )
  55613. }
  55614. : {
  55615. type: 'Sector',
  55616. shape: makeSectorShape(
  55617. polar.cx, polar.cy,
  55618. coordValue - bandWidth / 2,
  55619. coordValue + bandWidth / 2,
  55620. 0, Math.PI * 2
  55621. )
  55622. };
  55623. }
  55624. };
  55625. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  55626. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  55627. registerLayout(curry(barLayoutPolar, 'bar'));
  55628. // Polar view
  55629. extendComponentView({
  55630. type: 'polar'
  55631. });
  55632. var GeoModel = ComponentModel.extend({
  55633. type: 'geo',
  55634. /**
  55635. * @type {module:echarts/coord/geo/Geo}
  55636. */
  55637. coordinateSystem: null,
  55638. layoutMode: 'box',
  55639. init: function (option) {
  55640. ComponentModel.prototype.init.apply(this, arguments);
  55641. // Default label emphasis `show`
  55642. defaultEmphasis(option, 'label', ['show']);
  55643. },
  55644. optionUpdated: function () {
  55645. var option = this.option;
  55646. var self = this;
  55647. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  55648. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  55649. if (regionOpt.name) {
  55650. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  55651. }
  55652. return optionModelMap;
  55653. }, createHashMap());
  55654. this.updateSelectedMap(option.regions);
  55655. },
  55656. defaultOption: {
  55657. zlevel: 0,
  55658. z: 0,
  55659. show: true,
  55660. left: 'center',
  55661. top: 'center',
  55662. // width:,
  55663. // height:,
  55664. // right
  55665. // bottom
  55666. // Aspect is width / height. Inited to be geoJson bbox aspect
  55667. // This parameter is used for scale this aspect
  55668. aspectScale: 0.75,
  55669. ///// Layout with center and size
  55670. // If you wan't to put map in a fixed size box with right aspect ratio
  55671. // This two properties may more conveninet
  55672. // layoutCenter: [50%, 50%]
  55673. // layoutSize: 100
  55674. silent: false,
  55675. // Map type
  55676. map: '',
  55677. // Define left-top, right-bottom coords to control view
  55678. // For example, [ [180, 90], [-180, -90] ]
  55679. boundingCoords: null,
  55680. // Default on center of map
  55681. center: null,
  55682. zoom: 1,
  55683. scaleLimit: null,
  55684. // selectedMode: false
  55685. label: {
  55686. show: false,
  55687. color: '#000'
  55688. },
  55689. itemStyle: {
  55690. // color: 各异,
  55691. borderWidth: 0.5,
  55692. borderColor: '#444',
  55693. color: '#eee'
  55694. },
  55695. emphasis: {
  55696. label: {
  55697. show: true,
  55698. color: 'rgb(100,0,0)'
  55699. },
  55700. itemStyle: {
  55701. color: 'rgba(255,215,0,0.8)'
  55702. }
  55703. },
  55704. regions: []
  55705. },
  55706. /**
  55707. * Get model of region
  55708. * @param {string} name
  55709. * @return {module:echarts/model/Model}
  55710. */
  55711. getRegionModel: function (name) {
  55712. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  55713. },
  55714. /**
  55715. * Format label
  55716. * @param {string} name Region name
  55717. * @param {string} [status='normal'] 'normal' or 'emphasis'
  55718. * @return {string}
  55719. */
  55720. getFormattedLabel: function (name, status) {
  55721. var regionModel = this.getRegionModel(name);
  55722. var formatter = regionModel.get('label.' + status + '.formatter');
  55723. var params = {
  55724. name: name
  55725. };
  55726. if (typeof formatter === 'function') {
  55727. params.status = status;
  55728. return formatter(params);
  55729. }
  55730. else if (typeof formatter === 'string') {
  55731. return formatter.replace('{a}', name != null ? name : '');
  55732. }
  55733. },
  55734. setZoom: function (zoom) {
  55735. this.option.zoom = zoom;
  55736. },
  55737. setCenter: function (center) {
  55738. this.option.center = center;
  55739. }
  55740. });
  55741. mixin(GeoModel, selectableMixin);
  55742. extendComponentView({
  55743. type: 'geo',
  55744. init: function (ecModel, api) {
  55745. var mapDraw = new MapDraw(api, true);
  55746. this._mapDraw = mapDraw;
  55747. this.group.add(mapDraw.group);
  55748. },
  55749. render: function (geoModel, ecModel, api, payload) {
  55750. // Not render if it is an toggleSelect action from self
  55751. if (payload && payload.type === 'geoToggleSelect'
  55752. && payload.from === this.uid
  55753. ) {
  55754. return;
  55755. }
  55756. var mapDraw = this._mapDraw;
  55757. if (geoModel.get('show')) {
  55758. mapDraw.draw(geoModel, ecModel, api, this, payload);
  55759. }
  55760. else {
  55761. this._mapDraw.group.removeAll();
  55762. }
  55763. this.group.silent = geoModel.get('silent');
  55764. },
  55765. dispose: function () {
  55766. this._mapDraw && this._mapDraw.remove();
  55767. }
  55768. });
  55769. function makeAction(method, actionInfo) {
  55770. actionInfo.update = 'updateView';
  55771. registerAction(actionInfo, function (payload, ecModel) {
  55772. var selected = {};
  55773. ecModel.eachComponent(
  55774. { mainType: 'geo', query: payload},
  55775. function (geoModel) {
  55776. geoModel[method](payload.name);
  55777. var geo = geoModel.coordinateSystem;
  55778. each$1(geo.regions, function (region) {
  55779. selected[region.name] = geoModel.isSelected(region.name) || false;
  55780. });
  55781. }
  55782. );
  55783. return {
  55784. selected: selected,
  55785. name: payload.name
  55786. };
  55787. });
  55788. }
  55789. makeAction('toggleSelected', {
  55790. type: 'geoToggleSelect',
  55791. event: 'geoselectchanged'
  55792. });
  55793. makeAction('select', {
  55794. type: 'geoSelect',
  55795. event: 'geoselected'
  55796. });
  55797. makeAction('unSelect', {
  55798. type: 'geoUnSelect',
  55799. event: 'geounselected'
  55800. });
  55801. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  55802. var preprocessor$1 = function (option, isNew) {
  55803. var brushComponents = option && option.brush;
  55804. if (!isArray(brushComponents)) {
  55805. brushComponents = brushComponents ? [brushComponents] : [];
  55806. }
  55807. if (!brushComponents.length) {
  55808. return;
  55809. }
  55810. var brushComponentSpecifiedBtns = [];
  55811. each$1(brushComponents, function (brushOpt) {
  55812. var tbs = brushOpt.hasOwnProperty('toolbox')
  55813. ? brushOpt.toolbox : [];
  55814. if (tbs instanceof Array) {
  55815. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  55816. }
  55817. });
  55818. var toolbox = option && option.toolbox;
  55819. if (isArray(toolbox)) {
  55820. toolbox = toolbox[0];
  55821. }
  55822. if (!toolbox) {
  55823. toolbox = {feature: {}};
  55824. option.toolbox = [toolbox];
  55825. }
  55826. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  55827. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  55828. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  55829. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  55830. removeDuplicate(brushTypes);
  55831. if (isNew && !brushTypes.length) {
  55832. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  55833. }
  55834. };
  55835. function removeDuplicate(arr) {
  55836. var map$$1 = {};
  55837. each$1(arr, function (val) {
  55838. map$$1[val] = 1;
  55839. });
  55840. arr.length = 0;
  55841. each$1(map$$1, function (flag, val) {
  55842. arr.push(val);
  55843. });
  55844. }
  55845. /**
  55846. * @file Visual solution, for consistent option specification.
  55847. */
  55848. var each$20 = each$1;
  55849. function hasKeys(obj) {
  55850. if (obj) {
  55851. for (var name in obj){
  55852. if (obj.hasOwnProperty(name)) {
  55853. return true;
  55854. }
  55855. }
  55856. }
  55857. }
  55858. /**
  55859. * @param {Object} option
  55860. * @param {Array.<string>} stateList
  55861. * @param {Function} [supplementVisualOption]
  55862. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  55863. */
  55864. function createVisualMappings(option, stateList, supplementVisualOption) {
  55865. var visualMappings = {};
  55866. each$20(stateList, function (state) {
  55867. var mappings = visualMappings[state] = createMappings();
  55868. each$20(option[state], function (visualData, visualType) {
  55869. if (!VisualMapping.isValidType(visualType)) {
  55870. return;
  55871. }
  55872. var mappingOption = {
  55873. type: visualType,
  55874. visual: visualData
  55875. };
  55876. supplementVisualOption && supplementVisualOption(mappingOption, state);
  55877. mappings[visualType] = new VisualMapping(mappingOption);
  55878. // Prepare a alpha for opacity, for some case that opacity
  55879. // is not supported, such as rendering using gradient color.
  55880. if (visualType === 'opacity') {
  55881. mappingOption = clone(mappingOption);
  55882. mappingOption.type = 'colorAlpha';
  55883. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  55884. }
  55885. });
  55886. });
  55887. return visualMappings;
  55888. function createMappings() {
  55889. var Creater = function () {};
  55890. // Make sure hidden fields will not be visited by
  55891. // object iteration (with hasOwnProperty checking).
  55892. Creater.prototype.__hidden = Creater.prototype;
  55893. var obj = new Creater();
  55894. return obj;
  55895. }
  55896. }
  55897. /**
  55898. * @param {Object} thisOption
  55899. * @param {Object} newOption
  55900. * @param {Array.<string>} keys
  55901. */
  55902. function replaceVisualOption(thisOption, newOption, keys) {
  55903. // Visual attributes merge is not supported, otherwise it
  55904. // brings overcomplicated merge logic. See #2853. So if
  55905. // newOption has anyone of these keys, all of these keys
  55906. // will be reset. Otherwise, all keys remain.
  55907. var has;
  55908. each$1(keys, function (key) {
  55909. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  55910. has = true;
  55911. }
  55912. });
  55913. has && each$1(keys, function (key) {
  55914. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  55915. thisOption[key] = clone(newOption[key]);
  55916. }
  55917. else {
  55918. delete thisOption[key];
  55919. }
  55920. });
  55921. }
  55922. /**
  55923. * @param {Array.<string>} stateList
  55924. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  55925. * @param {module:echarts/data/List} list
  55926. * @param {Function} getValueState param: valueOrIndex, return: state.
  55927. * @param {object} [scope] Scope for getValueState
  55928. * @param {string} [dimension] Concrete dimension, if used.
  55929. */
  55930. // ???! handle brush?
  55931. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  55932. var visualTypesMap = {};
  55933. each$1(stateList, function (state) {
  55934. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  55935. visualTypesMap[state] = visualTypes;
  55936. });
  55937. var dataIndex;
  55938. function getVisual(key) {
  55939. return data.getItemVisual(dataIndex, key);
  55940. }
  55941. function setVisual(key, value) {
  55942. data.setItemVisual(dataIndex, key, value);
  55943. }
  55944. if (dimension == null) {
  55945. data.each(eachItem, true);
  55946. }
  55947. else {
  55948. data.each([dimension], eachItem, true);
  55949. }
  55950. function eachItem(valueOrIndex, index) {
  55951. dataIndex = dimension == null ? valueOrIndex : index;
  55952. var rawDataItem = data.getRawDataItem(dataIndex);
  55953. // Consider performance
  55954. if (rawDataItem && rawDataItem.visualMap === false) {
  55955. return;
  55956. }
  55957. var valueState = getValueState.call(scope, valueOrIndex);
  55958. var mappings = visualMappings[valueState];
  55959. var visualTypes = visualTypesMap[valueState];
  55960. for (var i = 0, len = visualTypes.length; i < len; i++) {
  55961. var type = visualTypes[i];
  55962. mappings[type] && mappings[type].applyVisual(
  55963. valueOrIndex, getVisual, setVisual
  55964. );
  55965. }
  55966. }
  55967. }
  55968. /**
  55969. * @param {module:echarts/data/List} data
  55970. * @param {Array.<string>} stateList
  55971. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  55972. * @param {Function} getValueState param: valueOrIndex, return: state.
  55973. * @param {number} [dim] dimension or dimension index.
  55974. */
  55975. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  55976. var visualTypesMap = {};
  55977. each$1(stateList, function (state) {
  55978. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  55979. visualTypesMap[state] = visualTypes;
  55980. });
  55981. function progress(params, data) {
  55982. if (dim != null) {
  55983. dim = data.getDimension(dim);
  55984. }
  55985. function getVisual(key) {
  55986. return data.getItemVisual(dataIndex, key);
  55987. }
  55988. function setVisual(key, value) {
  55989. data.setItemVisual(dataIndex, key, value);
  55990. }
  55991. for (var dataIndex = params.start; dataIndex < params.end; dataIndex++) {
  55992. var rawDataItem = data.getRawDataItem(dataIndex);
  55993. // Consider performance
  55994. if (rawDataItem && rawDataItem.visualMap === false) {
  55995. return;
  55996. }
  55997. var value = dim != null
  55998. ? data.get(dim, dataIndex, true)
  55999. : dataIndex;
  56000. var valueState = getValueState(value);
  56001. var mappings = visualMappings[valueState];
  56002. var visualTypes = visualTypesMap[valueState];
  56003. for (var i = 0, len = visualTypes.length; i < len; i++) {
  56004. var type = visualTypes[i];
  56005. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  56006. }
  56007. }
  56008. }
  56009. return {progress: progress};
  56010. }
  56011. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  56012. // Key of the second level is chart element type: `point`, `rect`.
  56013. // See moudule:echarts/component/helper/BrushController
  56014. // function param:
  56015. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  56016. // {Object} selectors {point: selector, rect: selector, ...}
  56017. // {Object} area {range: [[], [], ..], boudingRect}
  56018. // function return:
  56019. // {boolean} Whether in the given brush.
  56020. var selector = {
  56021. lineX: getLineSelectors(0),
  56022. lineY: getLineSelectors(1),
  56023. rect: {
  56024. point: function (itemLayout, selectors, area) {
  56025. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  56026. },
  56027. rect: function (itemLayout, selectors, area) {
  56028. return itemLayout && area.boundingRect.intersect(itemLayout);
  56029. }
  56030. },
  56031. polygon: {
  56032. point: function (itemLayout, selectors, area) {
  56033. return itemLayout
  56034. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  56035. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  56036. },
  56037. rect: function (itemLayout, selectors, area) {
  56038. var points = area.range;
  56039. if (!itemLayout || points.length <= 1) {
  56040. return false;
  56041. }
  56042. var x = itemLayout.x;
  56043. var y = itemLayout.y;
  56044. var width = itemLayout.width;
  56045. var height = itemLayout.height;
  56046. var p = points[0];
  56047. if (contain$1(points, x, y)
  56048. || contain$1(points, x + width, y)
  56049. || contain$1(points, x, y + height)
  56050. || contain$1(points, x + width, y + height)
  56051. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  56052. || lineIntersectPolygon(x, y, x + width, y, points)
  56053. || lineIntersectPolygon(x, y, x, y + height, points)
  56054. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  56055. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  56056. ) {
  56057. return true;
  56058. }
  56059. }
  56060. }
  56061. };
  56062. function getLineSelectors(xyIndex) {
  56063. var xy = ['x', 'y'];
  56064. var wh = ['width', 'height'];
  56065. return {
  56066. point: function (itemLayout, selectors, area) {
  56067. if (itemLayout) {
  56068. var range = area.range;
  56069. var p = itemLayout[xyIndex];
  56070. return inLineRange(p, range);
  56071. }
  56072. },
  56073. rect: function (itemLayout, selectors, area) {
  56074. if (itemLayout) {
  56075. var range = area.range;
  56076. var layoutRange = [
  56077. itemLayout[xy[xyIndex]],
  56078. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  56079. ];
  56080. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  56081. return inLineRange(layoutRange[0], range)
  56082. || inLineRange(layoutRange[1], range)
  56083. || inLineRange(range[0], layoutRange)
  56084. || inLineRange(range[1], layoutRange);
  56085. }
  56086. }
  56087. };
  56088. }
  56089. function inLineRange(p, range) {
  56090. return range[0] <= p && p <= range[1];
  56091. }
  56092. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  56093. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  56094. var p = points[i];
  56095. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  56096. return true;
  56097. }
  56098. p2 = p;
  56099. }
  56100. }
  56101. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  56102. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  56103. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  56104. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  56105. if (nearZero(delta)) { // parallel
  56106. return false;
  56107. }
  56108. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  56109. if (namenda < 0 || namenda > 1) {
  56110. return false;
  56111. }
  56112. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  56113. if (miu < 0 || miu > 1) {
  56114. return false;
  56115. }
  56116. return true;
  56117. }
  56118. function nearZero(val) {
  56119. return val <= (1e-6) && val >= -(1e-6);
  56120. }
  56121. function determinant(v1, v2, v3, v4) {
  56122. return v1 * v4 - v2 * v3;
  56123. }
  56124. var each$21 = each$1;
  56125. var indexOf$1 = indexOf;
  56126. var curry$5 = curry;
  56127. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  56128. // FIXME
  56129. // how to genarialize to more coordinate systems.
  56130. var INCLUDE_FINDER_MAIN_TYPES = [
  56131. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  56132. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  56133. ];
  56134. /**
  56135. * [option in constructor]:
  56136. * {
  56137. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  56138. * }
  56139. *
  56140. *
  56141. * [targetInfo]:
  56142. *
  56143. * There can be multiple axes in a single targetInfo. Consider the case
  56144. * of `grid` component, a targetInfo represents a grid which contains one or more
  56145. * cartesian and one or more axes. And consider the case of parallel system,
  56146. * which has multiple axes in a coordinate system.
  56147. * Can be {
  56148. * panelId: ...,
  56149. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  56150. * coordSyses: all cartesians.
  56151. * gridModel: <grid component>
  56152. * xAxes: correspond to coordSyses on index
  56153. * yAxes: correspond to coordSyses on index
  56154. * }
  56155. * or {
  56156. * panelId: ...,
  56157. * coordSys: <geo coord sys>
  56158. * coordSyses: [<geo coord sys>]
  56159. * geoModel: <geo component>
  56160. * }
  56161. *
  56162. *
  56163. * [panelOpt]:
  56164. *
  56165. * Make from targetInfo. Input to BrushController.
  56166. * {
  56167. * panelId: ...,
  56168. * rect: ...
  56169. * }
  56170. *
  56171. *
  56172. * [area]:
  56173. *
  56174. * Generated by BrushController or user input.
  56175. * {
  56176. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  56177. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  56178. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  56179. * range: pixel range.
  56180. * coordRange: representitive coord range (the first one of coordRanges).
  56181. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  56182. * }
  56183. */
  56184. /**
  56185. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  56186. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  56187. * @param {module:echarts/model/Global} ecModel
  56188. * @param {Object} [opt]
  56189. * @param {Array.<string>} [opt.include] include coordinate system types.
  56190. */
  56191. function BrushTargetManager(option, ecModel, opt) {
  56192. /**
  56193. * @private
  56194. * @type {Array.<Object>}
  56195. */
  56196. var targetInfoList = this._targetInfoList = [];
  56197. var info = {};
  56198. var foundCpts = parseFinder$1(ecModel, option);
  56199. each$21(targetInfoBuilders, function (builder, type) {
  56200. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  56201. builder(foundCpts, targetInfoList, info);
  56202. }
  56203. });
  56204. }
  56205. var proto$2 = BrushTargetManager.prototype;
  56206. proto$2.setOutputRanges = function (areas, ecModel) {
  56207. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  56208. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  56209. // area.coordRange is the first of area.coordRanges
  56210. if (!area.coordRange) {
  56211. area.coordRange = coordRange;
  56212. // In 'category' axis, coord to pixel is not reversible, so we can not
  56213. // rebuild range by coordRange accrately, which may bring trouble when
  56214. // brushing only one item. So we use __rangeOffset to rebuilding range
  56215. // by coordRange. And this it only used in brush component so it is no
  56216. // need to be adapted to coordRanges.
  56217. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  56218. area.__rangeOffset = {
  56219. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  56220. xyMinMax: result.xyMinMax
  56221. };
  56222. }
  56223. });
  56224. };
  56225. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  56226. each$21(areas, function (area) {
  56227. var targetInfo = this.findTargetInfo(area, ecModel);
  56228. if (targetInfo && targetInfo !== true) {
  56229. each$1(
  56230. targetInfo.coordSyses,
  56231. function (coordSys) {
  56232. var result = coordConvert[area.brushType](1, coordSys, area.range);
  56233. cb(area, result.values, coordSys, ecModel);
  56234. }
  56235. );
  56236. }
  56237. }, this);
  56238. };
  56239. proto$2.setInputRanges = function (areas, ecModel) {
  56240. each$21(areas, function (area) {
  56241. var targetInfo = this.findTargetInfo(area, ecModel);
  56242. if (__DEV__) {
  56243. assert$1(
  56244. !targetInfo || targetInfo === true || area.coordRange,
  56245. 'coordRange must be specified when coord index specified.'
  56246. );
  56247. assert$1(
  56248. !targetInfo || targetInfo !== true || area.range,
  56249. 'range must be specified in global brush.'
  56250. );
  56251. }
  56252. area.range = area.range || [];
  56253. // convert coordRange to global range and set panelId.
  56254. if (targetInfo && targetInfo !== true) {
  56255. area.panelId = targetInfo.panelId;
  56256. // (1) area.range shoule always be calculate from coordRange but does
  56257. // not keep its original value, for the sake of the dataZoom scenario,
  56258. // where area.coordRange remains unchanged but area.range may be changed.
  56259. // (2) Only support converting one coordRange to pixel range in brush
  56260. // component. So do not consider `coordRanges`.
  56261. // (3) About __rangeOffset, see comment above.
  56262. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  56263. var rangeOffset = area.__rangeOffset;
  56264. area.range = rangeOffset
  56265. ? diffProcessor[area.brushType](
  56266. result.values,
  56267. rangeOffset.offset,
  56268. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  56269. )
  56270. : result.values;
  56271. }
  56272. }, this);
  56273. };
  56274. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  56275. return map(this._targetInfoList, function (targetInfo) {
  56276. var rect = targetInfo.getPanelRect();
  56277. return {
  56278. panelId: targetInfo.panelId,
  56279. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  56280. clipPath: makeRectPanelClipPath(rect),
  56281. isTargetByCursor: makeRectIsTargetByCursor(
  56282. rect, api, targetInfo.coordSysModel
  56283. ),
  56284. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  56285. };
  56286. });
  56287. };
  56288. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  56289. // Check whether area is bound in coord, and series do not belong to that coord.
  56290. // If do not do this check, some brush (like lineX) will controll all axes.
  56291. var targetInfo = this.findTargetInfo(area, ecModel);
  56292. return targetInfo === true || (
  56293. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  56294. );
  56295. };
  56296. /**
  56297. * If return Object, a coord found.
  56298. * If reutrn true, global found.
  56299. * Otherwise nothing found.
  56300. *
  56301. * @param {Object} area
  56302. * @param {Array} targetInfoList
  56303. * @return {Object|boolean}
  56304. */
  56305. proto$2.findTargetInfo = function (area, ecModel) {
  56306. var targetInfoList = this._targetInfoList;
  56307. var foundCpts = parseFinder$1(ecModel, area);
  56308. for (var i = 0; i < targetInfoList.length; i++) {
  56309. var targetInfo = targetInfoList[i];
  56310. var areaPanelId = area.panelId;
  56311. if (areaPanelId) {
  56312. if (targetInfo.panelId === areaPanelId) {
  56313. return targetInfo;
  56314. }
  56315. }
  56316. else {
  56317. for (var i = 0; i < targetInfoMatchers.length; i++) {
  56318. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  56319. return targetInfo;
  56320. }
  56321. }
  56322. }
  56323. }
  56324. return true;
  56325. };
  56326. function formatMinMax(minMax) {
  56327. minMax[0] > minMax[1] && minMax.reverse();
  56328. return minMax;
  56329. }
  56330. function parseFinder$1(ecModel, option) {
  56331. return parseFinder(
  56332. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  56333. );
  56334. }
  56335. var targetInfoBuilders = {
  56336. grid: function (foundCpts, targetInfoList) {
  56337. var xAxisModels = foundCpts.xAxisModels;
  56338. var yAxisModels = foundCpts.yAxisModels;
  56339. var gridModels = foundCpts.gridModels;
  56340. // Remove duplicated.
  56341. var gridModelMap = createHashMap();
  56342. var xAxesHas = {};
  56343. var yAxesHas = {};
  56344. if (!xAxisModels && !yAxisModels && !gridModels) {
  56345. return;
  56346. }
  56347. each$21(xAxisModels, function (axisModel) {
  56348. var gridModel = axisModel.axis.grid.model;
  56349. gridModelMap.set(gridModel.id, gridModel);
  56350. xAxesHas[gridModel.id] = true;
  56351. });
  56352. each$21(yAxisModels, function (axisModel) {
  56353. var gridModel = axisModel.axis.grid.model;
  56354. gridModelMap.set(gridModel.id, gridModel);
  56355. yAxesHas[gridModel.id] = true;
  56356. });
  56357. each$21(gridModels, function (gridModel) {
  56358. gridModelMap.set(gridModel.id, gridModel);
  56359. xAxesHas[gridModel.id] = true;
  56360. yAxesHas[gridModel.id] = true;
  56361. });
  56362. gridModelMap.each(function (gridModel) {
  56363. var grid = gridModel.coordinateSystem;
  56364. var cartesians = [];
  56365. each$21(grid.getCartesians(), function (cartesian, index) {
  56366. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  56367. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  56368. ) {
  56369. cartesians.push(cartesian);
  56370. }
  56371. });
  56372. targetInfoList.push({
  56373. panelId: 'grid--' + gridModel.id,
  56374. gridModel: gridModel,
  56375. coordSysModel: gridModel,
  56376. // Use the first one as the representitive coordSys.
  56377. coordSys: cartesians[0],
  56378. coordSyses: cartesians,
  56379. getPanelRect: panelRectBuilder.grid,
  56380. xAxisDeclared: xAxesHas[gridModel.id],
  56381. yAxisDeclared: yAxesHas[gridModel.id]
  56382. });
  56383. });
  56384. },
  56385. geo: function (foundCpts, targetInfoList) {
  56386. each$21(foundCpts.geoModels, function (geoModel) {
  56387. var coordSys = geoModel.coordinateSystem;
  56388. targetInfoList.push({
  56389. panelId: 'geo--' + geoModel.id,
  56390. geoModel: geoModel,
  56391. coordSysModel: geoModel,
  56392. coordSys: coordSys,
  56393. coordSyses: [coordSys],
  56394. getPanelRect: panelRectBuilder.geo
  56395. });
  56396. });
  56397. }
  56398. };
  56399. var targetInfoMatchers = [
  56400. // grid
  56401. function (foundCpts, targetInfo) {
  56402. var xAxisModel = foundCpts.xAxisModel;
  56403. var yAxisModel = foundCpts.yAxisModel;
  56404. var gridModel = foundCpts.gridModel;
  56405. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  56406. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  56407. return gridModel && gridModel === targetInfo.gridModel;
  56408. },
  56409. // geo
  56410. function (foundCpts, targetInfo) {
  56411. var geoModel = foundCpts.geoModel;
  56412. return geoModel && geoModel === targetInfo.geoModel;
  56413. }
  56414. ];
  56415. var panelRectBuilder = {
  56416. grid: function () {
  56417. // grid is not Transformable.
  56418. return this.coordSys.grid.getRect().clone();
  56419. },
  56420. geo: function () {
  56421. var coordSys = this.coordSys;
  56422. var rect = coordSys.getBoundingRect().clone();
  56423. // geo roam and zoom transform
  56424. rect.applyTransform(getTransform(coordSys));
  56425. return rect;
  56426. }
  56427. };
  56428. var coordConvert = {
  56429. lineX: curry$5(axisConvert, 0),
  56430. lineY: curry$5(axisConvert, 1),
  56431. rect: function (to, coordSys, rangeOrCoordRange) {
  56432. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  56433. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  56434. var values = [
  56435. formatMinMax([xminymin[0], xmaxymax[0]]),
  56436. formatMinMax([xminymin[1], xmaxymax[1]])
  56437. ];
  56438. return {values: values, xyMinMax: values};
  56439. },
  56440. polygon: function (to, coordSys, rangeOrCoordRange) {
  56441. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  56442. var values = map(rangeOrCoordRange, function (item) {
  56443. var p = coordSys[COORD_CONVERTS[to]](item);
  56444. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  56445. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  56446. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  56447. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  56448. return p;
  56449. });
  56450. return {values: values, xyMinMax: xyMinMax};
  56451. }
  56452. };
  56453. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  56454. if (__DEV__) {
  56455. assert$1(
  56456. coordSys.type === 'cartesian2d',
  56457. 'lineX/lineY brush is available only in cartesian2d.'
  56458. );
  56459. }
  56460. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  56461. var values = formatMinMax(map([0, 1], function (i) {
  56462. return to
  56463. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  56464. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  56465. }));
  56466. var xyMinMax = [];
  56467. xyMinMax[axisNameIndex] = values;
  56468. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  56469. return {values: values, xyMinMax: xyMinMax};
  56470. }
  56471. var diffProcessor = {
  56472. lineX: curry$5(axisDiffProcessor, 0),
  56473. lineY: curry$5(axisDiffProcessor, 1),
  56474. rect: function (values, refer, scales) {
  56475. return [
  56476. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  56477. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  56478. ];
  56479. },
  56480. polygon: function (values, refer, scales) {
  56481. return map(values, function (item, idx) {
  56482. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  56483. });
  56484. }
  56485. };
  56486. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  56487. return [
  56488. values[0] - scales[axisNameIndex] * refer[0],
  56489. values[1] - scales[axisNameIndex] * refer[1]
  56490. ];
  56491. }
  56492. // We have to process scale caused by dataZoom manually,
  56493. // although it might be not accurate.
  56494. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  56495. var sizeCurr = getSize(xyMinMaxCurr);
  56496. var sizeOrigin = getSize(xyMinMaxOrigin);
  56497. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  56498. isNaN(scales[0]) && (scales[0] = 1);
  56499. isNaN(scales[1]) && (scales[1] = 1);
  56500. return scales;
  56501. }
  56502. function getSize(xyMinMax) {
  56503. return xyMinMax
  56504. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  56505. : [NaN, NaN];
  56506. }
  56507. var STATE_LIST = ['inBrush', 'outOfBrush'];
  56508. var DISPATCH_METHOD = '__ecBrushSelect';
  56509. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  56510. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  56511. /**
  56512. * Layout for visual, the priority higher than other layout, and before brush visual.
  56513. */
  56514. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  56515. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  56516. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  56517. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  56518. );
  56519. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  56520. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  56521. });
  56522. });
  56523. /**
  56524. * Register the visual encoding if this modules required.
  56525. */
  56526. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  56527. var brushSelected = [];
  56528. var throttleType;
  56529. var throttleDelay;
  56530. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  56531. var thisBrushSelected = {
  56532. brushId: brushModel.id,
  56533. brushIndex: brushIndex,
  56534. brushName: brushModel.name,
  56535. areas: clone(brushModel.areas),
  56536. selected: []
  56537. };
  56538. // Every brush component exists in event params, convenient
  56539. // for user to find by index.
  56540. brushSelected.push(thisBrushSelected);
  56541. var brushOption = brushModel.option;
  56542. var brushLink = brushOption.brushLink;
  56543. var linkedSeriesMap = [];
  56544. var selectedDataIndexForLink = [];
  56545. var rangeInfoBySeries = [];
  56546. var hasBrushExists = 0;
  56547. if (!brushIndex) { // Only the first throttle setting works.
  56548. throttleType = brushOption.throttleType;
  56549. throttleDelay = brushOption.throttleDelay;
  56550. }
  56551. // Add boundingRect and selectors to range.
  56552. var areas = map(brushModel.areas, function (area) {
  56553. return bindSelector(
  56554. defaults(
  56555. {boundingRect: boundingRectBuilders[area.brushType](area)},
  56556. area
  56557. )
  56558. );
  56559. });
  56560. var visualMappings = createVisualMappings(
  56561. brushModel.option, STATE_LIST, function (mappingOption) {
  56562. mappingOption.mappingMethod = 'fixed';
  56563. }
  56564. );
  56565. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  56566. linkedSeriesMap[seriesIndex] = 1;
  56567. });
  56568. function linkOthers(seriesIndex) {
  56569. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  56570. }
  56571. // If no supported brush or no brush on the series,
  56572. // all visuals should be in original state.
  56573. function brushed(rangeInfoList) {
  56574. return !!rangeInfoList.length;
  56575. }
  56576. /**
  56577. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  56578. *
  56579. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  56580. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  56581. * └!hasBrushExist┘ └nothing.
  56582. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  56583. * └!hasBrushExist┘ └nothing.
  56584. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  56585. * !brushed┘ └nothing.
  56586. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  56587. */
  56588. // Step A
  56589. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  56590. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  56591. seriesModel.subType === 'parallel'
  56592. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  56593. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  56594. });
  56595. function stepAParallel(seriesModel, seriesIndex) {
  56596. var coordSys = seriesModel.coordinateSystem;
  56597. hasBrushExists |= coordSys.hasAxisBrushed();
  56598. linkOthers(seriesIndex) && coordSys.eachActiveState(
  56599. seriesModel.getData(),
  56600. function (activeState, dataIndex) {
  56601. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  56602. }
  56603. );
  56604. }
  56605. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  56606. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  56607. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  56608. return;
  56609. }
  56610. each$1(areas, function (area) {
  56611. selectorsByBrushType[area.brushType]
  56612. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  56613. && rangeInfoList.push(area);
  56614. hasBrushExists |= brushed(rangeInfoList);
  56615. });
  56616. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  56617. var data = seriesModel.getData();
  56618. data.each(function (dataIndex) {
  56619. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  56620. selectedDataIndexForLink[dataIndex] = 1;
  56621. }
  56622. });
  56623. }
  56624. }
  56625. // Step B
  56626. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  56627. var seriesBrushSelected = {
  56628. seriesId: seriesModel.id,
  56629. seriesIndex: seriesIndex,
  56630. seriesName: seriesModel.name,
  56631. dataIndex: []
  56632. };
  56633. // Every series exists in event params, convenient
  56634. // for user to find series by seriesIndex.
  56635. thisBrushSelected.selected.push(seriesBrushSelected);
  56636. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  56637. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  56638. var data = seriesModel.getData();
  56639. var getValueState = linkOthers(seriesIndex)
  56640. ? function (dataIndex) {
  56641. return selectedDataIndexForLink[dataIndex]
  56642. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  56643. : 'outOfBrush';
  56644. }
  56645. : function (dataIndex) {
  56646. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  56647. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  56648. : 'outOfBrush';
  56649. };
  56650. // If no supported brush or no brush, all visuals are in original state.
  56651. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  56652. && applyVisual(
  56653. STATE_LIST, visualMappings, data, getValueState
  56654. );
  56655. });
  56656. });
  56657. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  56658. });
  56659. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  56660. // This event will not be triggered when `setOpion`, otherwise dead lock may
  56661. // triggered when do `setOption` in event listener, which we do not find
  56662. // satisfactory way to solve yet. Some considered resolutions:
  56663. // (a) Diff with prevoius selected data ant only trigger event when changed.
  56664. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  56665. // also detect value changes in selected data) might bring complexity or fragility.
  56666. // (b) Use spectial param like `silent` to suppress event triggering.
  56667. // But such kind of volatile param may be weird in `setOption`.
  56668. if (!payload) {
  56669. return;
  56670. }
  56671. var zr = api.getZr();
  56672. if (zr[DISPATCH_FLAG]) {
  56673. return;
  56674. }
  56675. if (!zr[DISPATCH_METHOD]) {
  56676. zr[DISPATCH_METHOD] = doDispatch;
  56677. }
  56678. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  56679. fn(api, brushSelected);
  56680. }
  56681. function doDispatch(api, brushSelected) {
  56682. if (!api.isDisposed()) {
  56683. var zr = api.getZr();
  56684. zr[DISPATCH_FLAG] = true;
  56685. api.dispatchAction({
  56686. type: 'brushSelect',
  56687. batch: brushSelected
  56688. });
  56689. zr[DISPATCH_FLAG] = false;
  56690. }
  56691. }
  56692. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  56693. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  56694. var area = rangeInfoList[i];
  56695. if (selectorsByBrushType[area.brushType](
  56696. dataIndex, data, area.selectors, area
  56697. )) {
  56698. return true;
  56699. }
  56700. }
  56701. }
  56702. function getSelectorsByBrushType(seriesModel) {
  56703. var brushSelector = seriesModel.brushSelector;
  56704. if (isString(brushSelector)) {
  56705. var sels = [];
  56706. each$1(selector, function (selectorsByElementType, brushType) {
  56707. sels[brushType] = function (dataIndex, data, selectors, area) {
  56708. var itemLayout = data.getItemLayout(dataIndex);
  56709. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  56710. };
  56711. });
  56712. return sels;
  56713. }
  56714. else if (isFunction$1(brushSelector)) {
  56715. var bSelector = {};
  56716. each$1(selector, function (sel, brushType) {
  56717. bSelector[brushType] = brushSelector;
  56718. });
  56719. return bSelector;
  56720. }
  56721. return brushSelector;
  56722. }
  56723. function brushModelNotControll(brushModel, seriesIndex) {
  56724. var seriesIndices = brushModel.option.seriesIndex;
  56725. return seriesIndices != null
  56726. && seriesIndices !== 'all'
  56727. && (
  56728. isArray(seriesIndices)
  56729. ? indexOf(seriesIndices, seriesIndex) < 0
  56730. : seriesIndex !== seriesIndices
  56731. );
  56732. }
  56733. function bindSelector(area) {
  56734. var selectors = area.selectors = {};
  56735. each$1(selector[area.brushType], function (selFn, elType) {
  56736. // Do not use function binding or curry for performance.
  56737. selectors[elType] = function (itemLayout) {
  56738. return selFn(itemLayout, selectors, area);
  56739. };
  56740. });
  56741. return area;
  56742. }
  56743. var boundingRectBuilders = {
  56744. lineX: noop,
  56745. lineY: noop,
  56746. rect: function (area) {
  56747. return getBoundingRectFromMinMax(area.range);
  56748. },
  56749. polygon: function (area) {
  56750. var minMax;
  56751. var range = area.range;
  56752. for (var i = 0, len = range.length; i < len; i++) {
  56753. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  56754. var rg = range[i];
  56755. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  56756. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  56757. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  56758. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  56759. }
  56760. return minMax && getBoundingRectFromMinMax(minMax);
  56761. }
  56762. };
  56763. function getBoundingRectFromMinMax(minMax) {
  56764. return new BoundingRect(
  56765. minMax[0][0],
  56766. minMax[1][0],
  56767. minMax[0][1] - minMax[0][0],
  56768. minMax[1][1] - minMax[1][0]
  56769. );
  56770. }
  56771. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  56772. var BrushModel = extendComponentModel({
  56773. type: 'brush',
  56774. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  56775. /**
  56776. * @protected
  56777. */
  56778. defaultOption: {
  56779. // inBrush: null,
  56780. // outOfBrush: null,
  56781. toolbox: null, // Default value see preprocessor.
  56782. brushLink: null, // Series indices array, broadcast using dataIndex.
  56783. // or 'all', which means all series. 'none' or null means no series.
  56784. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  56785. geoIndex: null, //
  56786. xAxisIndex: null,
  56787. yAxisIndex: null,
  56788. brushType: 'rect', // Default brushType, see BrushController.
  56789. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  56790. transformable: true, // Default transformable.
  56791. brushStyle: { // Default brushStyle
  56792. borderWidth: 1,
  56793. color: 'rgba(120,140,180,0.3)',
  56794. borderColor: 'rgba(120,140,180,0.8)'
  56795. },
  56796. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  56797. // If null, no throttle. Valid only in the first brush component
  56798. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  56799. // FIXME
  56800. // 试验效果
  56801. removeOnClick: true,
  56802. z: 10000
  56803. },
  56804. /**
  56805. * @readOnly
  56806. * @type {Array.<Object>}
  56807. */
  56808. areas: [],
  56809. /**
  56810. * Current activated brush type.
  56811. * If null, brush is inactived.
  56812. * see module:echarts/component/helper/BrushController
  56813. * @readOnly
  56814. * @type {string}
  56815. */
  56816. brushType: null,
  56817. /**
  56818. * Current brush opt.
  56819. * see module:echarts/component/helper/BrushController
  56820. * @readOnly
  56821. * @type {Object}
  56822. */
  56823. brushOption: {},
  56824. /**
  56825. * @readOnly
  56826. * @type {Array.<Object>}
  56827. */
  56828. coordInfoList: [],
  56829. optionUpdated: function (newOption, isInit) {
  56830. var thisOption = this.option;
  56831. !isInit && replaceVisualOption(
  56832. thisOption, newOption, ['inBrush', 'outOfBrush']
  56833. );
  56834. thisOption.inBrush = thisOption.inBrush || {};
  56835. // Always give default visual, consider setOption at the second time.
  56836. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  56837. },
  56838. /**
  56839. * If ranges is null/undefined, range state remain.
  56840. *
  56841. * @param {Array.<Object>} [ranges]
  56842. */
  56843. setAreas: function (areas) {
  56844. if (__DEV__) {
  56845. assert$1(isArray(areas));
  56846. each$1(areas, function (area) {
  56847. assert$1(area.brushType, 'Illegal areas');
  56848. });
  56849. }
  56850. // If ranges is null/undefined, range state remain.
  56851. // This helps user to dispatchAction({type: 'brush'}) with no areas
  56852. // set but just want to get the current brush select info from a `brush` event.
  56853. if (!areas) {
  56854. return;
  56855. }
  56856. this.areas = map(areas, function (area) {
  56857. return generateBrushOption(this.option, area);
  56858. }, this);
  56859. },
  56860. /**
  56861. * see module:echarts/component/helper/BrushController
  56862. * @param {Object} brushOption
  56863. */
  56864. setBrushOption: function (brushOption) {
  56865. this.brushOption = generateBrushOption(this.option, brushOption);
  56866. this.brushType = this.brushOption.brushType;
  56867. }
  56868. });
  56869. function generateBrushOption(option, brushOption) {
  56870. return merge(
  56871. {
  56872. brushType: option.brushType,
  56873. brushMode: option.brushMode,
  56874. transformable: option.transformable,
  56875. brushStyle: new Model(option.brushStyle).getItemStyle(),
  56876. removeOnClick: option.removeOnClick,
  56877. z: option.z
  56878. },
  56879. brushOption,
  56880. true
  56881. );
  56882. }
  56883. extendComponentView({
  56884. type: 'brush',
  56885. init: function (ecModel, api) {
  56886. /**
  56887. * @readOnly
  56888. * @type {module:echarts/model/Global}
  56889. */
  56890. this.ecModel = ecModel;
  56891. /**
  56892. * @readOnly
  56893. * @type {module:echarts/ExtensionAPI}
  56894. */
  56895. this.api = api;
  56896. /**
  56897. * @readOnly
  56898. * @type {module:echarts/component/brush/BrushModel}
  56899. */
  56900. this.model;
  56901. /**
  56902. * @private
  56903. * @type {module:echarts/component/helper/BrushController}
  56904. */
  56905. (this._brushController = new BrushController(api.getZr()))
  56906. .on('brush', bind(this._onBrush, this))
  56907. .mount();
  56908. },
  56909. /**
  56910. * @override
  56911. */
  56912. render: function (brushModel) {
  56913. this.model = brushModel;
  56914. return updateController.apply(this, arguments);
  56915. },
  56916. /**
  56917. * @override
  56918. */
  56919. updateView: updateController,
  56920. // /**
  56921. // * @override
  56922. // */
  56923. // updateLayout: updateController,
  56924. // /**
  56925. // * @override
  56926. // */
  56927. // updateVisual: updateController,
  56928. /**
  56929. * @override
  56930. */
  56931. dispose: function () {
  56932. this._brushController.dispose();
  56933. },
  56934. /**
  56935. * @private
  56936. */
  56937. _onBrush: function (areas, opt) {
  56938. var modelId = this.model.id;
  56939. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  56940. // Action is not dispatched on drag end, because the drag end
  56941. // emits the same params with the last drag move event, and
  56942. // may have some delay when using touch pad, which makes
  56943. // animation not smooth (when using debounce).
  56944. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  56945. type: 'brush',
  56946. brushId: modelId,
  56947. areas: clone(areas),
  56948. $from: modelId
  56949. });
  56950. }
  56951. });
  56952. function updateController(brushModel, ecModel, api, payload) {
  56953. // Do not update controller when drawing.
  56954. (!payload || payload.$from !== brushModel.id) && this._brushController
  56955. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  56956. .enableBrush(brushModel.brushOption)
  56957. .updateCovers(brushModel.areas.slice());
  56958. }
  56959. /**
  56960. * payload: {
  56961. * brushIndex: number, or,
  56962. * brushId: string, or,
  56963. * brushName: string,
  56964. * globalRanges: Array
  56965. * }
  56966. */
  56967. registerAction(
  56968. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  56969. function (payload, ecModel) {
  56970. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  56971. brushModel.setAreas(payload.areas);
  56972. });
  56973. }
  56974. );
  56975. /**
  56976. * payload: {
  56977. * brushComponents: [
  56978. * {
  56979. * brushId,
  56980. * brushIndex,
  56981. * brushName,
  56982. * series: [
  56983. * {
  56984. * seriesId,
  56985. * seriesIndex,
  56986. * seriesName,
  56987. * rawIndices: [21, 34, ...]
  56988. * },
  56989. * ...
  56990. * ]
  56991. * },
  56992. * ...
  56993. * ]
  56994. * }
  56995. */
  56996. registerAction(
  56997. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  56998. function () {}
  56999. );
  57000. var features = {};
  57001. function register$1(name, ctor) {
  57002. features[name] = ctor;
  57003. }
  57004. function get$1(name) {
  57005. return features[name];
  57006. }
  57007. var brushLang = lang.toolbox.brush;
  57008. function Brush(model, ecModel, api) {
  57009. this.model = model;
  57010. this.ecModel = ecModel;
  57011. this.api = api;
  57012. /**
  57013. * @private
  57014. * @type {string}
  57015. */
  57016. this._brushType;
  57017. /**
  57018. * @private
  57019. * @type {string}
  57020. */
  57021. this._brushMode;
  57022. }
  57023. Brush.defaultOption = {
  57024. show: true,
  57025. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  57026. icon: {
  57027. rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13', // jshint ignore:line
  57028. polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2', // jshint ignore:line
  57029. lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4', // jshint ignore:line
  57030. lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4', // jshint ignore:line
  57031. keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z', // jshint ignore:line
  57032. clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' // jshint ignore:line
  57033. },
  57034. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  57035. title: clone(brushLang.title)
  57036. };
  57037. var proto$3 = Brush.prototype;
  57038. // proto.updateLayout = function (featureModel, ecModel, api) {
  57039. proto$3.render =
  57040. proto$3.updateView = function (featureModel, ecModel, api) {
  57041. var brushType;
  57042. var brushMode;
  57043. var isBrushed;
  57044. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  57045. brushType = brushModel.brushType;
  57046. brushMode = brushModel.brushOption.brushMode || 'single';
  57047. isBrushed |= brushModel.areas.length;
  57048. });
  57049. this._brushType = brushType;
  57050. this._brushMode = brushMode;
  57051. each$1(featureModel.get('type', true), function (type) {
  57052. featureModel.setIconStatus(
  57053. type,
  57054. (
  57055. type === 'keep'
  57056. ? brushMode === 'multiple'
  57057. : type === 'clear'
  57058. ? isBrushed
  57059. : type === brushType
  57060. ) ? 'emphasis' : 'normal'
  57061. );
  57062. });
  57063. };
  57064. proto$3.getIcons = function () {
  57065. var model = this.model;
  57066. var availableIcons = model.get('icon', true);
  57067. var icons = {};
  57068. each$1(model.get('type', true), function (type) {
  57069. if (availableIcons[type]) {
  57070. icons[type] = availableIcons[type];
  57071. }
  57072. });
  57073. return icons;
  57074. };
  57075. proto$3.onclick = function (ecModel, api, type) {
  57076. var brushType = this._brushType;
  57077. var brushMode = this._brushMode;
  57078. if (type === 'clear') {
  57079. // Trigger parallel action firstly
  57080. api.dispatchAction({
  57081. type: 'axisAreaSelect',
  57082. intervals: []
  57083. });
  57084. api.dispatchAction({
  57085. type: 'brush',
  57086. command: 'clear',
  57087. // Clear all areas of all brush components.
  57088. areas: []
  57089. });
  57090. }
  57091. else {
  57092. api.dispatchAction({
  57093. type: 'takeGlobalCursor',
  57094. key: 'brush',
  57095. brushOption: {
  57096. brushType: type === 'keep'
  57097. ? brushType
  57098. : (brushType === type ? false : type),
  57099. brushMode: type === 'keep'
  57100. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  57101. : brushMode
  57102. }
  57103. });
  57104. }
  57105. };
  57106. register$1('brush', Brush);
  57107. /**
  57108. * Brush component entry
  57109. */
  57110. registerPreprocessor(preprocessor$1);
  57111. // (24*60*60*1000)
  57112. var PROXIMATE_ONE_DAY = 86400000;
  57113. /**
  57114. * Calendar
  57115. *
  57116. * @constructor
  57117. *
  57118. * @param {Object} calendarModel calendarModel
  57119. * @param {Object} ecModel ecModel
  57120. * @param {Object} api api
  57121. */
  57122. function Calendar(calendarModel, ecModel, api) {
  57123. this._model = calendarModel;
  57124. }
  57125. Calendar.prototype = {
  57126. constructor: Calendar,
  57127. type: 'calendar',
  57128. dimensions: ['time', 'value'],
  57129. // Required in createListFromData
  57130. getDimensionsInfo: function () {
  57131. return [{name: 'time', type: 'time'}];
  57132. },
  57133. getRangeInfo: function () {
  57134. return this._rangeInfo;
  57135. },
  57136. getModel: function () {
  57137. return this._model;
  57138. },
  57139. getRect: function () {
  57140. return this._rect;
  57141. },
  57142. getCellWidth: function () {
  57143. return this._sw;
  57144. },
  57145. getCellHeight: function () {
  57146. return this._sh;
  57147. },
  57148. getOrient: function () {
  57149. return this._orient;
  57150. },
  57151. /**
  57152. * getFirstDayOfWeek
  57153. *
  57154. * @example
  57155. * 0 : start at Sunday
  57156. * 1 : start at Monday
  57157. *
  57158. * @return {number}
  57159. */
  57160. getFirstDayOfWeek: function () {
  57161. return this._firstDayOfWeek;
  57162. },
  57163. /**
  57164. * get date info
  57165. *
  57166. * @param {string|number} date date
  57167. * @return {Object}
  57168. * {
  57169. * y: string, local full year, eg., '1940',
  57170. * m: string, local month, from '01' ot '12',
  57171. * d: string, local date, from '01' to '31' (if exists),
  57172. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  57173. * time: timestamp,
  57174. * formatedDate: string, yyyy-MM-dd,
  57175. * date: original date object.
  57176. * }
  57177. */
  57178. getDateInfo: function (date) {
  57179. date = parseDate(date);
  57180. var y = date.getFullYear();
  57181. var m = date.getMonth() + 1;
  57182. m = m < 10 ? '0' + m : m;
  57183. var d = date.getDate();
  57184. d = d < 10 ? '0' + d : d;
  57185. var day = date.getDay();
  57186. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  57187. return {
  57188. y: y,
  57189. m: m,
  57190. d: d,
  57191. day: day,
  57192. time: date.getTime(),
  57193. formatedDate: y + '-' + m + '-' + d,
  57194. date: date
  57195. };
  57196. },
  57197. getNextNDay: function (date, n) {
  57198. n = n || 0;
  57199. if (n === 0) {
  57200. return this.getDateInfo(date);
  57201. }
  57202. date = new Date(this.getDateInfo(date).time);
  57203. date.setDate(date.getDate() + n);
  57204. return this.getDateInfo(date);
  57205. },
  57206. update: function (ecModel, api) {
  57207. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  57208. this._orient = this._model.get('orient');
  57209. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  57210. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  57211. var weeks = this._rangeInfo.weeks || 1;
  57212. var whNames = ['width', 'height'];
  57213. var cellSize = this._model.get('cellSize').slice();
  57214. var layoutParams = this._model.getBoxLayoutParams();
  57215. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  57216. each$1([0, 1], function (idx) {
  57217. if (cellSizeSpecified(cellSize, idx)) {
  57218. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  57219. }
  57220. });
  57221. var whGlobal = {
  57222. width: api.getWidth(),
  57223. height: api.getHeight()
  57224. };
  57225. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  57226. each$1([0, 1], function (idx) {
  57227. if (!cellSizeSpecified(cellSize, idx)) {
  57228. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  57229. }
  57230. });
  57231. function cellSizeSpecified(cellSize, idx) {
  57232. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  57233. }
  57234. this._sw = cellSize[0];
  57235. this._sh = cellSize[1];
  57236. },
  57237. /**
  57238. * Convert a time data(time, value) item to (x, y) point.
  57239. *
  57240. * @override
  57241. * @param {Array|number} data data
  57242. * @param {boolean} [clamp=true] out of range
  57243. * @return {Array} point
  57244. */
  57245. dataToPoint: function (data, clamp) {
  57246. isArray(data) && (data = data[0]);
  57247. clamp == null && (clamp = true);
  57248. var dayInfo = this.getDateInfo(data);
  57249. var range = this._rangeInfo;
  57250. var date = dayInfo.formatedDate;
  57251. // if not in range return [NaN, NaN]
  57252. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) {
  57253. return [NaN, NaN];
  57254. }
  57255. var week = dayInfo.day;
  57256. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  57257. if (this._orient === 'vertical') {
  57258. return [
  57259. this._rect.x + week * this._sw + this._sw / 2,
  57260. this._rect.y + nthWeek * this._sh + this._sh / 2
  57261. ];
  57262. }
  57263. return [
  57264. this._rect.x + nthWeek * this._sw + this._sw / 2,
  57265. this._rect.y + week * this._sh + this._sh / 2
  57266. ];
  57267. },
  57268. /**
  57269. * Convert a (x, y) point to time data
  57270. *
  57271. * @override
  57272. * @param {string} point point
  57273. * @return {string} data
  57274. */
  57275. pointToData: function (point) {
  57276. var date = this.pointToDate(point);
  57277. return date && date.time;
  57278. },
  57279. /**
  57280. * Convert a time date item to (x, y) four point.
  57281. *
  57282. * @param {Array} data date[0] is date
  57283. * @param {boolean} [clamp=true] out of range
  57284. * @return {Object} point
  57285. */
  57286. dataToRect: function (data, clamp) {
  57287. var point = this.dataToPoint(data, clamp);
  57288. return {
  57289. contentShape: {
  57290. x: point[0] - (this._sw - this._lineWidth) / 2,
  57291. y: point[1] - (this._sh - this._lineWidth) / 2,
  57292. width: this._sw - this._lineWidth,
  57293. height: this._sh - this._lineWidth
  57294. },
  57295. center: point,
  57296. tl: [
  57297. point[0] - this._sw / 2,
  57298. point[1] - this._sh / 2
  57299. ],
  57300. tr: [
  57301. point[0] + this._sw / 2,
  57302. point[1] - this._sh / 2
  57303. ],
  57304. br: [
  57305. point[0] + this._sw / 2,
  57306. point[1] + this._sh / 2
  57307. ],
  57308. bl: [
  57309. point[0] - this._sw / 2,
  57310. point[1] + this._sh / 2
  57311. ]
  57312. };
  57313. },
  57314. /**
  57315. * Convert a (x, y) point to time date
  57316. *
  57317. * @param {Array} point point
  57318. * @return {Object} date
  57319. */
  57320. pointToDate: function (point) {
  57321. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  57322. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  57323. var range = this._rangeInfo.range;
  57324. if (this._orient === 'vertical') {
  57325. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  57326. }
  57327. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  57328. },
  57329. /**
  57330. * @inheritDoc
  57331. */
  57332. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  57333. /**
  57334. * @inheritDoc
  57335. */
  57336. convertFromPixel: curry(doConvert$2, 'pointToData'),
  57337. /**
  57338. * initRange
  57339. *
  57340. * @private
  57341. * @return {Array} [start, end]
  57342. */
  57343. _initRangeOption: function () {
  57344. var range = this._model.get('range');
  57345. var rg = range;
  57346. if (isArray(rg) && rg.length === 1) {
  57347. rg = rg[0];
  57348. }
  57349. if (/^\d{4}$/.test(rg)) {
  57350. range = [rg + '-01-01', rg + '-12-31'];
  57351. }
  57352. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  57353. var start = this.getDateInfo(rg);
  57354. var firstDay = start.date;
  57355. firstDay.setMonth(firstDay.getMonth() + 1);
  57356. var end = this.getNextNDay(firstDay, -1);
  57357. range = [start.formatedDate, end.formatedDate];
  57358. }
  57359. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  57360. range = [rg, rg];
  57361. }
  57362. var tmp = this._getRangeInfo(range);
  57363. if (tmp.start.time > tmp.end.time) {
  57364. range.reverse();
  57365. }
  57366. return range;
  57367. },
  57368. /**
  57369. * range info
  57370. *
  57371. * @private
  57372. * @param {Array} range range ['2017-01-01', '2017-07-08']
  57373. * If range[0] > range[1], they will not be reversed.
  57374. * @return {Object} obj
  57375. */
  57376. _getRangeInfo: function (range) {
  57377. range = [
  57378. this.getDateInfo(range[0]),
  57379. this.getDateInfo(range[1])
  57380. ];
  57381. var reversed;
  57382. if (range[0].time > range[1].time) {
  57383. reversed = true;
  57384. range.reverse();
  57385. }
  57386. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  57387. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  57388. // Consider case:
  57389. // Firstly set system timezone as "Time Zone: America/Toronto",
  57390. // ```
  57391. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  57392. // var second = new Date(1478412000000);
  57393. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  57394. // ```
  57395. // will get wrong result because of DST. So we should fix it.
  57396. var date = new Date(range[0].time);
  57397. var startDateNum = date.getDate();
  57398. var endDateNum = range[1].date.getDate();
  57399. date.setDate(startDateNum + allDay - 1);
  57400. // The bias can not over a month, so just compare date.
  57401. if (date.getDate() !== endDateNum) {
  57402. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  57403. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  57404. allDay -= sign;
  57405. date.setDate(startDateNum + allDay - 1);
  57406. }
  57407. }
  57408. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  57409. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  57410. reversed && range.reverse();
  57411. return {
  57412. range: [range[0].formatedDate, range[1].formatedDate],
  57413. start: range[0],
  57414. end: range[1],
  57415. allDay: allDay,
  57416. weeks: weeks,
  57417. // From 0.
  57418. nthWeek: nthWeek,
  57419. fweek: range[0].day,
  57420. lweek: range[1].day
  57421. };
  57422. },
  57423. /**
  57424. * get date by nthWeeks and week day in range
  57425. *
  57426. * @private
  57427. * @param {number} nthWeek the week
  57428. * @param {number} day the week day
  57429. * @param {Array} range [d1, d2]
  57430. * @return {Object}
  57431. */
  57432. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  57433. var rangeInfo = this._getRangeInfo(range);
  57434. if (nthWeek > rangeInfo.weeks
  57435. || (nthWeek === 0 && day < rangeInfo.fweek)
  57436. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  57437. ) {
  57438. return false;
  57439. }
  57440. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  57441. var date = new Date(rangeInfo.start.time);
  57442. date.setDate(rangeInfo.start.d + nthDay);
  57443. return this.getDateInfo(date);
  57444. }
  57445. };
  57446. Calendar.dimensions = Calendar.prototype.dimensions;
  57447. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  57448. Calendar.create = function (ecModel, api) {
  57449. var calendarList = [];
  57450. ecModel.eachComponent('calendar', function (calendarModel) {
  57451. var calendar = new Calendar(calendarModel, ecModel, api);
  57452. calendarList.push(calendar);
  57453. calendarModel.coordinateSystem = calendar;
  57454. });
  57455. ecModel.eachSeries(function (calendarSeries) {
  57456. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  57457. // Inject coordinate system
  57458. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  57459. }
  57460. });
  57461. return calendarList;
  57462. };
  57463. function doConvert$2(methodName, ecModel, finder, value) {
  57464. var calendarModel = finder.calendarModel;
  57465. var seriesModel = finder.seriesModel;
  57466. var coordSys = calendarModel
  57467. ? calendarModel.coordinateSystem
  57468. : seriesModel
  57469. ? seriesModel.coordinateSystem
  57470. : null;
  57471. return coordSys === this ? coordSys[methodName](value) : null;
  57472. }
  57473. CoordinateSystemManager.register('calendar', Calendar);
  57474. var CalendarModel = ComponentModel.extend({
  57475. type: 'calendar',
  57476. /**
  57477. * @type {module:echarts/coord/calendar/Calendar}
  57478. */
  57479. coordinateSystem: null,
  57480. defaultOption: {
  57481. zlevel: 0,
  57482. z: 2,
  57483. left: 80,
  57484. top: 60,
  57485. cellSize: 20,
  57486. // horizontal vertical
  57487. orient: 'horizontal',
  57488. // month separate line style
  57489. splitLine: {
  57490. show: true,
  57491. lineStyle: {
  57492. color: '#000',
  57493. width: 1,
  57494. type: 'solid'
  57495. }
  57496. },
  57497. // rect style temporarily unused emphasis
  57498. itemStyle: {
  57499. color: '#fff',
  57500. borderWidth: 1,
  57501. borderColor: '#ccc'
  57502. },
  57503. // week text style
  57504. dayLabel: {
  57505. show: true,
  57506. // a week first day
  57507. firstDay: 0,
  57508. // start end
  57509. position: 'start',
  57510. margin: '50%', // 50% of cellSize
  57511. nameMap: 'en',
  57512. color: '#000'
  57513. },
  57514. // month text style
  57515. monthLabel: {
  57516. show: true,
  57517. // start end
  57518. position: 'start',
  57519. margin: 5,
  57520. // center or left
  57521. align: 'center',
  57522. // cn en []
  57523. nameMap: 'en',
  57524. formatter: null,
  57525. color: '#000'
  57526. },
  57527. // year text style
  57528. yearLabel: {
  57529. show: true,
  57530. // top bottom left right
  57531. position: null,
  57532. margin: 30,
  57533. formatter: null,
  57534. color: '#ccc',
  57535. fontFamily: 'sans-serif',
  57536. fontWeight: 'bolder',
  57537. fontSize: 20
  57538. }
  57539. },
  57540. /**
  57541. * @override
  57542. */
  57543. init: function (option, parentModel, ecModel, extraOpt) {
  57544. var inputPositionParams = getLayoutParams(option);
  57545. CalendarModel.superApply(this, 'init', arguments);
  57546. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  57547. },
  57548. /**
  57549. * @override
  57550. */
  57551. mergeOption: function (option, extraOpt) {
  57552. CalendarModel.superApply(this, 'mergeOption', arguments);
  57553. mergeAndNormalizeLayoutParams$1(this.option, option);
  57554. }
  57555. });
  57556. function mergeAndNormalizeLayoutParams$1(target, raw) {
  57557. // Normalize cellSize
  57558. var cellSize = target.cellSize;
  57559. if (!isArray(cellSize)) {
  57560. cellSize = target.cellSize = [cellSize, cellSize];
  57561. }
  57562. else if (cellSize.length === 1) {
  57563. cellSize[1] = cellSize[0];
  57564. }
  57565. var ignoreSize = map([0, 1], function (hvIdx) {
  57566. // If user have set `width` or both `left` and `right`, cellSize
  57567. // will be automatically set to 'auto', otherwise the default
  57568. // setting of cellSize will make `width` setting not work.
  57569. if (sizeCalculable(raw, hvIdx)) {
  57570. cellSize[hvIdx] = 'auto';
  57571. }
  57572. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  57573. });
  57574. mergeLayoutParam(target, raw, {
  57575. type: 'box', ignoreSize: ignoreSize
  57576. });
  57577. }
  57578. var MONTH_TEXT = {
  57579. EN: [
  57580. 'Jan', 'Feb', 'Mar',
  57581. 'Apr', 'May', 'Jun',
  57582. 'Jul', 'Aug', 'Sep',
  57583. 'Oct', 'Nov', 'Dec'
  57584. ],
  57585. CN: [
  57586. '一月', '二月', '三月',
  57587. '四月', '五月', '六月',
  57588. '七月', '八月', '九月',
  57589. '十月', '十一月', '十二月'
  57590. ]
  57591. };
  57592. var WEEK_TEXT = {
  57593. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  57594. CN: ['日', '一', '二', '三', '四', '五', '六']
  57595. };
  57596. extendComponentView({
  57597. type: 'calendar',
  57598. /**
  57599. * top/left line points
  57600. * @private
  57601. */
  57602. _tlpoints: null,
  57603. /**
  57604. * bottom/right line points
  57605. * @private
  57606. */
  57607. _blpoints: null,
  57608. /**
  57609. * first day of month
  57610. * @private
  57611. */
  57612. _firstDayOfMonth: null,
  57613. /**
  57614. * first day point of month
  57615. * @private
  57616. */
  57617. _firstDayPoints: null,
  57618. render: function (calendarModel, ecModel, api) {
  57619. var group = this.group;
  57620. group.removeAll();
  57621. var coordSys = calendarModel.coordinateSystem;
  57622. // range info
  57623. var rangeData = coordSys.getRangeInfo();
  57624. var orient = coordSys.getOrient();
  57625. this._renderDayRect(calendarModel, rangeData, group);
  57626. // _renderLines must be called prior to following function
  57627. this._renderLines(calendarModel, rangeData, orient, group);
  57628. this._renderYearText(calendarModel, rangeData, orient, group);
  57629. this._renderMonthText(calendarModel, orient, group);
  57630. this._renderWeekText(calendarModel, rangeData, orient, group);
  57631. },
  57632. // render day rect
  57633. _renderDayRect: function (calendarModel, rangeData, group) {
  57634. var coordSys = calendarModel.coordinateSystem;
  57635. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  57636. var sw = coordSys.getCellWidth();
  57637. var sh = coordSys.getCellHeight();
  57638. for (var i = rangeData.start.time;
  57639. i <= rangeData.end.time;
  57640. i = coordSys.getNextNDay(i, 1).time
  57641. ) {
  57642. var point = coordSys.dataToRect([i], false).tl;
  57643. // every rect
  57644. var rect = new Rect({
  57645. shape: {
  57646. x: point[0],
  57647. y: point[1],
  57648. width: sw,
  57649. height: sh
  57650. },
  57651. cursor: 'default',
  57652. style: itemRectStyleModel
  57653. });
  57654. group.add(rect);
  57655. }
  57656. },
  57657. // render separate line
  57658. _renderLines: function (calendarModel, rangeData, orient, group) {
  57659. var self = this;
  57660. var coordSys = calendarModel.coordinateSystem;
  57661. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  57662. var show = calendarModel.get('splitLine.show');
  57663. var lineWidth = lineStyleModel.lineWidth;
  57664. this._tlpoints = [];
  57665. this._blpoints = [];
  57666. this._firstDayOfMonth = [];
  57667. this._firstDayPoints = [];
  57668. var firstDay = rangeData.start;
  57669. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  57670. addPoints(firstDay.formatedDate);
  57671. if (i === 0) {
  57672. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  57673. }
  57674. var date = firstDay.date;
  57675. date.setMonth(date.getMonth() + 1);
  57676. firstDay = coordSys.getDateInfo(date);
  57677. }
  57678. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  57679. function addPoints(date) {
  57680. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  57681. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  57682. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  57683. self._tlpoints.push(points[0]);
  57684. self._blpoints.push(points[points.length - 1]);
  57685. show && self._drawSplitline(points, lineStyleModel, group);
  57686. }
  57687. // render top/left line
  57688. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  57689. // render bottom/right line
  57690. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  57691. },
  57692. // get points at both ends
  57693. _getEdgesPoints: function (points, lineWidth, orient) {
  57694. var rs = [points[0].slice(), points[points.length - 1].slice()];
  57695. var idx = orient === 'horizontal' ? 0 : 1;
  57696. // both ends of the line are extend half lineWidth
  57697. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  57698. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  57699. return rs;
  57700. },
  57701. // render split line
  57702. _drawSplitline: function (points, lineStyleModel, group) {
  57703. var poyline = new Polyline({
  57704. z2: 20,
  57705. shape: {
  57706. points: points
  57707. },
  57708. style: lineStyleModel
  57709. });
  57710. group.add(poyline);
  57711. },
  57712. // render month line of one week points
  57713. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  57714. var coordSys = calendarModel.coordinateSystem;
  57715. date = coordSys.getDateInfo(date);
  57716. var points = [];
  57717. for (var i = 0; i < 7; i++) {
  57718. var tmpD = coordSys.getNextNDay(date.time, i);
  57719. var point = coordSys.dataToRect([tmpD.time], false);
  57720. points[2 * tmpD.day] = point.tl;
  57721. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  57722. }
  57723. return points;
  57724. },
  57725. _formatterLabel: function (formatter, params) {
  57726. if (typeof formatter === 'string' && formatter) {
  57727. return formatTplSimple(formatter, params);
  57728. }
  57729. if (typeof formatter === 'function') {
  57730. return formatter(params);
  57731. }
  57732. return params.nameMap;
  57733. },
  57734. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  57735. point = point.slice();
  57736. var aligns = ['center', 'bottom'];
  57737. if (position === 'bottom') {
  57738. point[1] += margin;
  57739. aligns = ['center', 'top'];
  57740. }
  57741. else if (position === 'left') {
  57742. point[0] -= margin;
  57743. }
  57744. else if (position === 'right') {
  57745. point[0] += margin;
  57746. aligns = ['center', 'top'];
  57747. }
  57748. else { // top
  57749. point[1] -= margin;
  57750. }
  57751. var rotate = 0;
  57752. if (position === 'left' || position === 'right') {
  57753. rotate = Math.PI / 2;
  57754. }
  57755. return {
  57756. rotation: rotate,
  57757. position: point,
  57758. style: {
  57759. textAlign: aligns[0],
  57760. textVerticalAlign: aligns[1]
  57761. }
  57762. };
  57763. },
  57764. // render year
  57765. _renderYearText: function (calendarModel, rangeData, orient, group) {
  57766. var yearLabel = calendarModel.getModel('yearLabel');
  57767. if (!yearLabel.get('show')) {
  57768. return;
  57769. }
  57770. var margin = yearLabel.get('margin');
  57771. var pos = yearLabel.get('position');
  57772. if (!pos) {
  57773. pos = orient !== 'horizontal' ? 'top' : 'left';
  57774. }
  57775. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  57776. var xc = (points[0][0] + points[1][0]) / 2;
  57777. var yc = (points[0][1] + points[1][1]) / 2;
  57778. var idx = orient === 'horizontal' ? 0 : 1;
  57779. var posPoints = {
  57780. top: [xc, points[idx][1]],
  57781. bottom: [xc, points[1 - idx][1]],
  57782. left: [points[1 - idx][0], yc],
  57783. right: [points[idx][0], yc]
  57784. };
  57785. var name = rangeData.start.y;
  57786. if (+rangeData.end.y > +rangeData.start.y) {
  57787. name = name + '-' + rangeData.end.y;
  57788. }
  57789. var formatter = yearLabel.get('formatter');
  57790. var params = {
  57791. start: rangeData.start.y,
  57792. end: rangeData.end.y,
  57793. nameMap: name
  57794. };
  57795. var content = this._formatterLabel(formatter, params);
  57796. var yearText = new Text({z2: 30});
  57797. setTextStyle(yearText.style, yearLabel, {text: content}),
  57798. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  57799. group.add(yearText);
  57800. },
  57801. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  57802. var align = 'left';
  57803. var vAlign = 'top';
  57804. var x = point[0];
  57805. var y = point[1];
  57806. if (orient === 'horizontal') {
  57807. y = y + margin;
  57808. if (isCenter) {
  57809. align = 'center';
  57810. }
  57811. if (position === 'start') {
  57812. vAlign = 'bottom';
  57813. }
  57814. }
  57815. else {
  57816. x = x + margin;
  57817. if (isCenter) {
  57818. vAlign = 'middle';
  57819. }
  57820. if (position === 'start') {
  57821. align = 'right';
  57822. }
  57823. }
  57824. return {
  57825. x: x,
  57826. y: y,
  57827. textAlign: align,
  57828. textVerticalAlign: vAlign
  57829. };
  57830. },
  57831. // render month and year text
  57832. _renderMonthText: function (calendarModel, orient, group) {
  57833. var monthLabel = calendarModel.getModel('monthLabel');
  57834. if (!monthLabel.get('show')) {
  57835. return;
  57836. }
  57837. var nameMap = monthLabel.get('nameMap');
  57838. var margin = monthLabel.get('margin');
  57839. var pos = monthLabel.get('position');
  57840. var align = monthLabel.get('align');
  57841. var termPoints = [this._tlpoints, this._blpoints];
  57842. if (isString(nameMap)) {
  57843. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  57844. }
  57845. var idx = pos === 'start' ? 0 : 1;
  57846. var axis = orient === 'horizontal' ? 0 : 1;
  57847. margin = pos === 'start' ? -margin : margin;
  57848. var isCenter = (align === 'center');
  57849. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  57850. var tmp = termPoints[idx][i].slice();
  57851. var firstDay = this._firstDayOfMonth[i];
  57852. if (isCenter) {
  57853. var firstDayPoints = this._firstDayPoints[i];
  57854. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  57855. }
  57856. var formatter = monthLabel.get('formatter');
  57857. var name = nameMap[+firstDay.m - 1];
  57858. var params = {
  57859. yyyy: firstDay.y,
  57860. yy: (firstDay.y + '').slice(2),
  57861. MM: firstDay.m,
  57862. M: +firstDay.m,
  57863. nameMap: name
  57864. };
  57865. var content = this._formatterLabel(formatter, params);
  57866. var monthText = new Text({z2: 30});
  57867. extend(
  57868. setTextStyle(monthText.style, monthLabel, {text: content}),
  57869. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  57870. );
  57871. group.add(monthText);
  57872. }
  57873. },
  57874. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  57875. var align = 'center';
  57876. var vAlign = 'middle';
  57877. var x = point[0];
  57878. var y = point[1];
  57879. var isStart = position === 'start';
  57880. if (orient === 'horizontal') {
  57881. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  57882. align = isStart ? 'right' : 'left';
  57883. }
  57884. else {
  57885. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  57886. vAlign = isStart ? 'bottom' : 'top';
  57887. }
  57888. return {
  57889. x: x,
  57890. y: y,
  57891. textAlign: align,
  57892. textVerticalAlign: vAlign
  57893. };
  57894. },
  57895. // render weeks
  57896. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  57897. var dayLabel = calendarModel.getModel('dayLabel');
  57898. if (!dayLabel.get('show')) {
  57899. return;
  57900. }
  57901. var coordSys = calendarModel.coordinateSystem;
  57902. var pos = dayLabel.get('position');
  57903. var nameMap = dayLabel.get('nameMap');
  57904. var margin = dayLabel.get('margin');
  57905. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  57906. if (isString(nameMap)) {
  57907. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  57908. }
  57909. var start = coordSys.getNextNDay(
  57910. rangeData.end.time, (7 - rangeData.lweek)
  57911. ).time;
  57912. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  57913. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  57914. if (pos === 'start') {
  57915. start = coordSys.getNextNDay(
  57916. rangeData.start.time, -(7 + rangeData.fweek)
  57917. ).time;
  57918. margin = -margin;
  57919. }
  57920. for (var i = 0; i < 7; i++) {
  57921. var tmpD = coordSys.getNextNDay(start, i);
  57922. var point = coordSys.dataToRect([tmpD.time], false).center;
  57923. var day = i;
  57924. day = Math.abs((i + firstDayOfWeek) % 7);
  57925. var weekText = new Text({z2: 30});
  57926. extend(
  57927. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  57928. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  57929. );
  57930. group.add(weekText);
  57931. }
  57932. }
  57933. });
  57934. /**
  57935. * @file calendar.js
  57936. * @author dxh
  57937. */
  57938. // Model
  57939. extendComponentModel({
  57940. type: 'title',
  57941. layoutMode: {type: 'box', ignoreSize: true},
  57942. defaultOption: {
  57943. // 一级层叠
  57944. zlevel: 0,
  57945. // 二级层叠
  57946. z: 6,
  57947. show: true,
  57948. text: '',
  57949. // 超链接跳转
  57950. // link: null,
  57951. // 仅支持self | blank
  57952. target: 'blank',
  57953. subtext: '',
  57954. // 超链接跳转
  57955. // sublink: null,
  57956. // 仅支持self | blank
  57957. subtarget: 'blank',
  57958. // 'center' ¦ 'left' ¦ 'right'
  57959. // ¦ {number}(x坐标,单位px)
  57960. left: 0,
  57961. // 'top' ¦ 'bottom' ¦ 'center'
  57962. // ¦ {number}(y坐标,单位px)
  57963. top: 0,
  57964. // 水平对齐
  57965. // 'auto' | 'left' | 'right' | 'center'
  57966. // 默认根据 left 的位置判断是左对齐还是右对齐
  57967. // textAlign: null
  57968. //
  57969. // 垂直对齐
  57970. // 'auto' | 'top' | 'bottom' | 'middle'
  57971. // 默认根据 top 位置判断是上对齐还是下对齐
  57972. // textBaseline: null
  57973. backgroundColor: 'rgba(0,0,0,0)',
  57974. // 标题边框颜色
  57975. borderColor: '#ccc',
  57976. // 标题边框线宽,单位px,默认为0(无边框)
  57977. borderWidth: 0,
  57978. // 标题内边距,单位px,默认各方向内边距为5,
  57979. // 接受数组分别设定上右下左边距,同css
  57980. padding: 5,
  57981. // 主副标题纵向间隔,单位px,默认为10,
  57982. itemGap: 10,
  57983. textStyle: {
  57984. fontSize: 18,
  57985. fontWeight: 'bolder',
  57986. color: '#333'
  57987. },
  57988. subtextStyle: {
  57989. color: '#aaa'
  57990. }
  57991. }
  57992. });
  57993. // View
  57994. extendComponentView({
  57995. type: 'title',
  57996. render: function (titleModel, ecModel, api) {
  57997. this.group.removeAll();
  57998. if (!titleModel.get('show')) {
  57999. return;
  58000. }
  58001. var group = this.group;
  58002. var textStyleModel = titleModel.getModel('textStyle');
  58003. var subtextStyleModel = titleModel.getModel('subtextStyle');
  58004. var textAlign = titleModel.get('textAlign');
  58005. var textBaseline = titleModel.get('textBaseline');
  58006. var textEl = new Text({
  58007. style: setTextStyle({}, textStyleModel, {
  58008. text: titleModel.get('text'),
  58009. textFill: textStyleModel.getTextColor()
  58010. }, {disableBox: true}),
  58011. z2: 10
  58012. });
  58013. var textRect = textEl.getBoundingRect();
  58014. var subText = titleModel.get('subtext');
  58015. var subTextEl = new Text({
  58016. style: setTextStyle({}, subtextStyleModel, {
  58017. text: subText,
  58018. textFill: subtextStyleModel.getTextColor(),
  58019. y: textRect.height + titleModel.get('itemGap'),
  58020. textVerticalAlign: 'top'
  58021. }, {disableBox: true}),
  58022. z2: 10
  58023. });
  58024. var link = titleModel.get('link');
  58025. var sublink = titleModel.get('sublink');
  58026. textEl.silent = !link;
  58027. subTextEl.silent = !sublink;
  58028. if (link) {
  58029. textEl.on('click', function () {
  58030. window.open(link, '_' + titleModel.get('target'));
  58031. });
  58032. }
  58033. if (sublink) {
  58034. subTextEl.on('click', function () {
  58035. window.open(sublink, '_' + titleModel.get('subtarget'));
  58036. });
  58037. }
  58038. group.add(textEl);
  58039. subText && group.add(subTextEl);
  58040. // If no subText, but add subTextEl, there will be an empty line.
  58041. var groupRect = group.getBoundingRect();
  58042. var layoutOption = titleModel.getBoxLayoutParams();
  58043. layoutOption.width = groupRect.width;
  58044. layoutOption.height = groupRect.height;
  58045. var layoutRect = getLayoutRect(
  58046. layoutOption, {
  58047. width: api.getWidth(),
  58048. height: api.getHeight()
  58049. }, titleModel.get('padding')
  58050. );
  58051. // Adjust text align based on position
  58052. if (!textAlign) {
  58053. // Align left if title is on the left. center and right is same
  58054. textAlign = titleModel.get('left') || titleModel.get('right');
  58055. if (textAlign === 'middle') {
  58056. textAlign = 'center';
  58057. }
  58058. // Adjust layout by text align
  58059. if (textAlign === 'right') {
  58060. layoutRect.x += layoutRect.width;
  58061. }
  58062. else if (textAlign === 'center') {
  58063. layoutRect.x += layoutRect.width / 2;
  58064. }
  58065. }
  58066. if (!textBaseline) {
  58067. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  58068. if (textBaseline === 'center') {
  58069. textBaseline = 'middle';
  58070. }
  58071. if (textBaseline === 'bottom') {
  58072. layoutRect.y += layoutRect.height;
  58073. }
  58074. else if (textBaseline === 'middle') {
  58075. layoutRect.y += layoutRect.height / 2;
  58076. }
  58077. textBaseline = textBaseline || 'top';
  58078. }
  58079. group.attr('position', [layoutRect.x, layoutRect.y]);
  58080. var alignStyle = {
  58081. textAlign: textAlign,
  58082. textVerticalAlign: textBaseline
  58083. };
  58084. textEl.setStyle(alignStyle);
  58085. subTextEl.setStyle(alignStyle);
  58086. // Render background
  58087. // Get groupRect again because textAlign has been changed
  58088. groupRect = group.getBoundingRect();
  58089. var padding = layoutRect.margin;
  58090. var style = titleModel.getItemStyle(['color', 'opacity']);
  58091. style.fill = titleModel.get('backgroundColor');
  58092. var rect = new Rect({
  58093. shape: {
  58094. x: groupRect.x - padding[3],
  58095. y: groupRect.y - padding[0],
  58096. width: groupRect.width + padding[1] + padding[3],
  58097. height: groupRect.height + padding[0] + padding[2],
  58098. r: titleModel.get('borderRadius')
  58099. },
  58100. style: style,
  58101. silent: true
  58102. });
  58103. subPixelOptimizeRect(rect);
  58104. group.add(rect);
  58105. }
  58106. });
  58107. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  58108. // Default 'slider' when no type specified.
  58109. return 'slider';
  58110. });
  58111. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  58112. // Supported coords.
  58113. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  58114. /**
  58115. * @param {string} coordType
  58116. * @return {boolean}
  58117. */
  58118. function isCoordSupported(coordType) {
  58119. return indexOf(COORDS, coordType) >= 0;
  58120. }
  58121. /**
  58122. * Create "each" method to iterate names.
  58123. *
  58124. * @pubilc
  58125. * @param {Array.<string>} names
  58126. * @param {Array.<string>=} attrs
  58127. * @return {Function}
  58128. */
  58129. function createNameEach(names, attrs) {
  58130. names = names.slice();
  58131. var capitalNames = map(names, capitalFirst);
  58132. attrs = (attrs || []).slice();
  58133. var capitalAttrs = map(attrs, capitalFirst);
  58134. return function (callback, context) {
  58135. each$1(names, function (name, index) {
  58136. var nameObj = {name: name, capital: capitalNames[index]};
  58137. for (var j = 0; j < attrs.length; j++) {
  58138. nameObj[attrs[j]] = name + capitalAttrs[j];
  58139. }
  58140. callback.call(context, nameObj);
  58141. });
  58142. };
  58143. }
  58144. /**
  58145. * Iterate each dimension name.
  58146. *
  58147. * @public
  58148. * @param {Function} callback The parameter is like:
  58149. * {
  58150. * name: 'angle',
  58151. * capital: 'Angle',
  58152. * axis: 'angleAxis',
  58153. * axisIndex: 'angleAixs',
  58154. * index: 'angleIndex'
  58155. * }
  58156. * @param {Object} context
  58157. */
  58158. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  58159. /**
  58160. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  58161. * dataZoomModels and 'links' make up one or more graphics.
  58162. * This function finds the graphic where the source dataZoomModel is in.
  58163. *
  58164. * @public
  58165. * @param {Function} forEachNode Node iterator.
  58166. * @param {Function} forEachEdgeType edgeType iterator
  58167. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  58168. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  58169. */
  58170. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  58171. return function (sourceNode) {
  58172. var result = {
  58173. nodes: [],
  58174. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  58175. };
  58176. forEachEdgeType(function (edgeType) {
  58177. result.records[edgeType.name] = {};
  58178. });
  58179. if (!sourceNode) {
  58180. return result;
  58181. }
  58182. absorb(sourceNode, result);
  58183. var existsLink;
  58184. do {
  58185. existsLink = false;
  58186. forEachNode(processSingleNode);
  58187. }
  58188. while (existsLink);
  58189. function processSingleNode(node) {
  58190. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  58191. absorb(node, result);
  58192. existsLink = true;
  58193. }
  58194. }
  58195. return result;
  58196. };
  58197. function isNodeAbsorded(node, result) {
  58198. return indexOf(result.nodes, node) >= 0;
  58199. }
  58200. function isLinked(node, result) {
  58201. var hasLink = false;
  58202. forEachEdgeType(function (edgeType) {
  58203. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  58204. result.records[edgeType.name][edgeId] && (hasLink = true);
  58205. });
  58206. });
  58207. return hasLink;
  58208. }
  58209. function absorb(node, result) {
  58210. result.nodes.push(node);
  58211. forEachEdgeType(function (edgeType) {
  58212. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  58213. result.records[edgeType.name][edgeId] = true;
  58214. });
  58215. });
  58216. }
  58217. }
  58218. var each$23 = each$1;
  58219. var asc$1 = asc;
  58220. /**
  58221. * Operate single axis.
  58222. * One axis can only operated by one axis operator.
  58223. * Different dataZoomModels may be defined to operate the same axis.
  58224. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  58225. * So dataZoomModels share one axisProxy in that case.
  58226. *
  58227. * @class
  58228. */
  58229. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  58230. /**
  58231. * @private
  58232. * @type {string}
  58233. */
  58234. this._dimName = dimName;
  58235. /**
  58236. * @private
  58237. */
  58238. this._axisIndex = axisIndex;
  58239. /**
  58240. * @private
  58241. * @type {Array.<number>}
  58242. */
  58243. this._valueWindow;
  58244. /**
  58245. * @private
  58246. * @type {Array.<number>}
  58247. */
  58248. this._percentWindow;
  58249. /**
  58250. * @private
  58251. * @type {Array.<number>}
  58252. */
  58253. this._dataExtent;
  58254. /**
  58255. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  58256. * @private
  58257. * @type {Object}
  58258. */
  58259. this._minMaxSpan;
  58260. /**
  58261. * @readOnly
  58262. * @type {module: echarts/model/Global}
  58263. */
  58264. this.ecModel = ecModel;
  58265. /**
  58266. * @private
  58267. * @type {module: echarts/component/dataZoom/DataZoomModel}
  58268. */
  58269. this._dataZoomModel = dataZoomModel;
  58270. /**
  58271. * @readOnly
  58272. * @private
  58273. */
  58274. this.hasSeriesStacked;
  58275. };
  58276. AxisProxy.prototype = {
  58277. constructor: AxisProxy,
  58278. /**
  58279. * Whether the axisProxy is hosted by dataZoomModel.
  58280. *
  58281. * @public
  58282. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  58283. * @return {boolean}
  58284. */
  58285. hostedBy: function (dataZoomModel) {
  58286. return this._dataZoomModel === dataZoomModel;
  58287. },
  58288. /**
  58289. * @return {Array.<number>} Value can only be NaN or finite value.
  58290. */
  58291. getDataValueWindow: function () {
  58292. return this._valueWindow.slice();
  58293. },
  58294. /**
  58295. * @return {Array.<number>}
  58296. */
  58297. getDataPercentWindow: function () {
  58298. return this._percentWindow.slice();
  58299. },
  58300. /**
  58301. * @public
  58302. * @param {number} axisIndex
  58303. * @return {Array} seriesModels
  58304. */
  58305. getTargetSeriesModels: function () {
  58306. var seriesModels = [];
  58307. var ecModel = this.ecModel;
  58308. ecModel.eachSeries(function (seriesModel) {
  58309. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  58310. var dimName = this._dimName;
  58311. var axisModel = ecModel.queryComponents({
  58312. mainType: dimName + 'Axis',
  58313. index: seriesModel.get(dimName + 'AxisIndex'),
  58314. id: seriesModel.get(dimName + 'AxisId')
  58315. })[0];
  58316. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  58317. seriesModels.push(seriesModel);
  58318. }
  58319. }
  58320. }, this);
  58321. return seriesModels;
  58322. },
  58323. getAxisModel: function () {
  58324. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  58325. },
  58326. getOtherAxisModel: function () {
  58327. var axisDim = this._dimName;
  58328. var ecModel = this.ecModel;
  58329. var axisModel = this.getAxisModel();
  58330. var isCartesian = axisDim === 'x' || axisDim === 'y';
  58331. var otherAxisDim;
  58332. var coordSysIndexName;
  58333. if (isCartesian) {
  58334. coordSysIndexName = 'gridIndex';
  58335. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  58336. }
  58337. else {
  58338. coordSysIndexName = 'polarIndex';
  58339. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  58340. }
  58341. var foundOtherAxisModel;
  58342. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  58343. if ((otherAxisModel.get(coordSysIndexName) || 0)
  58344. === (axisModel.get(coordSysIndexName) || 0)
  58345. ) {
  58346. foundOtherAxisModel = otherAxisModel;
  58347. }
  58348. });
  58349. return foundOtherAxisModel;
  58350. },
  58351. getMinMaxSpan: function () {
  58352. return clone(this._minMaxSpan);
  58353. },
  58354. /**
  58355. * Only calculate by given range and this._dataExtent, do not change anything.
  58356. *
  58357. * @param {Object} opt
  58358. * @param {number} [opt.start]
  58359. * @param {number} [opt.end]
  58360. * @param {number} [opt.startValue]
  58361. * @param {number} [opt.endValue]
  58362. */
  58363. calculateDataWindow: function (opt) {
  58364. var dataExtent = this._dataExtent;
  58365. var axisModel = this.getAxisModel();
  58366. var scale = axisModel.axis.scale;
  58367. var rangePropMode = this._dataZoomModel.getRangePropMode();
  58368. var percentExtent = [0, 100];
  58369. var percentWindow = [
  58370. opt.start,
  58371. opt.end
  58372. ];
  58373. var valueWindow = [];
  58374. each$23(['startValue', 'endValue'], function (prop) {
  58375. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  58376. });
  58377. // Normalize bound.
  58378. each$23([0, 1], function (idx) {
  58379. var boundValue = valueWindow[idx];
  58380. var boundPercent = percentWindow[idx];
  58381. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  58382. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  58383. // for cases that a dataZoom component controls multiple axes with different
  58384. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  58385. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  58386. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  58387. // accurately (because all of values that are overflow the `dataExtent` will
  58388. // be calculated to percent '100%'). So we have to use
  58389. // `dataZoom.getRangePropMode()` to mark which prop is used.
  58390. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  58391. // it remains its original value.
  58392. if (rangePropMode[idx] === 'percent') {
  58393. if (boundPercent == null) {
  58394. boundPercent = percentExtent[idx];
  58395. }
  58396. // Use scale.parse to math round for category or time axis.
  58397. boundValue = scale.parse(linearMap(
  58398. boundPercent, percentExtent, dataExtent, true
  58399. ));
  58400. }
  58401. else {
  58402. // Calculating `percent` from `value` may be not accurate, because
  58403. // This calculation can not be inversed, because all of values that
  58404. // are overflow the `dataExtent` will be calculated to percent '100%'
  58405. boundPercent = linearMap(
  58406. boundValue, dataExtent, percentExtent, true
  58407. );
  58408. }
  58409. // valueWindow[idx] = round(boundValue);
  58410. // percentWindow[idx] = round(boundPercent);
  58411. valueWindow[idx] = boundValue;
  58412. percentWindow[idx] = boundPercent;
  58413. });
  58414. return {
  58415. valueWindow: asc$1(valueWindow),
  58416. percentWindow: asc$1(percentWindow)
  58417. };
  58418. },
  58419. /**
  58420. * Notice: reset should not be called before series.restoreData() called,
  58421. * so it is recommanded to be called in "process stage" but not "model init
  58422. * stage".
  58423. *
  58424. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  58425. */
  58426. reset: function (dataZoomModel) {
  58427. if (dataZoomModel !== this._dataZoomModel) {
  58428. return;
  58429. }
  58430. var targetSeries = this.getTargetSeriesModels();
  58431. // Culculate data window and data extent, and record them.
  58432. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  58433. this.hasSeriesStacked = false;
  58434. each$23(targetSeries, function (series) {
  58435. var data = series.getData();
  58436. var dataDim = data.mapDimension(this._dimName);
  58437. if (data.isStacked(dataDim)) {
  58438. this.hasSeriesStacked = true;
  58439. }
  58440. }, this);
  58441. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  58442. this._valueWindow = dataWindow.valueWindow;
  58443. this._percentWindow = dataWindow.percentWindow;
  58444. setMinMaxSpan(this);
  58445. // Update axis setting then.
  58446. setAxisModel(this);
  58447. },
  58448. /**
  58449. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  58450. */
  58451. restore: function (dataZoomModel) {
  58452. if (dataZoomModel !== this._dataZoomModel) {
  58453. return;
  58454. }
  58455. this._valueWindow = this._percentWindow = null;
  58456. setAxisModel(this, true);
  58457. },
  58458. /**
  58459. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  58460. */
  58461. filterData: function (dataZoomModel, api) {
  58462. if (dataZoomModel !== this._dataZoomModel) {
  58463. return;
  58464. }
  58465. var axisDim = this._dimName;
  58466. var seriesModels = this.getTargetSeriesModels();
  58467. var filterMode = dataZoomModel.get('filterMode');
  58468. var valueWindow = this._valueWindow;
  58469. if (filterMode === 'none') {
  58470. return;
  58471. }
  58472. // FIXME
  58473. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  58474. // with NaN data, NaN will be filtered and stack will be wrong.
  58475. // So we need to force the mode to be set empty.
  58476. // In fect, it is not a big deal that do not support filterMode-'filter'
  58477. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  58478. // selection" some day, which might need "adapt to data extent on the
  58479. // otherAxis", which is disabled by filterMode-'empty'.
  58480. var otherAxisModel = this.getOtherAxisModel();
  58481. if (dataZoomModel.get('$fromToolbox')
  58482. && otherAxisModel
  58483. && otherAxisModel.hasSeriesStacked
  58484. ) {
  58485. filterMode = 'empty';
  58486. }
  58487. // TODO
  58488. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  58489. // Process series data
  58490. each$23(seriesModels, function (seriesModel) {
  58491. var seriesData = seriesModel.getData();
  58492. var dataDims = seriesData.mapDimension(axisDim, true);
  58493. if (filterMode === 'weakFilter') {
  58494. seriesData.filterSelf(function (dataIndex) {
  58495. var leftOut;
  58496. var rightOut;
  58497. var hasValue;
  58498. for (var i = 0; i < dataDims.length; i++) {
  58499. var value = seriesData.get(dataDims[i], dataIndex);
  58500. var thisHasValue = !isNaN(value);
  58501. var thisLeftOut = value < valueWindow[0];
  58502. var thisRightOut = value > valueWindow[1];
  58503. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  58504. return true;
  58505. }
  58506. thisHasValue && (hasValue = true);
  58507. thisLeftOut && (leftOut = true);
  58508. thisRightOut && (rightOut = true);
  58509. }
  58510. // If both left out and right out, do not filter.
  58511. return hasValue && leftOut && rightOut;
  58512. });
  58513. }
  58514. else {
  58515. each$23(dataDims, function (dim) {
  58516. if (filterMode === 'empty') {
  58517. seriesModel.setData(
  58518. seriesData.map(dim, function (value) {
  58519. return !isInWindow(value) ? NaN : value;
  58520. })
  58521. );
  58522. }
  58523. else {
  58524. var range = {};
  58525. range[dim] = valueWindow;
  58526. // console.time('select');
  58527. seriesData.selectRange(range);
  58528. // console.timeEnd('select');
  58529. }
  58530. });
  58531. }
  58532. each$23(dataDims, function (dim) {
  58533. seriesData.setApproximateExtent(valueWindow, dim);
  58534. });
  58535. });
  58536. function isInWindow(value) {
  58537. return value >= valueWindow[0] && value <= valueWindow[1];
  58538. }
  58539. }
  58540. };
  58541. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  58542. var dataExtent = [Infinity, -Infinity];
  58543. each$23(seriesModels, function (seriesModel) {
  58544. var seriesData = seriesModel.getData();
  58545. if (seriesData) {
  58546. each$23(seriesData.mapDimension(axisDim, true), function (dim) {
  58547. var seriesExtent = seriesData.getApproximateExtent(dim);
  58548. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  58549. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  58550. });
  58551. }
  58552. });
  58553. if (dataExtent[1] < dataExtent[0]) {
  58554. dataExtent = [NaN, NaN];
  58555. }
  58556. // It is important to get "consistent" extent when more then one axes is
  58557. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  58558. // when zooming. But it is difficult to know what is "consistent", considering
  58559. // axes have different type or even different meanings (For example, two
  58560. // time axes are used to compare data of the same date in different years).
  58561. // So basically dataZoom just obtains extent by series.data (in category axis
  58562. // extent can be obtained from axis.data).
  58563. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  58564. // consistent.
  58565. fixExtentByAxis(axisProxy, dataExtent);
  58566. return dataExtent;
  58567. }
  58568. function fixExtentByAxis(axisProxy, dataExtent) {
  58569. var axisModel = axisProxy.getAxisModel();
  58570. var min = axisModel.getMin(true);
  58571. // For category axis, if min/max/scale are not set, extent is determined
  58572. // by axis.data by default.
  58573. var isCategoryAxis = axisModel.get('type') === 'category';
  58574. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  58575. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  58576. dataExtent[0] = min;
  58577. }
  58578. else if (isCategoryAxis) {
  58579. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  58580. }
  58581. var max = axisModel.getMax(true);
  58582. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  58583. dataExtent[1] = max;
  58584. }
  58585. else if (isCategoryAxis) {
  58586. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  58587. }
  58588. if (!axisModel.get('scale', true)) {
  58589. dataExtent[0] > 0 && (dataExtent[0] = 0);
  58590. dataExtent[1] < 0 && (dataExtent[1] = 0);
  58591. }
  58592. // For value axis, if min/max/scale are not set, we just use the extent obtained
  58593. // by series data, which may be a little different from the extent calculated by
  58594. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  58595. // little when zooming. So it will not be fixed until some users require it strongly.
  58596. return dataExtent;
  58597. }
  58598. function setAxisModel(axisProxy, isRestore) {
  58599. var axisModel = axisProxy.getAxisModel();
  58600. var percentWindow = axisProxy._percentWindow;
  58601. var valueWindow = axisProxy._valueWindow;
  58602. if (!percentWindow) {
  58603. return;
  58604. }
  58605. // [0, 500]: arbitrary value, guess axis extent.
  58606. var precision = getPixelPrecision(valueWindow, [0, 500]);
  58607. precision = Math.min(precision, 20);
  58608. // isRestore or isFull
  58609. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  58610. axisModel.setRange(
  58611. useOrigin ? null : +valueWindow[0].toFixed(precision),
  58612. useOrigin ? null : +valueWindow[1].toFixed(precision)
  58613. );
  58614. }
  58615. function setMinMaxSpan(axisProxy) {
  58616. var minMaxSpan = axisProxy._minMaxSpan = {};
  58617. var dataZoomModel = axisProxy._dataZoomModel;
  58618. each$23(['min', 'max'], function (minMax) {
  58619. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  58620. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  58621. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  58622. if (valueSpan != null) {
  58623. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  58624. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  58625. if (valueSpan != null) {
  58626. var dataExtent = axisProxy._dataExtent;
  58627. minMaxSpan[minMax + 'Span'] = linearMap(
  58628. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  58629. );
  58630. }
  58631. }
  58632. });
  58633. }
  58634. var each$22 = each$1;
  58635. var eachAxisDim = eachAxisDim$1;
  58636. var DataZoomModel = extendComponentModel({
  58637. type: 'dataZoom',
  58638. dependencies: [
  58639. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  58640. ],
  58641. /**
  58642. * @protected
  58643. */
  58644. defaultOption: {
  58645. zlevel: 0,
  58646. z: 4, // Higher than normal component (z: 2).
  58647. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  58648. xAxisIndex: null, // Default the first horizontal category axis.
  58649. yAxisIndex: null, // Default the first vertical category axis.
  58650. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  58651. // 'filter': data items which are out of window will be removed. This option is
  58652. // applicable when filtering outliers. For each data item, it will be
  58653. // filtered if one of the relevant dimensions is out of the window.
  58654. // 'weakFilter': data items which are out of window will be removed. This option
  58655. // is applicable when filtering outliers. For each data item, it will be
  58656. // filtered only if all of the relevant dimensions are out of the same
  58657. // side of the window.
  58658. // 'empty': data items which are out of window will be set to empty.
  58659. // This option is applicable when user should not neglect
  58660. // that there are some data items out of window.
  58661. // 'none': Do not filter.
  58662. // Taking line chart as an example, line will be broken in
  58663. // the filtered points when filterModel is set to 'empty', but
  58664. // be connected when set to 'filter'.
  58665. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  58666. // default 100. Do not throttle when use null/undefined.
  58667. // If animation === true and animationDurationUpdate > 0,
  58668. // default value is 100, otherwise 20.
  58669. start: 0, // Start percent. 0 ~ 100
  58670. end: 100, // End percent. 0 ~ 100
  58671. startValue: null, // Start value. If startValue specified, start is ignored.
  58672. endValue: null, // End value. If endValue specified, end is ignored.
  58673. minSpan: null, // 0 ~ 100
  58674. maxSpan: null, // 0 ~ 100
  58675. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  58676. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  58677. rangeMode: null // Array, can be 'value' or 'percent'.
  58678. },
  58679. /**
  58680. * @override
  58681. */
  58682. init: function (option, parentModel, ecModel) {
  58683. /**
  58684. * key like x_0, y_1
  58685. * @private
  58686. * @type {Object}
  58687. */
  58688. this._dataIntervalByAxis = {};
  58689. /**
  58690. * @private
  58691. */
  58692. this._dataInfo = {};
  58693. /**
  58694. * key like x_0, y_1
  58695. * @private
  58696. */
  58697. this._axisProxies = {};
  58698. /**
  58699. * @readOnly
  58700. */
  58701. this.textStyleModel;
  58702. /**
  58703. * @private
  58704. */
  58705. this._autoThrottle = true;
  58706. /**
  58707. * 'percent' or 'value'
  58708. * @private
  58709. */
  58710. this._rangePropMode = ['percent', 'percent'];
  58711. var rawOption = retrieveRaw(option);
  58712. this.mergeDefaultAndTheme(option, ecModel);
  58713. this.doInit(rawOption);
  58714. },
  58715. /**
  58716. * @override
  58717. */
  58718. mergeOption: function (newOption) {
  58719. var rawOption = retrieveRaw(newOption);
  58720. //FIX #2591
  58721. merge(this.option, newOption, true);
  58722. this.doInit(rawOption);
  58723. },
  58724. /**
  58725. * @protected
  58726. */
  58727. doInit: function (rawOption) {
  58728. var thisOption = this.option;
  58729. // Disable realtime view update if canvas is not supported.
  58730. if (!env$1.canvasSupported) {
  58731. thisOption.realtime = false;
  58732. }
  58733. this._setDefaultThrottle(rawOption);
  58734. updateRangeUse(this, rawOption);
  58735. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  58736. // start/end has higher priority over startValue/endValue if they
  58737. // both set, but we should make chart.setOption({endValue: 1000})
  58738. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  58739. if (this._rangePropMode[index] === 'value') {
  58740. thisOption[names[0]] = null;
  58741. }
  58742. // Otherwise do nothing and use the merge result.
  58743. }, this);
  58744. this.textStyleModel = this.getModel('textStyle');
  58745. this._resetTarget();
  58746. this._giveAxisProxies();
  58747. },
  58748. /**
  58749. * @private
  58750. */
  58751. _giveAxisProxies: function () {
  58752. var axisProxies = this._axisProxies;
  58753. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  58754. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  58755. // If exists, share axisProxy with other dataZoomModels.
  58756. var axisProxy = axisModel.__dzAxisProxy || (
  58757. // Use the first dataZoomModel as the main model of axisProxy.
  58758. axisModel.__dzAxisProxy = new AxisProxy(
  58759. dimNames.name, axisIndex, this, ecModel
  58760. )
  58761. );
  58762. // FIXME
  58763. // dispose __dzAxisProxy
  58764. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  58765. }, this);
  58766. },
  58767. /**
  58768. * @private
  58769. */
  58770. _resetTarget: function () {
  58771. var thisOption = this.option;
  58772. var autoMode = this._judgeAutoMode();
  58773. eachAxisDim(function (dimNames) {
  58774. var axisIndexName = dimNames.axisIndex;
  58775. thisOption[axisIndexName] = normalizeToArray(
  58776. thisOption[axisIndexName]
  58777. );
  58778. }, this);
  58779. if (autoMode === 'axisIndex') {
  58780. this._autoSetAxisIndex();
  58781. }
  58782. else if (autoMode === 'orient') {
  58783. this._autoSetOrient();
  58784. }
  58785. },
  58786. /**
  58787. * @private
  58788. */
  58789. _judgeAutoMode: function () {
  58790. // Auto set only works for setOption at the first time.
  58791. // The following is user's reponsibility. So using merged
  58792. // option is OK.
  58793. var thisOption = this.option;
  58794. var hasIndexSpecified = false;
  58795. eachAxisDim(function (dimNames) {
  58796. // When user set axisIndex as a empty array, we think that user specify axisIndex
  58797. // but do not want use auto mode. Because empty array may be encountered when
  58798. // some error occured.
  58799. if (thisOption[dimNames.axisIndex] != null) {
  58800. hasIndexSpecified = true;
  58801. }
  58802. }, this);
  58803. var orient = thisOption.orient;
  58804. if (orient == null && hasIndexSpecified) {
  58805. return 'orient';
  58806. }
  58807. else if (!hasIndexSpecified) {
  58808. if (orient == null) {
  58809. thisOption.orient = 'horizontal';
  58810. }
  58811. return 'axisIndex';
  58812. }
  58813. },
  58814. /**
  58815. * @private
  58816. */
  58817. _autoSetAxisIndex: function () {
  58818. var autoAxisIndex = true;
  58819. var orient = this.get('orient', true);
  58820. var thisOption = this.option;
  58821. var dependentModels = this.dependentModels;
  58822. if (autoAxisIndex) {
  58823. // Find axis that parallel to dataZoom as default.
  58824. var dimName = orient === 'vertical' ? 'y' : 'x';
  58825. if (dependentModels[dimName + 'Axis'].length) {
  58826. thisOption[dimName + 'AxisIndex'] = [0];
  58827. autoAxisIndex = false;
  58828. }
  58829. else {
  58830. each$22(dependentModels.singleAxis, function (singleAxisModel) {
  58831. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  58832. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  58833. autoAxisIndex = false;
  58834. }
  58835. });
  58836. }
  58837. }
  58838. if (autoAxisIndex) {
  58839. // Find the first category axis as default. (consider polar)
  58840. eachAxisDim(function (dimNames) {
  58841. if (!autoAxisIndex) {
  58842. return;
  58843. }
  58844. var axisIndices = [];
  58845. var axisModels = this.dependentModels[dimNames.axis];
  58846. if (axisModels.length && !axisIndices.length) {
  58847. for (var i = 0, len = axisModels.length; i < len; i++) {
  58848. if (axisModels[i].get('type') === 'category') {
  58849. axisIndices.push(i);
  58850. }
  58851. }
  58852. }
  58853. thisOption[dimNames.axisIndex] = axisIndices;
  58854. if (axisIndices.length) {
  58855. autoAxisIndex = false;
  58856. }
  58857. }, this);
  58858. }
  58859. if (autoAxisIndex) {
  58860. // FIXME
  58861. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  58862. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  58863. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  58864. // dataZoom component auto adopts series that reference to
  58865. // both xAxis and yAxis which type is 'value'.
  58866. this.ecModel.eachSeries(function (seriesModel) {
  58867. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  58868. eachAxisDim(function (dimNames) {
  58869. var axisIndices = thisOption[dimNames.axisIndex];
  58870. var axisIndex = seriesModel.get(dimNames.axisIndex);
  58871. var axisId = seriesModel.get(dimNames.axisId);
  58872. var axisModel = seriesModel.ecModel.queryComponents({
  58873. mainType: dimNames.axis,
  58874. index: axisIndex,
  58875. id: axisId
  58876. })[0];
  58877. if (__DEV__) {
  58878. if (!axisModel) {
  58879. throw new Error(
  58880. dimNames.axis + ' "' + retrieve(
  58881. axisIndex,
  58882. axisId,
  58883. 0
  58884. ) + '" not found'
  58885. );
  58886. }
  58887. }
  58888. axisIndex = axisModel.componentIndex;
  58889. if (indexOf(axisIndices, axisIndex) < 0) {
  58890. axisIndices.push(axisIndex);
  58891. }
  58892. });
  58893. }
  58894. }, this);
  58895. }
  58896. },
  58897. /**
  58898. * @private
  58899. */
  58900. _autoSetOrient: function () {
  58901. var dim;
  58902. // Find the first axis
  58903. this.eachTargetAxis(function (dimNames) {
  58904. !dim && (dim = dimNames.name);
  58905. }, this);
  58906. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  58907. },
  58908. /**
  58909. * @private
  58910. */
  58911. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  58912. // FIXME
  58913. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  58914. // 例如series.type === scatter时。
  58915. var is = true;
  58916. eachAxisDim(function (dimNames) {
  58917. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  58918. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  58919. if (!axisModel || axisModel.get('type') !== axisType) {
  58920. is = false;
  58921. }
  58922. }, this);
  58923. return is;
  58924. },
  58925. /**
  58926. * @private
  58927. */
  58928. _setDefaultThrottle: function (rawOption) {
  58929. // When first time user set throttle, auto throttle ends.
  58930. if (rawOption.hasOwnProperty('throttle')) {
  58931. this._autoThrottle = false;
  58932. }
  58933. if (this._autoThrottle) {
  58934. var globalOption = this.ecModel.option;
  58935. this.option.throttle =
  58936. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  58937. ? 100 : 20;
  58938. }
  58939. },
  58940. /**
  58941. * @public
  58942. */
  58943. getFirstTargetAxisModel: function () {
  58944. var firstAxisModel;
  58945. eachAxisDim(function (dimNames) {
  58946. if (firstAxisModel == null) {
  58947. var indices = this.get(dimNames.axisIndex);
  58948. if (indices.length) {
  58949. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  58950. }
  58951. }
  58952. }, this);
  58953. return firstAxisModel;
  58954. },
  58955. /**
  58956. * @public
  58957. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  58958. */
  58959. eachTargetAxis: function (callback, context) {
  58960. var ecModel = this.ecModel;
  58961. eachAxisDim(function (dimNames) {
  58962. each$22(
  58963. this.get(dimNames.axisIndex),
  58964. function (axisIndex) {
  58965. callback.call(context, dimNames, axisIndex, this, ecModel);
  58966. },
  58967. this
  58968. );
  58969. }, this);
  58970. },
  58971. /**
  58972. * @param {string} dimName
  58973. * @param {number} axisIndex
  58974. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  58975. */
  58976. getAxisProxy: function (dimName, axisIndex) {
  58977. return this._axisProxies[dimName + '_' + axisIndex];
  58978. },
  58979. /**
  58980. * @param {string} dimName
  58981. * @param {number} axisIndex
  58982. * @return {module:echarts/model/Model} If not found, return null/undefined.
  58983. */
  58984. getAxisModel: function (dimName, axisIndex) {
  58985. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  58986. return axisProxy && axisProxy.getAxisModel();
  58987. },
  58988. /**
  58989. * If not specified, set to undefined.
  58990. *
  58991. * @public
  58992. * @param {Object} opt
  58993. * @param {number} [opt.start]
  58994. * @param {number} [opt.end]
  58995. * @param {number} [opt.startValue]
  58996. * @param {number} [opt.endValue]
  58997. * @param {boolean} [ignoreUpdateRangeUsg=false]
  58998. */
  58999. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  59000. var option = this.option;
  59001. each$22([['start', 'startValue'], ['end', 'endValue']], function (names) {
  59002. // If only one of 'start' and 'startValue' is not null/undefined, the other
  59003. // should be cleared, which enable clear the option.
  59004. // If both of them are not set, keep option with the original value, which
  59005. // enable use only set start but not set end when calling `dispatchAction`.
  59006. // The same as 'end' and 'endValue'.
  59007. if (opt[names[0]] != null || opt[names[1]] != null) {
  59008. option[names[0]] = opt[names[0]];
  59009. option[names[1]] = opt[names[1]];
  59010. }
  59011. }, this);
  59012. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  59013. },
  59014. /**
  59015. * @public
  59016. * @return {Array.<number>} [startPercent, endPercent]
  59017. */
  59018. getPercentRange: function () {
  59019. var axisProxy = this.findRepresentativeAxisProxy();
  59020. if (axisProxy) {
  59021. return axisProxy.getDataPercentWindow();
  59022. }
  59023. },
  59024. /**
  59025. * @public
  59026. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  59027. *
  59028. * @param {string} [axisDimName]
  59029. * @param {number} [axisIndex]
  59030. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  59031. */
  59032. getValueRange: function (axisDimName, axisIndex) {
  59033. if (axisDimName == null && axisIndex == null) {
  59034. var axisProxy = this.findRepresentativeAxisProxy();
  59035. if (axisProxy) {
  59036. return axisProxy.getDataValueWindow();
  59037. }
  59038. }
  59039. else {
  59040. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  59041. }
  59042. },
  59043. /**
  59044. * @public
  59045. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  59046. * corresponding to the axisModel
  59047. * @return {module:echarts/component/dataZoom/AxisProxy}
  59048. */
  59049. findRepresentativeAxisProxy: function (axisModel) {
  59050. if (axisModel) {
  59051. return axisModel.__dzAxisProxy;
  59052. }
  59053. // Find the first hosted axisProxy
  59054. var axisProxies = this._axisProxies;
  59055. for (var key in axisProxies) {
  59056. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  59057. return axisProxies[key];
  59058. }
  59059. }
  59060. // If no hosted axis find not hosted axisProxy.
  59061. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  59062. // and the option.start or option.end settings are different. The percentRange
  59063. // should follow axisProxy.
  59064. // (We encounter this problem in toolbox data zoom.)
  59065. for (var key in axisProxies) {
  59066. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  59067. return axisProxies[key];
  59068. }
  59069. }
  59070. },
  59071. /**
  59072. * @return {Array.<string>}
  59073. */
  59074. getRangePropMode: function () {
  59075. return this._rangePropMode.slice();
  59076. }
  59077. });
  59078. function retrieveRaw(option) {
  59079. var ret = {};
  59080. each$22(
  59081. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  59082. function (name) {
  59083. option.hasOwnProperty(name) && (ret[name] = option[name]);
  59084. }
  59085. );
  59086. return ret;
  59087. }
  59088. function updateRangeUse(dataZoomModel, rawOption) {
  59089. var rangePropMode = dataZoomModel._rangePropMode;
  59090. var rangeModeInOption = dataZoomModel.get('rangeMode');
  59091. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  59092. var percentSpecified = rawOption[names[0]] != null;
  59093. var valueSpecified = rawOption[names[1]] != null;
  59094. if (percentSpecified && !valueSpecified) {
  59095. rangePropMode[index] = 'percent';
  59096. }
  59097. else if (!percentSpecified && valueSpecified) {
  59098. rangePropMode[index] = 'value';
  59099. }
  59100. else if (rangeModeInOption) {
  59101. rangePropMode[index] = rangeModeInOption[index];
  59102. }
  59103. else if (percentSpecified) { // percentSpecified && valueSpecified
  59104. rangePropMode[index] = 'percent';
  59105. }
  59106. // else remain its original setting.
  59107. });
  59108. }
  59109. var DataZoomView = Component.extend({
  59110. type: 'dataZoom',
  59111. render: function (dataZoomModel, ecModel, api, payload) {
  59112. this.dataZoomModel = dataZoomModel;
  59113. this.ecModel = ecModel;
  59114. this.api = api;
  59115. },
  59116. /**
  59117. * Find the first target coordinate system.
  59118. *
  59119. * @protected
  59120. * @return {Object} {
  59121. * grid: [
  59122. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  59123. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  59124. * ...
  59125. * ], // cartesians must not be null/undefined.
  59126. * polar: [
  59127. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  59128. * ...
  59129. * ], // polars must not be null/undefined.
  59130. * singleAxis: [
  59131. * {model: coord0, axisModels: [], coordIndex: 0}
  59132. * ]
  59133. */
  59134. getTargetCoordInfo: function () {
  59135. var dataZoomModel = this.dataZoomModel;
  59136. var ecModel = this.ecModel;
  59137. var coordSysLists = {};
  59138. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  59139. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  59140. if (axisModel) {
  59141. var coordModel = axisModel.getCoordSysModel();
  59142. coordModel && save(
  59143. coordModel,
  59144. axisModel,
  59145. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  59146. coordModel.componentIndex
  59147. );
  59148. }
  59149. }, this);
  59150. function save(coordModel, axisModel, store, coordIndex) {
  59151. var item;
  59152. for (var i = 0; i < store.length; i++) {
  59153. if (store[i].model === coordModel) {
  59154. item = store[i];
  59155. break;
  59156. }
  59157. }
  59158. if (!item) {
  59159. store.push(item = {
  59160. model: coordModel, axisModels: [], coordIndex: coordIndex
  59161. });
  59162. }
  59163. item.axisModels.push(axisModel);
  59164. }
  59165. return coordSysLists;
  59166. }
  59167. });
  59168. var SliderZoomModel = DataZoomModel.extend({
  59169. type: 'dataZoom.slider',
  59170. layoutMode: 'box',
  59171. /**
  59172. * @protected
  59173. */
  59174. defaultOption: {
  59175. show: true,
  59176. // ph => placeholder. Using placehoder here because
  59177. // deault value can only be drived in view stage.
  59178. right: 'ph', // Default align to grid rect.
  59179. top: 'ph', // Default align to grid rect.
  59180. width: 'ph', // Default align to grid rect.
  59181. height: 'ph', // Default align to grid rect.
  59182. left: null, // Default align to grid rect.
  59183. bottom: null, // Default align to grid rect.
  59184. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  59185. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  59186. // highest priority, remain for compatibility of
  59187. // previous version, but not recommended any more.
  59188. dataBackground: {
  59189. lineStyle: {
  59190. color: '#2f4554',
  59191. width: 0.5,
  59192. opacity: 0.3
  59193. },
  59194. areaStyle: {
  59195. color: 'rgba(47,69,84,0.3)',
  59196. opacity: 0.3
  59197. }
  59198. },
  59199. borderColor: '#ddd', // border color of the box. For compatibility,
  59200. // if dataBackgroundColor is set, borderColor
  59201. // is ignored.
  59202. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  59203. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  59204. // handleIcon: 'path://M4.9,17.8c0-1.4,4.5-10.5,5.5-12.4c0-0.1,0.6-1.1,0.9-1.1c0.4,0,0.9,1,0.9,1.1c1.1,2.2,5.4,11,5.4,12.4v17.8c0,1.5-0.6,2.1-1.3,2.1H6.1c-0.7,0-1.3-0.6-1.3-2.1V17.8z',
  59205. handleIcon: 'M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z',
  59206. // Percent of the slider height
  59207. handleSize: '100%',
  59208. handleStyle: {
  59209. color: '#a7b7cc'
  59210. },
  59211. labelPrecision: null,
  59212. labelFormatter: null,
  59213. showDetail: true,
  59214. showDataShadow: 'auto', // Default auto decision.
  59215. realtime: true,
  59216. zoomLock: false, // Whether disable zoom.
  59217. textStyle: {
  59218. color: '#333'
  59219. }
  59220. }
  59221. });
  59222. var Rect$2 = Rect;
  59223. var linearMap$2 = linearMap;
  59224. var asc$2 = asc;
  59225. var bind$4 = bind;
  59226. var each$24 = each$1;
  59227. // Constants
  59228. var DEFAULT_LOCATION_EDGE_GAP = 7;
  59229. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  59230. var DEFAULT_FILLER_SIZE = 30;
  59231. var HORIZONTAL = 'horizontal';
  59232. var VERTICAL = 'vertical';
  59233. var LABEL_GAP = 5;
  59234. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  59235. var SliderZoomView = DataZoomView.extend({
  59236. type: 'dataZoom.slider',
  59237. init: function (ecModel, api) {
  59238. /**
  59239. * @private
  59240. * @type {Object}
  59241. */
  59242. this._displayables = {};
  59243. /**
  59244. * @private
  59245. * @type {string}
  59246. */
  59247. this._orient;
  59248. /**
  59249. * [0, 100]
  59250. * @private
  59251. */
  59252. this._range;
  59253. /**
  59254. * [coord of the first handle, coord of the second handle]
  59255. * @private
  59256. */
  59257. this._handleEnds;
  59258. /**
  59259. * [length, thick]
  59260. * @private
  59261. * @type {Array.<number>}
  59262. */
  59263. this._size;
  59264. /**
  59265. * @private
  59266. * @type {number}
  59267. */
  59268. this._handleWidth;
  59269. /**
  59270. * @private
  59271. * @type {number}
  59272. */
  59273. this._handleHeight;
  59274. /**
  59275. * @private
  59276. */
  59277. this._location;
  59278. /**
  59279. * @private
  59280. */
  59281. this._dragging;
  59282. /**
  59283. * @private
  59284. */
  59285. this._dataShadowInfo;
  59286. this.api = api;
  59287. },
  59288. /**
  59289. * @override
  59290. */
  59291. render: function (dataZoomModel, ecModel, api, payload) {
  59292. SliderZoomView.superApply(this, 'render', arguments);
  59293. createOrUpdate(
  59294. this,
  59295. '_dispatchZoomAction',
  59296. this.dataZoomModel.get('throttle'),
  59297. 'fixRate'
  59298. );
  59299. this._orient = dataZoomModel.get('orient');
  59300. if (this.dataZoomModel.get('show') === false) {
  59301. this.group.removeAll();
  59302. return;
  59303. }
  59304. // Notice: this._resetInterval() should not be executed when payload.type
  59305. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  59306. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  59307. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  59308. this._buildView();
  59309. }
  59310. this._updateView();
  59311. },
  59312. /**
  59313. * @override
  59314. */
  59315. remove: function () {
  59316. SliderZoomView.superApply(this, 'remove', arguments);
  59317. clear(this, '_dispatchZoomAction');
  59318. },
  59319. /**
  59320. * @override
  59321. */
  59322. dispose: function () {
  59323. SliderZoomView.superApply(this, 'dispose', arguments);
  59324. clear(this, '_dispatchZoomAction');
  59325. },
  59326. _buildView: function () {
  59327. var thisGroup = this.group;
  59328. thisGroup.removeAll();
  59329. this._resetLocation();
  59330. this._resetInterval();
  59331. var barGroup = this._displayables.barGroup = new Group();
  59332. this._renderBackground();
  59333. this._renderHandle();
  59334. this._renderDataShadow();
  59335. thisGroup.add(barGroup);
  59336. this._positionGroup();
  59337. },
  59338. /**
  59339. * @private
  59340. */
  59341. _resetLocation: function () {
  59342. var dataZoomModel = this.dataZoomModel;
  59343. var api = this.api;
  59344. // If some of x/y/width/height are not specified,
  59345. // auto-adapt according to target grid.
  59346. var coordRect = this._findCoordRect();
  59347. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  59348. // Default align by coordinate system rect.
  59349. var positionInfo = this._orient === HORIZONTAL
  59350. ? {
  59351. // Why using 'right', because right should be used in vertical,
  59352. // and it is better to be consistent for dealing with position param merge.
  59353. right: ecSize.width - coordRect.x - coordRect.width,
  59354. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  59355. width: coordRect.width,
  59356. height: DEFAULT_FILLER_SIZE
  59357. }
  59358. : { // vertical
  59359. right: DEFAULT_LOCATION_EDGE_GAP,
  59360. top: coordRect.y,
  59361. width: DEFAULT_FILLER_SIZE,
  59362. height: coordRect.height
  59363. };
  59364. // Do not write back to option and replace value 'ph', because
  59365. // the 'ph' value should be recalculated when resize.
  59366. var layoutParams = getLayoutParams(dataZoomModel.option);
  59367. // Replace the placeholder value.
  59368. each$1(['right', 'top', 'width', 'height'], function (name) {
  59369. if (layoutParams[name] === 'ph') {
  59370. layoutParams[name] = positionInfo[name];
  59371. }
  59372. });
  59373. var layoutRect = getLayoutRect(
  59374. layoutParams,
  59375. ecSize,
  59376. dataZoomModel.padding
  59377. );
  59378. this._location = {x: layoutRect.x, y: layoutRect.y};
  59379. this._size = [layoutRect.width, layoutRect.height];
  59380. this._orient === VERTICAL && this._size.reverse();
  59381. },
  59382. /**
  59383. * @private
  59384. */
  59385. _positionGroup: function () {
  59386. var thisGroup = this.group;
  59387. var location = this._location;
  59388. var orient = this._orient;
  59389. // Just use the first axis to determine mapping.
  59390. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  59391. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  59392. var barGroup = this._displayables.barGroup;
  59393. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  59394. // Transform barGroup.
  59395. barGroup.attr(
  59396. (orient === HORIZONTAL && !inverse)
  59397. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  59398. : (orient === HORIZONTAL && inverse)
  59399. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  59400. : (orient === VERTICAL && !inverse)
  59401. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  59402. // Dont use Math.PI, considering shadow direction.
  59403. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  59404. );
  59405. // Position barGroup
  59406. var rect = thisGroup.getBoundingRect([barGroup]);
  59407. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  59408. },
  59409. /**
  59410. * @private
  59411. */
  59412. _getViewExtent: function () {
  59413. return [0, this._size[0]];
  59414. },
  59415. _renderBackground: function () {
  59416. var dataZoomModel = this.dataZoomModel;
  59417. var size = this._size;
  59418. var barGroup = this._displayables.barGroup;
  59419. barGroup.add(new Rect$2({
  59420. silent: true,
  59421. shape: {
  59422. x: 0, y: 0, width: size[0], height: size[1]
  59423. },
  59424. style: {
  59425. fill: dataZoomModel.get('backgroundColor')
  59426. },
  59427. z2: -40
  59428. }));
  59429. // Click panel, over shadow, below handles.
  59430. barGroup.add(new Rect$2({
  59431. shape: {
  59432. x: 0, y: 0, width: size[0], height: size[1]
  59433. },
  59434. style: {
  59435. fill: 'transparent'
  59436. },
  59437. z2: 0,
  59438. onclick: bind(this._onClickPanelClick, this)
  59439. }));
  59440. },
  59441. _renderDataShadow: function () {
  59442. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  59443. if (!info) {
  59444. return;
  59445. }
  59446. var size = this._size;
  59447. var seriesModel = info.series;
  59448. var data = seriesModel.getRawData();
  59449. var otherDim = seriesModel.getShadowDim
  59450. ? seriesModel.getShadowDim() // @see candlestick
  59451. : info.otherDim;
  59452. if (otherDim == null) {
  59453. return;
  59454. }
  59455. var otherDataExtent = data.getDataExtent(otherDim);
  59456. // Nice extent.
  59457. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  59458. otherDataExtent = [
  59459. otherDataExtent[0] - otherOffset,
  59460. otherDataExtent[1] + otherOffset
  59461. ];
  59462. var otherShadowExtent = [0, size[1]];
  59463. var thisShadowExtent = [0, size[0]];
  59464. var areaPoints = [[size[0], 0], [0, 0]];
  59465. var linePoints = [];
  59466. var step = thisShadowExtent[1] / (data.count() - 1);
  59467. var thisCoord = 0;
  59468. // Optimize for large data shadow
  59469. var stride = Math.round(data.count() / size[0]);
  59470. var lastIsEmpty;
  59471. data.each([otherDim], function (value, index) {
  59472. if (stride > 0 && (index % stride)) {
  59473. thisCoord += step;
  59474. return;
  59475. }
  59476. // FIXME
  59477. // Should consider axis.min/axis.max when drawing dataShadow.
  59478. // FIXME
  59479. // 应该使用统一的空判断?还是在list里进行空判断?
  59480. var isEmpty = value == null || isNaN(value) || value === '';
  59481. // See #4235.
  59482. var otherCoord = isEmpty
  59483. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  59484. // Attempt to draw data shadow precisely when there are empty value.
  59485. if (isEmpty && !lastIsEmpty && index) {
  59486. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  59487. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  59488. }
  59489. else if (!isEmpty && lastIsEmpty) {
  59490. areaPoints.push([thisCoord, 0]);
  59491. linePoints.push([thisCoord, 0]);
  59492. }
  59493. areaPoints.push([thisCoord, otherCoord]);
  59494. linePoints.push([thisCoord, otherCoord]);
  59495. thisCoord += step;
  59496. lastIsEmpty = isEmpty;
  59497. });
  59498. var dataZoomModel = this.dataZoomModel;
  59499. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  59500. this._displayables.barGroup.add(new Polygon({
  59501. shape: {points: areaPoints},
  59502. style: defaults(
  59503. {fill: dataZoomModel.get('dataBackgroundColor')},
  59504. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  59505. ),
  59506. silent: true,
  59507. z2: -20
  59508. }));
  59509. this._displayables.barGroup.add(new Polyline({
  59510. shape: {points: linePoints},
  59511. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  59512. silent: true,
  59513. z2: -19
  59514. }));
  59515. },
  59516. _prepareDataShadowInfo: function () {
  59517. var dataZoomModel = this.dataZoomModel;
  59518. var showDataShadow = dataZoomModel.get('showDataShadow');
  59519. if (showDataShadow === false) {
  59520. return;
  59521. }
  59522. // Find a representative series.
  59523. var result;
  59524. var ecModel = this.ecModel;
  59525. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  59526. var seriesModels = dataZoomModel
  59527. .getAxisProxy(dimNames.name, axisIndex)
  59528. .getTargetSeriesModels();
  59529. each$1(seriesModels, function (seriesModel) {
  59530. if (result) {
  59531. return;
  59532. }
  59533. if (showDataShadow !== true && indexOf(
  59534. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  59535. ) < 0
  59536. ) {
  59537. return;
  59538. }
  59539. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  59540. var otherDim = getOtherDim(dimNames.name);
  59541. var otherAxisInverse;
  59542. var coordSys = seriesModel.coordinateSystem;
  59543. if (otherDim != null && coordSys.getOtherAxis) {
  59544. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  59545. }
  59546. otherDim = seriesModel.getData().mapDimension(otherDim);
  59547. result = {
  59548. thisAxis: thisAxis,
  59549. series: seriesModel,
  59550. thisDim: dimNames.name,
  59551. otherDim: otherDim,
  59552. otherAxisInverse: otherAxisInverse
  59553. };
  59554. }, this);
  59555. }, this);
  59556. return result;
  59557. },
  59558. _renderHandle: function () {
  59559. var displaybles = this._displayables;
  59560. var handles = displaybles.handles = [];
  59561. var handleLabels = displaybles.handleLabels = [];
  59562. var barGroup = this._displayables.barGroup;
  59563. var size = this._size;
  59564. var dataZoomModel = this.dataZoomModel;
  59565. barGroup.add(displaybles.filler = new Rect$2({
  59566. draggable: true,
  59567. cursor: getCursor(this._orient),
  59568. drift: bind$4(this._onDragMove, this, 'all'),
  59569. onmousemove: function (e) {
  59570. // Fot mobile devicem, prevent screen slider on the button.
  59571. stop(e.event);
  59572. },
  59573. ondragstart: bind$4(this._showDataInfo, this, true),
  59574. ondragend: bind$4(this._onDragEnd, this),
  59575. onmouseover: bind$4(this._showDataInfo, this, true),
  59576. onmouseout: bind$4(this._showDataInfo, this, false),
  59577. style: {
  59578. fill: dataZoomModel.get('fillerColor'),
  59579. textPosition : 'inside'
  59580. }
  59581. }));
  59582. // Frame border.
  59583. barGroup.add(new Rect$2(subPixelOptimizeRect({
  59584. silent: true,
  59585. shape: {
  59586. x: 0,
  59587. y: 0,
  59588. width: size[0],
  59589. height: size[1]
  59590. },
  59591. style: {
  59592. stroke: dataZoomModel.get('dataBackgroundColor')
  59593. || dataZoomModel.get('borderColor'),
  59594. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  59595. fill: 'rgba(0,0,0,0)'
  59596. }
  59597. })));
  59598. each$24([0, 1], function (handleIndex) {
  59599. var path = createIcon(
  59600. dataZoomModel.get('handleIcon'),
  59601. {
  59602. cursor: getCursor(this._orient),
  59603. draggable: true,
  59604. drift: bind$4(this._onDragMove, this, handleIndex),
  59605. onmousemove: function (e) {
  59606. // Fot mobile devicem, prevent screen slider on the button.
  59607. stop(e.event);
  59608. },
  59609. ondragend: bind$4(this._onDragEnd, this),
  59610. onmouseover: bind$4(this._showDataInfo, this, true),
  59611. onmouseout: bind$4(this._showDataInfo, this, false)
  59612. },
  59613. {x: -1, y: 0, width: 2, height: 2}
  59614. );
  59615. var bRect = path.getBoundingRect();
  59616. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  59617. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  59618. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  59619. var handleColor = dataZoomModel.get('handleColor');
  59620. // Compatitable with previous version
  59621. if (handleColor != null) {
  59622. path.style.fill = handleColor;
  59623. }
  59624. barGroup.add(handles[handleIndex] = path);
  59625. var textStyleModel = dataZoomModel.textStyleModel;
  59626. this.group.add(
  59627. handleLabels[handleIndex] = new Text({
  59628. silent: true,
  59629. invisible: true,
  59630. style: {
  59631. x: 0, y: 0, text: '',
  59632. textVerticalAlign: 'middle',
  59633. textAlign: 'center',
  59634. textFill: textStyleModel.getTextColor(),
  59635. textFont: textStyleModel.getFont()
  59636. },
  59637. z2: 10
  59638. }));
  59639. }, this);
  59640. },
  59641. /**
  59642. * @private
  59643. */
  59644. _resetInterval: function () {
  59645. var range = this._range = this.dataZoomModel.getPercentRange();
  59646. var viewExtent = this._getViewExtent();
  59647. this._handleEnds = [
  59648. linearMap$2(range[0], [0, 100], viewExtent, true),
  59649. linearMap$2(range[1], [0, 100], viewExtent, true)
  59650. ];
  59651. },
  59652. /**
  59653. * @private
  59654. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  59655. * @param {number} delta
  59656. */
  59657. _updateInterval: function (handleIndex, delta) {
  59658. var dataZoomModel = this.dataZoomModel;
  59659. var handleEnds = this._handleEnds;
  59660. var viewExtend = this._getViewExtent();
  59661. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  59662. var percentExtent = [0, 100];
  59663. sliderMove(
  59664. delta,
  59665. handleEnds,
  59666. viewExtend,
  59667. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  59668. minMaxSpan.minSpan != null
  59669. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  59670. minMaxSpan.maxSpan != null
  59671. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  59672. );
  59673. this._range = asc$2([
  59674. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  59675. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  59676. ]);
  59677. },
  59678. /**
  59679. * @private
  59680. */
  59681. _updateView: function (nonRealtime) {
  59682. var displaybles = this._displayables;
  59683. var handleEnds = this._handleEnds;
  59684. var handleInterval = asc$2(handleEnds.slice());
  59685. var size = this._size;
  59686. each$24([0, 1], function (handleIndex) {
  59687. // Handles
  59688. var handle = displaybles.handles[handleIndex];
  59689. var handleHeight = this._handleHeight;
  59690. handle.attr({
  59691. scale: [handleHeight / 2, handleHeight / 2],
  59692. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  59693. });
  59694. }, this);
  59695. // Filler
  59696. displaybles.filler.setShape({
  59697. x: handleInterval[0],
  59698. y: 0,
  59699. width: handleInterval[1] - handleInterval[0],
  59700. height: size[1]
  59701. });
  59702. this._updateDataInfo(nonRealtime);
  59703. },
  59704. /**
  59705. * @private
  59706. */
  59707. _updateDataInfo: function (nonRealtime) {
  59708. var dataZoomModel = this.dataZoomModel;
  59709. var displaybles = this._displayables;
  59710. var handleLabels = displaybles.handleLabels;
  59711. var orient = this._orient;
  59712. var labelTexts = ['', ''];
  59713. // FIXME
  59714. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  59715. if (dataZoomModel.get('showDetail')) {
  59716. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  59717. if (axisProxy) {
  59718. var axis = axisProxy.getAxisModel().axis;
  59719. var range = this._range;
  59720. var dataInterval = nonRealtime
  59721. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  59722. ? axisProxy.calculateDataWindow({
  59723. start: range[0], end: range[1]
  59724. }).valueWindow
  59725. : axisProxy.getDataValueWindow();
  59726. labelTexts = [
  59727. this._formatLabel(dataInterval[0], axis),
  59728. this._formatLabel(dataInterval[1], axis)
  59729. ];
  59730. }
  59731. }
  59732. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  59733. setLabel.call(this, 0);
  59734. setLabel.call(this, 1);
  59735. function setLabel(handleIndex) {
  59736. // Label
  59737. // Text should not transform by barGroup.
  59738. // Ignore handlers transform
  59739. var barTransform = getTransform(
  59740. displaybles.handles[handleIndex].parent, this.group
  59741. );
  59742. var direction = transformDirection(
  59743. handleIndex === 0 ? 'right' : 'left', barTransform
  59744. );
  59745. var offset = this._handleWidth / 2 + LABEL_GAP;
  59746. var textPoint = applyTransform$1(
  59747. [
  59748. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  59749. this._size[1] / 2
  59750. ],
  59751. barTransform
  59752. );
  59753. handleLabels[handleIndex].setStyle({
  59754. x: textPoint[0],
  59755. y: textPoint[1],
  59756. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  59757. textAlign: orient === HORIZONTAL ? direction : 'center',
  59758. text: labelTexts[handleIndex]
  59759. });
  59760. }
  59761. },
  59762. /**
  59763. * @private
  59764. */
  59765. _formatLabel: function (value, axis) {
  59766. var dataZoomModel = this.dataZoomModel;
  59767. var labelFormatter = dataZoomModel.get('labelFormatter');
  59768. var labelPrecision = dataZoomModel.get('labelPrecision');
  59769. if (labelPrecision == null || labelPrecision === 'auto') {
  59770. labelPrecision = axis.getPixelPrecision();
  59771. }
  59772. var valueStr = (value == null || isNaN(value))
  59773. ? ''
  59774. // FIXME Glue code
  59775. : (axis.type === 'category' || axis.type === 'time')
  59776. ? axis.scale.getLabel(Math.round(value))
  59777. // param of toFixed should less then 20.
  59778. : value.toFixed(Math.min(labelPrecision, 20));
  59779. return isFunction$1(labelFormatter)
  59780. ? labelFormatter(value, valueStr)
  59781. : isString(labelFormatter)
  59782. ? labelFormatter.replace('{value}', valueStr)
  59783. : valueStr;
  59784. },
  59785. /**
  59786. * @private
  59787. * @param {boolean} showOrHide true: show, false: hide
  59788. */
  59789. _showDataInfo: function (showOrHide) {
  59790. // Always show when drgging.
  59791. showOrHide = this._dragging || showOrHide;
  59792. var handleLabels = this._displayables.handleLabels;
  59793. handleLabels[0].attr('invisible', !showOrHide);
  59794. handleLabels[1].attr('invisible', !showOrHide);
  59795. },
  59796. _onDragMove: function (handleIndex, dx, dy) {
  59797. this._dragging = true;
  59798. // Transform dx, dy to bar coordination.
  59799. var barTransform = this._displayables.barGroup.getLocalTransform();
  59800. var vertex = applyTransform$1([dx, dy], barTransform, true);
  59801. this._updateInterval(handleIndex, vertex[0]);
  59802. var realtime = this.dataZoomModel.get('realtime');
  59803. this._updateView(!realtime);
  59804. realtime && this._dispatchZoomAction();
  59805. },
  59806. _onDragEnd: function () {
  59807. this._dragging = false;
  59808. this._showDataInfo(false);
  59809. // While in realtime mode and stream mode, dispatch action when
  59810. // drag end will cause the whole view rerender, which is unnecessary.
  59811. var realtime = this.dataZoomModel.get('realtime');
  59812. !realtime && this._dispatchZoomAction();
  59813. },
  59814. _onClickPanelClick: function (e) {
  59815. var size = this._size;
  59816. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  59817. if (localPoint[0] < 0 || localPoint[0] > size[0]
  59818. || localPoint[1] < 0 || localPoint[1] > size[1]
  59819. ) {
  59820. return;
  59821. }
  59822. var handleEnds = this._handleEnds;
  59823. var center = (handleEnds[0] + handleEnds[1]) / 2;
  59824. this._updateInterval('all', localPoint[0] - center);
  59825. this._updateView();
  59826. this._dispatchZoomAction();
  59827. },
  59828. /**
  59829. * This action will be throttled.
  59830. * @private
  59831. */
  59832. _dispatchZoomAction: function () {
  59833. var range = this._range;
  59834. this.api.dispatchAction({
  59835. type: 'dataZoom',
  59836. from: this.uid,
  59837. dataZoomId: this.dataZoomModel.id,
  59838. start: range[0],
  59839. end: range[1]
  59840. });
  59841. },
  59842. /**
  59843. * @private
  59844. */
  59845. _findCoordRect: function () {
  59846. // Find the grid coresponding to the first axis referred by dataZoom.
  59847. var rect;
  59848. each$24(this.getTargetCoordInfo(), function (coordInfoList) {
  59849. if (!rect && coordInfoList.length) {
  59850. var coordSys = coordInfoList[0].model.coordinateSystem;
  59851. rect = coordSys.getRect && coordSys.getRect();
  59852. }
  59853. });
  59854. if (!rect) {
  59855. var width = this.api.getWidth();
  59856. var height = this.api.getHeight();
  59857. rect = {
  59858. x: width * 0.2,
  59859. y: height * 0.2,
  59860. width: width * 0.6,
  59861. height: height * 0.6
  59862. };
  59863. }
  59864. return rect;
  59865. }
  59866. });
  59867. function getOtherDim(thisDim) {
  59868. // FIXME
  59869. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  59870. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  59871. return map$$1[thisDim];
  59872. }
  59873. function getCursor(orient) {
  59874. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  59875. }
  59876. DataZoomModel.extend({
  59877. type: 'dataZoom.inside',
  59878. /**
  59879. * @protected
  59880. */
  59881. defaultOption: {
  59882. disabled: false, // Whether disable this inside zoom.
  59883. zoomLock: false, // Whether disable zoom but only pan.
  59884. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  59885. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  59886. preventDefaultMouseMove: true
  59887. }
  59888. });
  59889. // Only create one roam controller for each coordinate system.
  59890. // one roam controller might be refered by two inside data zoom
  59891. // components (for example, one for x and one for y). When user
  59892. // pan or zoom, only dispatch one action for those data zoom
  59893. // components.
  59894. var curry$6 = curry;
  59895. var ATTR$1 = '\0_ec_dataZoom_roams';
  59896. /**
  59897. * @public
  59898. * @param {module:echarts/ExtensionAPI} api
  59899. * @param {Object} dataZoomInfo
  59900. * @param {string} dataZoomInfo.coordId
  59901. * @param {Function} dataZoomInfo.containsPoint
  59902. * @param {Array.<string>} dataZoomInfo.allCoordIds
  59903. * @param {string} dataZoomInfo.dataZoomId
  59904. * @param {number} dataZoomInfo.throttleRate
  59905. * @param {Function} dataZoomInfo.panGetRange
  59906. * @param {Function} dataZoomInfo.zoomGetRange
  59907. * @param {boolean} [dataZoomInfo.zoomLock]
  59908. * @param {boolean} [dataZoomInfo.disabled]
  59909. */
  59910. function register$2(api, dataZoomInfo) {
  59911. var store = giveStore(api);
  59912. var theDataZoomId = dataZoomInfo.dataZoomId;
  59913. var theCoordId = dataZoomInfo.coordId;
  59914. // Do clean when a dataZoom changes its target coordnate system.
  59915. // Avoid memory leak, dispose all not-used-registered.
  59916. each$1(store, function (record, coordId) {
  59917. var dataZoomInfos = record.dataZoomInfos;
  59918. if (dataZoomInfos[theDataZoomId]
  59919. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  59920. ) {
  59921. delete dataZoomInfos[theDataZoomId];
  59922. record.count--;
  59923. }
  59924. });
  59925. cleanStore(store);
  59926. var record = store[theCoordId];
  59927. // Create if needed.
  59928. if (!record) {
  59929. record = store[theCoordId] = {
  59930. coordId: theCoordId,
  59931. dataZoomInfos: {},
  59932. count: 0
  59933. };
  59934. record.controller = createController(api, record);
  59935. record.dispatchAction = curry(dispatchAction$1, api);
  59936. }
  59937. // Update reference of dataZoom.
  59938. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  59939. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  59940. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  59941. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  59942. // Consider resize, area should be always updated.
  59943. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  59944. // Update throttle.
  59945. createOrUpdate(
  59946. record,
  59947. 'dispatchAction',
  59948. dataZoomInfo.throttleRate,
  59949. 'fixRate'
  59950. );
  59951. }
  59952. /**
  59953. * @public
  59954. * @param {module:echarts/ExtensionAPI} api
  59955. * @param {string} dataZoomId
  59956. */
  59957. function unregister$1(api, dataZoomId) {
  59958. var store = giveStore(api);
  59959. each$1(store, function (record) {
  59960. record.controller.dispose();
  59961. var dataZoomInfos = record.dataZoomInfos;
  59962. if (dataZoomInfos[dataZoomId]) {
  59963. delete dataZoomInfos[dataZoomId];
  59964. record.count--;
  59965. }
  59966. });
  59967. cleanStore(store);
  59968. }
  59969. /**
  59970. * @public
  59971. */
  59972. function shouldRecordRange(payload, dataZoomId) {
  59973. if (payload && payload.type === 'dataZoom' && payload.batch) {
  59974. for (var i = 0, len = payload.batch.length; i < len; i++) {
  59975. if (payload.batch[i].dataZoomId === dataZoomId) {
  59976. return false;
  59977. }
  59978. }
  59979. }
  59980. return true;
  59981. }
  59982. /**
  59983. * @public
  59984. */
  59985. function generateCoordId(coordModel) {
  59986. return coordModel.type + '\0_' + coordModel.id;
  59987. }
  59988. /**
  59989. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  59990. * @type {Array.<Object>}
  59991. */
  59992. function giveStore(api) {
  59993. // Mount store on zrender instance, so that we do not
  59994. // need to worry about dispose.
  59995. var zr = api.getZr();
  59996. return zr[ATTR$1] || (zr[ATTR$1] = {});
  59997. }
  59998. function createController(api, newRecord) {
  59999. var controller = new RoamController(api.getZr());
  60000. controller.on('pan', curry$6(onPan, newRecord));
  60001. controller.on('zoom', curry$6(onZoom, newRecord));
  60002. return controller;
  60003. }
  60004. function cleanStore(store) {
  60005. each$1(store, function (record, coordId) {
  60006. if (!record.count) {
  60007. record.controller.dispose();
  60008. delete store[coordId];
  60009. }
  60010. });
  60011. }
  60012. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  60013. wrapAndDispatch(record, function (info) {
  60014. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  60015. });
  60016. }
  60017. function onZoom(record, scale, mouseX, mouseY) {
  60018. wrapAndDispatch(record, function (info) {
  60019. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  60020. });
  60021. }
  60022. function wrapAndDispatch(record, getRange) {
  60023. var batch = [];
  60024. each$1(record.dataZoomInfos, function (info) {
  60025. var range = getRange(info);
  60026. !info.disabled && range && batch.push({
  60027. dataZoomId: info.dataZoomId,
  60028. start: range[0],
  60029. end: range[1]
  60030. });
  60031. });
  60032. record.dispatchAction(batch);
  60033. }
  60034. /**
  60035. * This action will be throttled.
  60036. */
  60037. function dispatchAction$1(api, batch) {
  60038. api.dispatchAction({
  60039. type: 'dataZoom',
  60040. batch: batch
  60041. });
  60042. }
  60043. /**
  60044. * Merge roamController settings when multiple dataZooms share one roamController.
  60045. */
  60046. function mergeControllerParams(dataZoomInfos) {
  60047. var controlType;
  60048. var opt = {};
  60049. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  60050. // as string, it is probably revert to reserved word by compress tool. See #7411.
  60051. var prefix = 'type_';
  60052. var typePriority = {
  60053. 'type_true': 2,
  60054. 'type_move': 1,
  60055. 'type_false': 0,
  60056. 'type_undefined': -1
  60057. };
  60058. each$1(dataZoomInfos, function (dataZoomInfo) {
  60059. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  60060. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  60061. controlType = oneType;
  60062. }
  60063. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  60064. extend(opt, dataZoomInfo.roamControllerOpt);
  60065. });
  60066. return {
  60067. controlType: controlType,
  60068. opt: opt
  60069. };
  60070. }
  60071. var bind$5 = bind;
  60072. var InsideZoomView = DataZoomView.extend({
  60073. type: 'dataZoom.inside',
  60074. /**
  60075. * @override
  60076. */
  60077. init: function (ecModel, api) {
  60078. /**
  60079. * 'throttle' is used in this.dispatchAction, so we save range
  60080. * to avoid missing some 'pan' info.
  60081. * @private
  60082. * @type {Array.<number>}
  60083. */
  60084. this._range;
  60085. },
  60086. /**
  60087. * @override
  60088. */
  60089. render: function (dataZoomModel, ecModel, api, payload) {
  60090. InsideZoomView.superApply(this, 'render', arguments);
  60091. // Notice: origin this._range should be maintained, and should not be re-fetched
  60092. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  60093. // info will be missed because of 'throttle' of this.dispatchAction.
  60094. if (shouldRecordRange(payload, dataZoomModel.id)) {
  60095. this._range = dataZoomModel.getPercentRange();
  60096. }
  60097. // Reset controllers.
  60098. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  60099. var allCoordIds = map(coordInfoList, function (coordInfo) {
  60100. return generateCoordId(coordInfo.model);
  60101. });
  60102. each$1(coordInfoList, function (coordInfo) {
  60103. var coordModel = coordInfo.model;
  60104. var dataZoomOption = dataZoomModel.option;
  60105. register$2(
  60106. api,
  60107. {
  60108. coordId: generateCoordId(coordModel),
  60109. allCoordIds: allCoordIds,
  60110. containsPoint: function (e, x, y) {
  60111. return coordModel.coordinateSystem.containPoint([x, y]);
  60112. },
  60113. dataZoomId: dataZoomModel.id,
  60114. throttleRate: dataZoomModel.get('throttle', true),
  60115. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  60116. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  60117. zoomLock: dataZoomOption.zoomLock,
  60118. disabled: dataZoomOption.disabled,
  60119. roamControllerOpt: {
  60120. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  60121. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  60122. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  60123. }
  60124. }
  60125. );
  60126. }, this);
  60127. }, this);
  60128. },
  60129. /**
  60130. * @override
  60131. */
  60132. dispose: function () {
  60133. unregister$1(this.api, this.dataZoomModel.id);
  60134. InsideZoomView.superApply(this, 'dispose', arguments);
  60135. this._range = null;
  60136. },
  60137. /**
  60138. * @private
  60139. */
  60140. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  60141. var range = this._range.slice();
  60142. // Calculate transform by the first axis.
  60143. var axisModel = coordInfo.axisModels[0];
  60144. if (!axisModel) {
  60145. return;
  60146. }
  60147. var directionInfo = getDirectionInfo[coordSysName](
  60148. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  60149. );
  60150. var percentDelta = directionInfo.signal
  60151. * (range[1] - range[0])
  60152. * directionInfo.pixel / directionInfo.pixelLength;
  60153. sliderMove(percentDelta, range, [0, 100], 'all');
  60154. return (this._range = range);
  60155. },
  60156. /**
  60157. * @private
  60158. */
  60159. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  60160. var range = this._range.slice();
  60161. // Calculate transform by the first axis.
  60162. var axisModel = coordInfo.axisModels[0];
  60163. if (!axisModel) {
  60164. return;
  60165. }
  60166. var directionInfo = getDirectionInfo[coordSysName](
  60167. null, [mouseX, mouseY], axisModel, controller, coordInfo
  60168. );
  60169. var percentPoint = (
  60170. directionInfo.signal > 0
  60171. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  60172. : (directionInfo.pixel - directionInfo.pixelStart)
  60173. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  60174. scale = Math.max(1 / scale, 0);
  60175. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  60176. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  60177. // Restrict range.
  60178. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  60179. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  60180. return (this._range = range);
  60181. }
  60182. });
  60183. var getDirectionInfo = {
  60184. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  60185. var axis = axisModel.axis;
  60186. var ret = {};
  60187. var rect = coordInfo.model.coordinateSystem.getRect();
  60188. oldPoint = oldPoint || [0, 0];
  60189. if (axis.dim === 'x') {
  60190. ret.pixel = newPoint[0] - oldPoint[0];
  60191. ret.pixelLength = rect.width;
  60192. ret.pixelStart = rect.x;
  60193. ret.signal = axis.inverse ? 1 : -1;
  60194. }
  60195. else { // axis.dim === 'y'
  60196. ret.pixel = newPoint[1] - oldPoint[1];
  60197. ret.pixelLength = rect.height;
  60198. ret.pixelStart = rect.y;
  60199. ret.signal = axis.inverse ? -1 : 1;
  60200. }
  60201. return ret;
  60202. },
  60203. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  60204. var axis = axisModel.axis;
  60205. var ret = {};
  60206. var polar = coordInfo.model.coordinateSystem;
  60207. var radiusExtent = polar.getRadiusAxis().getExtent();
  60208. var angleExtent = polar.getAngleAxis().getExtent();
  60209. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  60210. newPoint = polar.pointToCoord(newPoint);
  60211. if (axisModel.mainType === 'radiusAxis') {
  60212. ret.pixel = newPoint[0] - oldPoint[0];
  60213. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  60214. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  60215. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  60216. ret.pixelStart = radiusExtent[0];
  60217. ret.signal = axis.inverse ? 1 : -1;
  60218. }
  60219. else { // 'angleAxis'
  60220. ret.pixel = newPoint[1] - oldPoint[1];
  60221. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  60222. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  60223. ret.pixelLength = angleExtent[1] - angleExtent[0];
  60224. ret.pixelStart = angleExtent[0];
  60225. ret.signal = axis.inverse ? -1 : 1;
  60226. }
  60227. return ret;
  60228. },
  60229. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  60230. var axis = axisModel.axis;
  60231. var rect = coordInfo.model.coordinateSystem.getRect();
  60232. var ret = {};
  60233. oldPoint = oldPoint || [0, 0];
  60234. if (axis.orient === 'horizontal') {
  60235. ret.pixel = newPoint[0] - oldPoint[0];
  60236. ret.pixelLength = rect.width;
  60237. ret.pixelStart = rect.x;
  60238. ret.signal = axis.inverse ? 1 : -1;
  60239. }
  60240. else { // 'vertical'
  60241. ret.pixel = newPoint[1] - oldPoint[1];
  60242. ret.pixelLength = rect.height;
  60243. ret.pixelStart = rect.y;
  60244. ret.signal = axis.inverse ? -1 : 1;
  60245. }
  60246. return ret;
  60247. }
  60248. };
  60249. registerProcessor({
  60250. getTargetSeries: function (ecModel) {
  60251. var seriesModelMap = createHashMap();
  60252. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  60253. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  60254. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  60255. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  60256. seriesModelMap.set(seriesModel.uid, seriesModel);
  60257. });
  60258. });
  60259. });
  60260. return seriesModelMap;
  60261. },
  60262. isOverallFilter: true,
  60263. // Consider appendData, where filter should be performed. Because data process is
  60264. // in block mode currently, it is not need to worry about that the overallProgress
  60265. // execute every frame.
  60266. overallReset: function (ecModel, api) {
  60267. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  60268. // We calculate window and reset axis here but not in model
  60269. // init stage and not after action dispatch handler, because
  60270. // reset should be called after seriesData.restoreData.
  60271. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  60272. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  60273. });
  60274. // Caution: data zoom filtering is order sensitive when using
  60275. // percent range and no min/max/scale set on axis.
  60276. // For example, we have dataZoom definition:
  60277. // [
  60278. // {xAxisIndex: 0, start: 30, end: 70},
  60279. // {yAxisIndex: 0, start: 20, end: 80}
  60280. // ]
  60281. // In this case, [20, 80] of y-dataZoom should be based on data
  60282. // that have filtered by x-dataZoom using range of [30, 70],
  60283. // but should not be based on full raw data. Thus sliding
  60284. // x-dataZoom will change both ranges of xAxis and yAxis,
  60285. // while sliding y-dataZoom will only change the range of yAxis.
  60286. // So we should filter x-axis after reset x-axis immediately,
  60287. // and then reset y-axis and filter y-axis.
  60288. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  60289. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  60290. });
  60291. });
  60292. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  60293. // Fullfill all of the range props so that user
  60294. // is able to get them from chart.getOption().
  60295. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  60296. var percentRange = axisProxy.getDataPercentWindow();
  60297. var valueRange = axisProxy.getDataValueWindow();
  60298. dataZoomModel.setRawRange({
  60299. start: percentRange[0],
  60300. end: percentRange[1],
  60301. startValue: valueRange[0],
  60302. endValue: valueRange[1]
  60303. }, true);
  60304. });
  60305. }
  60306. });
  60307. registerAction('dataZoom', function (payload, ecModel) {
  60308. var linkedNodesFinder = createLinkedNodesFinder(
  60309. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  60310. eachAxisDim$1,
  60311. function (model, dimNames) {
  60312. return model.get(dimNames.axisIndex);
  60313. }
  60314. );
  60315. var effectedModels = [];
  60316. ecModel.eachComponent(
  60317. {mainType: 'dataZoom', query: payload},
  60318. function (model, index) {
  60319. effectedModels.push.apply(
  60320. effectedModels, linkedNodesFinder(model).nodes
  60321. );
  60322. }
  60323. );
  60324. each$1(effectedModels, function (dataZoomModel, index) {
  60325. dataZoomModel.setRawRange({
  60326. start: payload.start,
  60327. end: payload.end,
  60328. startValue: payload.startValue,
  60329. endValue: payload.endValue
  60330. });
  60331. });
  60332. });
  60333. /**
  60334. * DataZoom component entry
  60335. */
  60336. var each$25 = each$1;
  60337. var preprocessor$2 = function (option) {
  60338. var visualMap = option && option.visualMap;
  60339. if (!isArray(visualMap)) {
  60340. visualMap = visualMap ? [visualMap] : [];
  60341. }
  60342. each$25(visualMap, function (opt) {
  60343. if (!opt) {
  60344. return;
  60345. }
  60346. // rename splitList to pieces
  60347. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  60348. opt.pieces = opt.splitList;
  60349. delete opt.splitList;
  60350. }
  60351. var pieces = opt.pieces;
  60352. if (pieces && isArray(pieces)) {
  60353. each$25(pieces, function (piece) {
  60354. if (isObject$1(piece)) {
  60355. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  60356. piece.min = piece.start;
  60357. }
  60358. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  60359. piece.max = piece.end;
  60360. }
  60361. }
  60362. });
  60363. }
  60364. });
  60365. };
  60366. function has$1(obj, name) {
  60367. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  60368. }
  60369. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  60370. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  60371. return (
  60372. !option.categories
  60373. && (
  60374. !(
  60375. option.pieces
  60376. ? option.pieces.length > 0
  60377. : option.splitNumber > 0
  60378. )
  60379. || option.calculable
  60380. )
  60381. )
  60382. ? 'continuous' : 'piecewise';
  60383. });
  60384. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  60385. registerVisual(VISUAL_PRIORITY, {
  60386. createOnAllSeries: true,
  60387. reset: function (seriesModel, ecModel) {
  60388. var resetDefines = [];
  60389. ecModel.eachComponent('visualMap', function (visualMapModel) {
  60390. if (!visualMapModel.isTargetSeries(seriesModel)) {
  60391. return;
  60392. }
  60393. resetDefines.push(incrementalApplyVisual(
  60394. visualMapModel.stateList,
  60395. visualMapModel.targetVisuals,
  60396. bind(visualMapModel.getValueState, visualMapModel),
  60397. visualMapModel.getDataDimension(seriesModel.getData())
  60398. ));
  60399. });
  60400. return resetDefines;
  60401. }
  60402. });
  60403. // Only support color.
  60404. registerVisual(VISUAL_PRIORITY, {
  60405. createOnAllSeries: true,
  60406. reset: function (seriesModel, ecModel) {
  60407. var data = seriesModel.getData();
  60408. var visualMetaList = [];
  60409. ecModel.eachComponent('visualMap', function (visualMapModel) {
  60410. if (visualMapModel.isTargetSeries(seriesModel)) {
  60411. var visualMeta = visualMapModel.getVisualMeta(
  60412. bind(getColorVisual, null, seriesModel, visualMapModel)
  60413. ) || {stops: [], outerColors: []};
  60414. var concreteDim = visualMapModel.getDataDimension(data);
  60415. var dimInfo = data.getDimensionInfo(concreteDim);
  60416. if (dimInfo != null) {
  60417. // visualMeta.dimension should be dimension index, but not concrete dimension.
  60418. visualMeta.dimension = dimInfo.index;
  60419. visualMetaList.push(visualMeta);
  60420. }
  60421. }
  60422. });
  60423. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  60424. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  60425. }
  60426. });
  60427. // FIXME
  60428. // performance and export for heatmap?
  60429. // value can be Infinity or -Infinity
  60430. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  60431. var mappings = visualMapModel.targetVisuals[valueState];
  60432. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  60433. var resultVisual = {
  60434. color: seriesModel.getData().getVisual('color') // default color.
  60435. };
  60436. for (var i = 0, len = visualTypes.length; i < len; i++) {
  60437. var type = visualTypes[i];
  60438. var mapping = mappings[
  60439. type === 'opacity' ? '__alphaForOpacity' : type
  60440. ];
  60441. mapping && mapping.applyVisual(value, getVisual, setVisual);
  60442. }
  60443. return resultVisual.color;
  60444. function getVisual(key) {
  60445. return resultVisual[key];
  60446. }
  60447. function setVisual(key, value) {
  60448. resultVisual[key] = value;
  60449. }
  60450. }
  60451. /**
  60452. * @file Visual mapping.
  60453. */
  60454. var visualDefault = {
  60455. /**
  60456. * @public
  60457. */
  60458. get: function (visualType, key, isCategory) {
  60459. var value = clone(
  60460. (defaultOption$3[visualType] || {})[key]
  60461. );
  60462. return isCategory
  60463. ? (isArray(value) ? value[value.length - 1] : value)
  60464. : value;
  60465. }
  60466. };
  60467. var defaultOption$3 = {
  60468. color: {
  60469. active: ['#006edd', '#e0ffff'],
  60470. inactive: ['rgba(0,0,0,0)']
  60471. },
  60472. colorHue: {
  60473. active: [0, 360],
  60474. inactive: [0, 0]
  60475. },
  60476. colorSaturation: {
  60477. active: [0.3, 1],
  60478. inactive: [0, 0]
  60479. },
  60480. colorLightness: {
  60481. active: [0.9, 0.5],
  60482. inactive: [0, 0]
  60483. },
  60484. colorAlpha: {
  60485. active: [0.3, 1],
  60486. inactive: [0, 0]
  60487. },
  60488. opacity: {
  60489. active: [0.3, 1],
  60490. inactive: [0, 0]
  60491. },
  60492. symbol: {
  60493. active: ['circle', 'roundRect', 'diamond'],
  60494. inactive: ['none']
  60495. },
  60496. symbolSize: {
  60497. active: [10, 50],
  60498. inactive: [0, 0]
  60499. }
  60500. };
  60501. var mapVisual$2 = VisualMapping.mapVisual;
  60502. var eachVisual = VisualMapping.eachVisual;
  60503. var isArray$3 = isArray;
  60504. var each$26 = each$1;
  60505. var asc$3 = asc;
  60506. var linearMap$3 = linearMap;
  60507. var noop$2 = noop;
  60508. var VisualMapModel = extendComponentModel({
  60509. type: 'visualMap',
  60510. dependencies: ['series'],
  60511. /**
  60512. * @readOnly
  60513. * @type {Array.<string>}
  60514. */
  60515. stateList: ['inRange', 'outOfRange'],
  60516. /**
  60517. * @readOnly
  60518. * @type {Array.<string>}
  60519. */
  60520. replacableOptionKeys: [
  60521. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  60522. ],
  60523. /**
  60524. * [lowerBound, upperBound]
  60525. *
  60526. * @readOnly
  60527. * @type {Array.<number>}
  60528. */
  60529. dataBound: [-Infinity, Infinity],
  60530. /**
  60531. * @readOnly
  60532. * @type {string|Object}
  60533. */
  60534. layoutMode: {type: 'box', ignoreSize: true},
  60535. /**
  60536. * @protected
  60537. */
  60538. defaultOption: {
  60539. show: true,
  60540. zlevel: 0,
  60541. z: 4,
  60542. seriesIndex: 'all', // 'all' or null/undefined: all series.
  60543. // A number or an array of number: the specified series.
  60544. // set min: 0, max: 200, only for campatible with ec2.
  60545. // In fact min max should not have default value.
  60546. min: 0, // min value, must specified if pieces is not specified.
  60547. max: 200, // max value, must specified if pieces is not specified.
  60548. dimension: null,
  60549. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  60550. // 'symbol', 'symbolSize'
  60551. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  60552. // 'colorLightness', 'colorAlpha',
  60553. // 'symbol', 'symbolSize'
  60554. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  60555. right: null, // The same as left.
  60556. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  60557. bottom: 0, // The same as top.
  60558. itemWidth: null,
  60559. itemHeight: null,
  60560. inverse: false,
  60561. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  60562. backgroundColor: 'rgba(0,0,0,0)',
  60563. borderColor: '#ccc', // 值域边框颜色
  60564. contentColor: '#5793f3',
  60565. inactiveColor: '#aaa',
  60566. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  60567. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  60568. // 接受数组分别设定上右下左边距,同css
  60569. textGap: 10, //
  60570. precision: 0, // 小数精度,默认为0,无小数点
  60571. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  60572. formatter: null,
  60573. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  60574. textStyle: {
  60575. color: '#333' // 值域文字颜色
  60576. }
  60577. },
  60578. /**
  60579. * @protected
  60580. */
  60581. init: function (option, parentModel, ecModel) {
  60582. /**
  60583. * @private
  60584. * @type {Array.<number>}
  60585. */
  60586. this._dataExtent;
  60587. /**
  60588. * @readOnly
  60589. */
  60590. this.targetVisuals = {};
  60591. /**
  60592. * @readOnly
  60593. */
  60594. this.controllerVisuals = {};
  60595. /**
  60596. * @readOnly
  60597. */
  60598. this.textStyleModel;
  60599. /**
  60600. * [width, height]
  60601. * @readOnly
  60602. * @type {Array.<number>}
  60603. */
  60604. this.itemSize;
  60605. this.mergeDefaultAndTheme(option, ecModel);
  60606. },
  60607. /**
  60608. * @protected
  60609. */
  60610. optionUpdated: function (newOption, isInit) {
  60611. var thisOption = this.option;
  60612. // FIXME
  60613. // necessary?
  60614. // Disable realtime view update if canvas is not supported.
  60615. if (!env$1.canvasSupported) {
  60616. thisOption.realtime = false;
  60617. }
  60618. !isInit && replaceVisualOption(
  60619. thisOption, newOption, this.replacableOptionKeys
  60620. );
  60621. this.textStyleModel = this.getModel('textStyle');
  60622. this.resetItemSize();
  60623. this.completeVisualOption();
  60624. },
  60625. /**
  60626. * @protected
  60627. */
  60628. resetVisual: function (supplementVisualOption) {
  60629. var stateList = this.stateList;
  60630. supplementVisualOption = bind(supplementVisualOption, this);
  60631. this.controllerVisuals = createVisualMappings(
  60632. this.option.controller, stateList, supplementVisualOption
  60633. );
  60634. this.targetVisuals = createVisualMappings(
  60635. this.option.target, stateList, supplementVisualOption
  60636. );
  60637. },
  60638. /**
  60639. * @protected
  60640. * @return {Array.<number>} An array of series indices.
  60641. */
  60642. getTargetSeriesIndices: function () {
  60643. var optionSeriesIndex = this.option.seriesIndex;
  60644. var seriesIndices = [];
  60645. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  60646. this.ecModel.eachSeries(function (seriesModel, index) {
  60647. seriesIndices.push(index);
  60648. });
  60649. }
  60650. else {
  60651. seriesIndices = normalizeToArray(optionSeriesIndex);
  60652. }
  60653. return seriesIndices;
  60654. },
  60655. /**
  60656. * @public
  60657. */
  60658. eachTargetSeries: function (callback, context) {
  60659. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  60660. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  60661. }, this);
  60662. },
  60663. /**
  60664. * @pubilc
  60665. */
  60666. isTargetSeries: function (seriesModel) {
  60667. var is = false;
  60668. this.eachTargetSeries(function (model) {
  60669. model === seriesModel && (is = true);
  60670. });
  60671. return is;
  60672. },
  60673. /**
  60674. * @example
  60675. * this.formatValueText(someVal); // format single numeric value to text.
  60676. * this.formatValueText(someVal, true); // format single category value to text.
  60677. * this.formatValueText([min, max]); // format numeric min-max to text.
  60678. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  60679. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  60680. *
  60681. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  60682. * @param {boolean} [isCategory=false] Only available when value is number.
  60683. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  60684. * @return {string}
  60685. * @protected
  60686. */
  60687. formatValueText: function(value, isCategory, edgeSymbols) {
  60688. var option = this.option;
  60689. var precision = option.precision;
  60690. var dataBound = this.dataBound;
  60691. var formatter = option.formatter;
  60692. var isMinMax;
  60693. var textValue;
  60694. edgeSymbols = edgeSymbols || ['<', '>'];
  60695. if (isArray(value)) {
  60696. value = value.slice();
  60697. isMinMax = true;
  60698. }
  60699. textValue = isCategory
  60700. ? value
  60701. : (isMinMax
  60702. ? [toFixed(value[0]), toFixed(value[1])]
  60703. : toFixed(value)
  60704. );
  60705. if (isString(formatter)) {
  60706. return formatter
  60707. .replace('{value}', isMinMax ? textValue[0] : textValue)
  60708. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  60709. }
  60710. else if (isFunction$1(formatter)) {
  60711. return isMinMax
  60712. ? formatter(value[0], value[1])
  60713. : formatter(value);
  60714. }
  60715. if (isMinMax) {
  60716. if (value[0] === dataBound[0]) {
  60717. return edgeSymbols[0] + ' ' + textValue[1];
  60718. }
  60719. else if (value[1] === dataBound[1]) {
  60720. return edgeSymbols[1] + ' ' + textValue[0];
  60721. }
  60722. else {
  60723. return textValue[0] + ' - ' + textValue[1];
  60724. }
  60725. }
  60726. else { // Format single value (includes category case).
  60727. return textValue;
  60728. }
  60729. function toFixed(val) {
  60730. return val === dataBound[0]
  60731. ? 'min'
  60732. : val === dataBound[1]
  60733. ? 'max'
  60734. : (+val).toFixed(Math.min(precision, 20));
  60735. }
  60736. },
  60737. /**
  60738. * @protected
  60739. */
  60740. resetExtent: function () {
  60741. var thisOption = this.option;
  60742. // Can not calculate data extent by data here.
  60743. // Because series and data may be modified in processing stage.
  60744. // So we do not support the feature "auto min/max".
  60745. var extent = asc$3([thisOption.min, thisOption.max]);
  60746. this._dataExtent = extent;
  60747. },
  60748. /**
  60749. * @public
  60750. * @param {module:echarts/data/List} list
  60751. * @return {string} Concrete dimention. If return null/undefined,
  60752. * no dimension used.
  60753. */
  60754. getDataDimension: function (list) {
  60755. var optDim = this.option.dimension;
  60756. var listDimensions = list.dimensions;
  60757. if (optDim == null && !listDimensions.length) {
  60758. return;
  60759. }
  60760. return list.getDimension(
  60761. optDim != null ? optDim : listDimensions.length - 1
  60762. );
  60763. },
  60764. /**
  60765. * @public
  60766. * @override
  60767. */
  60768. getExtent: function () {
  60769. return this._dataExtent.slice();
  60770. },
  60771. /**
  60772. * @protected
  60773. */
  60774. completeVisualOption: function () {
  60775. var ecModel = this.ecModel;
  60776. var thisOption = this.option;
  60777. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  60778. var target = thisOption.target || (thisOption.target = {});
  60779. var controller = thisOption.controller || (thisOption.controller = {});
  60780. merge(target, base); // Do not override
  60781. merge(controller, base); // Do not override
  60782. var isCategory = this.isCategory();
  60783. completeSingle.call(this, target);
  60784. completeSingle.call(this, controller);
  60785. completeInactive.call(this, target, 'inRange', 'outOfRange');
  60786. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  60787. completeController.call(this, controller);
  60788. function completeSingle(base) {
  60789. // Compatible with ec2 dataRange.color.
  60790. // The mapping order of dataRange.color is: [high value, ..., low value]
  60791. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  60792. // Notice: ec2 has no inverse.
  60793. if (isArray$3(thisOption.color)
  60794. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  60795. // So adding color only when no inRange defined.
  60796. && !base.inRange
  60797. ) {
  60798. base.inRange = {color: thisOption.color.slice().reverse()};
  60799. }
  60800. // Compatible with previous logic, always give a defautl color, otherwise
  60801. // simple config with no inRange and outOfRange will not work.
  60802. // Originally we use visualMap.color as the default color, but setOption at
  60803. // the second time the default color will be erased. So we change to use
  60804. // constant DEFAULT_COLOR.
  60805. // If user do not want the defualt color, set inRange: {color: null}.
  60806. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  60807. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  60808. each$26(this.stateList, function (state) {
  60809. var visualType = base[state];
  60810. if (isString(visualType)) {
  60811. var defa = visualDefault.get(visualType, 'active', isCategory);
  60812. if (defa) {
  60813. base[state] = {};
  60814. base[state][visualType] = defa;
  60815. }
  60816. else {
  60817. // Mark as not specified.
  60818. delete base[state];
  60819. }
  60820. }
  60821. }, this);
  60822. }
  60823. function completeInactive(base, stateExist, stateAbsent) {
  60824. var optExist = base[stateExist];
  60825. var optAbsent = base[stateAbsent];
  60826. if (optExist && !optAbsent) {
  60827. optAbsent = base[stateAbsent] = {};
  60828. each$26(optExist, function (visualData, visualType) {
  60829. if (!VisualMapping.isValidType(visualType)) {
  60830. return;
  60831. }
  60832. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  60833. if (defa != null) {
  60834. optAbsent[visualType] = defa;
  60835. // Compatibable with ec2:
  60836. // Only inactive color to rgba(0,0,0,0) can not
  60837. // make label transparent, so use opacity also.
  60838. if (visualType === 'color'
  60839. && !optAbsent.hasOwnProperty('opacity')
  60840. && !optAbsent.hasOwnProperty('colorAlpha')
  60841. ) {
  60842. optAbsent.opacity = [0, 0];
  60843. }
  60844. }
  60845. });
  60846. }
  60847. }
  60848. function completeController(controller) {
  60849. var symbolExists = (controller.inRange || {}).symbol
  60850. || (controller.outOfRange || {}).symbol;
  60851. var symbolSizeExists = (controller.inRange || {}).symbolSize
  60852. || (controller.outOfRange || {}).symbolSize;
  60853. var inactiveColor = this.get('inactiveColor');
  60854. each$26(this.stateList, function (state) {
  60855. var itemSize = this.itemSize;
  60856. var visuals = controller[state];
  60857. // Set inactive color for controller if no other color
  60858. // attr (like colorAlpha) specified.
  60859. if (!visuals) {
  60860. visuals = controller[state] = {
  60861. color: isCategory ? inactiveColor : [inactiveColor]
  60862. };
  60863. }
  60864. // Consistent symbol and symbolSize if not specified.
  60865. if (visuals.symbol == null) {
  60866. visuals.symbol = symbolExists
  60867. && clone(symbolExists)
  60868. || (isCategory ? 'roundRect' : ['roundRect']);
  60869. }
  60870. if (visuals.symbolSize == null) {
  60871. visuals.symbolSize = symbolSizeExists
  60872. && clone(symbolSizeExists)
  60873. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  60874. }
  60875. // Filter square and none.
  60876. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  60877. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  60878. });
  60879. // Normalize symbolSize
  60880. var symbolSize = visuals.symbolSize;
  60881. if (symbolSize != null) {
  60882. var max = -Infinity;
  60883. // symbolSize can be object when categories defined.
  60884. eachVisual(symbolSize, function (value) {
  60885. value > max && (max = value);
  60886. });
  60887. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  60888. return linearMap$3(value, [0, max], [0, itemSize[0]], true);
  60889. });
  60890. }
  60891. }, this);
  60892. }
  60893. },
  60894. /**
  60895. * @protected
  60896. */
  60897. resetItemSize: function () {
  60898. this.itemSize = [
  60899. parseFloat(this.get('itemWidth')),
  60900. parseFloat(this.get('itemHeight'))
  60901. ];
  60902. },
  60903. /**
  60904. * @public
  60905. */
  60906. isCategory: function () {
  60907. return !!this.option.categories;
  60908. },
  60909. /**
  60910. * @public
  60911. * @abstract
  60912. */
  60913. setSelected: noop$2,
  60914. /**
  60915. * @public
  60916. * @abstract
  60917. * @param {*|module:echarts/data/List} valueOrData
  60918. * @param {number} dataIndex
  60919. * @return {string} state See this.stateList
  60920. */
  60921. getValueState: noop$2,
  60922. /**
  60923. * FIXME
  60924. * Do not publish to thirt-part-dev temporarily
  60925. * util the interface is stable. (Should it return
  60926. * a function but not visual meta?)
  60927. *
  60928. * @pubilc
  60929. * @abstract
  60930. * @param {Function} getColorVisual
  60931. * params: value, valueState
  60932. * return: color
  60933. * @return {Object} visualMeta
  60934. * should includes {stops, outerColors}
  60935. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  60936. */
  60937. getVisualMeta: noop$2
  60938. });
  60939. // Constant
  60940. var DEFAULT_BAR_BOUND = [20, 140];
  60941. var ContinuousModel = VisualMapModel.extend({
  60942. type: 'visualMap.continuous',
  60943. /**
  60944. * @protected
  60945. */
  60946. defaultOption: {
  60947. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  60948. calculable: false, // This prop effect default component type determine,
  60949. // See echarts/component/visualMap/typeDefaulter.
  60950. range: null, // selected range. In default case `range` is [min, max]
  60951. // and can auto change along with modification of min max,
  60952. // util use specifid a range.
  60953. realtime: true, // Whether realtime update.
  60954. itemHeight: null, // The length of the range control edge.
  60955. itemWidth: null, // The length of the other side.
  60956. hoverLink: true, // Enable hover highlight.
  60957. hoverLinkDataSize: null,// The size of hovered data.
  60958. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  60959. // If not specified, follow the value of `realtime`.
  60960. },
  60961. /**
  60962. * @override
  60963. */
  60964. optionUpdated: function (newOption, isInit) {
  60965. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  60966. this.resetExtent();
  60967. this.resetVisual(function (mappingOption) {
  60968. mappingOption.mappingMethod = 'linear';
  60969. mappingOption.dataExtent = this.getExtent();
  60970. });
  60971. this._resetRange();
  60972. },
  60973. /**
  60974. * @protected
  60975. * @override
  60976. */
  60977. resetItemSize: function () {
  60978. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  60979. var itemSize = this.itemSize;
  60980. this._orient === 'horizontal' && itemSize.reverse();
  60981. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  60982. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  60983. },
  60984. /**
  60985. * @private
  60986. */
  60987. _resetRange: function () {
  60988. var dataExtent = this.getExtent();
  60989. var range = this.option.range;
  60990. if (!range || range.auto) {
  60991. // `range` should always be array (so we dont use other
  60992. // value like 'auto') for user-friend. (consider getOption).
  60993. dataExtent.auto = 1;
  60994. this.option.range = dataExtent;
  60995. }
  60996. else if (isArray(range)) {
  60997. if (range[0] > range[1]) {
  60998. range.reverse();
  60999. }
  61000. range[0] = Math.max(range[0], dataExtent[0]);
  61001. range[1] = Math.min(range[1], dataExtent[1]);
  61002. }
  61003. },
  61004. /**
  61005. * @protected
  61006. * @override
  61007. */
  61008. completeVisualOption: function () {
  61009. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  61010. each$1(this.stateList, function (state) {
  61011. var symbolSize = this.option.controller[state].symbolSize;
  61012. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  61013. symbolSize[0] = 0; // For good looking.
  61014. }
  61015. }, this);
  61016. },
  61017. /**
  61018. * @override
  61019. */
  61020. setSelected: function (selected) {
  61021. this.option.range = selected.slice();
  61022. this._resetRange();
  61023. },
  61024. /**
  61025. * @public
  61026. */
  61027. getSelected: function () {
  61028. var dataExtent = this.getExtent();
  61029. var dataInterval = asc(
  61030. (this.get('range') || []).slice()
  61031. );
  61032. // Clamp
  61033. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  61034. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  61035. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  61036. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  61037. return dataInterval;
  61038. },
  61039. /**
  61040. * @override
  61041. */
  61042. getValueState: function (value) {
  61043. var range = this.option.range;
  61044. var dataExtent = this.getExtent();
  61045. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  61046. // range[1] is processed likewise.
  61047. return (
  61048. (range[0] <= dataExtent[0] || range[0] <= value)
  61049. && (range[1] >= dataExtent[1] || value <= range[1])
  61050. ) ? 'inRange' : 'outOfRange';
  61051. },
  61052. /**
  61053. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  61054. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  61055. */
  61056. findTargetDataIndices: function (range) {
  61057. var result = [];
  61058. this.eachTargetSeries(function (seriesModel) {
  61059. var dataIndices = [];
  61060. var data = seriesModel.getData();
  61061. data.each(this.getDataDimension(data), function (value, dataIndex) {
  61062. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  61063. }, true, this);
  61064. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  61065. }, this);
  61066. return result;
  61067. },
  61068. /**
  61069. * @implement
  61070. */
  61071. getVisualMeta: function (getColorVisual) {
  61072. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  61073. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  61074. var stops = [];
  61075. function setStop(value, valueState) {
  61076. stops.push({
  61077. value: value,
  61078. color: getColorVisual(value, valueState)
  61079. });
  61080. }
  61081. // Format to: outOfRange -- inRange -- outOfRange.
  61082. var iIdx = 0;
  61083. var oIdx = 0;
  61084. var iLen = iVals.length;
  61085. var oLen = oVals.length;
  61086. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  61087. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  61088. if (oVals[oIdx] < iVals[iIdx]) {
  61089. setStop(oVals[oIdx], 'outOfRange');
  61090. }
  61091. }
  61092. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  61093. // If range is full, value beyond min, max will be clamped.
  61094. // make a singularity
  61095. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  61096. setStop(iVals[iIdx], 'inRange');
  61097. }
  61098. for (var first = 1; oIdx < oLen; oIdx++) {
  61099. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  61100. // make a singularity
  61101. if (first) {
  61102. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  61103. first = 0;
  61104. }
  61105. setStop(oVals[oIdx], 'outOfRange');
  61106. }
  61107. }
  61108. var stopsLen = stops.length;
  61109. return {
  61110. stops: stops,
  61111. outerColors: [
  61112. stopsLen ? stops[0].color : 'transparent',
  61113. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  61114. ]
  61115. };
  61116. }
  61117. });
  61118. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  61119. if (dataExtent[0] === dataExtent[1]) {
  61120. return dataExtent.slice();
  61121. }
  61122. // When using colorHue mapping, it is not linear color any more.
  61123. // Moreover, canvas gradient seems not to be accurate linear.
  61124. // FIXME
  61125. // Should be arbitrary value 100? or based on pixel size?
  61126. var count = 200;
  61127. var step = (dataExtent[1] - dataExtent[0]) / count;
  61128. var value = dataExtent[0];
  61129. var stopValues = [];
  61130. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  61131. stopValues.push(value);
  61132. value += step;
  61133. }
  61134. stopValues.push(dataExtent[1]);
  61135. return stopValues;
  61136. }
  61137. var VisualMapView = extendComponentView({
  61138. type: 'visualMap',
  61139. /**
  61140. * @readOnly
  61141. * @type {Object}
  61142. */
  61143. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  61144. init: function (ecModel, api) {
  61145. /**
  61146. * @readOnly
  61147. * @type {module:echarts/model/Global}
  61148. */
  61149. this.ecModel = ecModel;
  61150. /**
  61151. * @readOnly
  61152. * @type {module:echarts/ExtensionAPI}
  61153. */
  61154. this.api = api;
  61155. /**
  61156. * @readOnly
  61157. * @type {module:echarts/component/visualMap/visualMapModel}
  61158. */
  61159. this.visualMapModel;
  61160. },
  61161. /**
  61162. * @protected
  61163. */
  61164. render: function (visualMapModel, ecModel, api, payload) {
  61165. this.visualMapModel = visualMapModel;
  61166. if (visualMapModel.get('show') === false) {
  61167. this.group.removeAll();
  61168. return;
  61169. }
  61170. this.doRender.apply(this, arguments);
  61171. },
  61172. /**
  61173. * @protected
  61174. */
  61175. renderBackground: function (group) {
  61176. var visualMapModel = this.visualMapModel;
  61177. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  61178. var rect = group.getBoundingRect();
  61179. group.add(new Rect({
  61180. z2: -1, // Lay background rect on the lowest layer.
  61181. silent: true,
  61182. shape: {
  61183. x: rect.x - padding[3],
  61184. y: rect.y - padding[0],
  61185. width: rect.width + padding[3] + padding[1],
  61186. height: rect.height + padding[0] + padding[2]
  61187. },
  61188. style: {
  61189. fill: visualMapModel.get('backgroundColor'),
  61190. stroke: visualMapModel.get('borderColor'),
  61191. lineWidth: visualMapModel.get('borderWidth')
  61192. }
  61193. }));
  61194. },
  61195. /**
  61196. * @protected
  61197. * @param {number} targetValue can be Infinity or -Infinity
  61198. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  61199. * @param {Object} [opts]
  61200. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  61201. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  61202. * @return {*} Visual value.
  61203. */
  61204. getControllerVisual: function (targetValue, visualCluster, opts) {
  61205. opts = opts || {};
  61206. var forceState = opts.forceState;
  61207. var visualMapModel = this.visualMapModel;
  61208. var visualObj = {};
  61209. // Default values.
  61210. if (visualCluster === 'symbol') {
  61211. visualObj.symbol = visualMapModel.get('itemSymbol');
  61212. }
  61213. if (visualCluster === 'color') {
  61214. var defaultColor = visualMapModel.get('contentColor');
  61215. visualObj.color = defaultColor;
  61216. }
  61217. function getter(key) {
  61218. return visualObj[key];
  61219. }
  61220. function setter(key, value) {
  61221. visualObj[key] = value;
  61222. }
  61223. var mappings = visualMapModel.controllerVisuals[
  61224. forceState || visualMapModel.getValueState(targetValue)
  61225. ];
  61226. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  61227. each$1(visualTypes, function (type) {
  61228. var visualMapping = mappings[type];
  61229. if (opts.convertOpacityToAlpha && type === 'opacity') {
  61230. type = 'colorAlpha';
  61231. visualMapping = mappings.__alphaForOpacity;
  61232. }
  61233. if (VisualMapping.dependsOn(type, visualCluster)) {
  61234. visualMapping && visualMapping.applyVisual(
  61235. targetValue, getter, setter
  61236. );
  61237. }
  61238. });
  61239. return visualObj[visualCluster];
  61240. },
  61241. /**
  61242. * @protected
  61243. */
  61244. positionGroup: function (group) {
  61245. var model = this.visualMapModel;
  61246. var api = this.api;
  61247. positionElement(
  61248. group,
  61249. model.getBoxLayoutParams(),
  61250. {width: api.getWidth(), height: api.getHeight()}
  61251. );
  61252. },
  61253. /**
  61254. * @protected
  61255. * @abstract
  61256. */
  61257. doRender: noop
  61258. });
  61259. /**
  61260. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  61261. * @param {module:echarts/ExtensionAPI} api
  61262. * @param {Array.<number>} itemSize always [short, long]
  61263. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  61264. */
  61265. function getItemAlign(visualMapModel, api, itemSize) {
  61266. var modelOption = visualMapModel.option;
  61267. var itemAlign = modelOption.align;
  61268. if (itemAlign != null && itemAlign !== 'auto') {
  61269. return itemAlign;
  61270. }
  61271. // Auto decision align.
  61272. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  61273. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  61274. var paramsSet = [
  61275. ['left', 'right', 'width'],
  61276. ['top', 'bottom', 'height']
  61277. ];
  61278. var reals = paramsSet[realIndex];
  61279. var fakeValue = [0, null, 10];
  61280. var layoutInput = {};
  61281. for (var i = 0; i < 3; i++) {
  61282. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  61283. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  61284. }
  61285. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  61286. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  61287. return reals[
  61288. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  61289. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  61290. ];
  61291. }
  61292. /**
  61293. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  61294. * dataIndexInside means filtered index.
  61295. */
  61296. function convertDataIndex(batch) {
  61297. each$1(batch || [], function (batchItem) {
  61298. if (batch.dataIndex != null) {
  61299. batch.dataIndexInside = batch.dataIndex;
  61300. batch.dataIndex = null;
  61301. }
  61302. });
  61303. return batch;
  61304. }
  61305. var linearMap$4 = linearMap;
  61306. var each$27 = each$1;
  61307. var mathMin$7 = Math.min;
  61308. var mathMax$7 = Math.max;
  61309. // Arbitrary value
  61310. var HOVER_LINK_SIZE = 12;
  61311. var HOVER_LINK_OUT = 6;
  61312. // Notice:
  61313. // Any "interval" should be by the order of [low, high].
  61314. // "handle0" (handleIndex === 0) maps to
  61315. // low data value: this._dataInterval[0] and has low coord.
  61316. // "handle1" (handleIndex === 1) maps to
  61317. // high data value: this._dataInterval[1] and has high coord.
  61318. // The logic of transform is implemented in this._createBarGroup.
  61319. var ContinuousView = VisualMapView.extend({
  61320. type: 'visualMap.continuous',
  61321. /**
  61322. * @override
  61323. */
  61324. init: function () {
  61325. ContinuousView.superApply(this, 'init', arguments);
  61326. /**
  61327. * @private
  61328. */
  61329. this._shapes = {};
  61330. /**
  61331. * @private
  61332. */
  61333. this._dataInterval = [];
  61334. /**
  61335. * @private
  61336. */
  61337. this._handleEnds = [];
  61338. /**
  61339. * @private
  61340. */
  61341. this._orient;
  61342. /**
  61343. * @private
  61344. */
  61345. this._useHandle;
  61346. /**
  61347. * @private
  61348. */
  61349. this._hoverLinkDataIndices = [];
  61350. /**
  61351. * @private
  61352. */
  61353. this._dragging;
  61354. /**
  61355. * @private
  61356. */
  61357. this._hovering;
  61358. },
  61359. /**
  61360. * @protected
  61361. * @override
  61362. */
  61363. doRender: function (visualMapModel, ecModel, api, payload) {
  61364. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  61365. this._buildView();
  61366. }
  61367. },
  61368. /**
  61369. * @private
  61370. */
  61371. _buildView: function () {
  61372. this.group.removeAll();
  61373. var visualMapModel = this.visualMapModel;
  61374. var thisGroup = this.group;
  61375. this._orient = visualMapModel.get('orient');
  61376. this._useHandle = visualMapModel.get('calculable');
  61377. this._resetInterval();
  61378. this._renderBar(thisGroup);
  61379. var dataRangeText = visualMapModel.get('text');
  61380. this._renderEndsText(thisGroup, dataRangeText, 0);
  61381. this._renderEndsText(thisGroup, dataRangeText, 1);
  61382. // Do this for background size calculation.
  61383. this._updateView(true);
  61384. // After updating view, inner shapes is built completely,
  61385. // and then background can be rendered.
  61386. this.renderBackground(thisGroup);
  61387. // Real update view
  61388. this._updateView();
  61389. this._enableHoverLinkToSeries();
  61390. this._enableHoverLinkFromSeries();
  61391. this.positionGroup(thisGroup);
  61392. },
  61393. /**
  61394. * @private
  61395. */
  61396. _renderEndsText: function (group, dataRangeText, endsIndex) {
  61397. if (!dataRangeText) {
  61398. return;
  61399. }
  61400. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  61401. var text = dataRangeText[1 - endsIndex];
  61402. text = text != null ? text + '' : '';
  61403. var visualMapModel = this.visualMapModel;
  61404. var textGap = visualMapModel.get('textGap');
  61405. var itemSize = visualMapModel.itemSize;
  61406. var barGroup = this._shapes.barGroup;
  61407. var position = this._applyTransform(
  61408. [
  61409. itemSize[0] / 2,
  61410. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  61411. ],
  61412. barGroup
  61413. );
  61414. var align = this._applyTransform(
  61415. endsIndex === 0 ? 'bottom' : 'top',
  61416. barGroup
  61417. );
  61418. var orient = this._orient;
  61419. var textStyleModel = this.visualMapModel.textStyleModel;
  61420. this.group.add(new Text({
  61421. style: {
  61422. x: position[0],
  61423. y: position[1],
  61424. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  61425. textAlign: orient === 'horizontal' ? align : 'center',
  61426. text: text,
  61427. textFont: textStyleModel.getFont(),
  61428. textFill: textStyleModel.getTextColor()
  61429. }
  61430. }));
  61431. },
  61432. /**
  61433. * @private
  61434. */
  61435. _renderBar: function (targetGroup) {
  61436. var visualMapModel = this.visualMapModel;
  61437. var shapes = this._shapes;
  61438. var itemSize = visualMapModel.itemSize;
  61439. var orient = this._orient;
  61440. var useHandle = this._useHandle;
  61441. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  61442. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  61443. // Bar
  61444. barGroup.add(shapes.outOfRange = createPolygon());
  61445. barGroup.add(shapes.inRange = createPolygon(
  61446. null,
  61447. useHandle ? getCursor$1(this._orient) : null,
  61448. bind(this._dragHandle, this, 'all', false),
  61449. bind(this._dragHandle, this, 'all', true)
  61450. ));
  61451. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  61452. var textSize = mathMax$7(textRect.width, textRect.height);
  61453. // Handle
  61454. if (useHandle) {
  61455. shapes.handleThumbs = [];
  61456. shapes.handleLabels = [];
  61457. shapes.handleLabelPoints = [];
  61458. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  61459. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  61460. }
  61461. this._createIndicator(barGroup, itemSize, textSize, orient);
  61462. targetGroup.add(barGroup);
  61463. },
  61464. /**
  61465. * @private
  61466. */
  61467. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  61468. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  61469. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  61470. var handleThumb = createPolygon(
  61471. createHandlePoints(handleIndex, textSize),
  61472. getCursor$1(this._orient),
  61473. onDrift,
  61474. onDragEnd
  61475. );
  61476. handleThumb.position[0] = itemSize[0];
  61477. barGroup.add(handleThumb);
  61478. // Text is always horizontal layout but should not be effected by
  61479. // transform (orient/inverse). So label is built separately but not
  61480. // use zrender/graphic/helper/RectText, and is located based on view
  61481. // group (according to handleLabelPoint) but not barGroup.
  61482. var textStyleModel = this.visualMapModel.textStyleModel;
  61483. var handleLabel = new Text({
  61484. draggable: true,
  61485. drift: onDrift,
  61486. onmousemove: function (e) {
  61487. // Fot mobile devicem, prevent screen slider on the button.
  61488. stop(e.event);
  61489. },
  61490. ondragend: onDragEnd,
  61491. style: {
  61492. x: 0, y: 0, text: '',
  61493. textFont: textStyleModel.getFont(),
  61494. textFill: textStyleModel.getTextColor()
  61495. }
  61496. });
  61497. this.group.add(handleLabel);
  61498. var handleLabelPoint = [
  61499. orient === 'horizontal'
  61500. ? textSize / 2
  61501. : textSize * 1.5,
  61502. orient === 'horizontal'
  61503. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  61504. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  61505. ];
  61506. var shapes = this._shapes;
  61507. shapes.handleThumbs[handleIndex] = handleThumb;
  61508. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  61509. shapes.handleLabels[handleIndex] = handleLabel;
  61510. },
  61511. /**
  61512. * @private
  61513. */
  61514. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  61515. var indicator = createPolygon([[0, 0]], 'move');
  61516. indicator.position[0] = itemSize[0];
  61517. indicator.attr({invisible: true, silent: true});
  61518. barGroup.add(indicator);
  61519. var textStyleModel = this.visualMapModel.textStyleModel;
  61520. var indicatorLabel = new Text({
  61521. silent: true,
  61522. invisible: true,
  61523. style: {
  61524. x: 0, y: 0, text: '',
  61525. textFont: textStyleModel.getFont(),
  61526. textFill: textStyleModel.getTextColor()
  61527. }
  61528. });
  61529. this.group.add(indicatorLabel);
  61530. var indicatorLabelPoint = [
  61531. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  61532. 0
  61533. ];
  61534. var shapes = this._shapes;
  61535. shapes.indicator = indicator;
  61536. shapes.indicatorLabel = indicatorLabel;
  61537. shapes.indicatorLabelPoint = indicatorLabelPoint;
  61538. },
  61539. /**
  61540. * @private
  61541. */
  61542. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  61543. if (!this._useHandle) {
  61544. return;
  61545. }
  61546. this._dragging = !isEnd;
  61547. if (!isEnd) {
  61548. // Transform dx, dy to bar coordination.
  61549. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  61550. this._updateInterval(handleIndex, vertex[1]);
  61551. // Considering realtime, update view should be executed
  61552. // before dispatch action.
  61553. this._updateView();
  61554. }
  61555. // dragEnd do not dispatch action when realtime.
  61556. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  61557. this.api.dispatchAction({
  61558. type: 'selectDataRange',
  61559. from: this.uid,
  61560. visualMapId: this.visualMapModel.id,
  61561. selected: this._dataInterval.slice()
  61562. });
  61563. }
  61564. if (isEnd) {
  61565. !this._hovering && this._clearHoverLinkToSeries();
  61566. }
  61567. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  61568. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  61569. }
  61570. },
  61571. /**
  61572. * @private
  61573. */
  61574. _resetInterval: function () {
  61575. var visualMapModel = this.visualMapModel;
  61576. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  61577. var dataExtent = visualMapModel.getExtent();
  61578. var sizeExtent = [0, visualMapModel.itemSize[1]];
  61579. this._handleEnds = [
  61580. linearMap$4(dataInterval[0], dataExtent, sizeExtent, true),
  61581. linearMap$4(dataInterval[1], dataExtent, sizeExtent, true)
  61582. ];
  61583. },
  61584. /**
  61585. * @private
  61586. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  61587. * @param {number} dx
  61588. * @param {number} dy
  61589. */
  61590. _updateInterval: function (handleIndex, delta) {
  61591. delta = delta || 0;
  61592. var visualMapModel = this.visualMapModel;
  61593. var handleEnds = this._handleEnds;
  61594. var sizeExtent = [0, visualMapModel.itemSize[1]];
  61595. sliderMove(
  61596. delta,
  61597. handleEnds,
  61598. sizeExtent,
  61599. handleIndex,
  61600. // cross is forbiden
  61601. 0
  61602. );
  61603. var dataExtent = visualMapModel.getExtent();
  61604. // Update data interval.
  61605. this._dataInterval = [
  61606. linearMap$4(handleEnds[0], sizeExtent, dataExtent, true),
  61607. linearMap$4(handleEnds[1], sizeExtent, dataExtent, true)
  61608. ];
  61609. },
  61610. /**
  61611. * @private
  61612. */
  61613. _updateView: function (forSketch) {
  61614. var visualMapModel = this.visualMapModel;
  61615. var dataExtent = visualMapModel.getExtent();
  61616. var shapes = this._shapes;
  61617. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  61618. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  61619. var visualInRange = this._createBarVisual(
  61620. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  61621. );
  61622. var visualOutOfRange = this._createBarVisual(
  61623. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  61624. );
  61625. shapes.inRange
  61626. .setStyle({
  61627. fill: visualInRange.barColor,
  61628. opacity: visualInRange.opacity
  61629. })
  61630. .setShape('points', visualInRange.barPoints);
  61631. shapes.outOfRange
  61632. .setStyle({
  61633. fill: visualOutOfRange.barColor,
  61634. opacity: visualOutOfRange.opacity
  61635. })
  61636. .setShape('points', visualOutOfRange.barPoints);
  61637. this._updateHandle(inRangeHandleEnds, visualInRange);
  61638. },
  61639. /**
  61640. * @private
  61641. */
  61642. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  61643. var opts = {
  61644. forceState: forceState,
  61645. convertOpacityToAlpha: true
  61646. };
  61647. var colorStops = this._makeColorGradient(dataInterval, opts);
  61648. var symbolSizes = [
  61649. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  61650. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  61651. ];
  61652. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  61653. return {
  61654. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  61655. barPoints: barPoints,
  61656. handlesColor: [
  61657. colorStops[0].color,
  61658. colorStops[colorStops.length - 1].color
  61659. ]
  61660. };
  61661. },
  61662. /**
  61663. * @private
  61664. */
  61665. _makeColorGradient: function (dataInterval, opts) {
  61666. // Considering colorHue, which is not linear, so we have to sample
  61667. // to calculate gradient color stops, but not only caculate head
  61668. // and tail.
  61669. var sampleNumber = 100; // Arbitrary value.
  61670. var colorStops = [];
  61671. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  61672. colorStops.push({
  61673. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  61674. offset: 0
  61675. });
  61676. for (var i = 1; i < sampleNumber; i++) {
  61677. var currValue = dataInterval[0] + step * i;
  61678. if (currValue > dataInterval[1]) {
  61679. break;
  61680. }
  61681. colorStops.push({
  61682. color: this.getControllerVisual(currValue, 'color', opts),
  61683. offset: i / sampleNumber
  61684. });
  61685. }
  61686. colorStops.push({
  61687. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  61688. offset: 1
  61689. });
  61690. return colorStops;
  61691. },
  61692. /**
  61693. * @private
  61694. */
  61695. _createBarPoints: function (handleEnds, symbolSizes) {
  61696. var itemSize = this.visualMapModel.itemSize;
  61697. return [
  61698. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  61699. [itemSize[0], handleEnds[0]],
  61700. [itemSize[0], handleEnds[1]],
  61701. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  61702. ];
  61703. },
  61704. /**
  61705. * @private
  61706. */
  61707. _createBarGroup: function (itemAlign) {
  61708. var orient = this._orient;
  61709. var inverse = this.visualMapModel.get('inverse');
  61710. return new Group(
  61711. (orient === 'horizontal' && !inverse)
  61712. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  61713. : (orient === 'horizontal' && inverse)
  61714. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  61715. : (orient === 'vertical' && !inverse)
  61716. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  61717. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  61718. );
  61719. },
  61720. /**
  61721. * @private
  61722. */
  61723. _updateHandle: function (handleEnds, visualInRange) {
  61724. if (!this._useHandle) {
  61725. return;
  61726. }
  61727. var shapes = this._shapes;
  61728. var visualMapModel = this.visualMapModel;
  61729. var handleThumbs = shapes.handleThumbs;
  61730. var handleLabels = shapes.handleLabels;
  61731. each$27([0, 1], function (handleIndex) {
  61732. var handleThumb = handleThumbs[handleIndex];
  61733. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  61734. handleThumb.position[1] = handleEnds[handleIndex];
  61735. // Update handle label position.
  61736. var textPoint = applyTransform$1(
  61737. shapes.handleLabelPoints[handleIndex],
  61738. getTransform(handleThumb, this.group)
  61739. );
  61740. handleLabels[handleIndex].setStyle({
  61741. x: textPoint[0],
  61742. y: textPoint[1],
  61743. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  61744. textVerticalAlign: 'middle',
  61745. textAlign: this._applyTransform(
  61746. this._orient === 'horizontal'
  61747. ? (handleIndex === 0 ? 'bottom' : 'top')
  61748. : 'left',
  61749. shapes.barGroup
  61750. )
  61751. });
  61752. }, this);
  61753. },
  61754. /**
  61755. * @private
  61756. * @param {number} cursorValue
  61757. * @param {number} textValue
  61758. * @param {string} [rangeSymbol]
  61759. * @param {number} [halfHoverLinkSize]
  61760. */
  61761. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  61762. var visualMapModel = this.visualMapModel;
  61763. var dataExtent = visualMapModel.getExtent();
  61764. var itemSize = visualMapModel.itemSize;
  61765. var sizeExtent = [0, itemSize[1]];
  61766. var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true);
  61767. var shapes = this._shapes;
  61768. var indicator = shapes.indicator;
  61769. if (!indicator) {
  61770. return;
  61771. }
  61772. indicator.position[1] = pos;
  61773. indicator.attr('invisible', false);
  61774. indicator.setShape('points', createIndicatorPoints(
  61775. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  61776. ));
  61777. var opts = {convertOpacityToAlpha: true};
  61778. var color = this.getControllerVisual(cursorValue, 'color', opts);
  61779. indicator.setStyle('fill', color);
  61780. // Update handle label position.
  61781. var textPoint = applyTransform$1(
  61782. shapes.indicatorLabelPoint,
  61783. getTransform(indicator, this.group)
  61784. );
  61785. var indicatorLabel = shapes.indicatorLabel;
  61786. indicatorLabel.attr('invisible', false);
  61787. var align = this._applyTransform('left', shapes.barGroup);
  61788. var orient = this._orient;
  61789. indicatorLabel.setStyle({
  61790. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  61791. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  61792. textAlign: orient === 'horizontal' ? 'center' : align,
  61793. x: textPoint[0],
  61794. y: textPoint[1]
  61795. });
  61796. },
  61797. /**
  61798. * @private
  61799. */
  61800. _enableHoverLinkToSeries: function () {
  61801. var self = this;
  61802. this._shapes.barGroup
  61803. .on('mousemove', function (e) {
  61804. self._hovering = true;
  61805. if (!self._dragging) {
  61806. var itemSize = self.visualMapModel.itemSize;
  61807. var pos = self._applyTransform(
  61808. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  61809. );
  61810. // For hover link show when hover handle, which might be
  61811. // below or upper than sizeExtent.
  61812. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  61813. self._doHoverLinkToSeries(
  61814. pos[1],
  61815. 0 <= pos[0] && pos[0] <= itemSize[0]
  61816. );
  61817. }
  61818. })
  61819. .on('mouseout', function () {
  61820. // When mouse is out of handle, hoverLink still need
  61821. // to be displayed when realtime is set as false.
  61822. self._hovering = false;
  61823. !self._dragging && self._clearHoverLinkToSeries();
  61824. });
  61825. },
  61826. /**
  61827. * @private
  61828. */
  61829. _enableHoverLinkFromSeries: function () {
  61830. var zr = this.api.getZr();
  61831. if (this.visualMapModel.option.hoverLink) {
  61832. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  61833. zr.on('mouseout', this._hideIndicator, this);
  61834. }
  61835. else {
  61836. this._clearHoverLinkFromSeries();
  61837. }
  61838. },
  61839. /**
  61840. * @private
  61841. */
  61842. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  61843. var visualMapModel = this.visualMapModel;
  61844. var itemSize = visualMapModel.itemSize;
  61845. if (!visualMapModel.option.hoverLink) {
  61846. return;
  61847. }
  61848. var sizeExtent = [0, itemSize[1]];
  61849. var dataExtent = visualMapModel.getExtent();
  61850. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  61851. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  61852. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  61853. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  61854. var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true);
  61855. var valueRange = [
  61856. linearMap$4(hoverRange[0], sizeExtent, dataExtent, true),
  61857. linearMap$4(hoverRange[1], sizeExtent, dataExtent, true)
  61858. ];
  61859. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  61860. // where china and india has very large population.
  61861. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  61862. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  61863. // Do not show indicator when mouse is over handle,
  61864. // otherwise labels overlap, especially when dragging.
  61865. if (hoverOnBar) {
  61866. if (valueRange[0] === -Infinity) {
  61867. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  61868. }
  61869. else if (valueRange[1] === Infinity) {
  61870. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  61871. }
  61872. else {
  61873. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  61874. }
  61875. }
  61876. // When realtime is set as false, handles, which are in barGroup,
  61877. // also trigger hoverLink, which help user to realize where they
  61878. // focus on when dragging. (see test/heatmap-large.html)
  61879. // When realtime is set as true, highlight will not show when hover
  61880. // handle, because the label on handle, which displays a exact value
  61881. // but not range, might mislead users.
  61882. var oldBatch = this._hoverLinkDataIndices;
  61883. var newBatch = [];
  61884. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  61885. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  61886. }
  61887. var resultBatches = compressBatches(oldBatch, newBatch);
  61888. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  61889. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  61890. },
  61891. /**
  61892. * @private
  61893. */
  61894. _hoverLinkFromSeriesMouseOver: function (e) {
  61895. var el = e.target;
  61896. var visualMapModel = this.visualMapModel;
  61897. if (!el || el.dataIndex == null) {
  61898. return;
  61899. }
  61900. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  61901. if (!visualMapModel.isTargetSeries(dataModel)) {
  61902. return;
  61903. }
  61904. var data = dataModel.getData(el.dataType);
  61905. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  61906. if (!isNaN(value)) {
  61907. this._showIndicator(value, value);
  61908. }
  61909. },
  61910. /**
  61911. * @private
  61912. */
  61913. _hideIndicator: function () {
  61914. var shapes = this._shapes;
  61915. shapes.indicator && shapes.indicator.attr('invisible', true);
  61916. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  61917. },
  61918. /**
  61919. * @private
  61920. */
  61921. _clearHoverLinkToSeries: function () {
  61922. this._hideIndicator();
  61923. var indices = this._hoverLinkDataIndices;
  61924. this._dispatchHighDown('downplay', convertDataIndex(indices));
  61925. indices.length = 0;
  61926. },
  61927. /**
  61928. * @private
  61929. */
  61930. _clearHoverLinkFromSeries: function () {
  61931. this._hideIndicator();
  61932. var zr = this.api.getZr();
  61933. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  61934. zr.off('mouseout', this._hideIndicator);
  61935. },
  61936. /**
  61937. * @private
  61938. */
  61939. _applyTransform: function (vertex, element, inverse, global) {
  61940. var transform = getTransform(element, global ? null : this.group);
  61941. return graphic[
  61942. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  61943. ](vertex, transform, inverse);
  61944. },
  61945. /**
  61946. * @private
  61947. */
  61948. _dispatchHighDown: function (type, batch) {
  61949. batch && batch.length && this.api.dispatchAction({
  61950. type: type,
  61951. batch: batch
  61952. });
  61953. },
  61954. /**
  61955. * @override
  61956. */
  61957. dispose: function () {
  61958. this._clearHoverLinkFromSeries();
  61959. this._clearHoverLinkToSeries();
  61960. },
  61961. /**
  61962. * @override
  61963. */
  61964. remove: function () {
  61965. this._clearHoverLinkFromSeries();
  61966. this._clearHoverLinkToSeries();
  61967. }
  61968. });
  61969. function createPolygon(points, cursor, onDrift, onDragEnd) {
  61970. return new Polygon({
  61971. shape: {points: points},
  61972. draggable: !!onDrift,
  61973. cursor: cursor,
  61974. drift: onDrift,
  61975. onmousemove: function (e) {
  61976. // Fot mobile devicem, prevent screen slider on the button.
  61977. stop(e.event);
  61978. },
  61979. ondragend: onDragEnd
  61980. });
  61981. }
  61982. function createHandlePoints(handleIndex, textSize) {
  61983. return handleIndex === 0
  61984. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  61985. : [[0, 0], [textSize, 0], [textSize, textSize]];
  61986. }
  61987. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  61988. return isRange
  61989. ? [ // indicate range
  61990. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  61991. [HOVER_LINK_OUT, 0],
  61992. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  61993. ]
  61994. : [ // indicate single value
  61995. [0, 0], [5, -5], [5, 5]
  61996. ];
  61997. }
  61998. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  61999. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  62000. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  62001. if (hoverLinkDataSize) {
  62002. halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  62003. }
  62004. return halfHoverLinkSize;
  62005. }
  62006. function useHoverLinkOnHandle(visualMapModel) {
  62007. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  62008. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  62009. }
  62010. function getCursor$1(orient) {
  62011. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  62012. }
  62013. var actionInfo$2 = {
  62014. type: 'selectDataRange',
  62015. event: 'dataRangeSelected',
  62016. // FIXME use updateView appears wrong
  62017. update: 'update'
  62018. };
  62019. registerAction(actionInfo$2, function (payload, ecModel) {
  62020. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  62021. model.setSelected(payload.selected);
  62022. });
  62023. });
  62024. /**
  62025. * DataZoom component entry
  62026. */
  62027. registerPreprocessor(preprocessor$2);
  62028. var PiecewiseModel = VisualMapModel.extend({
  62029. type: 'visualMap.piecewise',
  62030. /**
  62031. * Order Rule:
  62032. *
  62033. * option.categories / option.pieces / option.text / option.selected:
  62034. * If !option.inverse,
  62035. * Order when vertical: ['top', ..., 'bottom'].
  62036. * Order when horizontal: ['left', ..., 'right'].
  62037. * If option.inverse, the meaning of
  62038. * the order should be reversed.
  62039. *
  62040. * this._pieceList:
  62041. * The order is always [low, ..., high].
  62042. *
  62043. * Mapping from location to low-high:
  62044. * If !option.inverse
  62045. * When vertical, top is high.
  62046. * When horizontal, right is high.
  62047. * If option.inverse, reverse.
  62048. */
  62049. /**
  62050. * @protected
  62051. */
  62052. defaultOption: {
  62053. selected: null, // Object. If not specified, means selected.
  62054. // When pieces and splitNumber: {'0': true, '5': true}
  62055. // When categories: {'cate1': false, 'cate3': true}
  62056. // When selected === false, means all unselected.
  62057. minOpen: false, // Whether include values that smaller than `min`.
  62058. maxOpen: false, // Whether include values that bigger than `max`.
  62059. align: 'auto', // 'auto', 'left', 'right'
  62060. itemWidth: 20, // When put the controller vertically, it is the length of
  62061. // horizontal side of each item. Otherwise, vertical side.
  62062. itemHeight: 14, // When put the controller vertically, it is the length of
  62063. // vertical side of each item. Otherwise, horizontal side.
  62064. itemSymbol: 'roundRect',
  62065. pieceList: null, // Each item is Object, with some of those attrs:
  62066. // {min, max, lt, gt, lte, gte, value,
  62067. // color, colorSaturation, colorAlpha, opacity,
  62068. // symbol, symbolSize}, which customize the range or visual
  62069. // coding of the certain piece. Besides, see "Order Rule".
  62070. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  62071. // Attr min/max are ignored when categories set. See "Order Rule"
  62072. splitNumber: 5, // If set to 5, auto split five pieces equally.
  62073. // If set to 0 and component type not set, component type will be
  62074. // determined as "continuous". (It is less reasonable but for ec2
  62075. // compatibility, see echarts/component/visualMap/typeDefaulter)
  62076. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  62077. itemGap: 10, // The gap between two items, in px.
  62078. hoverLink: true, // Enable hover highlight.
  62079. showLabel: null // By default, when text is used, label will hide (the logic
  62080. // is remained for compatibility reason)
  62081. },
  62082. /**
  62083. * @override
  62084. */
  62085. optionUpdated: function (newOption, isInit) {
  62086. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  62087. /**
  62088. * The order is always [low, ..., high].
  62089. * [{text: string, interval: Array.<number>}, ...]
  62090. * @private
  62091. * @type {Array.<Object>}
  62092. */
  62093. this._pieceList = [];
  62094. this.resetExtent();
  62095. /**
  62096. * 'pieces', 'categories', 'splitNumber'
  62097. * @type {string}
  62098. */
  62099. var mode = this._mode = this._determineMode();
  62100. resetMethods[this._mode].call(this);
  62101. this._resetSelected(newOption, isInit);
  62102. var categories = this.option.categories;
  62103. this.resetVisual(function (mappingOption, state) {
  62104. if (mode === 'categories') {
  62105. mappingOption.mappingMethod = 'category';
  62106. mappingOption.categories = clone(categories);
  62107. }
  62108. else {
  62109. mappingOption.dataExtent = this.getExtent();
  62110. mappingOption.mappingMethod = 'piecewise';
  62111. mappingOption.pieceList = map(this._pieceList, function (piece) {
  62112. var piece = clone(piece);
  62113. if (state !== 'inRange') {
  62114. // FIXME
  62115. // outOfRange do not support special visual in pieces.
  62116. piece.visual = null;
  62117. }
  62118. return piece;
  62119. });
  62120. }
  62121. });
  62122. },
  62123. /**
  62124. * @protected
  62125. * @override
  62126. */
  62127. completeVisualOption: function () {
  62128. // Consider this case:
  62129. // visualMap: {
  62130. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  62131. // }
  62132. // where no inRange/outOfRange set but only pieces. So we should make
  62133. // default inRange/outOfRange for this case, otherwise visuals that only
  62134. // appear in `pieces` will not be taken into account in visual encoding.
  62135. var option = this.option;
  62136. var visualTypesInPieces = {};
  62137. var visualTypes = VisualMapping.listVisualTypes();
  62138. var isCategory = this.isCategory();
  62139. each$1(option.pieces, function (piece) {
  62140. each$1(visualTypes, function (visualType) {
  62141. if (piece.hasOwnProperty(visualType)) {
  62142. visualTypesInPieces[visualType] = 1;
  62143. }
  62144. });
  62145. });
  62146. each$1(visualTypesInPieces, function (v, visualType) {
  62147. var exists = 0;
  62148. each$1(this.stateList, function (state) {
  62149. exists |= has(option, state, visualType)
  62150. || has(option.target, state, visualType);
  62151. }, this);
  62152. !exists && each$1(this.stateList, function (state) {
  62153. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  62154. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  62155. );
  62156. });
  62157. }, this);
  62158. function has(obj, state, visualType) {
  62159. return obj && obj[state] && (
  62160. isObject$1(obj[state])
  62161. ? obj[state].hasOwnProperty(visualType)
  62162. : obj[state] === visualType // e.g., inRange: 'symbol'
  62163. );
  62164. }
  62165. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  62166. },
  62167. _resetSelected: function (newOption, isInit) {
  62168. var thisOption = this.option;
  62169. var pieceList = this._pieceList;
  62170. // Selected do not merge but all override.
  62171. var selected = (isInit ? thisOption : newOption).selected || {};
  62172. thisOption.selected = selected;
  62173. // Consider 'not specified' means true.
  62174. each$1(pieceList, function (piece, index) {
  62175. var key = this.getSelectedMapKey(piece);
  62176. if (!selected.hasOwnProperty(key)) {
  62177. selected[key] = true;
  62178. }
  62179. }, this);
  62180. if (thisOption.selectedMode === 'single') {
  62181. // Ensure there is only one selected.
  62182. var hasSel = false;
  62183. each$1(pieceList, function (piece, index) {
  62184. var key = this.getSelectedMapKey(piece);
  62185. if (selected[key]) {
  62186. hasSel
  62187. ? (selected[key] = false)
  62188. : (hasSel = true);
  62189. }
  62190. }, this);
  62191. }
  62192. // thisOption.selectedMode === 'multiple', default: all selected.
  62193. },
  62194. /**
  62195. * @public
  62196. */
  62197. getSelectedMapKey: function (piece) {
  62198. return this._mode === 'categories'
  62199. ? piece.value + '' : piece.index + '';
  62200. },
  62201. /**
  62202. * @public
  62203. */
  62204. getPieceList: function () {
  62205. return this._pieceList;
  62206. },
  62207. /**
  62208. * @private
  62209. * @return {string}
  62210. */
  62211. _determineMode: function () {
  62212. var option = this.option;
  62213. return option.pieces && option.pieces.length > 0
  62214. ? 'pieces'
  62215. : this.option.categories
  62216. ? 'categories'
  62217. : 'splitNumber';
  62218. },
  62219. /**
  62220. * @public
  62221. * @override
  62222. */
  62223. setSelected: function (selected) {
  62224. this.option.selected = clone(selected);
  62225. },
  62226. /**
  62227. * @public
  62228. * @override
  62229. */
  62230. getValueState: function (value) {
  62231. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  62232. return index != null
  62233. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  62234. ? 'inRange' : 'outOfRange'
  62235. )
  62236. : 'outOfRange';
  62237. },
  62238. /**
  62239. * @public
  62240. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  62241. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  62242. */
  62243. findTargetDataIndices: function (pieceIndex) {
  62244. var result = [];
  62245. this.eachTargetSeries(function (seriesModel) {
  62246. var dataIndices = [];
  62247. var data = seriesModel.getData();
  62248. data.each(this.getDataDimension(data), function (value, dataIndex) {
  62249. // Should always base on model pieceList, because it is order sensitive.
  62250. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  62251. pIdx === pieceIndex && dataIndices.push(dataIndex);
  62252. }, true, this);
  62253. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  62254. }, this);
  62255. return result;
  62256. },
  62257. /**
  62258. * @private
  62259. * @param {Object} piece piece.value or piece.interval is required.
  62260. * @return {number} Can be Infinity or -Infinity
  62261. */
  62262. getRepresentValue: function (piece) {
  62263. var representValue;
  62264. if (this.isCategory()) {
  62265. representValue = piece.value;
  62266. }
  62267. else {
  62268. if (piece.value != null) {
  62269. representValue = piece.value;
  62270. }
  62271. else {
  62272. var pieceInterval = piece.interval || [];
  62273. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  62274. ? 0
  62275. : (pieceInterval[0] + pieceInterval[1]) / 2;
  62276. }
  62277. }
  62278. return representValue;
  62279. },
  62280. getVisualMeta: function (getColorVisual) {
  62281. // Do not support category. (category axis is ordinal, numerical)
  62282. if (this.isCategory()) {
  62283. return;
  62284. }
  62285. var stops = [];
  62286. var outerColors = [];
  62287. var visualMapModel = this;
  62288. function setStop(interval, valueState) {
  62289. var representValue = visualMapModel.getRepresentValue({interval: interval});
  62290. if (!valueState) {
  62291. valueState = visualMapModel.getValueState(representValue);
  62292. }
  62293. var color = getColorVisual(representValue, valueState);
  62294. if (interval[0] === -Infinity) {
  62295. outerColors[0] = color;
  62296. }
  62297. else if (interval[1] === Infinity) {
  62298. outerColors[1] = color;
  62299. }
  62300. else {
  62301. stops.push(
  62302. {value: interval[0], color: color},
  62303. {value: interval[1], color: color}
  62304. );
  62305. }
  62306. }
  62307. // Suplement
  62308. var pieceList = this._pieceList.slice();
  62309. if (!pieceList.length) {
  62310. pieceList.push({interval: [-Infinity, Infinity]});
  62311. }
  62312. else {
  62313. var edge = pieceList[0].interval[0];
  62314. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  62315. edge = pieceList[pieceList.length - 1].interval[1];
  62316. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  62317. }
  62318. var curr = -Infinity;
  62319. each$1(pieceList, function (piece) {
  62320. var interval = piece.interval;
  62321. if (interval) {
  62322. // Fulfill gap.
  62323. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  62324. setStop(interval.slice());
  62325. curr = interval[1];
  62326. }
  62327. }, this);
  62328. return {stops: stops, outerColors: outerColors};
  62329. }
  62330. });
  62331. /**
  62332. * Key is this._mode
  62333. * @type {Object}
  62334. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  62335. */
  62336. var resetMethods = {
  62337. splitNumber: function () {
  62338. var thisOption = this.option;
  62339. var pieceList = this._pieceList;
  62340. var precision = Math.min(thisOption.precision, 20);
  62341. var dataExtent = this.getExtent();
  62342. var splitNumber = thisOption.splitNumber;
  62343. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  62344. thisOption.splitNumber = splitNumber;
  62345. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  62346. // Precision auto-adaption
  62347. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  62348. precision++;
  62349. }
  62350. thisOption.precision = precision;
  62351. splitStep = +splitStep.toFixed(precision);
  62352. var index = 0;
  62353. if (thisOption.minOpen) {
  62354. pieceList.push({
  62355. index: index++,
  62356. interval: [-Infinity, dataExtent[0]],
  62357. close: [0, 0]
  62358. });
  62359. }
  62360. for (
  62361. var curr = dataExtent[0], len = index + splitNumber;
  62362. index < len;
  62363. curr += splitStep
  62364. ) {
  62365. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  62366. pieceList.push({
  62367. index: index++,
  62368. interval: [curr, max],
  62369. close: [1, 1]
  62370. });
  62371. }
  62372. if (thisOption.maxOpen) {
  62373. pieceList.push({
  62374. index: index++,
  62375. interval: [dataExtent[1], Infinity],
  62376. close: [0, 0]
  62377. });
  62378. }
  62379. reformIntervals(pieceList);
  62380. each$1(pieceList, function (piece) {
  62381. piece.text = this.formatValueText(piece.interval);
  62382. }, this);
  62383. },
  62384. categories: function () {
  62385. var thisOption = this.option;
  62386. each$1(thisOption.categories, function (cate) {
  62387. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  62388. // 是否改一致。
  62389. this._pieceList.push({
  62390. text: this.formatValueText(cate, true),
  62391. value: cate
  62392. });
  62393. }, this);
  62394. // See "Order Rule".
  62395. normalizeReverse(thisOption, this._pieceList);
  62396. },
  62397. pieces: function () {
  62398. var thisOption = this.option;
  62399. var pieceList = this._pieceList;
  62400. each$1(thisOption.pieces, function (pieceListItem, index) {
  62401. if (!isObject$1(pieceListItem)) {
  62402. pieceListItem = {value: pieceListItem};
  62403. }
  62404. var item = {text: '', index: index};
  62405. if (pieceListItem.label != null) {
  62406. item.text = pieceListItem.label;
  62407. }
  62408. if (pieceListItem.hasOwnProperty('value')) {
  62409. var value = item.value = pieceListItem.value;
  62410. item.interval = [value, value];
  62411. item.close = [1, 1];
  62412. }
  62413. else {
  62414. // `min` `max` is legacy option.
  62415. // `lt` `gt` `lte` `gte` is recommanded.
  62416. var interval = item.interval = [];
  62417. var close = item.close = [0, 0];
  62418. var closeList = [1, 0, 1];
  62419. var infinityList = [-Infinity, Infinity];
  62420. var useMinMax = [];
  62421. for (var lg = 0; lg < 2; lg++) {
  62422. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  62423. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  62424. interval[lg] = pieceListItem[names[i]];
  62425. close[lg] = closeList[i];
  62426. useMinMax[lg] = i === 2;
  62427. }
  62428. interval[lg] == null && (interval[lg] = infinityList[lg]);
  62429. }
  62430. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  62431. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  62432. if (__DEV__) {
  62433. if (interval[0] > interval[1]) {
  62434. console.warn(
  62435. 'Piece ' + index + 'is illegal: ' + interval
  62436. + ' lower bound should not greater then uppper bound.'
  62437. );
  62438. }
  62439. }
  62440. if (interval[0] === interval[1] && close[0] && close[1]) {
  62441. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  62442. // we use value to lift the priority when min === max
  62443. item.value = interval[0];
  62444. }
  62445. }
  62446. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  62447. pieceList.push(item);
  62448. }, this);
  62449. // See "Order Rule".
  62450. normalizeReverse(thisOption, pieceList);
  62451. // Only pieces
  62452. reformIntervals(pieceList);
  62453. each$1(pieceList, function (piece) {
  62454. var close = piece.close;
  62455. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  62456. piece.text = piece.text || this.formatValueText(
  62457. piece.value != null ? piece.value : piece.interval,
  62458. false,
  62459. edgeSymbols
  62460. );
  62461. }, this);
  62462. }
  62463. };
  62464. function normalizeReverse(thisOption, pieceList) {
  62465. var inverse = thisOption.inverse;
  62466. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  62467. pieceList.reverse();
  62468. }
  62469. }
  62470. var PiecewiseVisualMapView = VisualMapView.extend({
  62471. type: 'visualMap.piecewise',
  62472. /**
  62473. * @protected
  62474. * @override
  62475. */
  62476. doRender: function () {
  62477. var thisGroup = this.group;
  62478. thisGroup.removeAll();
  62479. var visualMapModel = this.visualMapModel;
  62480. var textGap = visualMapModel.get('textGap');
  62481. var textStyleModel = visualMapModel.textStyleModel;
  62482. var textFont = textStyleModel.getFont();
  62483. var textFill = textStyleModel.getTextColor();
  62484. var itemAlign = this._getItemAlign();
  62485. var itemSize = visualMapModel.itemSize;
  62486. var viewData = this._getViewData();
  62487. var endsText = viewData.endsText;
  62488. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  62489. endsText && this._renderEndsText(
  62490. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  62491. );
  62492. each$1(viewData.viewPieceList, renderItem, this);
  62493. endsText && this._renderEndsText(
  62494. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  62495. );
  62496. box(
  62497. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  62498. );
  62499. this.renderBackground(thisGroup);
  62500. this.positionGroup(thisGroup);
  62501. function renderItem(item) {
  62502. var piece = item.piece;
  62503. var itemGroup = new Group();
  62504. itemGroup.onclick = bind(this._onItemClick, this, piece);
  62505. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  62506. var representValue = visualMapModel.getRepresentValue(piece);
  62507. this._createItemSymbol(
  62508. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  62509. );
  62510. if (showLabel) {
  62511. var visualState = this.visualMapModel.getValueState(representValue);
  62512. itemGroup.add(new Text({
  62513. style: {
  62514. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  62515. y: itemSize[1] / 2,
  62516. text: piece.text,
  62517. textVerticalAlign: 'middle',
  62518. textAlign: itemAlign,
  62519. textFont: textFont,
  62520. textFill: textFill,
  62521. opacity: visualState === 'outOfRange' ? 0.5 : 1
  62522. }
  62523. }));
  62524. }
  62525. thisGroup.add(itemGroup);
  62526. }
  62527. },
  62528. /**
  62529. * @private
  62530. */
  62531. _enableHoverLink: function (itemGroup, pieceIndex) {
  62532. itemGroup
  62533. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  62534. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  62535. function onHoverLink(method) {
  62536. var visualMapModel = this.visualMapModel;
  62537. visualMapModel.option.hoverLink && this.api.dispatchAction({
  62538. type: method,
  62539. batch: convertDataIndex(
  62540. visualMapModel.findTargetDataIndices(pieceIndex)
  62541. )
  62542. });
  62543. }
  62544. },
  62545. /**
  62546. * @private
  62547. */
  62548. _getItemAlign: function () {
  62549. var visualMapModel = this.visualMapModel;
  62550. var modelOption = visualMapModel.option;
  62551. if (modelOption.orient === 'vertical') {
  62552. return getItemAlign(
  62553. visualMapModel, this.api, visualMapModel.itemSize
  62554. );
  62555. }
  62556. else { // horizontal, most case left unless specifying right.
  62557. var align = modelOption.align;
  62558. if (!align || align === 'auto') {
  62559. align = 'left';
  62560. }
  62561. return align;
  62562. }
  62563. },
  62564. /**
  62565. * @private
  62566. */
  62567. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  62568. if (!text) {
  62569. return;
  62570. }
  62571. var itemGroup = new Group();
  62572. var textStyleModel = this.visualMapModel.textStyleModel;
  62573. itemGroup.add(new Text({
  62574. style: {
  62575. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  62576. y: itemSize[1] / 2,
  62577. textVerticalAlign: 'middle',
  62578. textAlign: showLabel ? itemAlign : 'center',
  62579. text: text,
  62580. textFont: textStyleModel.getFont(),
  62581. textFill: textStyleModel.getTextColor()
  62582. }
  62583. }));
  62584. group.add(itemGroup);
  62585. },
  62586. /**
  62587. * @private
  62588. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  62589. */
  62590. _getViewData: function () {
  62591. var visualMapModel = this.visualMapModel;
  62592. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  62593. return {piece: piece, indexInModelPieceList: index};
  62594. });
  62595. var endsText = visualMapModel.get('text');
  62596. // Consider orient and inverse.
  62597. var orient = visualMapModel.get('orient');
  62598. var inverse = visualMapModel.get('inverse');
  62599. // Order of model pieceList is always [low, ..., high]
  62600. if (orient === 'horizontal' ? inverse : !inverse) {
  62601. viewPieceList.reverse();
  62602. }
  62603. // Origin order of endsText is [high, low]
  62604. else if (endsText) {
  62605. endsText = endsText.slice().reverse();
  62606. }
  62607. return {viewPieceList: viewPieceList, endsText: endsText};
  62608. },
  62609. /**
  62610. * @private
  62611. */
  62612. _createItemSymbol: function (group, representValue, shapeParam) {
  62613. group.add(createSymbol(
  62614. this.getControllerVisual(representValue, 'symbol'),
  62615. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  62616. this.getControllerVisual(representValue, 'color')
  62617. ));
  62618. },
  62619. /**
  62620. * @private
  62621. */
  62622. _onItemClick: function (piece) {
  62623. var visualMapModel = this.visualMapModel;
  62624. var option = visualMapModel.option;
  62625. var selected = clone(option.selected);
  62626. var newKey = visualMapModel.getSelectedMapKey(piece);
  62627. if (option.selectedMode === 'single') {
  62628. selected[newKey] = true;
  62629. each$1(selected, function (o, key) {
  62630. selected[key] = key === newKey;
  62631. });
  62632. }
  62633. else {
  62634. selected[newKey] = !selected[newKey];
  62635. }
  62636. this.api.dispatchAction({
  62637. type: 'selectDataRange',
  62638. from: this.uid,
  62639. visualMapId: this.visualMapModel.id,
  62640. selected: selected
  62641. });
  62642. }
  62643. });
  62644. /**
  62645. * DataZoom component entry
  62646. */
  62647. registerPreprocessor(preprocessor$2);
  62648. /**
  62649. * visualMap component entry
  62650. */
  62651. var addCommas$1 = addCommas;
  62652. var encodeHTML$1 = encodeHTML;
  62653. function fillLabel(opt) {
  62654. defaultEmphasis(opt, 'label', ['show']);
  62655. }
  62656. var MarkerModel = extendComponentModel({
  62657. type: 'marker',
  62658. dependencies: ['series', 'grid', 'polar', 'geo'],
  62659. /**
  62660. * @overrite
  62661. */
  62662. init: function (option, parentModel, ecModel, extraOpt) {
  62663. if (__DEV__) {
  62664. if (this.type === 'marker') {
  62665. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  62666. }
  62667. }
  62668. this.mergeDefaultAndTheme(option, ecModel);
  62669. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  62670. },
  62671. /**
  62672. * @return {boolean}
  62673. */
  62674. isAnimationEnabled: function () {
  62675. if (env$1.node) {
  62676. return false;
  62677. }
  62678. var hostSeries = this.__hostSeries;
  62679. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  62680. },
  62681. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  62682. var MarkerModel = this.constructor;
  62683. var modelPropName = this.mainType + 'Model';
  62684. if (!createdBySelf) {
  62685. ecModel.eachSeries(function (seriesModel) {
  62686. var markerOpt = seriesModel.get(this.mainType);
  62687. var markerModel = seriesModel[modelPropName];
  62688. if (!markerOpt || !markerOpt.data) {
  62689. seriesModel[modelPropName] = null;
  62690. return;
  62691. }
  62692. if (!markerModel) {
  62693. if (isInit) {
  62694. // Default label emphasis `position` and `show`
  62695. fillLabel(markerOpt);
  62696. }
  62697. each$1(markerOpt.data, function (item) {
  62698. // FIXME Overwrite fillLabel method ?
  62699. if (item instanceof Array) {
  62700. fillLabel(item[0]);
  62701. fillLabel(item[1]);
  62702. }
  62703. else {
  62704. fillLabel(item);
  62705. }
  62706. });
  62707. markerModel = new MarkerModel(
  62708. markerOpt, this, ecModel
  62709. );
  62710. extend(markerModel, {
  62711. mainType: this.mainType,
  62712. // Use the same series index and name
  62713. seriesIndex: seriesModel.seriesIndex,
  62714. name: seriesModel.name,
  62715. createdBySelf: true
  62716. });
  62717. markerModel.__hostSeries = seriesModel;
  62718. }
  62719. else {
  62720. markerModel.mergeOption(markerOpt, ecModel, true);
  62721. }
  62722. seriesModel[modelPropName] = markerModel;
  62723. }, this);
  62724. }
  62725. },
  62726. formatTooltip: function (dataIndex) {
  62727. var data = this.getData();
  62728. var value = this.getRawValue(dataIndex);
  62729. var formattedValue = isArray(value)
  62730. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  62731. var name = data.getName(dataIndex);
  62732. var html = encodeHTML$1(this.name);
  62733. if (value != null || name) {
  62734. html += '<br />';
  62735. }
  62736. if (name) {
  62737. html += encodeHTML$1(name);
  62738. if (value != null) {
  62739. html += ' : ';
  62740. }
  62741. }
  62742. if (value != null) {
  62743. html += encodeHTML$1(formattedValue);
  62744. }
  62745. return html;
  62746. },
  62747. getData: function () {
  62748. return this._data;
  62749. },
  62750. setData: function (data) {
  62751. this._data = data;
  62752. }
  62753. });
  62754. mixin(MarkerModel, dataFormatMixin);
  62755. MarkerModel.extend({
  62756. type: 'markPoint',
  62757. defaultOption: {
  62758. zlevel: 0,
  62759. z: 5,
  62760. symbol: 'pin',
  62761. symbolSize: 50,
  62762. //symbolRotate: 0,
  62763. //symbolOffset: [0, 0]
  62764. tooltip: {
  62765. trigger: 'item'
  62766. },
  62767. label: {
  62768. show: true,
  62769. position: 'inside'
  62770. },
  62771. itemStyle: {
  62772. borderWidth: 2
  62773. },
  62774. emphasis: {
  62775. label: {
  62776. show: true
  62777. }
  62778. }
  62779. }
  62780. });
  62781. var indexOf$2 = indexOf;
  62782. function hasXOrY(item) {
  62783. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  62784. }
  62785. function hasXAndY(item) {
  62786. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  62787. }
  62788. function getPrecision$1(data, valueAxisDim, dataIndex) {
  62789. var precision = -1;
  62790. do {
  62791. precision = Math.max(
  62792. getPrecision(data.get(
  62793. valueAxisDim, dataIndex
  62794. )),
  62795. precision
  62796. );
  62797. data = data.stackedOn;
  62798. } while (data);
  62799. return precision;
  62800. }
  62801. function markerTypeCalculatorWithExtent(
  62802. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  62803. ) {
  62804. var coordArr = [];
  62805. var value = numCalculate(data, targetDataDim, mlType);
  62806. var dataIndex = data.indicesOfNearest(targetDataDim, value, true)[0];
  62807. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex, true);
  62808. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex, true);
  62809. var precision = getPrecision$1(data, targetDataDim, dataIndex);
  62810. precision = Math.min(precision, 20);
  62811. if (precision >= 0) {
  62812. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  62813. }
  62814. return coordArr;
  62815. }
  62816. var curry$7 = curry;
  62817. // TODO Specified percent
  62818. var markerTypeCalculator = {
  62819. /**
  62820. * @method
  62821. * @param {module:echarts/data/List} data
  62822. * @param {string} baseAxisDim
  62823. * @param {string} valueAxisDim
  62824. */
  62825. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  62826. /**
  62827. * @method
  62828. * @param {module:echarts/data/List} data
  62829. * @param {string} baseAxisDim
  62830. * @param {string} valueAxisDim
  62831. */
  62832. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  62833. /**
  62834. * @method
  62835. * @param {module:echarts/data/List} data
  62836. * @param {string} baseAxisDim
  62837. * @param {string} valueAxisDim
  62838. */
  62839. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  62840. };
  62841. /**
  62842. * Transform markPoint data item to format used in List by do the following
  62843. * 1. Calculate statistic like `max`, `min`, `average`
  62844. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  62845. * @param {module:echarts/model/Series} seriesModel
  62846. * @param {module:echarts/coord/*} [coordSys]
  62847. * @param {Object} item
  62848. * @return {Object}
  62849. */
  62850. function dataTransform(seriesModel, item) {
  62851. var data = seriesModel.getData();
  62852. var coordSys = seriesModel.coordinateSystem;
  62853. // 1. If not specify the position with pixel directly
  62854. // 2. If `coord` is not a data array. Which uses `xAxis`,
  62855. // `yAxis` to specify the coord on each dimension
  62856. // parseFloat first because item.x and item.y can be percent string like '20%'
  62857. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  62858. var dims = coordSys.dimensions;
  62859. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  62860. // Clone the option
  62861. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  62862. item = clone(item);
  62863. if (item.type
  62864. && markerTypeCalculator[item.type]
  62865. && axisInfo.baseAxis && axisInfo.valueAxis
  62866. ) {
  62867. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  62868. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  62869. item.coord = markerTypeCalculator[item.type](
  62870. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  62871. otherCoordIndex, targetCoordIndex
  62872. );
  62873. // Force to use the value of calculated value.
  62874. item.value = item.coord[targetCoordIndex];
  62875. }
  62876. else {
  62877. // FIXME Only has one of xAxis and yAxis.
  62878. var coord = [
  62879. item.xAxis != null ? item.xAxis : item.radiusAxis,
  62880. item.yAxis != null ? item.yAxis : item.angleAxis
  62881. ];
  62882. // Each coord support max, min, average
  62883. for (var i = 0; i < 2; i++) {
  62884. if (markerTypeCalculator[coord[i]]) {
  62885. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  62886. }
  62887. }
  62888. item.coord = coord;
  62889. }
  62890. }
  62891. return item;
  62892. }
  62893. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  62894. var ret = {};
  62895. if (item.valueIndex != null || item.valueDim != null) {
  62896. ret.valueDataDim = item.valueIndex != null
  62897. ? data.getDimension(item.valueIndex) : item.valueDim;
  62898. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  62899. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  62900. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  62901. }
  62902. else {
  62903. ret.baseAxis = seriesModel.getBaseAxis();
  62904. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  62905. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  62906. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  62907. }
  62908. return ret;
  62909. }
  62910. function dataDimToCoordDim(seriesModel, dataDim) {
  62911. var data = seriesModel.getData();
  62912. var dimensions = data.dimensions;
  62913. dataDim = data.getDimension(dataDim);
  62914. for (var i = 0; i < dimensions.length; i++) {
  62915. var dimItem = data.getDimensionInfo(dimensions[i]);
  62916. if (dimItem.name === dataDim) {
  62917. return dimItem.coordDim;
  62918. }
  62919. }
  62920. }
  62921. /**
  62922. * Filter data which is out of coordinateSystem range
  62923. * [dataFilter description]
  62924. * @param {module:echarts/coord/*} [coordSys]
  62925. * @param {Object} item
  62926. * @return {boolean}
  62927. */
  62928. function dataFilter$1(coordSys, item) {
  62929. // Alwalys return true if there is no coordSys
  62930. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  62931. ? coordSys.containData(item.coord) : true;
  62932. }
  62933. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  62934. // x, y, radius, angle
  62935. if (dimIndex < 2) {
  62936. return item.coord && item.coord[dimIndex];
  62937. }
  62938. return item.value;
  62939. }
  62940. function numCalculate(data, valueDataDim, type) {
  62941. if (type === 'average') {
  62942. var sum = 0;
  62943. var count = 0;
  62944. data.each(valueDataDim, function (val, idx) {
  62945. if (!isNaN(val)) {
  62946. sum += val;
  62947. count++;
  62948. }
  62949. }, true);
  62950. return sum / count;
  62951. }
  62952. else {
  62953. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  62954. }
  62955. }
  62956. var MarkerView = extendComponentView({
  62957. type: 'marker',
  62958. init: function () {
  62959. /**
  62960. * Markline grouped by series
  62961. * @private
  62962. * @type {module:zrender/core/util.HashMap}
  62963. */
  62964. this.markerGroupMap = createHashMap();
  62965. },
  62966. render: function (markerModel, ecModel, api) {
  62967. var markerGroupMap = this.markerGroupMap;
  62968. markerGroupMap.each(function (item) {
  62969. item.__keep = false;
  62970. });
  62971. var markerModelKey = this.type + 'Model';
  62972. ecModel.eachSeries(function (seriesModel) {
  62973. var markerModel = seriesModel[markerModelKey];
  62974. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  62975. }, this);
  62976. markerGroupMap.each(function (item) {
  62977. !item.__keep && this.group.remove(item.group);
  62978. }, this);
  62979. },
  62980. renderSeries: function () {}
  62981. });
  62982. function updateMarkerLayout(mpData, seriesModel, api) {
  62983. var coordSys = seriesModel.coordinateSystem;
  62984. mpData.each(function (idx) {
  62985. var itemModel = mpData.getItemModel(idx);
  62986. var point;
  62987. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  62988. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  62989. if (!isNaN(xPx) && !isNaN(yPx)) {
  62990. point = [xPx, yPx];
  62991. }
  62992. // Chart like bar may have there own marker positioning logic
  62993. else if (seriesModel.getMarkerPosition) {
  62994. // Use the getMarkerPoisition
  62995. point = seriesModel.getMarkerPosition(
  62996. mpData.getValues(mpData.dimensions, idx)
  62997. );
  62998. }
  62999. else if (coordSys) {
  63000. var x = mpData.get(coordSys.dimensions[0], idx);
  63001. var y = mpData.get(coordSys.dimensions[1], idx);
  63002. point = coordSys.dataToPoint([x, y]);
  63003. }
  63004. // Use x, y if has any
  63005. if (!isNaN(xPx)) {
  63006. point[0] = xPx;
  63007. }
  63008. if (!isNaN(yPx)) {
  63009. point[1] = yPx;
  63010. }
  63011. mpData.setItemLayout(idx, point);
  63012. });
  63013. }
  63014. MarkerView.extend({
  63015. type: 'markPoint',
  63016. // updateLayout: function (markPointModel, ecModel, api) {
  63017. // ecModel.eachSeries(function (seriesModel) {
  63018. // var mpModel = seriesModel.markPointModel;
  63019. // if (mpModel) {
  63020. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63021. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63022. // }
  63023. // }, this);
  63024. // },
  63025. updateTransform: function (markPointModel, ecModel, api) {
  63026. ecModel.eachSeries(function (seriesModel) {
  63027. var mpModel = seriesModel.markPointModel;
  63028. if (mpModel) {
  63029. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63030. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63031. }
  63032. }, this);
  63033. },
  63034. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  63035. var coordSys = seriesModel.coordinateSystem;
  63036. var seriesId = seriesModel.id;
  63037. var seriesData = seriesModel.getData();
  63038. var symbolDrawMap = this.markerGroupMap;
  63039. var symbolDraw = symbolDrawMap.get(seriesId)
  63040. || symbolDrawMap.set(seriesId, new SymbolDraw());
  63041. var mpData = createList$1(coordSys, seriesModel, mpModel);
  63042. // FIXME
  63043. mpModel.setData(mpData);
  63044. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63045. mpData.each(function (idx) {
  63046. var itemModel = mpData.getItemModel(idx);
  63047. var symbolSize = itemModel.getShallow('symbolSize');
  63048. if (typeof symbolSize === 'function') {
  63049. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  63050. symbolSize = symbolSize(
  63051. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  63052. );
  63053. }
  63054. mpData.setItemVisual(idx, {
  63055. symbolSize: symbolSize,
  63056. color: itemModel.get('itemStyle.color')
  63057. || seriesData.getVisual('color'),
  63058. symbol: itemModel.getShallow('symbol')
  63059. });
  63060. });
  63061. // TODO Text are wrong
  63062. symbolDraw.updateData(mpData);
  63063. this.group.add(symbolDraw.group);
  63064. // Set host model for tooltip
  63065. // FIXME
  63066. mpData.eachItemGraphicEl(function (el) {
  63067. el.traverse(function (child) {
  63068. child.dataModel = mpModel;
  63069. });
  63070. });
  63071. symbolDraw.__keep = true;
  63072. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  63073. }
  63074. });
  63075. /**
  63076. * @inner
  63077. * @param {module:echarts/coord/*} [coordSys]
  63078. * @param {module:echarts/model/Series} seriesModel
  63079. * @param {module:echarts/model/Model} mpModel
  63080. */
  63081. function createList$1(coordSys, seriesModel, mpModel) {
  63082. var coordDimsInfos;
  63083. if (coordSys) {
  63084. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  63085. var info = seriesModel.getData().getDimensionInfo(
  63086. seriesModel.getData().mapDimension(coordDim)
  63087. ) || {};
  63088. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  63089. return defaults({name: coordDim, isSysCoord: true}, info);
  63090. });
  63091. }
  63092. else {
  63093. coordDimsInfos =[{
  63094. name: 'value',
  63095. type: 'float',
  63096. isSysCoord: true
  63097. }];
  63098. }
  63099. var mpData = new List(coordDimsInfos, mpModel);
  63100. var dataOpt = map(mpModel.get('data'), curry(
  63101. dataTransform, seriesModel
  63102. ));
  63103. if (coordSys) {
  63104. dataOpt = filter(
  63105. dataOpt, curry(dataFilter$1, coordSys)
  63106. );
  63107. }
  63108. mpData.initData(dataOpt, null,
  63109. coordSys ? dimValueGetter : function (item) {
  63110. return item.value;
  63111. }
  63112. );
  63113. return mpData;
  63114. }
  63115. // HINT Markpoint can't be used too much
  63116. registerPreprocessor(function (opt) {
  63117. // Make sure markPoint component is enabled
  63118. opt.markPoint = opt.markPoint || {};
  63119. });
  63120. MarkerModel.extend({
  63121. type: 'markLine',
  63122. defaultOption: {
  63123. zlevel: 0,
  63124. z: 5,
  63125. symbol: ['circle', 'arrow'],
  63126. symbolSize: [8, 16],
  63127. //symbolRotate: 0,
  63128. precision: 2,
  63129. tooltip: {
  63130. trigger: 'item'
  63131. },
  63132. label: {
  63133. show: true,
  63134. position: 'end'
  63135. },
  63136. lineStyle: {
  63137. type: 'dashed'
  63138. },
  63139. emphasis: {
  63140. label: {
  63141. show: true
  63142. },
  63143. lineStyle: {
  63144. width: 3
  63145. }
  63146. },
  63147. animationEasing: 'linear'
  63148. }
  63149. });
  63150. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  63151. var data = seriesModel.getData();
  63152. // Special type markLine like 'min', 'max', 'average'
  63153. var mlType = item.type;
  63154. if (!isArray(item)
  63155. && (
  63156. mlType === 'min' || mlType === 'max' || mlType === 'average'
  63157. // In case
  63158. // data: [{
  63159. // yAxis: 10
  63160. // }]
  63161. || (item.xAxis != null || item.yAxis != null)
  63162. )
  63163. ) {
  63164. var valueAxis;
  63165. var valueDataDim;
  63166. var value;
  63167. if (item.yAxis != null || item.xAxis != null) {
  63168. valueDataDim = item.yAxis != null ? 'y' : 'x';
  63169. valueAxis = coordSys.getAxis(valueDataDim);
  63170. value = retrieve(item.yAxis, item.xAxis);
  63171. }
  63172. else {
  63173. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  63174. valueDataDim = axisInfo.valueDataDim;
  63175. valueAxis = axisInfo.valueAxis;
  63176. value = numCalculate(data, valueDataDim, mlType);
  63177. }
  63178. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  63179. var baseIndex = 1 - valueIndex;
  63180. var mlFrom = clone(item);
  63181. var mlTo = {};
  63182. mlFrom.type = null;
  63183. mlFrom.coord = [];
  63184. mlTo.coord = [];
  63185. mlFrom.coord[baseIndex] = -Infinity;
  63186. mlTo.coord[baseIndex] = Infinity;
  63187. var precision = mlModel.get('precision');
  63188. if (precision >= 0 && typeof value === 'number') {
  63189. value = +value.toFixed(Math.min(precision, 20));
  63190. }
  63191. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  63192. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  63193. type: mlType,
  63194. valueIndex: item.valueIndex,
  63195. // Force to use the value of calculated value.
  63196. value: value
  63197. }];
  63198. }
  63199. item = [
  63200. dataTransform(seriesModel, item[0]),
  63201. dataTransform(seriesModel, item[1]),
  63202. extend({}, item[2])
  63203. ];
  63204. // Avoid line data type is extended by from(to) data type
  63205. item[2].type = item[2].type || '';
  63206. // Merge from option and to option into line option
  63207. merge(item[2], item[0]);
  63208. merge(item[2], item[1]);
  63209. return item;
  63210. };
  63211. function isInifinity(val) {
  63212. return !isNaN(val) && !isFinite(val);
  63213. }
  63214. // If a markLine has one dim
  63215. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  63216. var otherDimIndex = 1 - dimIndex;
  63217. var dimName = coordSys.dimensions[dimIndex];
  63218. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  63219. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  63220. }
  63221. function markLineFilter(coordSys, item) {
  63222. if (coordSys.type === 'cartesian2d') {
  63223. var fromCoord = item[0].coord;
  63224. var toCoord = item[1].coord;
  63225. // In case
  63226. // {
  63227. // markLine: {
  63228. // data: [{ yAxis: 2 }]
  63229. // }
  63230. // }
  63231. if (
  63232. fromCoord && toCoord &&
  63233. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  63234. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  63235. ) {
  63236. return true;
  63237. }
  63238. }
  63239. return dataFilter$1(coordSys, item[0])
  63240. && dataFilter$1(coordSys, item[1]);
  63241. }
  63242. function updateSingleMarkerEndLayout(
  63243. data, idx, isFrom, seriesModel, api
  63244. ) {
  63245. var coordSys = seriesModel.coordinateSystem;
  63246. var itemModel = data.getItemModel(idx);
  63247. var point;
  63248. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  63249. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  63250. if (!isNaN(xPx) && !isNaN(yPx)) {
  63251. point = [xPx, yPx];
  63252. }
  63253. else {
  63254. // Chart like bar may have there own marker positioning logic
  63255. if (seriesModel.getMarkerPosition) {
  63256. // Use the getMarkerPoisition
  63257. point = seriesModel.getMarkerPosition(
  63258. data.getValues(data.dimensions, idx)
  63259. );
  63260. }
  63261. else {
  63262. var dims = coordSys.dimensions;
  63263. var x = data.get(dims[0], idx);
  63264. var y = data.get(dims[1], idx);
  63265. point = coordSys.dataToPoint([x, y]);
  63266. }
  63267. // Expand line to the edge of grid if value on one axis is Inifnity
  63268. // In case
  63269. // markLine: {
  63270. // data: [{
  63271. // yAxis: 2
  63272. // // or
  63273. // type: 'average'
  63274. // }]
  63275. // }
  63276. if (coordSys.type === 'cartesian2d') {
  63277. var xAxis = coordSys.getAxis('x');
  63278. var yAxis = coordSys.getAxis('y');
  63279. var dims = coordSys.dimensions;
  63280. if (isInifinity(data.get(dims[0], idx))) {
  63281. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  63282. }
  63283. else if (isInifinity(data.get(dims[1], idx))) {
  63284. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  63285. }
  63286. }
  63287. // Use x, y if has any
  63288. if (!isNaN(xPx)) {
  63289. point[0] = xPx;
  63290. }
  63291. if (!isNaN(yPx)) {
  63292. point[1] = yPx;
  63293. }
  63294. }
  63295. data.setItemLayout(idx, point);
  63296. }
  63297. MarkerView.extend({
  63298. type: 'markLine',
  63299. // updateLayout: function (markLineModel, ecModel, api) {
  63300. // ecModel.eachSeries(function (seriesModel) {
  63301. // var mlModel = seriesModel.markLineModel;
  63302. // if (mlModel) {
  63303. // var mlData = mlModel.getData();
  63304. // var fromData = mlModel.__from;
  63305. // var toData = mlModel.__to;
  63306. // // Update visual and layout of from symbol and to symbol
  63307. // fromData.each(function (idx) {
  63308. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  63309. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  63310. // });
  63311. // // Update layout of line
  63312. // mlData.each(function (idx) {
  63313. // mlData.setItemLayout(idx, [
  63314. // fromData.getItemLayout(idx),
  63315. // toData.getItemLayout(idx)
  63316. // ]);
  63317. // });
  63318. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  63319. // }
  63320. // }, this);
  63321. // },
  63322. updateTransform: function (markLineModel, ecModel, api) {
  63323. ecModel.eachSeries(function (seriesModel) {
  63324. var mlModel = seriesModel.markLineModel;
  63325. if (mlModel) {
  63326. var mlData = mlModel.getData();
  63327. var fromData = mlModel.__from;
  63328. var toData = mlModel.__to;
  63329. // Update visual and layout of from symbol and to symbol
  63330. fromData.each(function (idx) {
  63331. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  63332. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  63333. });
  63334. // Update layout of line
  63335. mlData.each(function (idx) {
  63336. mlData.setItemLayout(idx, [
  63337. fromData.getItemLayout(idx),
  63338. toData.getItemLayout(idx)
  63339. ]);
  63340. });
  63341. this.markerGroupMap.get(seriesModel.id).updateLayout();
  63342. }
  63343. }, this);
  63344. },
  63345. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  63346. var coordSys = seriesModel.coordinateSystem;
  63347. var seriesId = seriesModel.id;
  63348. var seriesData = seriesModel.getData();
  63349. var lineDrawMap = this.markerGroupMap;
  63350. var lineDraw = lineDrawMap.get(seriesId)
  63351. || lineDrawMap.set(seriesId, new LineDraw());
  63352. this.group.add(lineDraw.group);
  63353. var mlData = createList$2(coordSys, seriesModel, mlModel);
  63354. var fromData = mlData.from;
  63355. var toData = mlData.to;
  63356. var lineData = mlData.line;
  63357. mlModel.__from = fromData;
  63358. mlModel.__to = toData;
  63359. // Line data for tooltip and formatter
  63360. mlModel.setData(lineData);
  63361. var symbolType = mlModel.get('symbol');
  63362. var symbolSize = mlModel.get('symbolSize');
  63363. if (!isArray(symbolType)) {
  63364. symbolType = [symbolType, symbolType];
  63365. }
  63366. if (typeof symbolSize === 'number') {
  63367. symbolSize = [symbolSize, symbolSize];
  63368. }
  63369. // Update visual and layout of from symbol and to symbol
  63370. mlData.from.each(function (idx) {
  63371. updateDataVisualAndLayout(fromData, idx, true);
  63372. updateDataVisualAndLayout(toData, idx, false);
  63373. });
  63374. // Update visual and layout of line
  63375. lineData.each(function (idx) {
  63376. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  63377. lineData.setItemVisual(idx, {
  63378. color: lineColor || fromData.getItemVisual(idx, 'color')
  63379. });
  63380. lineData.setItemLayout(idx, [
  63381. fromData.getItemLayout(idx),
  63382. toData.getItemLayout(idx)
  63383. ]);
  63384. lineData.setItemVisual(idx, {
  63385. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  63386. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  63387. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  63388. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  63389. });
  63390. });
  63391. lineDraw.updateData(lineData);
  63392. // Set host model for tooltip
  63393. // FIXME
  63394. mlData.line.eachItemGraphicEl(function (el, idx) {
  63395. el.traverse(function (child) {
  63396. child.dataModel = mlModel;
  63397. });
  63398. });
  63399. function updateDataVisualAndLayout(data, idx, isFrom) {
  63400. var itemModel = data.getItemModel(idx);
  63401. updateSingleMarkerEndLayout(
  63402. data, idx, isFrom, seriesModel, api
  63403. );
  63404. data.setItemVisual(idx, {
  63405. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  63406. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  63407. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  63408. });
  63409. }
  63410. lineDraw.__keep = true;
  63411. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  63412. }
  63413. });
  63414. /**
  63415. * @inner
  63416. * @param {module:echarts/coord/*} coordSys
  63417. * @param {module:echarts/model/Series} seriesModel
  63418. * @param {module:echarts/model/Model} mpModel
  63419. */
  63420. function createList$2(coordSys, seriesModel, mlModel) {
  63421. var coordDimsInfos;
  63422. if (coordSys) {
  63423. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  63424. var info = seriesModel.getData().getDimensionInfo(
  63425. seriesModel.getData().mapDimension(coordDim)
  63426. ) || {};
  63427. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  63428. return defaults({name: coordDim}, info);
  63429. });
  63430. }
  63431. else {
  63432. coordDimsInfos =[{
  63433. name: 'value',
  63434. type: 'float'
  63435. }];
  63436. }
  63437. var fromData = new List(coordDimsInfos, mlModel);
  63438. var toData = new List(coordDimsInfos, mlModel);
  63439. // No dimensions
  63440. var lineData = new List([], mlModel);
  63441. var optData = map(mlModel.get('data'), curry(
  63442. markLineTransform, seriesModel, coordSys, mlModel
  63443. ));
  63444. if (coordSys) {
  63445. optData = filter(
  63446. optData, curry(markLineFilter, coordSys)
  63447. );
  63448. }
  63449. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  63450. return item.value;
  63451. };
  63452. fromData.initData(
  63453. map(optData, function (item) { return item[0]; }),
  63454. null, dimValueGetter$$1
  63455. );
  63456. toData.initData(
  63457. map(optData, function (item) { return item[1]; }),
  63458. null, dimValueGetter$$1
  63459. );
  63460. lineData.initData(
  63461. map(optData, function (item) { return item[2]; })
  63462. );
  63463. lineData.hasItemOption = true;
  63464. return {
  63465. from: fromData,
  63466. to: toData,
  63467. line: lineData
  63468. };
  63469. }
  63470. registerPreprocessor(function (opt) {
  63471. // Make sure markLine component is enabled
  63472. opt.markLine = opt.markLine || {};
  63473. });
  63474. MarkerModel.extend({
  63475. type: 'markArea',
  63476. defaultOption: {
  63477. zlevel: 0,
  63478. // PENDING
  63479. z: 1,
  63480. tooltip: {
  63481. trigger: 'item'
  63482. },
  63483. // markArea should fixed on the coordinate system
  63484. animation: false,
  63485. label: {
  63486. show: true,
  63487. position: 'top'
  63488. },
  63489. itemStyle: {
  63490. // color and borderColor default to use color from series
  63491. // color: 'auto'
  63492. // borderColor: 'auto'
  63493. borderWidth: 0
  63494. },
  63495. emphasis: {
  63496. label: {
  63497. show: true,
  63498. position: 'top'
  63499. }
  63500. }
  63501. }
  63502. });
  63503. // TODO Better on polar
  63504. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  63505. var lt = dataTransform(seriesModel, item[0]);
  63506. var rb = dataTransform(seriesModel, item[1]);
  63507. var retrieve$$1 = retrieve;
  63508. // FIXME make sure lt is less than rb
  63509. var ltCoord = lt.coord;
  63510. var rbCoord = rb.coord;
  63511. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  63512. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  63513. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  63514. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  63515. // Merge option into one
  63516. var result = mergeAll([{}, lt, rb]);
  63517. result.coord = [
  63518. lt.coord, rb.coord
  63519. ];
  63520. result.x0 = lt.x;
  63521. result.y0 = lt.y;
  63522. result.x1 = rb.x;
  63523. result.y1 = rb.y;
  63524. return result;
  63525. };
  63526. function isInifinity$1(val) {
  63527. return !isNaN(val) && !isFinite(val);
  63528. }
  63529. // If a markArea has one dim
  63530. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  63531. var otherDimIndex = 1 - dimIndex;
  63532. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  63533. }
  63534. function markAreaFilter(coordSys, item) {
  63535. var fromCoord = item.coord[0];
  63536. var toCoord = item.coord[1];
  63537. if (coordSys.type === 'cartesian2d') {
  63538. // In case
  63539. // {
  63540. // markArea: {
  63541. // data: [{ yAxis: 2 }]
  63542. // }
  63543. // }
  63544. if (
  63545. fromCoord && toCoord &&
  63546. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  63547. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  63548. ) {
  63549. return true;
  63550. }
  63551. }
  63552. return dataFilter$1(coordSys, {
  63553. coord: fromCoord,
  63554. x: item.x0,
  63555. y: item.y0
  63556. })
  63557. || dataFilter$1(coordSys, {
  63558. coord: toCoord,
  63559. x: item.x1,
  63560. y: item.y1
  63561. });
  63562. }
  63563. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  63564. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  63565. var coordSys = seriesModel.coordinateSystem;
  63566. var itemModel = data.getItemModel(idx);
  63567. var point;
  63568. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  63569. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  63570. if (!isNaN(xPx) && !isNaN(yPx)) {
  63571. point = [xPx, yPx];
  63572. }
  63573. else {
  63574. // Chart like bar may have there own marker positioning logic
  63575. if (seriesModel.getMarkerPosition) {
  63576. // Use the getMarkerPoisition
  63577. point = seriesModel.getMarkerPosition(
  63578. data.getValues(dims, idx)
  63579. );
  63580. }
  63581. else {
  63582. var x = data.get(dims[0], idx);
  63583. var y = data.get(dims[1], idx);
  63584. var pt = [x, y];
  63585. coordSys.clampData && coordSys.clampData(pt, pt);
  63586. point = coordSys.dataToPoint(pt, true);
  63587. }
  63588. if (coordSys.type === 'cartesian2d') {
  63589. var xAxis = coordSys.getAxis('x');
  63590. var yAxis = coordSys.getAxis('y');
  63591. var x = data.get(dims[0], idx);
  63592. var y = data.get(dims[1], idx);
  63593. if (isInifinity$1(x)) {
  63594. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  63595. }
  63596. else if (isInifinity$1(y)) {
  63597. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  63598. }
  63599. }
  63600. // Use x, y if has any
  63601. if (!isNaN(xPx)) {
  63602. point[0] = xPx;
  63603. }
  63604. if (!isNaN(yPx)) {
  63605. point[1] = yPx;
  63606. }
  63607. }
  63608. return point;
  63609. }
  63610. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  63611. MarkerView.extend({
  63612. type: 'markArea',
  63613. // updateLayout: function (markAreaModel, ecModel, api) {
  63614. // ecModel.eachSeries(function (seriesModel) {
  63615. // var maModel = seriesModel.markAreaModel;
  63616. // if (maModel) {
  63617. // var areaData = maModel.getData();
  63618. // areaData.each(function (idx) {
  63619. // var points = zrUtil.map(dimPermutations, function (dim) {
  63620. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  63621. // });
  63622. // // Layout
  63623. // areaData.setItemLayout(idx, points);
  63624. // var el = areaData.getItemGraphicEl(idx);
  63625. // el.setShape('points', points);
  63626. // });
  63627. // }
  63628. // }, this);
  63629. // },
  63630. updateTransform: function (markAreaModel, ecModel, api) {
  63631. ecModel.eachSeries(function (seriesModel) {
  63632. var maModel = seriesModel.markAreaModel;
  63633. if (maModel) {
  63634. var areaData = maModel.getData();
  63635. areaData.each(function (idx) {
  63636. var points = map(dimPermutations, function (dim) {
  63637. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  63638. });
  63639. // Layout
  63640. areaData.setItemLayout(idx, points);
  63641. var el = areaData.getItemGraphicEl(idx);
  63642. el.setShape('points', points);
  63643. });
  63644. }
  63645. }, this);
  63646. },
  63647. renderSeries: function (seriesModel, maModel, ecModel, api) {
  63648. var coordSys = seriesModel.coordinateSystem;
  63649. var seriesName = seriesModel.name;
  63650. var seriesData = seriesModel.getData();
  63651. var areaGroupMap = this.markerGroupMap;
  63652. var polygonGroup = areaGroupMap.get(seriesName)
  63653. || areaGroupMap.set(seriesName, {group: new Group()});
  63654. this.group.add(polygonGroup.group);
  63655. polygonGroup.__keep = true;
  63656. var areaData = createList$3(coordSys, seriesModel, maModel);
  63657. // Line data for tooltip and formatter
  63658. maModel.setData(areaData);
  63659. // Update visual and layout of line
  63660. areaData.each(function (idx) {
  63661. // Layout
  63662. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  63663. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  63664. }));
  63665. // Visual
  63666. areaData.setItemVisual(idx, {
  63667. color: seriesData.getVisual('color')
  63668. });
  63669. });
  63670. areaData.diff(polygonGroup.__data)
  63671. .add(function (idx) {
  63672. var polygon = new Polygon({
  63673. shape: {
  63674. points: areaData.getItemLayout(idx)
  63675. }
  63676. });
  63677. areaData.setItemGraphicEl(idx, polygon);
  63678. polygonGroup.group.add(polygon);
  63679. })
  63680. .update(function (newIdx, oldIdx) {
  63681. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  63682. updateProps(polygon, {
  63683. shape: {
  63684. points: areaData.getItemLayout(newIdx)
  63685. }
  63686. }, maModel, newIdx);
  63687. polygonGroup.group.add(polygon);
  63688. areaData.setItemGraphicEl(newIdx, polygon);
  63689. })
  63690. .remove(function (idx) {
  63691. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  63692. polygonGroup.group.remove(polygon);
  63693. })
  63694. .execute();
  63695. areaData.eachItemGraphicEl(function (polygon, idx) {
  63696. var itemModel = areaData.getItemModel(idx);
  63697. var labelModel = itemModel.getModel('label');
  63698. var labelHoverModel = itemModel.getModel('emphasis.label');
  63699. var color = areaData.getItemVisual(idx, 'color');
  63700. polygon.useStyle(
  63701. defaults(
  63702. itemModel.getModel('itemStyle').getItemStyle(),
  63703. {
  63704. fill: modifyAlpha(color, 0.4),
  63705. stroke: color
  63706. }
  63707. )
  63708. );
  63709. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  63710. setLabelStyle(
  63711. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  63712. {
  63713. labelFetcher: maModel,
  63714. labelDataIndex: idx,
  63715. defaultText: areaData.getName(idx) || '',
  63716. isRectText: true,
  63717. autoColor: color
  63718. }
  63719. );
  63720. setHoverStyle(polygon, {});
  63721. polygon.dataModel = maModel;
  63722. });
  63723. polygonGroup.__data = areaData;
  63724. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  63725. }
  63726. });
  63727. /**
  63728. * @inner
  63729. * @param {module:echarts/coord/*} coordSys
  63730. * @param {module:echarts/model/Series} seriesModel
  63731. * @param {module:echarts/model/Model} mpModel
  63732. */
  63733. function createList$3(coordSys, seriesModel, maModel) {
  63734. var coordDimsInfos;
  63735. var areaData;
  63736. var dims = ['x0', 'y0', 'x1', 'y1'];
  63737. if (coordSys) {
  63738. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  63739. var data = seriesModel.getData();
  63740. var info = data.getDimensionInfo(
  63741. data.mapDimension(coordDim)
  63742. ) || {};
  63743. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  63744. return defaults({name: coordDim}, info);
  63745. });
  63746. areaData = new List(map(dims, function (dim, idx) {
  63747. return {
  63748. name: dim,
  63749. type: coordDimsInfos[idx % 2].type
  63750. };
  63751. }), maModel);
  63752. }
  63753. else {
  63754. coordDimsInfos =[{
  63755. name: 'value',
  63756. type: 'float'
  63757. }];
  63758. areaData = new List(coordDimsInfos, maModel);
  63759. }
  63760. var optData = map(maModel.get('data'), curry(
  63761. markAreaTransform, seriesModel, coordSys, maModel
  63762. ));
  63763. if (coordSys) {
  63764. optData = filter(
  63765. optData, curry(markAreaFilter, coordSys)
  63766. );
  63767. }
  63768. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  63769. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  63770. } : function (item) {
  63771. return item.value;
  63772. };
  63773. areaData.initData(optData, null, dimValueGetter$$1);
  63774. areaData.hasItemOption = true;
  63775. return areaData;
  63776. }
  63777. registerPreprocessor(function (opt) {
  63778. // Make sure markArea component is enabled
  63779. opt.markArea = opt.markArea || {};
  63780. });
  63781. var preprocessor$3 = function (option) {
  63782. var timelineOpt = option && option.timeline;
  63783. if (!isArray(timelineOpt)) {
  63784. timelineOpt = timelineOpt ? [timelineOpt] : [];
  63785. }
  63786. each$1(timelineOpt, function (opt) {
  63787. if (!opt) {
  63788. return;
  63789. }
  63790. compatibleEC2(opt);
  63791. });
  63792. };
  63793. function compatibleEC2(opt) {
  63794. var type = opt.type;
  63795. var ec2Types = {'number': 'value', 'time': 'time'};
  63796. // Compatible with ec2
  63797. if (ec2Types[type]) {
  63798. opt.axisType = ec2Types[type];
  63799. delete opt.type;
  63800. }
  63801. transferItem(opt);
  63802. if (has$2(opt, 'controlPosition')) {
  63803. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  63804. if (!has$2(controlStyle, 'position')) {
  63805. controlStyle.position = opt.controlPosition;
  63806. }
  63807. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  63808. controlStyle.show = false;
  63809. delete controlStyle.position;
  63810. }
  63811. delete opt.controlPosition;
  63812. }
  63813. each$1(opt.data || [], function (dataItem) {
  63814. if (isObject$1(dataItem) && !isArray(dataItem)) {
  63815. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  63816. // In ec2, using name as value.
  63817. dataItem.value = dataItem.name;
  63818. }
  63819. transferItem(dataItem);
  63820. }
  63821. });
  63822. }
  63823. function transferItem(opt) {
  63824. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  63825. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  63826. // Transfer label out
  63827. var label = opt.label || (opt.label || {});
  63828. var labelNormal = label.normal || (label.normal = {});
  63829. var excludeLabelAttr = {normal: 1, emphasis: 1};
  63830. each$1(label, function (value, name) {
  63831. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  63832. labelNormal[name] = value;
  63833. }
  63834. });
  63835. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  63836. label.emphasis = itemStyleEmphasis.label;
  63837. delete itemStyleEmphasis.label;
  63838. }
  63839. }
  63840. function has$2(obj, attr) {
  63841. return obj.hasOwnProperty(attr);
  63842. }
  63843. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  63844. // Only slider now.
  63845. return 'slider';
  63846. });
  63847. registerAction(
  63848. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  63849. function (payload, ecModel) {
  63850. var timelineModel = ecModel.getComponent('timeline');
  63851. if (timelineModel && payload.currentIndex != null) {
  63852. timelineModel.setCurrentIndex(payload.currentIndex);
  63853. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  63854. timelineModel.setPlayState(false);
  63855. }
  63856. }
  63857. // Set normalized currentIndex to payload.
  63858. ecModel.resetOption('timeline');
  63859. return defaults({
  63860. currentIndex: timelineModel.option.currentIndex
  63861. }, payload);
  63862. }
  63863. );
  63864. registerAction(
  63865. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  63866. function (payload, ecModel) {
  63867. var timelineModel = ecModel.getComponent('timeline');
  63868. if (timelineModel && payload.playState != null) {
  63869. timelineModel.setPlayState(payload.playState);
  63870. }
  63871. }
  63872. );
  63873. var TimelineModel = ComponentModel.extend({
  63874. type: 'timeline',
  63875. layoutMode: 'box',
  63876. /**
  63877. * @protected
  63878. */
  63879. defaultOption: {
  63880. zlevel: 0, // 一级层叠
  63881. z: 4, // 二级层叠
  63882. show: true,
  63883. axisType: 'time', // 模式是时间类型,支持 value, category
  63884. realtime: true,
  63885. left: '20%',
  63886. top: null,
  63887. right: '20%',
  63888. bottom: 0,
  63889. width: null,
  63890. height: 40,
  63891. padding: 5,
  63892. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  63893. autoPlay: false,
  63894. rewind: false, // 反向播放
  63895. loop: true,
  63896. playInterval: 2000, // 播放时间间隔,单位ms
  63897. currentIndex: 0,
  63898. itemStyle: {},
  63899. label: {
  63900. color: '#000'
  63901. },
  63902. data: []
  63903. },
  63904. /**
  63905. * @override
  63906. */
  63907. init: function (option, parentModel, ecModel) {
  63908. /**
  63909. * @private
  63910. * @type {module:echarts/data/List}
  63911. */
  63912. this._data;
  63913. /**
  63914. * @private
  63915. * @type {Array.<string>}
  63916. */
  63917. this._names;
  63918. this.mergeDefaultAndTheme(option, ecModel);
  63919. this._initData();
  63920. },
  63921. /**
  63922. * @override
  63923. */
  63924. mergeOption: function (option) {
  63925. TimelineModel.superApply(this, 'mergeOption', arguments);
  63926. this._initData();
  63927. },
  63928. /**
  63929. * @param {number} [currentIndex]
  63930. */
  63931. setCurrentIndex: function (currentIndex) {
  63932. if (currentIndex == null) {
  63933. currentIndex = this.option.currentIndex;
  63934. }
  63935. var count = this._data.count();
  63936. if (this.option.loop) {
  63937. currentIndex = (currentIndex % count + count) % count;
  63938. }
  63939. else {
  63940. currentIndex >= count && (currentIndex = count - 1);
  63941. currentIndex < 0 && (currentIndex = 0);
  63942. }
  63943. this.option.currentIndex = currentIndex;
  63944. },
  63945. /**
  63946. * @return {number} currentIndex
  63947. */
  63948. getCurrentIndex: function () {
  63949. return this.option.currentIndex;
  63950. },
  63951. /**
  63952. * @return {boolean}
  63953. */
  63954. isIndexMax: function () {
  63955. return this.getCurrentIndex() >= this._data.count() - 1;
  63956. },
  63957. /**
  63958. * @param {boolean} state true: play, false: stop
  63959. */
  63960. setPlayState: function (state) {
  63961. this.option.autoPlay = !!state;
  63962. },
  63963. /**
  63964. * @return {boolean} true: play, false: stop
  63965. */
  63966. getPlayState: function () {
  63967. return !!this.option.autoPlay;
  63968. },
  63969. /**
  63970. * @private
  63971. */
  63972. _initData: function () {
  63973. var thisOption = this.option;
  63974. var dataArr = thisOption.data || [];
  63975. var axisType = thisOption.axisType;
  63976. var names = this._names = [];
  63977. if (axisType === 'category') {
  63978. var idxArr = [];
  63979. each$1(dataArr, function (item, index) {
  63980. var value = getDataItemValue(item);
  63981. var newItem;
  63982. if (isObject$1(item)) {
  63983. newItem = clone(item);
  63984. newItem.value = index;
  63985. }
  63986. else {
  63987. newItem = index;
  63988. }
  63989. idxArr.push(newItem);
  63990. if (!isString(value) && (value == null || isNaN(value))) {
  63991. value = '';
  63992. }
  63993. names.push(value + '');
  63994. });
  63995. dataArr = idxArr;
  63996. }
  63997. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  63998. var data = this._data = new List([{name: 'value', type: dimType}], this);
  63999. data.initData(dataArr, names);
  64000. },
  64001. getData: function () {
  64002. return this._data;
  64003. },
  64004. /**
  64005. * @public
  64006. * @return {Array.<string>} categoreis
  64007. */
  64008. getCategories: function () {
  64009. if (this.get('axisType') === 'category') {
  64010. return this._names.slice();
  64011. }
  64012. }
  64013. });
  64014. var SliderTimelineModel = TimelineModel.extend({
  64015. type: 'timeline.slider',
  64016. /**
  64017. * @protected
  64018. */
  64019. defaultOption: {
  64020. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  64021. borderColor: '#ccc', // 时间轴边框颜色
  64022. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  64023. orient: 'horizontal', // 'vertical'
  64024. inverse: false,
  64025. tooltip: { // boolean or Object
  64026. trigger: 'item' // data item may also have tootip attr.
  64027. },
  64028. symbol: 'emptyCircle',
  64029. symbolSize: 10,
  64030. lineStyle: {
  64031. show: true,
  64032. width: 2,
  64033. color: '#304654'
  64034. },
  64035. label: { // 文本标签
  64036. position: 'auto', // auto left right top bottom
  64037. // When using number, label position is not
  64038. // restricted by viewRect.
  64039. // positive: right/bottom, negative: left/top
  64040. show: true,
  64041. interval: 'auto',
  64042. rotate: 0,
  64043. // formatter: null,
  64044. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64045. color: '#304654'
  64046. },
  64047. itemStyle: {
  64048. color: '#304654',
  64049. borderWidth: 1
  64050. },
  64051. checkpointStyle: {
  64052. symbol: 'circle',
  64053. symbolSize: 13,
  64054. color: '#c23531',
  64055. borderWidth: 5,
  64056. borderColor: 'rgba(194,53,49, 0.5)',
  64057. animation: true,
  64058. animationDuration: 300,
  64059. animationEasing: 'quinticInOut'
  64060. },
  64061. controlStyle: {
  64062. show: true,
  64063. showPlayBtn: true,
  64064. showPrevBtn: true,
  64065. showNextBtn: true,
  64066. itemSize: 22,
  64067. itemGap: 12,
  64068. position: 'left', // 'left' 'right' 'top' 'bottom'
  64069. playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z', // jshint ignore:line
  64070. stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z', // jshint ignore:line
  64071. nextIcon: 'path://M18.6,50.8l22.5-22.5c0.2-0.2,0.3-0.4,0.3-0.7c0-0.3-0.1-0.5-0.3-0.7L18.7,4.4c-0.1-0.1-0.2-0.3-0.2-0.5 c0-0.4,0.3-0.8,0.8-0.8c0.2,0,0.5,0.1,0.6,0.3l23.5,23.5l0,0c0.2,0.2,0.3,0.4,0.3,0.7c0,0.3-0.1,0.5-0.3,0.7l-0.1,0.1L19.7,52 c-0.1,0.1-0.3,0.2-0.5,0.2c-0.4,0-0.8-0.3-0.8-0.8C18.4,51.2,18.5,51,18.6,50.8z', // jshint ignore:line
  64072. prevIcon: 'path://M43,52.8L20.4,30.3c-0.2-0.2-0.3-0.4-0.3-0.7c0-0.3,0.1-0.5,0.3-0.7L42.9,6.4c0.1-0.1,0.2-0.3,0.2-0.5 c0-0.4-0.3-0.8-0.8-0.8c-0.2,0-0.5,0.1-0.6,0.3L18.3,28.8l0,0c-0.2,0.2-0.3,0.4-0.3,0.7c0,0.3,0.1,0.5,0.3,0.7l0.1,0.1L41.9,54 c0.1,0.1,0.3,0.2,0.5,0.2c0.4,0,0.8-0.3,0.8-0.8C43.2,53.2,43.1,53,43,52.8z', // jshint ignore:line
  64073. color: '#304654',
  64074. borderColor: '#304654',
  64075. borderWidth: 1
  64076. },
  64077. emphasis: {
  64078. label: {
  64079. show: true,
  64080. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64081. color: '#c23531'
  64082. },
  64083. itemStyle: {
  64084. color: '#c23531'
  64085. },
  64086. controlStyle: {
  64087. color: '#c23531',
  64088. borderColor: '#c23531',
  64089. borderWidth: 2
  64090. }
  64091. },
  64092. data: []
  64093. }
  64094. });
  64095. mixin(SliderTimelineModel, dataFormatMixin);
  64096. var TimelineView = Component.extend({
  64097. type: 'timeline'
  64098. });
  64099. /**
  64100. * Extend axis 2d
  64101. * @constructor module:echarts/coord/cartesian/Axis2D
  64102. * @extends {module:echarts/coord/cartesian/Axis}
  64103. * @param {string} dim
  64104. * @param {*} scale
  64105. * @param {Array.<number>} coordExtent
  64106. * @param {string} axisType
  64107. * @param {string} position
  64108. */
  64109. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  64110. Axis.call(this, dim, scale, coordExtent);
  64111. /**
  64112. * Axis type
  64113. * - 'category'
  64114. * - 'value'
  64115. * - 'time'
  64116. * - 'log'
  64117. * @type {string}
  64118. */
  64119. this.type = axisType || 'value';
  64120. /**
  64121. * @private
  64122. * @type {number}
  64123. */
  64124. this._autoLabelInterval;
  64125. /**
  64126. * Axis model
  64127. * @param {module:echarts/component/TimelineModel}
  64128. */
  64129. this.model = null;
  64130. };
  64131. TimelineAxis.prototype = {
  64132. constructor: TimelineAxis,
  64133. /**
  64134. * @public
  64135. * @return {number}
  64136. */
  64137. getLabelInterval: function () {
  64138. var timelineModel = this.model;
  64139. var labelModel = timelineModel.getModel('label');
  64140. var labelInterval = labelModel.get('interval');
  64141. if (labelInterval != null && labelInterval != 'auto') {
  64142. return labelInterval;
  64143. }
  64144. var labelInterval = this._autoLabelInterval;
  64145. if (!labelInterval) {
  64146. labelInterval = this._autoLabelInterval = getAxisLabelInterval(
  64147. map(this.scale.getTicks(), this.dataToCoord, this),
  64148. getFormattedLabels(this, labelModel.get('formatter')),
  64149. labelModel.getFont(),
  64150. timelineModel.get('orient') === 'horizontal' ? 0 : 90,
  64151. labelModel.get('rotate')
  64152. );
  64153. }
  64154. return labelInterval;
  64155. },
  64156. /**
  64157. * If label is ignored.
  64158. * Automatically used when axis is category and label can not be all shown
  64159. * @public
  64160. * @param {number} idx
  64161. * @return {boolean}
  64162. */
  64163. isLabelIgnored: function (idx) {
  64164. if (this.type === 'category') {
  64165. var labelInterval = this.getLabelInterval();
  64166. return ((typeof labelInterval === 'function')
  64167. && !labelInterval(idx, this.scale.getLabel(idx)))
  64168. || idx % (labelInterval + 1);
  64169. }
  64170. }
  64171. };
  64172. inherits(TimelineAxis, Axis);
  64173. var bind$6 = bind;
  64174. var each$28 = each$1;
  64175. var PI$4 = Math.PI;
  64176. TimelineView.extend({
  64177. type: 'timeline.slider',
  64178. init: function (ecModel, api) {
  64179. this.api = api;
  64180. /**
  64181. * @private
  64182. * @type {module:echarts/component/timeline/TimelineAxis}
  64183. */
  64184. this._axis;
  64185. /**
  64186. * @private
  64187. * @type {module:zrender/core/BoundingRect}
  64188. */
  64189. this._viewRect;
  64190. /**
  64191. * @type {number}
  64192. */
  64193. this._timer;
  64194. /**
  64195. * @type {module:zrender/Element}
  64196. */
  64197. this._currentPointer;
  64198. /**
  64199. * @type {module:zrender/container/Group}
  64200. */
  64201. this._mainGroup;
  64202. /**
  64203. * @type {module:zrender/container/Group}
  64204. */
  64205. this._labelGroup;
  64206. },
  64207. /**
  64208. * @override
  64209. */
  64210. render: function (timelineModel, ecModel, api, payload) {
  64211. this.model = timelineModel;
  64212. this.api = api;
  64213. this.ecModel = ecModel;
  64214. this.group.removeAll();
  64215. if (timelineModel.get('show', true)) {
  64216. var layoutInfo = this._layout(timelineModel, api);
  64217. var mainGroup = this._createGroup('mainGroup');
  64218. var labelGroup = this._createGroup('labelGroup');
  64219. /**
  64220. * @private
  64221. * @type {module:echarts/component/timeline/TimelineAxis}
  64222. */
  64223. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  64224. timelineModel.formatTooltip = function (dataIndex) {
  64225. return encodeHTML(axis.scale.getLabel(dataIndex));
  64226. };
  64227. each$28(
  64228. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  64229. function (name) {
  64230. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  64231. },
  64232. this
  64233. );
  64234. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  64235. this._position(layoutInfo, timelineModel);
  64236. }
  64237. this._doPlayStop();
  64238. },
  64239. /**
  64240. * @override
  64241. */
  64242. remove: function () {
  64243. this._clearTimer();
  64244. this.group.removeAll();
  64245. },
  64246. /**
  64247. * @override
  64248. */
  64249. dispose: function () {
  64250. this._clearTimer();
  64251. },
  64252. _layout: function (timelineModel, api) {
  64253. var labelPosOpt = timelineModel.get('label.position');
  64254. var orient = timelineModel.get('orient');
  64255. var viewRect = getViewRect$4(timelineModel, api);
  64256. // Auto label offset.
  64257. if (labelPosOpt == null || labelPosOpt === 'auto') {
  64258. labelPosOpt = orient === 'horizontal'
  64259. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  64260. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  64261. }
  64262. else if (isNaN(labelPosOpt)) {
  64263. labelPosOpt = ({
  64264. horizontal: {top: '-', bottom: '+'},
  64265. vertical: {left: '-', right: '+'}
  64266. })[orient][labelPosOpt];
  64267. }
  64268. var labelAlignMap = {
  64269. horizontal: 'center',
  64270. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  64271. };
  64272. var labelBaselineMap = {
  64273. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  64274. vertical: 'middle'
  64275. };
  64276. var rotationMap = {
  64277. horizontal: 0,
  64278. vertical: PI$4 / 2
  64279. };
  64280. // Position
  64281. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  64282. var controlModel = timelineModel.getModel('controlStyle');
  64283. var showControl = controlModel.get('show', true);
  64284. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  64285. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  64286. var sizePlusGap = controlSize + controlGap;
  64287. // Special label rotate.
  64288. var labelRotation = timelineModel.get('label.rotate') || 0;
  64289. labelRotation = labelRotation * PI$4 / 180; // To radian.
  64290. var playPosition;
  64291. var prevBtnPosition;
  64292. var nextBtnPosition;
  64293. var axisExtent;
  64294. var controlPosition = controlModel.get('position', true);
  64295. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  64296. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  64297. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  64298. var xLeft = 0;
  64299. var xRight = mainLength;
  64300. // position[0] means left, position[1] means middle.
  64301. if (controlPosition === 'left' || controlPosition === 'bottom') {
  64302. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  64303. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  64304. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  64305. }
  64306. else { // 'top' 'right'
  64307. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  64308. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  64309. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  64310. }
  64311. axisExtent = [xLeft, xRight];
  64312. if (timelineModel.get('inverse')) {
  64313. axisExtent.reverse();
  64314. }
  64315. return {
  64316. viewRect: viewRect,
  64317. mainLength: mainLength,
  64318. orient: orient,
  64319. rotation: rotationMap[orient],
  64320. labelRotation: labelRotation,
  64321. labelPosOpt: labelPosOpt,
  64322. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  64323. labelBaseline: timelineModel.get('label.verticalAlign')
  64324. || timelineModel.get('label.baseline')
  64325. || labelBaselineMap[orient],
  64326. // Based on mainGroup.
  64327. playPosition: playPosition,
  64328. prevBtnPosition: prevBtnPosition,
  64329. nextBtnPosition: nextBtnPosition,
  64330. axisExtent: axisExtent,
  64331. controlSize: controlSize,
  64332. controlGap: controlGap
  64333. };
  64334. },
  64335. _position: function (layoutInfo, timelineModel) {
  64336. // Position is be called finally, because bounding rect is needed for
  64337. // adapt content to fill viewRect (auto adapt offset).
  64338. // Timeline may be not all in the viewRect when 'offset' is specified
  64339. // as a number, because it is more appropriate that label aligns at
  64340. // 'offset' but not the other edge defined by viewRect.
  64341. var mainGroup = this._mainGroup;
  64342. var labelGroup = this._labelGroup;
  64343. var viewRect = layoutInfo.viewRect;
  64344. if (layoutInfo.orient === 'vertical') {
  64345. // transform to horizontal, inverse rotate by left-top point.
  64346. var m = create$1();
  64347. var rotateOriginX = viewRect.x;
  64348. var rotateOriginY = viewRect.y + viewRect.height;
  64349. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  64350. rotate(m, m, -PI$4 / 2);
  64351. translate(m, m, [rotateOriginX, rotateOriginY]);
  64352. viewRect = viewRect.clone();
  64353. viewRect.applyTransform(m);
  64354. }
  64355. var viewBound = getBound(viewRect);
  64356. var mainBound = getBound(mainGroup.getBoundingRect());
  64357. var labelBound = getBound(labelGroup.getBoundingRect());
  64358. var mainPosition = mainGroup.position;
  64359. var labelsPosition = labelGroup.position;
  64360. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  64361. var labelPosOpt = layoutInfo.labelPosOpt;
  64362. if (isNaN(labelPosOpt)) { // '+' or '-'
  64363. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  64364. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  64365. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  64366. }
  64367. else {
  64368. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  64369. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  64370. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  64371. }
  64372. mainGroup.attr('position', mainPosition);
  64373. labelGroup.attr('position', labelsPosition);
  64374. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  64375. setOrigin(mainGroup);
  64376. setOrigin(labelGroup);
  64377. function setOrigin(targetGroup) {
  64378. var pos = targetGroup.position;
  64379. targetGroup.origin = [
  64380. viewBound[0][0] - pos[0],
  64381. viewBound[1][0] - pos[1]
  64382. ];
  64383. }
  64384. function getBound(rect) {
  64385. // [[xmin, xmax], [ymin, ymax]]
  64386. return [
  64387. [rect.x, rect.x + rect.width],
  64388. [rect.y, rect.y + rect.height]
  64389. ];
  64390. }
  64391. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  64392. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  64393. }
  64394. },
  64395. _createAxis: function (layoutInfo, timelineModel) {
  64396. var data = timelineModel.getData();
  64397. var axisType = timelineModel.get('axisType');
  64398. var scale = createScaleByModel(timelineModel, axisType);
  64399. var dataExtent = data.getDataExtent('value');
  64400. scale.setExtent(dataExtent[0], dataExtent[1]);
  64401. this._customizeScale(scale, data);
  64402. scale.niceTicks();
  64403. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  64404. axis.model = timelineModel;
  64405. return axis;
  64406. },
  64407. _customizeScale: function (scale, data) {
  64408. scale.getTicks = function () {
  64409. return data.mapArray(['value'], function (value) {
  64410. return value;
  64411. });
  64412. };
  64413. scale.getTicksLabels = function () {
  64414. return map(this.getTicks(), scale.getLabel, scale);
  64415. };
  64416. },
  64417. _createGroup: function (name) {
  64418. var newGroup = this['_' + name] = new Group();
  64419. this.group.add(newGroup);
  64420. return newGroup;
  64421. },
  64422. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  64423. var axisExtent = axis.getExtent();
  64424. if (!timelineModel.get('lineStyle.show')) {
  64425. return;
  64426. }
  64427. group.add(new Line({
  64428. shape: {
  64429. x1: axisExtent[0], y1: 0,
  64430. x2: axisExtent[1], y2: 0
  64431. },
  64432. style: extend(
  64433. {lineCap: 'round'},
  64434. timelineModel.getModel('lineStyle').getLineStyle()
  64435. ),
  64436. silent: true,
  64437. z2: 1
  64438. }));
  64439. },
  64440. /**
  64441. * @private
  64442. */
  64443. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  64444. var data = timelineModel.getData();
  64445. var ticks = axis.scale.getTicks();
  64446. each$28(ticks, function (value, dataIndex) {
  64447. var tickCoord = axis.dataToCoord(value);
  64448. var itemModel = data.getItemModel(dataIndex);
  64449. var itemStyleModel = itemModel.getModel('itemStyle');
  64450. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  64451. var symbolOpt = {
  64452. position: [tickCoord, 0],
  64453. onclick: bind$6(this._changeTimeline, this, dataIndex)
  64454. };
  64455. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  64456. setHoverStyle(el, hoverStyleModel.getItemStyle());
  64457. if (itemModel.get('tooltip')) {
  64458. el.dataIndex = dataIndex;
  64459. el.dataModel = timelineModel;
  64460. }
  64461. else {
  64462. el.dataIndex = el.dataModel = null;
  64463. }
  64464. }, this);
  64465. },
  64466. /**
  64467. * @private
  64468. */
  64469. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  64470. var labelModel = timelineModel.getModel('label');
  64471. if (!labelModel.get('show')) {
  64472. return;
  64473. }
  64474. var data = timelineModel.getData();
  64475. var ticks = axis.scale.getTicks();
  64476. var labels = getFormattedLabels(
  64477. axis, labelModel.get('formatter')
  64478. );
  64479. var labelInterval = axis.getLabelInterval();
  64480. each$28(ticks, function (tick, dataIndex) {
  64481. if (axis.isLabelIgnored(dataIndex, labelInterval)) {
  64482. return;
  64483. }
  64484. var itemModel = data.getItemModel(dataIndex);
  64485. var normalLabelModel = itemModel.getModel('label');
  64486. var hoverLabelModel = itemModel.getModel('emphasis.label');
  64487. var tickCoord = axis.dataToCoord(tick);
  64488. var textEl = new Text({
  64489. position: [tickCoord, 0],
  64490. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  64491. onclick: bind$6(this._changeTimeline, this, dataIndex),
  64492. silent: false
  64493. });
  64494. setTextStyle(textEl.style, normalLabelModel, {
  64495. text: labels[dataIndex],
  64496. textAlign: layoutInfo.labelAlign,
  64497. textVerticalAlign: layoutInfo.labelBaseline
  64498. });
  64499. group.add(textEl);
  64500. setHoverStyle(
  64501. textEl, setTextStyle({}, hoverLabelModel)
  64502. );
  64503. }, this);
  64504. },
  64505. /**
  64506. * @private
  64507. */
  64508. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  64509. var controlSize = layoutInfo.controlSize;
  64510. var rotation = layoutInfo.rotation;
  64511. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  64512. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  64513. var rect = [0, -controlSize / 2, controlSize, controlSize];
  64514. var playState = timelineModel.getPlayState();
  64515. var inverse = timelineModel.get('inverse', true);
  64516. makeBtn(
  64517. layoutInfo.nextBtnPosition,
  64518. 'controlStyle.nextIcon',
  64519. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  64520. );
  64521. makeBtn(
  64522. layoutInfo.prevBtnPosition,
  64523. 'controlStyle.prevIcon',
  64524. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  64525. );
  64526. makeBtn(
  64527. layoutInfo.playPosition,
  64528. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  64529. bind$6(this._handlePlayClick, this, !playState),
  64530. true
  64531. );
  64532. function makeBtn(position, iconPath, onclick, willRotate) {
  64533. if (!position) {
  64534. return;
  64535. }
  64536. var opt = {
  64537. position: position,
  64538. origin: [controlSize / 2, 0],
  64539. rotation: willRotate ? -rotation : 0,
  64540. rectHover: true,
  64541. style: itemStyle,
  64542. onclick: onclick
  64543. };
  64544. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  64545. group.add(btn);
  64546. setHoverStyle(btn, hoverStyle);
  64547. }
  64548. },
  64549. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  64550. var data = timelineModel.getData();
  64551. var currentIndex = timelineModel.getCurrentIndex();
  64552. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  64553. var me = this;
  64554. var callback = {
  64555. onCreate: function (pointer) {
  64556. pointer.draggable = true;
  64557. pointer.drift = bind$6(me._handlePointerDrag, me);
  64558. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  64559. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  64560. },
  64561. onUpdate: function (pointer) {
  64562. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  64563. }
  64564. };
  64565. // Reuse when exists, for animation and drag.
  64566. this._currentPointer = giveSymbol(
  64567. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  64568. );
  64569. },
  64570. _handlePlayClick: function (nextState) {
  64571. this._clearTimer();
  64572. this.api.dispatchAction({
  64573. type: 'timelinePlayChange',
  64574. playState: nextState,
  64575. from: this.uid
  64576. });
  64577. },
  64578. _handlePointerDrag: function (dx, dy, e) {
  64579. this._clearTimer();
  64580. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  64581. },
  64582. _handlePointerDragend: function (e) {
  64583. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  64584. },
  64585. _pointerChangeTimeline: function (mousePos, trigger) {
  64586. var toCoord = this._toAxisCoord(mousePos)[0];
  64587. var axis = this._axis;
  64588. var axisExtent = asc(axis.getExtent().slice());
  64589. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  64590. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  64591. this._currentPointer.position[0] = toCoord;
  64592. this._currentPointer.dirty();
  64593. var targetDataIndex = this._findNearestTick(toCoord);
  64594. var timelineModel = this.model;
  64595. if (trigger || (
  64596. targetDataIndex !== timelineModel.getCurrentIndex()
  64597. && timelineModel.get('realtime')
  64598. )) {
  64599. this._changeTimeline(targetDataIndex);
  64600. }
  64601. },
  64602. _doPlayStop: function () {
  64603. this._clearTimer();
  64604. if (this.model.getPlayState()) {
  64605. this._timer = setTimeout(
  64606. bind$6(handleFrame, this),
  64607. this.model.get('playInterval')
  64608. );
  64609. }
  64610. function handleFrame() {
  64611. // Do not cache
  64612. var timelineModel = this.model;
  64613. this._changeTimeline(
  64614. timelineModel.getCurrentIndex()
  64615. + (timelineModel.get('rewind', true) ? -1 : 1)
  64616. );
  64617. }
  64618. },
  64619. _toAxisCoord: function (vertex) {
  64620. var trans = this._mainGroup.getLocalTransform();
  64621. return applyTransform$1(vertex, trans, true);
  64622. },
  64623. _findNearestTick: function (axisCoord) {
  64624. var data = this.model.getData();
  64625. var dist = Infinity;
  64626. var targetDataIndex;
  64627. var axis = this._axis;
  64628. data.each(['value'], function (value, dataIndex) {
  64629. var coord = axis.dataToCoord(value);
  64630. var d = Math.abs(coord - axisCoord);
  64631. if (d < dist) {
  64632. dist = d;
  64633. targetDataIndex = dataIndex;
  64634. }
  64635. });
  64636. return targetDataIndex;
  64637. },
  64638. _clearTimer: function () {
  64639. if (this._timer) {
  64640. clearTimeout(this._timer);
  64641. this._timer = null;
  64642. }
  64643. },
  64644. _changeTimeline: function (nextIndex) {
  64645. var currentIndex = this.model.getCurrentIndex();
  64646. if (nextIndex === '+') {
  64647. nextIndex = currentIndex + 1;
  64648. }
  64649. else if (nextIndex === '-') {
  64650. nextIndex = currentIndex - 1;
  64651. }
  64652. this.api.dispatchAction({
  64653. type: 'timelineChange',
  64654. currentIndex: nextIndex,
  64655. from: this.uid
  64656. });
  64657. }
  64658. });
  64659. function getViewRect$4(model, api) {
  64660. return getLayoutRect(
  64661. model.getBoxLayoutParams(),
  64662. {
  64663. width: api.getWidth(),
  64664. height: api.getHeight()
  64665. },
  64666. model.get('padding')
  64667. );
  64668. }
  64669. function makeIcon(timelineModel, objPath, rect, opts) {
  64670. var icon = makePath(
  64671. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  64672. clone(opts || {}),
  64673. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  64674. 'center'
  64675. );
  64676. return icon;
  64677. }
  64678. /**
  64679. * Create symbol or update symbol
  64680. * opt: basic position and event handlers
  64681. */
  64682. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  64683. var color = itemStyleModel.get('color');
  64684. if (!symbol) {
  64685. var symbolType = hostModel.get('symbol');
  64686. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  64687. symbol.setStyle('strokeNoScale', true);
  64688. group.add(symbol);
  64689. callback && callback.onCreate(symbol);
  64690. }
  64691. else {
  64692. symbol.setColor(color);
  64693. group.add(symbol); // Group may be new, also need to add.
  64694. callback && callback.onUpdate(symbol);
  64695. }
  64696. // Style
  64697. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  64698. symbol.setStyle(itemStyle);
  64699. // Transform and events.
  64700. opt = merge({
  64701. rectHover: true,
  64702. z2: 100
  64703. }, opt, true);
  64704. var symbolSize = hostModel.get('symbolSize');
  64705. symbolSize = symbolSize instanceof Array
  64706. ? symbolSize.slice()
  64707. : [+symbolSize, +symbolSize];
  64708. symbolSize[0] /= 2;
  64709. symbolSize[1] /= 2;
  64710. opt.scale = symbolSize;
  64711. var symbolOffset = hostModel.get('symbolOffset');
  64712. if (symbolOffset) {
  64713. var pos = opt.position = opt.position || [0, 0];
  64714. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  64715. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  64716. }
  64717. var symbolRotate = hostModel.get('symbolRotate');
  64718. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  64719. symbol.attr(opt);
  64720. // FIXME
  64721. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  64722. // getBoundingRect will return wrong result.
  64723. // (This is supposed to be resolved in zrender, but it is a little difficult to
  64724. // leverage performance and auto updateTransform)
  64725. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  64726. symbol.updateTransform();
  64727. return symbol;
  64728. }
  64729. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  64730. if (pointer.dragging) {
  64731. return;
  64732. }
  64733. var pointerModel = timelineModel.getModel('checkpointStyle');
  64734. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  64735. if (noAnimation || !pointerModel.get('animation', true)) {
  64736. pointer.attr({position: [toCoord, 0]});
  64737. }
  64738. else {
  64739. pointer.stopAnimation(true);
  64740. pointer.animateTo(
  64741. {position: [toCoord, 0]},
  64742. pointerModel.get('animationDuration', true),
  64743. pointerModel.get('animationEasing', true)
  64744. );
  64745. }
  64746. }
  64747. /**
  64748. * DataZoom component entry
  64749. */
  64750. registerPreprocessor(preprocessor$3);
  64751. var ToolboxModel = extendComponentModel({
  64752. type: 'toolbox',
  64753. layoutMode: {
  64754. type: 'box',
  64755. ignoreSize: true
  64756. },
  64757. mergeDefaultAndTheme: function (option) {
  64758. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  64759. each$1(this.option.feature, function (featureOpt, featureName) {
  64760. var Feature = get$1(featureName);
  64761. Feature && merge(featureOpt, Feature.defaultOption);
  64762. });
  64763. },
  64764. defaultOption: {
  64765. show: true,
  64766. z: 6,
  64767. zlevel: 0,
  64768. orient: 'horizontal',
  64769. left: 'right',
  64770. top: 'top',
  64771. // right
  64772. // bottom
  64773. backgroundColor: 'transparent',
  64774. borderColor: '#ccc',
  64775. borderRadius: 0,
  64776. borderWidth: 0,
  64777. padding: 5,
  64778. itemSize: 15,
  64779. itemGap: 8,
  64780. showTitle: true,
  64781. iconStyle: {
  64782. borderColor: '#666',
  64783. color: 'none'
  64784. },
  64785. emphasis: {
  64786. iconStyle: {
  64787. borderColor: '#3E98C5'
  64788. }
  64789. }
  64790. // textStyle: {},
  64791. // feature
  64792. }
  64793. });
  64794. extendComponentView({
  64795. type: 'toolbox',
  64796. render: function (toolboxModel, ecModel, api, payload) {
  64797. var group = this.group;
  64798. group.removeAll();
  64799. if (!toolboxModel.get('show')) {
  64800. return;
  64801. }
  64802. var itemSize = +toolboxModel.get('itemSize');
  64803. var featureOpts = toolboxModel.get('feature') || {};
  64804. var features = this._features || (this._features = {});
  64805. var featureNames = [];
  64806. each$1(featureOpts, function (opt, name) {
  64807. featureNames.push(name);
  64808. });
  64809. (new DataDiffer(this._featureNames || [], featureNames))
  64810. .add(processFeature)
  64811. .update(processFeature)
  64812. .remove(curry(processFeature, null))
  64813. .execute();
  64814. // Keep for diff.
  64815. this._featureNames = featureNames;
  64816. function processFeature(newIndex, oldIndex) {
  64817. var featureName = featureNames[newIndex];
  64818. var oldName = featureNames[oldIndex];
  64819. var featureOpt = featureOpts[featureName];
  64820. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  64821. var feature;
  64822. if (featureName && !oldName) { // Create
  64823. if (isUserFeatureName(featureName)) {
  64824. feature = {
  64825. model: featureModel,
  64826. onclick: featureModel.option.onclick,
  64827. featureName: featureName
  64828. };
  64829. }
  64830. else {
  64831. var Feature = get$1(featureName);
  64832. if (!Feature) {
  64833. return;
  64834. }
  64835. feature = new Feature(featureModel, ecModel, api);
  64836. }
  64837. features[featureName] = feature;
  64838. }
  64839. else {
  64840. feature = features[oldName];
  64841. // If feature does not exsit.
  64842. if (!feature) {
  64843. return;
  64844. }
  64845. feature.model = featureModel;
  64846. feature.ecModel = ecModel;
  64847. feature.api = api;
  64848. }
  64849. if (!featureName && oldName) {
  64850. feature.dispose && feature.dispose(ecModel, api);
  64851. return;
  64852. }
  64853. if (!featureModel.get('show') || feature.unusable) {
  64854. feature.remove && feature.remove(ecModel, api);
  64855. return;
  64856. }
  64857. createIconPaths(featureModel, feature, featureName);
  64858. featureModel.setIconStatus = function (iconName, status) {
  64859. var option = this.option;
  64860. var iconPaths = this.iconPaths;
  64861. option.iconStatus = option.iconStatus || {};
  64862. option.iconStatus[iconName] = status;
  64863. // FIXME
  64864. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  64865. };
  64866. if (feature.render) {
  64867. feature.render(featureModel, ecModel, api, payload);
  64868. }
  64869. }
  64870. function createIconPaths(featureModel, feature, featureName) {
  64871. var iconStyleModel = featureModel.getModel('iconStyle');
  64872. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  64873. // If one feature has mutiple icon. they are orginaized as
  64874. // {
  64875. // icon: {
  64876. // foo: '',
  64877. // bar: ''
  64878. // },
  64879. // title: {
  64880. // foo: '',
  64881. // bar: ''
  64882. // }
  64883. // }
  64884. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  64885. var titles = featureModel.get('title') || {};
  64886. if (typeof icons === 'string') {
  64887. var icon = icons;
  64888. var title = titles;
  64889. icons = {};
  64890. titles = {};
  64891. icons[featureName] = icon;
  64892. titles[featureName] = title;
  64893. }
  64894. var iconPaths = featureModel.iconPaths = {};
  64895. each$1(icons, function (iconStr, iconName) {
  64896. var path = createIcon(
  64897. iconStr,
  64898. {},
  64899. {
  64900. x: -itemSize / 2,
  64901. y: -itemSize / 2,
  64902. width: itemSize,
  64903. height: itemSize
  64904. }
  64905. );
  64906. path.setStyle(iconStyleModel.getItemStyle());
  64907. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  64908. setHoverStyle(path);
  64909. if (toolboxModel.get('showTitle')) {
  64910. path.__title = titles[iconName];
  64911. path.on('mouseover', function () {
  64912. // Should not reuse above hoverStyle, which might be modified.
  64913. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  64914. path.setStyle({
  64915. text: titles[iconName],
  64916. textPosition: hoverStyle.textPosition || 'bottom',
  64917. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  64918. textAlign: hoverStyle.textAlign || 'center'
  64919. });
  64920. })
  64921. .on('mouseout', function () {
  64922. path.setStyle({
  64923. textFill: null
  64924. });
  64925. });
  64926. }
  64927. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  64928. group.add(path);
  64929. path.on('click', bind(
  64930. feature.onclick, feature, ecModel, api, iconName
  64931. ));
  64932. iconPaths[iconName] = path;
  64933. });
  64934. }
  64935. layout$3(group, toolboxModel, api);
  64936. // Render background after group is layout
  64937. // FIXME
  64938. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  64939. // Adjust icon title positions to avoid them out of screen
  64940. group.eachChild(function (icon) {
  64941. var titleText = icon.__title;
  64942. var hoverStyle = icon.hoverStyle;
  64943. // May be background element
  64944. if (hoverStyle && titleText) {
  64945. var rect = getBoundingRect(
  64946. titleText, makeFont(hoverStyle)
  64947. );
  64948. var offsetX = icon.position[0] + group.position[0];
  64949. var offsetY = icon.position[1] + group.position[1] + itemSize;
  64950. var needPutOnTop = false;
  64951. if (offsetY + rect.height > api.getHeight()) {
  64952. hoverStyle.textPosition = 'top';
  64953. needPutOnTop = true;
  64954. }
  64955. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  64956. if (offsetX + rect.width / 2 > api.getWidth()) {
  64957. hoverStyle.textPosition = ['100%', topOffset];
  64958. hoverStyle.textAlign = 'right';
  64959. }
  64960. else if (offsetX - rect.width / 2 < 0) {
  64961. hoverStyle.textPosition = [0, topOffset];
  64962. hoverStyle.textAlign = 'left';
  64963. }
  64964. }
  64965. });
  64966. },
  64967. updateView: function (toolboxModel, ecModel, api, payload) {
  64968. each$1(this._features, function (feature) {
  64969. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  64970. });
  64971. },
  64972. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  64973. // zrUtil.each(this._features, function (feature) {
  64974. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  64975. // });
  64976. // },
  64977. remove: function (ecModel, api) {
  64978. each$1(this._features, function (feature) {
  64979. feature.remove && feature.remove(ecModel, api);
  64980. });
  64981. this.group.removeAll();
  64982. },
  64983. dispose: function (ecModel, api) {
  64984. each$1(this._features, function (feature) {
  64985. feature.dispose && feature.dispose(ecModel, api);
  64986. });
  64987. }
  64988. });
  64989. function isUserFeatureName(featureName) {
  64990. return featureName.indexOf('my') === 0;
  64991. }
  64992. var saveAsImageLang = lang.toolbox.saveAsImage;
  64993. function SaveAsImage(model) {
  64994. this.model = model;
  64995. }
  64996. SaveAsImage.defaultOption = {
  64997. show: true,
  64998. icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0',
  64999. title: saveAsImageLang.title,
  65000. type: 'png',
  65001. // Default use option.backgroundColor
  65002. // backgroundColor: '#fff',
  65003. name: '',
  65004. excludeComponents: ['toolbox'],
  65005. pixelRatio: 1,
  65006. lang: saveAsImageLang.lang.slice()
  65007. };
  65008. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  65009. var proto$4 = SaveAsImage.prototype;
  65010. proto$4.onclick = function (ecModel, api) {
  65011. var model = this.model;
  65012. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  65013. var $a = document.createElement('a');
  65014. var type = model.get('type', true) || 'png';
  65015. $a.download = title + '.' + type;
  65016. $a.target = '_blank';
  65017. var url = api.getConnectedDataURL({
  65018. type: type,
  65019. backgroundColor: model.get('backgroundColor', true)
  65020. || ecModel.get('backgroundColor') || '#fff',
  65021. excludeComponents: model.get('excludeComponents'),
  65022. pixelRatio: model.get('pixelRatio')
  65023. });
  65024. $a.href = url;
  65025. // Chrome and Firefox
  65026. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  65027. var evt = new MouseEvent('click', {
  65028. view: window,
  65029. bubbles: true,
  65030. cancelable: false
  65031. });
  65032. $a.dispatchEvent(evt);
  65033. }
  65034. // IE
  65035. else {
  65036. if (window.navigator.msSaveOrOpenBlob) {
  65037. var bstr = atob(url.split(',')[1]);
  65038. var n = bstr.length;
  65039. var u8arr = new Uint8Array(n);
  65040. while(n--) {
  65041. u8arr[n] = bstr.charCodeAt(n);
  65042. }
  65043. var blob = new Blob([u8arr]);
  65044. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  65045. }
  65046. else {
  65047. var lang$$1 = model.get('lang');
  65048. var html = '' +
  65049. '<body style="margin:0;">' +
  65050. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  65051. '</body>';
  65052. var tab = window.open();
  65053. tab.document.write(html);
  65054. }
  65055. }
  65056. };
  65057. register$1(
  65058. 'saveAsImage', SaveAsImage
  65059. );
  65060. var magicTypeLang = lang.toolbox.magicType;
  65061. function MagicType(model) {
  65062. this.model = model;
  65063. }
  65064. MagicType.defaultOption = {
  65065. show: true,
  65066. type: [],
  65067. // Icon group
  65068. icon: {
  65069. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  65070. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  65071. stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
  65072. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  65073. },
  65074. // `line`, `bar`, `stack`, `tiled`
  65075. title: clone(magicTypeLang.title),
  65076. option: {},
  65077. seriesIndex: {}
  65078. };
  65079. var proto$5 = MagicType.prototype;
  65080. proto$5.getIcons = function () {
  65081. var model = this.model;
  65082. var availableIcons = model.get('icon');
  65083. var icons = {};
  65084. each$1(model.get('type'), function (type) {
  65085. if (availableIcons[type]) {
  65086. icons[type] = availableIcons[type];
  65087. }
  65088. });
  65089. return icons;
  65090. };
  65091. var seriesOptGenreator = {
  65092. 'line': function (seriesType, seriesId, seriesModel, model) {
  65093. if (seriesType === 'bar') {
  65094. return merge({
  65095. id: seriesId,
  65096. type: 'line',
  65097. // Preserve data related option
  65098. data: seriesModel.get('data'),
  65099. stack: seriesModel.get('stack'),
  65100. markPoint: seriesModel.get('markPoint'),
  65101. markLine: seriesModel.get('markLine')
  65102. }, model.get('option.line') || {}, true);
  65103. }
  65104. },
  65105. 'bar': function (seriesType, seriesId, seriesModel, model) {
  65106. if (seriesType === 'line') {
  65107. return merge({
  65108. id: seriesId,
  65109. type: 'bar',
  65110. // Preserve data related option
  65111. data: seriesModel.get('data'),
  65112. stack: seriesModel.get('stack'),
  65113. markPoint: seriesModel.get('markPoint'),
  65114. markLine: seriesModel.get('markLine')
  65115. }, model.get('option.bar') || {}, true);
  65116. }
  65117. },
  65118. 'stack': function (seriesType, seriesId, seriesModel, model) {
  65119. if (seriesType === 'line' || seriesType === 'bar') {
  65120. return merge({
  65121. id: seriesId,
  65122. stack: '__ec_magicType_stack__'
  65123. }, model.get('option.stack') || {}, true);
  65124. }
  65125. },
  65126. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  65127. if (seriesType === 'line' || seriesType === 'bar') {
  65128. return merge({
  65129. id: seriesId,
  65130. stack: ''
  65131. }, model.get('option.tiled') || {}, true);
  65132. }
  65133. }
  65134. };
  65135. var radioTypes = [
  65136. ['line', 'bar'],
  65137. ['stack', 'tiled']
  65138. ];
  65139. proto$5.onclick = function (ecModel, api, type) {
  65140. var model = this.model;
  65141. var seriesIndex = model.get('seriesIndex.' + type);
  65142. // Not supported magicType
  65143. if (!seriesOptGenreator[type]) {
  65144. return;
  65145. }
  65146. var newOption = {
  65147. series: []
  65148. };
  65149. var generateNewSeriesTypes = function (seriesModel) {
  65150. var seriesType = seriesModel.subType;
  65151. var seriesId = seriesModel.id;
  65152. var newSeriesOpt = seriesOptGenreator[type](
  65153. seriesType, seriesId, seriesModel, model
  65154. );
  65155. if (newSeriesOpt) {
  65156. // PENDING If merge original option?
  65157. defaults(newSeriesOpt, seriesModel.option);
  65158. newOption.series.push(newSeriesOpt);
  65159. }
  65160. // Modify boundaryGap
  65161. var coordSys = seriesModel.coordinateSystem;
  65162. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  65163. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  65164. if (categoryAxis) {
  65165. var axisDim = categoryAxis.dim;
  65166. var axisType = axisDim + 'Axis';
  65167. var axisModel = ecModel.queryComponents({
  65168. mainType: axisType,
  65169. index: seriesModel.get(name + 'Index'),
  65170. id: seriesModel.get(name + 'Id')
  65171. })[0];
  65172. var axisIndex = axisModel.componentIndex;
  65173. newOption[axisType] = newOption[axisType] || [];
  65174. for (var i = 0; i <= axisIndex; i++) {
  65175. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  65176. }
  65177. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  65178. }
  65179. }
  65180. };
  65181. each$1(radioTypes, function (radio) {
  65182. if (indexOf(radio, type) >= 0) {
  65183. each$1(radio, function (item) {
  65184. model.setIconStatus(item, 'normal');
  65185. });
  65186. }
  65187. });
  65188. model.setIconStatus(type, 'emphasis');
  65189. ecModel.eachComponent(
  65190. {
  65191. mainType: 'series',
  65192. query: seriesIndex == null ? null : {
  65193. seriesIndex: seriesIndex
  65194. }
  65195. }, generateNewSeriesTypes
  65196. );
  65197. api.dispatchAction({
  65198. type: 'changeMagicType',
  65199. currentType: type,
  65200. newOption: newOption
  65201. });
  65202. };
  65203. registerAction({
  65204. type: 'changeMagicType',
  65205. event: 'magicTypeChanged',
  65206. update: 'prepareAndUpdate'
  65207. }, function (payload, ecModel) {
  65208. ecModel.mergeOption(payload.newOption);
  65209. });
  65210. register$1('magicType', MagicType);
  65211. var dataViewLang = lang.toolbox.dataView;
  65212. var BLOCK_SPLITER = new Array(60).join('-');
  65213. var ITEM_SPLITER = '\t';
  65214. /**
  65215. * Group series into two types
  65216. * 1. on category axis, like line, bar
  65217. * 2. others, like scatter, pie
  65218. * @param {module:echarts/model/Global} ecModel
  65219. * @return {Object}
  65220. * @inner
  65221. */
  65222. function groupSeries(ecModel) {
  65223. var seriesGroupByCategoryAxis = {};
  65224. var otherSeries = [];
  65225. var meta = [];
  65226. ecModel.eachRawSeries(function (seriesModel) {
  65227. var coordSys = seriesModel.coordinateSystem;
  65228. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  65229. var baseAxis = coordSys.getBaseAxis();
  65230. if (baseAxis.type === 'category') {
  65231. var key = baseAxis.dim + '_' + baseAxis.index;
  65232. if (!seriesGroupByCategoryAxis[key]) {
  65233. seriesGroupByCategoryAxis[key] = {
  65234. categoryAxis: baseAxis,
  65235. valueAxis: coordSys.getOtherAxis(baseAxis),
  65236. series: []
  65237. };
  65238. meta.push({
  65239. axisDim: baseAxis.dim,
  65240. axisIndex: baseAxis.index
  65241. });
  65242. }
  65243. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  65244. }
  65245. else {
  65246. otherSeries.push(seriesModel);
  65247. }
  65248. }
  65249. else {
  65250. otherSeries.push(seriesModel);
  65251. }
  65252. });
  65253. return {
  65254. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  65255. other: otherSeries,
  65256. meta: meta
  65257. };
  65258. }
  65259. /**
  65260. * Assemble content of series on cateogory axis
  65261. * @param {Array.<module:echarts/model/Series>} series
  65262. * @return {string}
  65263. * @inner
  65264. */
  65265. function assembleSeriesWithCategoryAxis(series) {
  65266. var tables = [];
  65267. each$1(series, function (group, key) {
  65268. var categoryAxis = group.categoryAxis;
  65269. var valueAxis = group.valueAxis;
  65270. var valueAxisDim = valueAxis.dim;
  65271. var headers = [' '].concat(map(group.series, function (series) {
  65272. return series.name;
  65273. }));
  65274. var columns = [categoryAxis.model.getCategories()];
  65275. each$1(group.series, function (series) {
  65276. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  65277. return val;
  65278. }));
  65279. });
  65280. // Assemble table content
  65281. var lines = [headers.join(ITEM_SPLITER)];
  65282. for (var i = 0; i < columns[0].length; i++) {
  65283. var items = [];
  65284. for (var j = 0; j < columns.length; j++) {
  65285. items.push(columns[j][i]);
  65286. }
  65287. lines.push(items.join(ITEM_SPLITER));
  65288. }
  65289. tables.push(lines.join('\n'));
  65290. });
  65291. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  65292. }
  65293. /**
  65294. * Assemble content of other series
  65295. * @param {Array.<module:echarts/model/Series>} series
  65296. * @return {string}
  65297. * @inner
  65298. */
  65299. function assembleOtherSeries(series) {
  65300. return map(series, function (series) {
  65301. var data = series.getRawData();
  65302. var lines = [series.name];
  65303. var vals = [];
  65304. data.each(data.dimensions, function () {
  65305. var argLen = arguments.length;
  65306. var dataIndex = arguments[argLen - 1];
  65307. var name = data.getName(dataIndex);
  65308. for (var i = 0; i < argLen - 1; i++) {
  65309. vals[i] = arguments[i];
  65310. }
  65311. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  65312. });
  65313. return lines.join('\n');
  65314. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  65315. }
  65316. /**
  65317. * @param {module:echarts/model/Global}
  65318. * @return {Object}
  65319. * @inner
  65320. */
  65321. function getContentFromModel(ecModel) {
  65322. var result = groupSeries(ecModel);
  65323. return {
  65324. value: filter([
  65325. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  65326. assembleOtherSeries(result.other)
  65327. ], function (str) {
  65328. return str.replace(/[\n\t\s]/g, '');
  65329. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  65330. meta: result.meta
  65331. };
  65332. }
  65333. function trim$1(str) {
  65334. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  65335. }
  65336. /**
  65337. * If a block is tsv format
  65338. */
  65339. function isTSVFormat(block) {
  65340. // Simple method to find out if a block is tsv format
  65341. var firstLine = block.slice(0, block.indexOf('\n'));
  65342. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  65343. return true;
  65344. }
  65345. }
  65346. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  65347. /**
  65348. * @param {string} tsv
  65349. * @return {Object}
  65350. */
  65351. function parseTSVContents(tsv) {
  65352. var tsvLines = tsv.split(/\n+/g);
  65353. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  65354. var categories = [];
  65355. var series = map(headers, function (header) {
  65356. return {
  65357. name: header,
  65358. data: []
  65359. };
  65360. });
  65361. for (var i = 0; i < tsvLines.length; i++) {
  65362. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  65363. categories.push(items.shift());
  65364. for (var j = 0; j < items.length; j++) {
  65365. series[j] && (series[j].data[i] = items[j]);
  65366. }
  65367. }
  65368. return {
  65369. series: series,
  65370. categories: categories
  65371. };
  65372. }
  65373. /**
  65374. * @param {string} str
  65375. * @return {Array.<Object>}
  65376. * @inner
  65377. */
  65378. function parseListContents(str) {
  65379. var lines = str.split(/\n+/g);
  65380. var seriesName = trim$1(lines.shift());
  65381. var data = [];
  65382. for (var i = 0; i < lines.length; i++) {
  65383. var items = trim$1(lines[i]).split(itemSplitRegex);
  65384. var name = '';
  65385. var value;
  65386. var hasName = false;
  65387. if (isNaN(items[0])) { // First item is name
  65388. hasName = true;
  65389. name = items[0];
  65390. items = items.slice(1);
  65391. data[i] = {
  65392. name: name,
  65393. value: []
  65394. };
  65395. value = data[i].value;
  65396. }
  65397. else {
  65398. value = data[i] = [];
  65399. }
  65400. for (var j = 0; j < items.length; j++) {
  65401. value.push(+items[j]);
  65402. }
  65403. if (value.length === 1) {
  65404. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  65405. }
  65406. }
  65407. return {
  65408. name: seriesName,
  65409. data: data
  65410. };
  65411. }
  65412. /**
  65413. * @param {string} str
  65414. * @param {Array.<Object>} blockMetaList
  65415. * @return {Object}
  65416. * @inner
  65417. */
  65418. function parseContents(str, blockMetaList) {
  65419. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  65420. var newOption = {
  65421. series: []
  65422. };
  65423. each$1(blocks, function (block, idx) {
  65424. if (isTSVFormat(block)) {
  65425. var result = parseTSVContents(block);
  65426. var blockMeta = blockMetaList[idx];
  65427. var axisKey = blockMeta.axisDim + 'Axis';
  65428. if (blockMeta) {
  65429. newOption[axisKey] = newOption[axisKey] || [];
  65430. newOption[axisKey][blockMeta.axisIndex] = {
  65431. data: result.categories
  65432. };
  65433. newOption.series = newOption.series.concat(result.series);
  65434. }
  65435. }
  65436. else {
  65437. var result = parseListContents(block);
  65438. newOption.series.push(result);
  65439. }
  65440. });
  65441. return newOption;
  65442. }
  65443. /**
  65444. * @alias {module:echarts/component/toolbox/feature/DataView}
  65445. * @constructor
  65446. * @param {module:echarts/model/Model} model
  65447. */
  65448. function DataView(model) {
  65449. this._dom = null;
  65450. this.model = model;
  65451. }
  65452. DataView.defaultOption = {
  65453. show: true,
  65454. readOnly: false,
  65455. optionToContent: null,
  65456. contentToOption: null,
  65457. icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28',
  65458. title: clone(dataViewLang.title),
  65459. lang: clone(dataViewLang.lang),
  65460. backgroundColor: '#fff',
  65461. textColor: '#000',
  65462. textareaColor: '#fff',
  65463. textareaBorderColor: '#333',
  65464. buttonColor: '#c23531',
  65465. buttonTextColor: '#fff'
  65466. };
  65467. DataView.prototype.onclick = function (ecModel, api) {
  65468. var container = api.getDom();
  65469. var model = this.model;
  65470. if (this._dom) {
  65471. container.removeChild(this._dom);
  65472. }
  65473. var root = document.createElement('div');
  65474. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  65475. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  65476. // Create elements
  65477. var header = document.createElement('h4');
  65478. var lang$$1 = model.get('lang') || [];
  65479. header.innerHTML = lang$$1[0] || model.get('title');
  65480. header.style.cssText = 'margin: 10px 20px;';
  65481. header.style.color = model.get('textColor');
  65482. var viewMain = document.createElement('div');
  65483. var textarea = document.createElement('textarea');
  65484. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  65485. var optionToContent = model.get('optionToContent');
  65486. var contentToOption = model.get('contentToOption');
  65487. var result = getContentFromModel(ecModel);
  65488. if (typeof optionToContent === 'function') {
  65489. var htmlOrDom = optionToContent(api.getOption());
  65490. if (typeof htmlOrDom === 'string') {
  65491. viewMain.innerHTML = htmlOrDom;
  65492. }
  65493. else if (isDom(htmlOrDom)) {
  65494. viewMain.appendChild(htmlOrDom);
  65495. }
  65496. }
  65497. else {
  65498. // Use default textarea
  65499. viewMain.appendChild(textarea);
  65500. textarea.readOnly = model.get('readOnly');
  65501. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  65502. textarea.style.color = model.get('textColor');
  65503. textarea.style.borderColor = model.get('textareaBorderColor');
  65504. textarea.style.backgroundColor = model.get('textareaColor');
  65505. textarea.value = result.value;
  65506. }
  65507. var blockMetaList = result.meta;
  65508. var buttonContainer = document.createElement('div');
  65509. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  65510. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  65511. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  65512. var closeButton = document.createElement('div');
  65513. var refreshButton = document.createElement('div');
  65514. buttonStyle += ';background-color:' + model.get('buttonColor');
  65515. buttonStyle += ';color:' + model.get('buttonTextColor');
  65516. var self = this;
  65517. function close() {
  65518. container.removeChild(root);
  65519. self._dom = null;
  65520. }
  65521. addEventListener(closeButton, 'click', close);
  65522. addEventListener(refreshButton, 'click', function () {
  65523. var newOption;
  65524. try {
  65525. if (typeof contentToOption === 'function') {
  65526. newOption = contentToOption(viewMain, api.getOption());
  65527. }
  65528. else {
  65529. newOption = parseContents(textarea.value, blockMetaList);
  65530. }
  65531. }
  65532. catch (e) {
  65533. close();
  65534. throw new Error('Data view format error ' + e);
  65535. }
  65536. if (newOption) {
  65537. api.dispatchAction({
  65538. type: 'changeDataView',
  65539. newOption: newOption
  65540. });
  65541. }
  65542. close();
  65543. });
  65544. closeButton.innerHTML = lang$$1[1];
  65545. refreshButton.innerHTML = lang$$1[2];
  65546. refreshButton.style.cssText = buttonStyle;
  65547. closeButton.style.cssText = buttonStyle;
  65548. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  65549. buttonContainer.appendChild(closeButton);
  65550. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  65551. addEventListener(textarea, 'keydown', function (e) {
  65552. if ((e.keyCode || e.which) === 9) {
  65553. // get caret position/selection
  65554. var val = this.value;
  65555. var start = this.selectionStart;
  65556. var end = this.selectionEnd;
  65557. // set textarea value to: text before caret + tab + text after caret
  65558. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  65559. // put caret at right position again
  65560. this.selectionStart = this.selectionEnd = start + 1;
  65561. // prevent the focus lose
  65562. stop(e);
  65563. }
  65564. });
  65565. root.appendChild(header);
  65566. root.appendChild(viewMain);
  65567. root.appendChild(buttonContainer);
  65568. viewMain.style.height = (container.clientHeight - 80) + 'px';
  65569. container.appendChild(root);
  65570. this._dom = root;
  65571. };
  65572. DataView.prototype.remove = function (ecModel, api) {
  65573. this._dom && api.getDom().removeChild(this._dom);
  65574. };
  65575. DataView.prototype.dispose = function (ecModel, api) {
  65576. this.remove(ecModel, api);
  65577. };
  65578. /**
  65579. * @inner
  65580. */
  65581. function tryMergeDataOption(newData, originalData) {
  65582. return map(newData, function (newVal, idx) {
  65583. var original = originalData && originalData[idx];
  65584. if (isObject$1(original) && !isArray(original)) {
  65585. if (isObject$1(newVal) && !isArray(newVal)) {
  65586. newVal = newVal.value;
  65587. }
  65588. // Original data has option
  65589. return defaults({
  65590. value: newVal
  65591. }, original);
  65592. }
  65593. else {
  65594. return newVal;
  65595. }
  65596. });
  65597. }
  65598. register$1('dataView', DataView);
  65599. registerAction({
  65600. type: 'changeDataView',
  65601. event: 'dataViewChanged',
  65602. update: 'prepareAndUpdate'
  65603. }, function (payload, ecModel) {
  65604. var newSeriesOptList = [];
  65605. each$1(payload.newOption.series, function (seriesOpt) {
  65606. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  65607. if (!seriesModel) {
  65608. // New created series
  65609. // Geuss the series type
  65610. newSeriesOptList.push(extend({
  65611. // Default is scatter
  65612. type: 'scatter'
  65613. }, seriesOpt));
  65614. }
  65615. else {
  65616. var originalData = seriesModel.get('data');
  65617. newSeriesOptList.push({
  65618. name: seriesOpt.name,
  65619. data: tryMergeDataOption(seriesOpt.data, originalData)
  65620. });
  65621. }
  65622. });
  65623. ecModel.mergeOption(defaults({
  65624. series: newSeriesOptList
  65625. }, payload.newOption));
  65626. });
  65627. var each$30 = each$1;
  65628. var ATTR$2 = '\0_ec_hist_store';
  65629. /**
  65630. * @param {module:echarts/model/Global} ecModel
  65631. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  65632. */
  65633. function push(ecModel, newSnapshot) {
  65634. var store = giveStore$1(ecModel);
  65635. // If previous dataZoom can not be found,
  65636. // complete an range with current range.
  65637. each$30(newSnapshot, function (batchItem, dataZoomId) {
  65638. var i = store.length - 1;
  65639. for (; i >= 0; i--) {
  65640. var snapshot = store[i];
  65641. if (snapshot[dataZoomId]) {
  65642. break;
  65643. }
  65644. }
  65645. if (i < 0) {
  65646. // No origin range set, create one by current range.
  65647. var dataZoomModel = ecModel.queryComponents(
  65648. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  65649. )[0];
  65650. if (dataZoomModel) {
  65651. var percentRange = dataZoomModel.getPercentRange();
  65652. store[0][dataZoomId] = {
  65653. dataZoomId: dataZoomId,
  65654. start: percentRange[0],
  65655. end: percentRange[1]
  65656. };
  65657. }
  65658. }
  65659. });
  65660. store.push(newSnapshot);
  65661. }
  65662. /**
  65663. * @param {module:echarts/model/Global} ecModel
  65664. * @return {Object} snapshot
  65665. */
  65666. function pop(ecModel) {
  65667. var store = giveStore$1(ecModel);
  65668. var head = store[store.length - 1];
  65669. store.length > 1 && store.pop();
  65670. // Find top for all dataZoom.
  65671. var snapshot = {};
  65672. each$30(head, function (batchItem, dataZoomId) {
  65673. for (var i = store.length - 1; i >= 0; i--) {
  65674. var batchItem = store[i][dataZoomId];
  65675. if (batchItem) {
  65676. snapshot[dataZoomId] = batchItem;
  65677. break;
  65678. }
  65679. }
  65680. });
  65681. return snapshot;
  65682. }
  65683. /**
  65684. * @param {module:echarts/model/Global} ecModel
  65685. */
  65686. function clear$1(ecModel) {
  65687. ecModel[ATTR$2] = null;
  65688. }
  65689. /**
  65690. * @param {module:echarts/model/Global} ecModel
  65691. * @return {number} records. always >= 1.
  65692. */
  65693. function count(ecModel) {
  65694. return giveStore$1(ecModel).length;
  65695. }
  65696. /**
  65697. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  65698. * History length of each dataZoom may be different.
  65699. * this._history[0] is used to store origin range.
  65700. * @type {Array.<Object>}
  65701. */
  65702. function giveStore$1(ecModel) {
  65703. var store = ecModel[ATTR$2];
  65704. if (!store) {
  65705. store = ecModel[ATTR$2] = [{}];
  65706. }
  65707. return store;
  65708. }
  65709. DataZoomModel.extend({
  65710. type: 'dataZoom.select'
  65711. });
  65712. DataZoomView.extend({
  65713. type: 'dataZoom.select'
  65714. });
  65715. /**
  65716. * DataZoom component entry
  65717. */
  65718. // Use dataZoomSelect
  65719. var dataZoomLang = lang.toolbox.dataZoom;
  65720. var each$29 = each$1;
  65721. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  65722. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  65723. function DataZoom(model, ecModel, api) {
  65724. /**
  65725. * @private
  65726. * @type {module:echarts/component/helper/BrushController}
  65727. */
  65728. (this._brushController = new BrushController(api.getZr()))
  65729. .on('brush', bind(this._onBrush, this))
  65730. .mount();
  65731. /**
  65732. * @private
  65733. * @type {boolean}
  65734. */
  65735. this._isZoomActive;
  65736. }
  65737. DataZoom.defaultOption = {
  65738. show: true,
  65739. // Icon group
  65740. icon: {
  65741. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  65742. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  65743. },
  65744. // `zoom`, `back`
  65745. title: clone(dataZoomLang.title)
  65746. };
  65747. var proto$6 = DataZoom.prototype;
  65748. proto$6.render = function (featureModel, ecModel, api, payload) {
  65749. this.model = featureModel;
  65750. this.ecModel = ecModel;
  65751. this.api = api;
  65752. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  65753. updateBackBtnStatus(featureModel, ecModel);
  65754. };
  65755. proto$6.onclick = function (ecModel, api, type) {
  65756. handlers$1[type].call(this);
  65757. };
  65758. proto$6.remove = function (ecModel, api) {
  65759. this._brushController.unmount();
  65760. };
  65761. proto$6.dispose = function (ecModel, api) {
  65762. this._brushController.dispose();
  65763. };
  65764. /**
  65765. * @private
  65766. */
  65767. var handlers$1 = {
  65768. zoom: function () {
  65769. var nextActive = !this._isZoomActive;
  65770. this.api.dispatchAction({
  65771. type: 'takeGlobalCursor',
  65772. key: 'dataZoomSelect',
  65773. dataZoomSelectActive: nextActive
  65774. });
  65775. },
  65776. back: function () {
  65777. this._dispatchZoomAction(pop(this.ecModel));
  65778. }
  65779. };
  65780. /**
  65781. * @private
  65782. */
  65783. proto$6._onBrush = function (areas, opt) {
  65784. if (!opt.isEnd || !areas.length) {
  65785. return;
  65786. }
  65787. var snapshot = {};
  65788. var ecModel = this.ecModel;
  65789. this._brushController.updateCovers([]); // remove cover
  65790. var brushTargetManager = new BrushTargetManager(
  65791. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  65792. );
  65793. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  65794. if (coordSys.type !== 'cartesian2d') {
  65795. return;
  65796. }
  65797. var brushType = area.brushType;
  65798. if (brushType === 'rect') {
  65799. setBatch('x', coordSys, coordRange[0]);
  65800. setBatch('y', coordSys, coordRange[1]);
  65801. }
  65802. else {
  65803. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  65804. }
  65805. });
  65806. push(ecModel, snapshot);
  65807. this._dispatchZoomAction(snapshot);
  65808. function setBatch(dimName, coordSys, minMax) {
  65809. var axis = coordSys.getAxis(dimName);
  65810. var axisModel = axis.model;
  65811. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  65812. // Restrict range.
  65813. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  65814. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  65815. minMax = sliderMove(
  65816. 0, minMax.slice(), axis.scale.getExtent(), 0,
  65817. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  65818. );
  65819. }
  65820. dataZoomModel && (snapshot[dataZoomModel.id] = {
  65821. dataZoomId: dataZoomModel.id,
  65822. startValue: minMax[0],
  65823. endValue: minMax[1]
  65824. });
  65825. }
  65826. function findDataZoom(dimName, axisModel, ecModel) {
  65827. var found;
  65828. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  65829. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  65830. has && (found = dzModel);
  65831. });
  65832. return found;
  65833. }
  65834. };
  65835. /**
  65836. * @private
  65837. */
  65838. proto$6._dispatchZoomAction = function (snapshot) {
  65839. var batch = [];
  65840. // Convert from hash map to array.
  65841. each$29(snapshot, function (batchItem, dataZoomId) {
  65842. batch.push(clone(batchItem));
  65843. });
  65844. batch.length && this.api.dispatchAction({
  65845. type: 'dataZoom',
  65846. from: this.uid,
  65847. batch: batch
  65848. });
  65849. };
  65850. function retrieveAxisSetting(option) {
  65851. var setting = {};
  65852. // Compatible with previous setting: null => all axis, false => no axis.
  65853. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  65854. setting[name] = option[name];
  65855. setting[name] == null && (setting[name] = 'all');
  65856. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  65857. });
  65858. return setting;
  65859. }
  65860. function updateBackBtnStatus(featureModel, ecModel) {
  65861. featureModel.setIconStatus(
  65862. 'back',
  65863. count(ecModel) > 1 ? 'emphasis' : 'normal'
  65864. );
  65865. }
  65866. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  65867. var zoomActive = view._isZoomActive;
  65868. if (payload && payload.type === 'takeGlobalCursor') {
  65869. zoomActive = payload.key === 'dataZoomSelect'
  65870. ? payload.dataZoomSelectActive : false;
  65871. }
  65872. view._isZoomActive = zoomActive;
  65873. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  65874. var brushTargetManager = new BrushTargetManager(
  65875. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  65876. );
  65877. view._brushController
  65878. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  65879. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  65880. ? 'lineX'
  65881. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  65882. ? 'lineY'
  65883. : 'rect';
  65884. }))
  65885. .enableBrush(
  65886. zoomActive
  65887. ? {
  65888. brushType: 'auto',
  65889. brushStyle: {
  65890. // FIXME user customized?
  65891. lineWidth: 0,
  65892. fill: 'rgba(0,0,0,0.2)'
  65893. }
  65894. }
  65895. : false
  65896. );
  65897. }
  65898. register$1('dataZoom', DataZoom);
  65899. // Create special dataZoom option for select
  65900. registerPreprocessor(function (option) {
  65901. if (!option) {
  65902. return;
  65903. }
  65904. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  65905. if (!isArray(dataZoomOpts)) {
  65906. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  65907. }
  65908. var toolboxOpt = option.toolbox;
  65909. if (toolboxOpt) {
  65910. // Assume there is only one toolbox
  65911. if (isArray(toolboxOpt)) {
  65912. toolboxOpt = toolboxOpt[0];
  65913. }
  65914. if (toolboxOpt && toolboxOpt.feature) {
  65915. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  65916. addForAxis('xAxis', dataZoomOpt);
  65917. addForAxis('yAxis', dataZoomOpt);
  65918. }
  65919. }
  65920. function addForAxis(axisName, dataZoomOpt) {
  65921. if (!dataZoomOpt) {
  65922. return;
  65923. }
  65924. // Try not to modify model, because it is not merged yet.
  65925. var axisIndicesName = axisName + 'Index';
  65926. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  65927. if (givenAxisIndices != null
  65928. && givenAxisIndices != 'all'
  65929. && !isArray(givenAxisIndices)
  65930. ) {
  65931. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  65932. }
  65933. forEachComponent(axisName, function (axisOpt, axisIndex) {
  65934. if (givenAxisIndices != null
  65935. && givenAxisIndices != 'all'
  65936. && indexOf(givenAxisIndices, axisIndex) === -1
  65937. ) {
  65938. return;
  65939. }
  65940. var newOpt = {
  65941. type: 'select',
  65942. $fromToolbox: true,
  65943. // Id for merge mapping.
  65944. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  65945. };
  65946. // FIXME
  65947. // Only support one axis now.
  65948. newOpt[axisIndicesName] = axisIndex;
  65949. dataZoomOpts.push(newOpt);
  65950. });
  65951. }
  65952. function forEachComponent(mainType, cb) {
  65953. var opts = option[mainType];
  65954. if (!isArray(opts)) {
  65955. opts = opts ? [opts] : [];
  65956. }
  65957. each$29(opts, cb);
  65958. }
  65959. });
  65960. var restoreLang = lang.toolbox.restore;
  65961. function Restore(model) {
  65962. this.model = model;
  65963. }
  65964. Restore.defaultOption = {
  65965. show: true,
  65966. icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5',
  65967. title: restoreLang.title
  65968. };
  65969. var proto$7 = Restore.prototype;
  65970. proto$7.onclick = function (ecModel, api, type) {
  65971. clear$1(ecModel);
  65972. api.dispatchAction({
  65973. type: 'restore',
  65974. from: this.uid
  65975. });
  65976. };
  65977. register$1('restore', Restore);
  65978. registerAction(
  65979. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  65980. function (payload, ecModel) {
  65981. ecModel.resetOption('recreate');
  65982. }
  65983. );
  65984. var urn = 'urn:schemas-microsoft-com:vml';
  65985. var win = typeof window === 'undefined' ? null : window;
  65986. var vmlInited = false;
  65987. var doc = win && win.document;
  65988. function createNode(tagName) {
  65989. return doCreateNode(tagName);
  65990. }
  65991. // Avoid assign to an exported variable, for transforming to cjs.
  65992. var doCreateNode;
  65993. if (doc && !env$1.canvasSupported) {
  65994. try {
  65995. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  65996. doCreateNode = function (tagName) {
  65997. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  65998. };
  65999. }
  66000. catch (e) {
  66001. doCreateNode = function (tagName) {
  66002. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  66003. };
  66004. }
  66005. }
  66006. // From raphael
  66007. function initVML() {
  66008. if (vmlInited || !doc) {
  66009. return;
  66010. }
  66011. vmlInited = true;
  66012. var styleSheets = doc.styleSheets;
  66013. if (styleSheets.length < 31) {
  66014. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  66015. }
  66016. else {
  66017. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  66018. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  66019. }
  66020. }
  66021. // http://www.w3.org/TR/NOTE-VML
  66022. // TODO Use proxy like svg instead of overwrite brush methods
  66023. var CMD$3 = PathProxy.CMD;
  66024. var round$3 = Math.round;
  66025. var sqrt = Math.sqrt;
  66026. var abs$1 = Math.abs;
  66027. var cos = Math.cos;
  66028. var sin = Math.sin;
  66029. var mathMax$8 = Math.max;
  66030. if (!env$1.canvasSupported) {
  66031. var comma = ',';
  66032. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  66033. var Z = 21600;
  66034. var Z2 = Z / 2;
  66035. var ZLEVEL_BASE = 100000;
  66036. var Z_BASE$1 = 1000;
  66037. var initRootElStyle = function (el) {
  66038. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  66039. el.coordsize = Z + ',' + Z;
  66040. el.coordorigin = '0,0';
  66041. };
  66042. var encodeHtmlAttribute = function (s) {
  66043. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  66044. };
  66045. var rgb2Str = function (r, g, b) {
  66046. return 'rgb(' + [r, g, b].join(',') + ')';
  66047. };
  66048. var append = function (parent, child) {
  66049. if (child && parent && child.parentNode !== parent) {
  66050. parent.appendChild(child);
  66051. }
  66052. };
  66053. var remove = function (parent, child) {
  66054. if (child && parent && child.parentNode === parent) {
  66055. parent.removeChild(child);
  66056. }
  66057. };
  66058. var getZIndex = function (zlevel, z, z2) {
  66059. // z 的取值范围为 [0, 1000]
  66060. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  66061. };
  66062. var parsePercent$3 = function (value, maxValue) {
  66063. if (typeof value === 'string') {
  66064. if (value.lastIndexOf('%') >= 0) {
  66065. return parseFloat(value) / 100 * maxValue;
  66066. }
  66067. return parseFloat(value);
  66068. }
  66069. return value;
  66070. };
  66071. /***************************************************
  66072. * PATH
  66073. **************************************************/
  66074. var setColorAndOpacity = function (el, color, opacity) {
  66075. var colorArr = parse(color);
  66076. opacity = +opacity;
  66077. if (isNaN(opacity)) {
  66078. opacity = 1;
  66079. }
  66080. if (colorArr) {
  66081. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  66082. el.opacity = opacity * colorArr[3];
  66083. }
  66084. };
  66085. var getColorAndAlpha = function (color) {
  66086. var colorArr = parse(color);
  66087. return [
  66088. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  66089. colorArr[3]
  66090. ];
  66091. };
  66092. var updateFillNode = function (el, style, zrEl) {
  66093. // TODO pattern
  66094. var fill = style.fill;
  66095. if (fill != null) {
  66096. // Modified from excanvas
  66097. if (fill instanceof Gradient) {
  66098. var gradientType;
  66099. var angle = 0;
  66100. var focus = [0, 0];
  66101. // additional offset
  66102. var shift = 0;
  66103. // scale factor for offset
  66104. var expansion = 1;
  66105. var rect = zrEl.getBoundingRect();
  66106. var rectWidth = rect.width;
  66107. var rectHeight = rect.height;
  66108. if (fill.type === 'linear') {
  66109. gradientType = 'gradient';
  66110. var transform = zrEl.transform;
  66111. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66112. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  66113. if (transform) {
  66114. applyTransform(p0, p0, transform);
  66115. applyTransform(p1, p1, transform);
  66116. }
  66117. var dx = p1[0] - p0[0];
  66118. var dy = p1[1] - p0[1];
  66119. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  66120. // The angle should be a non-negative number.
  66121. if (angle < 0) {
  66122. angle += 360;
  66123. }
  66124. // Very small angles produce an unexpected result because they are
  66125. // converted to a scientific notation string.
  66126. if (angle < 1e-6) {
  66127. angle = 0;
  66128. }
  66129. }
  66130. else {
  66131. gradientType = 'gradientradial';
  66132. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66133. var transform = zrEl.transform;
  66134. var scale$$1 = zrEl.scale;
  66135. var width = rectWidth;
  66136. var height = rectHeight;
  66137. focus = [
  66138. // Percent in bounding rect
  66139. (p0[0] - rect.x) / width,
  66140. (p0[1] - rect.y) / height
  66141. ];
  66142. if (transform) {
  66143. applyTransform(p0, p0, transform);
  66144. }
  66145. width /= scale$$1[0] * Z;
  66146. height /= scale$$1[1] * Z;
  66147. var dimension = mathMax$8(width, height);
  66148. shift = 2 * 0 / dimension;
  66149. expansion = 2 * fill.r / dimension - shift;
  66150. }
  66151. // We need to sort the color stops in ascending order by offset,
  66152. // otherwise IE won't interpret it correctly.
  66153. var stops = fill.colorStops.slice();
  66154. stops.sort(function(cs1, cs2) {
  66155. return cs1.offset - cs2.offset;
  66156. });
  66157. var length$$1 = stops.length;
  66158. // Color and alpha list of first and last stop
  66159. var colorAndAlphaList = [];
  66160. var colors = [];
  66161. for (var i = 0; i < length$$1; i++) {
  66162. var stop = stops[i];
  66163. var colorAndAlpha = getColorAndAlpha(stop.color);
  66164. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  66165. if (i === 0 || i === length$$1 - 1) {
  66166. colorAndAlphaList.push(colorAndAlpha);
  66167. }
  66168. }
  66169. if (length$$1 >= 2) {
  66170. var color1 = colorAndAlphaList[0][0];
  66171. var color2 = colorAndAlphaList[1][0];
  66172. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  66173. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  66174. el.type = gradientType;
  66175. el.method = 'none';
  66176. el.focus = '100%';
  66177. el.angle = angle;
  66178. el.color = color1;
  66179. el.color2 = color2;
  66180. el.colors = colors.join(',');
  66181. // When colors attribute is used, the meanings of opacity and o:opacity2
  66182. // are reversed.
  66183. el.opacity = opacity2;
  66184. // FIXME g_o_:opacity ?
  66185. el.opacity2 = opacity1;
  66186. }
  66187. if (gradientType === 'radial') {
  66188. el.focusposition = focus.join(',');
  66189. }
  66190. }
  66191. else {
  66192. // FIXME Change from Gradient fill to color fill
  66193. setColorAndOpacity(el, fill, style.opacity);
  66194. }
  66195. }
  66196. };
  66197. var updateStrokeNode = function (el, style) {
  66198. // if (style.lineJoin != null) {
  66199. // el.joinstyle = style.lineJoin;
  66200. // }
  66201. // if (style.miterLimit != null) {
  66202. // el.miterlimit = style.miterLimit * Z;
  66203. // }
  66204. // if (style.lineCap != null) {
  66205. // el.endcap = style.lineCap;
  66206. // }
  66207. if (style.lineDash != null) {
  66208. el.dashstyle = style.lineDash.join(' ');
  66209. }
  66210. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  66211. setColorAndOpacity(el, style.stroke, style.opacity);
  66212. }
  66213. };
  66214. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  66215. var isFill = type == 'fill';
  66216. var el = vmlEl.getElementsByTagName(type)[0];
  66217. // Stroke must have lineWidth
  66218. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  66219. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  66220. // FIXME Remove before updating, or set `colors` will throw error
  66221. if (style[type] instanceof Gradient) {
  66222. remove(vmlEl, el);
  66223. }
  66224. if (!el) {
  66225. el = createNode(type);
  66226. }
  66227. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  66228. append(vmlEl, el);
  66229. }
  66230. else {
  66231. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  66232. remove(vmlEl, el);
  66233. }
  66234. };
  66235. var points$3 = [[], [], []];
  66236. var pathDataToString = function (path, m) {
  66237. var M = CMD$3.M;
  66238. var C = CMD$3.C;
  66239. var L = CMD$3.L;
  66240. var A = CMD$3.A;
  66241. var Q = CMD$3.Q;
  66242. var str = [];
  66243. var nPoint;
  66244. var cmdStr;
  66245. var cmd;
  66246. var i;
  66247. var xi;
  66248. var yi;
  66249. var data = path.data;
  66250. var dataLength = path.len();
  66251. for (i = 0; i < dataLength;) {
  66252. cmd = data[i++];
  66253. cmdStr = '';
  66254. nPoint = 0;
  66255. switch (cmd) {
  66256. case M:
  66257. cmdStr = ' m ';
  66258. nPoint = 1;
  66259. xi = data[i++];
  66260. yi = data[i++];
  66261. points$3[0][0] = xi;
  66262. points$3[0][1] = yi;
  66263. break;
  66264. case L:
  66265. cmdStr = ' l ';
  66266. nPoint = 1;
  66267. xi = data[i++];
  66268. yi = data[i++];
  66269. points$3[0][0] = xi;
  66270. points$3[0][1] = yi;
  66271. break;
  66272. case Q:
  66273. case C:
  66274. cmdStr = ' c ';
  66275. nPoint = 3;
  66276. var x1 = data[i++];
  66277. var y1 = data[i++];
  66278. var x2 = data[i++];
  66279. var y2 = data[i++];
  66280. var x3;
  66281. var y3;
  66282. if (cmd === Q) {
  66283. // Convert quadratic to cubic using degree elevation
  66284. x3 = x2;
  66285. y3 = y2;
  66286. x2 = (x2 + 2 * x1) / 3;
  66287. y2 = (y2 + 2 * y1) / 3;
  66288. x1 = (xi + 2 * x1) / 3;
  66289. y1 = (yi + 2 * y1) / 3;
  66290. }
  66291. else {
  66292. x3 = data[i++];
  66293. y3 = data[i++];
  66294. }
  66295. points$3[0][0] = x1;
  66296. points$3[0][1] = y1;
  66297. points$3[1][0] = x2;
  66298. points$3[1][1] = y2;
  66299. points$3[2][0] = x3;
  66300. points$3[2][1] = y3;
  66301. xi = x3;
  66302. yi = y3;
  66303. break;
  66304. case A:
  66305. var x = 0;
  66306. var y = 0;
  66307. var sx = 1;
  66308. var sy = 1;
  66309. var angle = 0;
  66310. if (m) {
  66311. // Extract SRT from matrix
  66312. x = m[4];
  66313. y = m[5];
  66314. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  66315. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  66316. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  66317. }
  66318. var cx = data[i++];
  66319. var cy = data[i++];
  66320. var rx = data[i++];
  66321. var ry = data[i++];
  66322. var startAngle = data[i++] + angle;
  66323. var endAngle = data[i++] + startAngle + angle;
  66324. // FIXME
  66325. // var psi = data[i++];
  66326. i++;
  66327. var clockwise = data[i++];
  66328. var x0 = cx + cos(startAngle) * rx;
  66329. var y0 = cy + sin(startAngle) * ry;
  66330. var x1 = cx + cos(endAngle) * rx;
  66331. var y1 = cy + sin(endAngle) * ry;
  66332. var type = clockwise ? ' wa ' : ' at ';
  66333. if (Math.abs(x0 - x1) < 1e-4) {
  66334. // IE won't render arches drawn counter clockwise if x0 == x1.
  66335. if (Math.abs(endAngle - startAngle) > 1e-2) {
  66336. // Offset x0 by 1/80 of a pixel. Use something
  66337. // that can be represented in binary
  66338. if (clockwise) {
  66339. x0 += 270 / Z;
  66340. }
  66341. }
  66342. else {
  66343. // Avoid case draw full circle
  66344. if (Math.abs(y0 - cy) < 1e-4) {
  66345. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  66346. y1 -= 270 / Z;
  66347. }
  66348. else {
  66349. y1 += 270 / Z;
  66350. }
  66351. }
  66352. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  66353. x1 += 270 / Z;
  66354. }
  66355. else {
  66356. x1 -= 270 / Z;
  66357. }
  66358. }
  66359. }
  66360. str.push(
  66361. type,
  66362. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  66363. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  66364. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  66365. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  66366. round$3((x0 * sx + x) * Z - Z2), comma,
  66367. round$3((y0 * sy + y) * Z - Z2), comma,
  66368. round$3((x1 * sx + x) * Z - Z2), comma,
  66369. round$3((y1 * sy + y) * Z - Z2)
  66370. );
  66371. xi = x1;
  66372. yi = y1;
  66373. break;
  66374. case CMD$3.R:
  66375. var p0 = points$3[0];
  66376. var p1 = points$3[1];
  66377. // x0, y0
  66378. p0[0] = data[i++];
  66379. p0[1] = data[i++];
  66380. // x1, y1
  66381. p1[0] = p0[0] + data[i++];
  66382. p1[1] = p0[1] + data[i++];
  66383. if (m) {
  66384. applyTransform(p0, p0, m);
  66385. applyTransform(p1, p1, m);
  66386. }
  66387. p0[0] = round$3(p0[0] * Z - Z2);
  66388. p1[0] = round$3(p1[0] * Z - Z2);
  66389. p0[1] = round$3(p0[1] * Z - Z2);
  66390. p1[1] = round$3(p1[1] * Z - Z2);
  66391. str.push(
  66392. // x0, y0
  66393. ' m ', p0[0], comma, p0[1],
  66394. // x1, y0
  66395. ' l ', p1[0], comma, p0[1],
  66396. // x1, y1
  66397. ' l ', p1[0], comma, p1[1],
  66398. // x0, y1
  66399. ' l ', p0[0], comma, p1[1]
  66400. );
  66401. break;
  66402. case CMD$3.Z:
  66403. // FIXME Update xi, yi
  66404. str.push(' x ');
  66405. }
  66406. if (nPoint > 0) {
  66407. str.push(cmdStr);
  66408. for (var k = 0; k < nPoint; k++) {
  66409. var p = points$3[k];
  66410. m && applyTransform(p, p, m);
  66411. // 不 round 会非常慢
  66412. str.push(
  66413. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  66414. k < nPoint - 1 ? comma : ''
  66415. );
  66416. }
  66417. }
  66418. }
  66419. return str.join('');
  66420. };
  66421. // Rewrite the original path method
  66422. Path.prototype.brushVML = function (vmlRoot) {
  66423. var style = this.style;
  66424. var vmlEl = this._vmlEl;
  66425. if (!vmlEl) {
  66426. vmlEl = createNode('shape');
  66427. initRootElStyle(vmlEl);
  66428. this._vmlEl = vmlEl;
  66429. }
  66430. updateFillAndStroke(vmlEl, 'fill', style, this);
  66431. updateFillAndStroke(vmlEl, 'stroke', style, this);
  66432. var m = this.transform;
  66433. var needTransform = m != null;
  66434. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  66435. if (strokeEl) {
  66436. var lineWidth = style.lineWidth;
  66437. // Get the line scale.
  66438. // Determinant of this.m_ means how much the area is enlarged by the
  66439. // transformation. So its square root can be used as a scale factor
  66440. // for width.
  66441. if (needTransform && !style.strokeNoScale) {
  66442. var det = m[0] * m[3] - m[1] * m[2];
  66443. lineWidth *= sqrt(abs$1(det));
  66444. }
  66445. strokeEl.weight = lineWidth + 'px';
  66446. }
  66447. var path = this.path || (this.path = new PathProxy());
  66448. if (this.__dirtyPath) {
  66449. path.beginPath();
  66450. this.buildPath(path, this.shape);
  66451. path.toStatic();
  66452. this.__dirtyPath = false;
  66453. }
  66454. vmlEl.path = pathDataToString(path, this.transform);
  66455. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  66456. // Append to root
  66457. append(vmlRoot, vmlEl);
  66458. // Text
  66459. if (style.text != null) {
  66460. this.drawRectText(vmlRoot, this.getBoundingRect());
  66461. }
  66462. else {
  66463. this.removeRectText(vmlRoot);
  66464. }
  66465. };
  66466. Path.prototype.onRemove = function (vmlRoot) {
  66467. remove(vmlRoot, this._vmlEl);
  66468. this.removeRectText(vmlRoot);
  66469. };
  66470. Path.prototype.onAdd = function (vmlRoot) {
  66471. append(vmlRoot, this._vmlEl);
  66472. this.appendRectText(vmlRoot);
  66473. };
  66474. /***************************************************
  66475. * IMAGE
  66476. **************************************************/
  66477. var isImage = function (img) {
  66478. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  66479. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  66480. // return img instanceof Image;
  66481. };
  66482. // Rewrite the original path method
  66483. ZImage.prototype.brushVML = function (vmlRoot) {
  66484. var style = this.style;
  66485. var image = style.image;
  66486. // Image original width, height
  66487. var ow;
  66488. var oh;
  66489. if (isImage(image)) {
  66490. var src = image.src;
  66491. if (src === this._imageSrc) {
  66492. ow = this._imageWidth;
  66493. oh = this._imageHeight;
  66494. }
  66495. else {
  66496. var imageRuntimeStyle = image.runtimeStyle;
  66497. var oldRuntimeWidth = imageRuntimeStyle.width;
  66498. var oldRuntimeHeight = imageRuntimeStyle.height;
  66499. imageRuntimeStyle.width = 'auto';
  66500. imageRuntimeStyle.height = 'auto';
  66501. // get the original size
  66502. ow = image.width;
  66503. oh = image.height;
  66504. // and remove overides
  66505. imageRuntimeStyle.width = oldRuntimeWidth;
  66506. imageRuntimeStyle.height = oldRuntimeHeight;
  66507. // Caching image original width, height and src
  66508. this._imageSrc = src;
  66509. this._imageWidth = ow;
  66510. this._imageHeight = oh;
  66511. }
  66512. image = src;
  66513. }
  66514. else {
  66515. if (image === this._imageSrc) {
  66516. ow = this._imageWidth;
  66517. oh = this._imageHeight;
  66518. }
  66519. }
  66520. if (!image) {
  66521. return;
  66522. }
  66523. var x = style.x || 0;
  66524. var y = style.y || 0;
  66525. var dw = style.width;
  66526. var dh = style.height;
  66527. var sw = style.sWidth;
  66528. var sh = style.sHeight;
  66529. var sx = style.sx || 0;
  66530. var sy = style.sy || 0;
  66531. var hasCrop = sw && sh;
  66532. var vmlEl = this._vmlEl;
  66533. if (!vmlEl) {
  66534. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  66535. // vmlEl = vmlCore.createNode('group');
  66536. vmlEl = doc.createElement('div');
  66537. initRootElStyle(vmlEl);
  66538. this._vmlEl = vmlEl;
  66539. }
  66540. var vmlElStyle = vmlEl.style;
  66541. var hasRotation = false;
  66542. var m;
  66543. var scaleX = 1;
  66544. var scaleY = 1;
  66545. if (this.transform) {
  66546. m = this.transform;
  66547. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  66548. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  66549. hasRotation = m[1] || m[2];
  66550. }
  66551. if (hasRotation) {
  66552. // If filters are necessary (rotation exists), create them
  66553. // filters are bog-slow, so only create them if abbsolutely necessary
  66554. // The following check doesn't account for skews (which don't exist
  66555. // in the canvas spec (yet) anyway.
  66556. // From excanvas
  66557. var p0 = [x, y];
  66558. var p1 = [x + dw, y];
  66559. var p2 = [x, y + dh];
  66560. var p3 = [x + dw, y + dh];
  66561. applyTransform(p0, p0, m);
  66562. applyTransform(p1, p1, m);
  66563. applyTransform(p2, p2, m);
  66564. applyTransform(p3, p3, m);
  66565. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  66566. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  66567. var transformFilter = [];
  66568. transformFilter.push('M11=', m[0] / scaleX, comma,
  66569. 'M12=', m[2] / scaleY, comma,
  66570. 'M21=', m[1] / scaleX, comma,
  66571. 'M22=', m[3] / scaleY, comma,
  66572. 'Dx=', round$3(x * scaleX + m[4]), comma,
  66573. 'Dy=', round$3(y * scaleY + m[5]));
  66574. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  66575. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  66576. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  66577. + transformFilter.join('') + ', SizingMethod=clip)';
  66578. }
  66579. else {
  66580. if (m) {
  66581. x = x * scaleX + m[4];
  66582. y = y * scaleY + m[5];
  66583. }
  66584. vmlElStyle.filter = '';
  66585. vmlElStyle.left = round$3(x) + 'px';
  66586. vmlElStyle.top = round$3(y) + 'px';
  66587. }
  66588. var imageEl = this._imageEl;
  66589. var cropEl = this._cropEl;
  66590. if (!imageEl) {
  66591. imageEl = doc.createElement('div');
  66592. this._imageEl = imageEl;
  66593. }
  66594. var imageELStyle = imageEl.style;
  66595. if (hasCrop) {
  66596. // Needs know image original width and height
  66597. if (! (ow && oh)) {
  66598. var tmpImage = new Image();
  66599. var self = this;
  66600. tmpImage.onload = function () {
  66601. tmpImage.onload = null;
  66602. ow = tmpImage.width;
  66603. oh = tmpImage.height;
  66604. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  66605. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  66606. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  66607. // Caching image original width, height and src
  66608. self._imageWidth = ow;
  66609. self._imageHeight = oh;
  66610. self._imageSrc = image;
  66611. };
  66612. tmpImage.src = image;
  66613. }
  66614. else {
  66615. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  66616. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  66617. }
  66618. if (! cropEl) {
  66619. cropEl = doc.createElement('div');
  66620. cropEl.style.overflow = 'hidden';
  66621. this._cropEl = cropEl;
  66622. }
  66623. var cropElStyle = cropEl.style;
  66624. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  66625. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  66626. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  66627. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  66628. if (! cropEl.parentNode) {
  66629. vmlEl.appendChild(cropEl);
  66630. }
  66631. if (imageEl.parentNode != cropEl) {
  66632. cropEl.appendChild(imageEl);
  66633. }
  66634. }
  66635. else {
  66636. imageELStyle.width = round$3(scaleX * dw) + 'px';
  66637. imageELStyle.height = round$3(scaleY * dh) + 'px';
  66638. vmlEl.appendChild(imageEl);
  66639. if (cropEl && cropEl.parentNode) {
  66640. vmlEl.removeChild(cropEl);
  66641. this._cropEl = null;
  66642. }
  66643. }
  66644. var filterStr = '';
  66645. var alpha = style.opacity;
  66646. if (alpha < 1) {
  66647. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  66648. }
  66649. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  66650. imageELStyle.filter = filterStr;
  66651. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  66652. // Append to root
  66653. append(vmlRoot, vmlEl);
  66654. // Text
  66655. if (style.text != null) {
  66656. this.drawRectText(vmlRoot, this.getBoundingRect());
  66657. }
  66658. };
  66659. ZImage.prototype.onRemove = function (vmlRoot) {
  66660. remove(vmlRoot, this._vmlEl);
  66661. this._vmlEl = null;
  66662. this._cropEl = null;
  66663. this._imageEl = null;
  66664. this.removeRectText(vmlRoot);
  66665. };
  66666. ZImage.prototype.onAdd = function (vmlRoot) {
  66667. append(vmlRoot, this._vmlEl);
  66668. this.appendRectText(vmlRoot);
  66669. };
  66670. /***************************************************
  66671. * TEXT
  66672. **************************************************/
  66673. var DEFAULT_STYLE_NORMAL = 'normal';
  66674. var fontStyleCache = {};
  66675. var fontStyleCacheCount = 0;
  66676. var MAX_FONT_CACHE_SIZE = 100;
  66677. var fontEl = document.createElement('div');
  66678. var getFontStyle = function (fontString) {
  66679. var fontStyle = fontStyleCache[fontString];
  66680. if (!fontStyle) {
  66681. // Clear cache
  66682. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  66683. fontStyleCacheCount = 0;
  66684. fontStyleCache = {};
  66685. }
  66686. var style = fontEl.style;
  66687. var fontFamily;
  66688. try {
  66689. style.font = fontString;
  66690. fontFamily = style.fontFamily.split(',')[0];
  66691. }
  66692. catch (e) {
  66693. }
  66694. fontStyle = {
  66695. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  66696. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  66697. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  66698. size: parseFloat(style.fontSize || 12) | 0,
  66699. family: fontFamily || 'Microsoft YaHei'
  66700. };
  66701. fontStyleCache[fontString] = fontStyle;
  66702. fontStyleCacheCount++;
  66703. }
  66704. return fontStyle;
  66705. };
  66706. var textMeasureEl;
  66707. // Overwrite measure text method
  66708. $override$1('measureText', function (text, textFont) {
  66709. var doc$$1 = doc;
  66710. if (!textMeasureEl) {
  66711. textMeasureEl = doc$$1.createElement('div');
  66712. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  66713. + 'padding:0;margin:0;border:none;white-space:pre;';
  66714. doc.body.appendChild(textMeasureEl);
  66715. }
  66716. try {
  66717. textMeasureEl.style.font = textFont;
  66718. } catch (ex) {
  66719. // Ignore failures to set to invalid font.
  66720. }
  66721. textMeasureEl.innerHTML = '';
  66722. // Don't use innerHTML or innerText because they allow markup/whitespace.
  66723. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  66724. return {
  66725. width: textMeasureEl.offsetWidth
  66726. };
  66727. });
  66728. var tmpRect$2 = new BoundingRect();
  66729. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  66730. var style = this.style;
  66731. // Optimize, avoid normalize every time.
  66732. this.__dirty && normalizeTextStyle(style, true);
  66733. var text = style.text;
  66734. // Convert to string
  66735. text != null && (text += '');
  66736. if (!text) {
  66737. return;
  66738. }
  66739. // Convert rich text to plain text. Rich text is not supported in
  66740. // IE8-, but tags in rich text template will be removed.
  66741. if (style.rich) {
  66742. var contentBlock = parseRichText(text, style);
  66743. text = [];
  66744. for (var i = 0; i < contentBlock.lines.length; i++) {
  66745. var tokens = contentBlock.lines[i].tokens;
  66746. var textLine = [];
  66747. for (var j = 0; j < tokens.length; j++) {
  66748. textLine.push(tokens[j].text);
  66749. }
  66750. text.push(textLine.join(''));
  66751. }
  66752. text = text.join('\n');
  66753. }
  66754. var x;
  66755. var y;
  66756. var align = style.textAlign;
  66757. var verticalAlign = style.textVerticalAlign;
  66758. var fontStyle = getFontStyle(style.font);
  66759. // FIXME encodeHtmlAttribute ?
  66760. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  66761. + fontStyle.size + 'px "' + fontStyle.family + '"';
  66762. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  66763. // Transform rect to view space
  66764. var m = this.transform;
  66765. // Ignore transform for text in other element
  66766. if (m && !fromTextEl) {
  66767. tmpRect$2.copy(rect);
  66768. tmpRect$2.applyTransform(m);
  66769. rect = tmpRect$2;
  66770. }
  66771. if (!fromTextEl) {
  66772. var textPosition = style.textPosition;
  66773. var distance$$1 = style.textDistance;
  66774. // Text position represented by coord
  66775. if (textPosition instanceof Array) {
  66776. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  66777. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  66778. align = align || 'left';
  66779. }
  66780. else {
  66781. var res = adjustTextPositionOnRect(
  66782. textPosition, rect, distance$$1
  66783. );
  66784. x = res.x;
  66785. y = res.y;
  66786. // Default align and baseline when has textPosition
  66787. align = align || res.textAlign;
  66788. verticalAlign = verticalAlign || res.textVerticalAlign;
  66789. }
  66790. }
  66791. else {
  66792. x = rect.x;
  66793. y = rect.y;
  66794. }
  66795. x = adjustTextX(x, textRect.width, align);
  66796. y = adjustTextY(y, textRect.height, verticalAlign);
  66797. // Force baseline 'middle'
  66798. y += textRect.height / 2;
  66799. // var fontSize = fontStyle.size;
  66800. // 1.75 is an arbitrary number, as there is no info about the text baseline
  66801. // switch (baseline) {
  66802. // case 'hanging':
  66803. // case 'top':
  66804. // y += fontSize / 1.75;
  66805. // break;
  66806. // case 'middle':
  66807. // break;
  66808. // default:
  66809. // // case null:
  66810. // // case 'alphabetic':
  66811. // // case 'ideographic':
  66812. // // case 'bottom':
  66813. // y -= fontSize / 2.25;
  66814. // break;
  66815. // }
  66816. // switch (align) {
  66817. // case 'left':
  66818. // break;
  66819. // case 'center':
  66820. // x -= textRect.width / 2;
  66821. // break;
  66822. // case 'right':
  66823. // x -= textRect.width;
  66824. // break;
  66825. // case 'end':
  66826. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  66827. // break;
  66828. // case 'start':
  66829. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  66830. // break;
  66831. // default:
  66832. // align = 'left';
  66833. // }
  66834. var createNode$$1 = createNode;
  66835. var textVmlEl = this._textVmlEl;
  66836. var pathEl;
  66837. var textPathEl;
  66838. var skewEl;
  66839. if (!textVmlEl) {
  66840. textVmlEl = createNode$$1('line');
  66841. pathEl = createNode$$1('path');
  66842. textPathEl = createNode$$1('textpath');
  66843. skewEl = createNode$$1('skew');
  66844. // FIXME Why here is not cammel case
  66845. // Align 'center' seems wrong
  66846. textPathEl.style['v-text-align'] = 'left';
  66847. initRootElStyle(textVmlEl);
  66848. pathEl.textpathok = true;
  66849. textPathEl.on = true;
  66850. textVmlEl.from = '0 0';
  66851. textVmlEl.to = '1000 0.05';
  66852. append(textVmlEl, skewEl);
  66853. append(textVmlEl, pathEl);
  66854. append(textVmlEl, textPathEl);
  66855. this._textVmlEl = textVmlEl;
  66856. }
  66857. else {
  66858. // 这里是在前面 appendChild 保证顺序的前提下
  66859. skewEl = textVmlEl.firstChild;
  66860. pathEl = skewEl.nextSibling;
  66861. textPathEl = pathEl.nextSibling;
  66862. }
  66863. var coords = [x, y];
  66864. var textVmlElStyle = textVmlEl.style;
  66865. // Ignore transform for text in other element
  66866. if (m && fromTextEl) {
  66867. applyTransform(coords, coords, m);
  66868. skewEl.on = true;
  66869. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  66870. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  66871. // Text position
  66872. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  66873. // Left top point as origin
  66874. skewEl.origin = '0 0';
  66875. textVmlElStyle.left = '0px';
  66876. textVmlElStyle.top = '0px';
  66877. }
  66878. else {
  66879. skewEl.on = false;
  66880. textVmlElStyle.left = round$3(x) + 'px';
  66881. textVmlElStyle.top = round$3(y) + 'px';
  66882. }
  66883. textPathEl.string = encodeHtmlAttribute(text);
  66884. // TODO
  66885. try {
  66886. textPathEl.style.font = font;
  66887. }
  66888. // Error font format
  66889. catch (e) {}
  66890. updateFillAndStroke(textVmlEl, 'fill', {
  66891. fill: style.textFill,
  66892. opacity: style.opacity
  66893. }, this);
  66894. updateFillAndStroke(textVmlEl, 'stroke', {
  66895. stroke: style.textStroke,
  66896. opacity: style.opacity,
  66897. lineDash: style.lineDash
  66898. }, this);
  66899. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  66900. // Attached to root
  66901. append(vmlRoot, textVmlEl);
  66902. };
  66903. var removeRectText = function (vmlRoot) {
  66904. remove(vmlRoot, this._textVmlEl);
  66905. this._textVmlEl = null;
  66906. };
  66907. var appendRectText = function (vmlRoot) {
  66908. append(vmlRoot, this._textVmlEl);
  66909. };
  66910. var list = [RectText, Displayable, ZImage, Path, Text];
  66911. // In case Displayable has been mixed in RectText
  66912. for (var i$3 = 0; i$3 < list.length; i$3++) {
  66913. var proto$8 = list[i$3].prototype;
  66914. proto$8.drawRectText = drawRectText;
  66915. proto$8.removeRectText = removeRectText;
  66916. proto$8.appendRectText = appendRectText;
  66917. }
  66918. Text.prototype.brushVML = function (vmlRoot) {
  66919. var style = this.style;
  66920. if (style.text != null) {
  66921. this.drawRectText(vmlRoot, {
  66922. x: style.x || 0, y: style.y || 0,
  66923. width: 0, height: 0
  66924. }, this.getBoundingRect(), true);
  66925. }
  66926. else {
  66927. this.removeRectText(vmlRoot);
  66928. }
  66929. };
  66930. Text.prototype.onRemove = function (vmlRoot) {
  66931. this.removeRectText(vmlRoot);
  66932. };
  66933. Text.prototype.onAdd = function (vmlRoot) {
  66934. this.appendRectText(vmlRoot);
  66935. };
  66936. }
  66937. /**
  66938. * VML Painter.
  66939. *
  66940. * @module zrender/vml/Painter
  66941. */
  66942. function parseInt10$1(val) {
  66943. return parseInt(val, 10);
  66944. }
  66945. /**
  66946. * @alias module:zrender/vml/Painter
  66947. */
  66948. function VMLPainter(root, storage) {
  66949. initVML();
  66950. this.root = root;
  66951. this.storage = storage;
  66952. var vmlViewport = document.createElement('div');
  66953. var vmlRoot = document.createElement('div');
  66954. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  66955. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  66956. root.appendChild(vmlViewport);
  66957. this._vmlRoot = vmlRoot;
  66958. this._vmlViewport = vmlViewport;
  66959. this.resize();
  66960. // Modify storage
  66961. var oldDelFromStorage = storage.delFromStorage;
  66962. var oldAddToStorage = storage.addToStorage;
  66963. storage.delFromStorage = function (el) {
  66964. oldDelFromStorage.call(storage, el);
  66965. if (el) {
  66966. el.onRemove && el.onRemove(vmlRoot);
  66967. }
  66968. };
  66969. storage.addToStorage = function (el) {
  66970. // Displayable already has a vml node
  66971. el.onAdd && el.onAdd(vmlRoot);
  66972. oldAddToStorage.call(storage, el);
  66973. };
  66974. this._firstPaint = true;
  66975. }
  66976. VMLPainter.prototype = {
  66977. constructor: VMLPainter,
  66978. getType: function () {
  66979. return 'vml';
  66980. },
  66981. /**
  66982. * @return {HTMLDivElement}
  66983. */
  66984. getViewportRoot: function () {
  66985. return this._vmlViewport;
  66986. },
  66987. getViewportRootOffset: function () {
  66988. var viewportRoot = this.getViewportRoot();
  66989. if (viewportRoot) {
  66990. return {
  66991. offsetLeft: viewportRoot.offsetLeft || 0,
  66992. offsetTop: viewportRoot.offsetTop || 0
  66993. };
  66994. }
  66995. },
  66996. /**
  66997. * 刷新
  66998. */
  66999. refresh: function () {
  67000. var list = this.storage.getDisplayList(true, true);
  67001. this._paintList(list);
  67002. },
  67003. _paintList: function (list) {
  67004. var vmlRoot = this._vmlRoot;
  67005. for (var i = 0; i < list.length; i++) {
  67006. var el = list[i];
  67007. if (el.invisible || el.ignore) {
  67008. if (!el.__alreadyNotVisible) {
  67009. el.onRemove(vmlRoot);
  67010. }
  67011. // Set as already invisible
  67012. el.__alreadyNotVisible = true;
  67013. }
  67014. else {
  67015. if (el.__alreadyNotVisible) {
  67016. el.onAdd(vmlRoot);
  67017. }
  67018. el.__alreadyNotVisible = false;
  67019. if (el.__dirty) {
  67020. el.beforeBrush && el.beforeBrush();
  67021. (el.brushVML || el.brush).call(el, vmlRoot);
  67022. el.afterBrush && el.afterBrush();
  67023. }
  67024. }
  67025. el.__dirty = false;
  67026. }
  67027. if (this._firstPaint) {
  67028. // Detached from document at first time
  67029. // to avoid page refreshing too many times
  67030. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  67031. this._vmlViewport.appendChild(vmlRoot);
  67032. this._firstPaint = false;
  67033. }
  67034. },
  67035. resize: function (width, height) {
  67036. var width = width == null ? this._getWidth() : width;
  67037. var height = height == null ? this._getHeight() : height;
  67038. if (this._width != width || this._height != height) {
  67039. this._width = width;
  67040. this._height = height;
  67041. var vmlViewportStyle = this._vmlViewport.style;
  67042. vmlViewportStyle.width = width + 'px';
  67043. vmlViewportStyle.height = height + 'px';
  67044. }
  67045. },
  67046. dispose: function () {
  67047. this.root.innerHTML = '';
  67048. this._vmlRoot =
  67049. this._vmlViewport =
  67050. this.storage = null;
  67051. },
  67052. getWidth: function () {
  67053. return this._width;
  67054. },
  67055. getHeight: function () {
  67056. return this._height;
  67057. },
  67058. clear: function () {
  67059. if (this._vmlViewport) {
  67060. this.root.removeChild(this._vmlViewport);
  67061. }
  67062. },
  67063. _getWidth: function () {
  67064. var root = this.root;
  67065. var stl = root.currentStyle;
  67066. return ((root.clientWidth || parseInt10$1(stl.width))
  67067. - parseInt10$1(stl.paddingLeft)
  67068. - parseInt10$1(stl.paddingRight)) | 0;
  67069. },
  67070. _getHeight: function () {
  67071. var root = this.root;
  67072. var stl = root.currentStyle;
  67073. return ((root.clientHeight || parseInt10$1(stl.height))
  67074. - parseInt10$1(stl.paddingTop)
  67075. - parseInt10$1(stl.paddingBottom)) | 0;
  67076. }
  67077. };
  67078. // Not supported methods
  67079. function createMethodNotSupport(method) {
  67080. return function () {
  67081. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  67082. };
  67083. }
  67084. // Unsupported methods
  67085. each$1([
  67086. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  67087. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  67088. ], function (name) {
  67089. VMLPainter.prototype[name] = createMethodNotSupport(name);
  67090. });
  67091. registerPainter('vml', VMLPainter);
  67092. var svgURI = 'http://www.w3.org/2000/svg';
  67093. function createElement(name) {
  67094. return document.createElementNS(svgURI, name);
  67095. }
  67096. // TODO
  67097. // 1. shadow
  67098. // 2. Image: sx, sy, sw, sh
  67099. var CMD$4 = PathProxy.CMD;
  67100. var arrayJoin = Array.prototype.join;
  67101. var NONE = 'none';
  67102. var mathRound = Math.round;
  67103. var mathSin$3 = Math.sin;
  67104. var mathCos$3 = Math.cos;
  67105. var PI$5 = Math.PI;
  67106. var PI2$7 = Math.PI * 2;
  67107. var degree = 180 / PI$5;
  67108. var EPSILON$4 = 1e-4;
  67109. function round4(val) {
  67110. return mathRound(val * 1e4) / 1e4;
  67111. }
  67112. function isAroundZero$1(val) {
  67113. return val < EPSILON$4 && val > -EPSILON$4;
  67114. }
  67115. function pathHasFill(style, isText) {
  67116. var fill = isText ? style.textFill : style.fill;
  67117. return fill != null && fill !== NONE;
  67118. }
  67119. function pathHasStroke(style, isText) {
  67120. var stroke = isText ? style.textStroke : style.stroke;
  67121. return stroke != null && stroke !== NONE;
  67122. }
  67123. function setTransform(svgEl, m) {
  67124. if (m) {
  67125. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  67126. }
  67127. }
  67128. function attr(el, key, val) {
  67129. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  67130. // Don't set attribute for gradient, since it need new dom nodes
  67131. el.setAttribute(key, val);
  67132. }
  67133. }
  67134. function attrXLink(el, key, val) {
  67135. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  67136. }
  67137. function bindStyle(svgEl, style, isText) {
  67138. if (pathHasFill(style, isText)) {
  67139. var fill = isText ? style.textFill : style.fill;
  67140. fill = fill === 'transparent' ? NONE : fill;
  67141. /**
  67142. * FIXME:
  67143. * This is a temporary fix for Chrome's clipping bug
  67144. * that happens when a clip-path is referring another one.
  67145. * This fix should be used before Chrome's bug is fixed.
  67146. * For an element that has clip-path, and fill is none,
  67147. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  67148. * Otherwise, it will show black fill color.
  67149. * 0.002 is used because this won't work for alpha values smaller
  67150. * than 0.002.
  67151. *
  67152. * See
  67153. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  67154. * for more information.
  67155. */
  67156. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  67157. fill = 'rgba(0, 0, 0, 0.002)';
  67158. }
  67159. attr(svgEl, 'fill', fill);
  67160. attr(svgEl, 'fill-opacity', style.opacity);
  67161. }
  67162. else {
  67163. attr(svgEl, 'fill', NONE);
  67164. }
  67165. if (pathHasStroke(style, isText)) {
  67166. var stroke = isText ? style.textStroke : style.stroke;
  67167. stroke = stroke === 'transparent' ? NONE : stroke;
  67168. attr(svgEl, 'stroke', stroke);
  67169. var strokeWidth = isText
  67170. ? style.textStrokeWidth
  67171. : style.lineWidth;
  67172. var strokeScale = !isText && style.strokeNoScale
  67173. ? style.host.getLineScale()
  67174. : 1;
  67175. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  67176. // stroke then fill for text; fill then stroke for others
  67177. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  67178. attr(svgEl, 'stroke-opacity', style.opacity);
  67179. var lineDash = style.lineDash;
  67180. if (lineDash) {
  67181. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  67182. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  67183. }
  67184. else {
  67185. attr(svgEl, 'stroke-dasharray', '');
  67186. }
  67187. // PENDING
  67188. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  67189. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  67190. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  67191. }
  67192. else {
  67193. attr(svgEl, 'stroke', NONE);
  67194. }
  67195. }
  67196. /***************************************************
  67197. * PATH
  67198. **************************************************/
  67199. function pathDataToString$1(path) {
  67200. var str = [];
  67201. var data = path.data;
  67202. var dataLength = path.len();
  67203. for (var i = 0; i < dataLength;) {
  67204. var cmd = data[i++];
  67205. var cmdStr = '';
  67206. var nData = 0;
  67207. switch (cmd) {
  67208. case CMD$4.M:
  67209. cmdStr = 'M';
  67210. nData = 2;
  67211. break;
  67212. case CMD$4.L:
  67213. cmdStr = 'L';
  67214. nData = 2;
  67215. break;
  67216. case CMD$4.Q:
  67217. cmdStr = 'Q';
  67218. nData = 4;
  67219. break;
  67220. case CMD$4.C:
  67221. cmdStr = 'C';
  67222. nData = 6;
  67223. break;
  67224. case CMD$4.A:
  67225. var cx = data[i++];
  67226. var cy = data[i++];
  67227. var rx = data[i++];
  67228. var ry = data[i++];
  67229. var theta = data[i++];
  67230. var dTheta = data[i++];
  67231. var psi = data[i++];
  67232. var clockwise = data[i++];
  67233. var dThetaPositive = Math.abs(dTheta);
  67234. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  67235. && !isAroundZero$1(dThetaPositive);
  67236. var large = false;
  67237. if (dThetaPositive >= PI2$7) {
  67238. large = true;
  67239. }
  67240. else if (isAroundZero$1(dThetaPositive)) {
  67241. large = false;
  67242. }
  67243. else {
  67244. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  67245. === !!clockwise;
  67246. }
  67247. var x0 = round4(cx + rx * mathCos$3(theta));
  67248. var y0 = round4(cy + ry * mathSin$3(theta));
  67249. // It will not draw if start point and end point are exactly the same
  67250. // We need to shift the end point with a small value
  67251. // FIXME A better way to draw circle ?
  67252. if (isCircle) {
  67253. if (clockwise) {
  67254. dTheta = PI2$7 - 1e-4;
  67255. }
  67256. else {
  67257. dTheta = -PI2$7 + 1e-4;
  67258. }
  67259. large = true;
  67260. if (i === 9) {
  67261. // Move to (x0, y0) only when CMD.A comes at the
  67262. // first position of a shape.
  67263. // For instance, when drawing a ring, CMD.A comes
  67264. // after CMD.M, so it's unnecessary to move to
  67265. // (x0, y0).
  67266. str.push('M', x0, y0);
  67267. }
  67268. }
  67269. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  67270. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  67271. // FIXME Ellipse
  67272. str.push('A', round4(rx), round4(ry),
  67273. mathRound(psi * degree), +large, +clockwise, x, y);
  67274. break;
  67275. case CMD$4.Z:
  67276. cmdStr = 'Z';
  67277. break;
  67278. case CMD$4.R:
  67279. var x = round4(data[i++]);
  67280. var y = round4(data[i++]);
  67281. var w = round4(data[i++]);
  67282. var h = round4(data[i++]);
  67283. str.push(
  67284. 'M', x, y,
  67285. 'L', x + w, y,
  67286. 'L', x + w, y + h,
  67287. 'L', x, y + h,
  67288. 'L', x, y
  67289. );
  67290. break;
  67291. }
  67292. cmdStr && str.push(cmdStr);
  67293. for (var j = 0; j < nData; j++) {
  67294. // PENDING With scale
  67295. str.push(round4(data[i++]));
  67296. }
  67297. }
  67298. return str.join(' ');
  67299. }
  67300. var svgPath = {};
  67301. svgPath.brush = function (el) {
  67302. var style = el.style;
  67303. var svgEl = el.__svgEl;
  67304. if (!svgEl) {
  67305. svgEl = createElement('path');
  67306. el.__svgEl = svgEl;
  67307. }
  67308. if (!el.path) {
  67309. el.createPathProxy();
  67310. }
  67311. var path = el.path;
  67312. if (el.__dirtyPath) {
  67313. path.beginPath();
  67314. el.buildPath(path, el.shape);
  67315. el.__dirtyPath = false;
  67316. var pathStr = pathDataToString$1(path);
  67317. if (pathStr.indexOf('NaN') < 0) {
  67318. // Ignore illegal path, which may happen such in out-of-range
  67319. // data in Calendar series.
  67320. attr(svgEl, 'd', pathStr);
  67321. }
  67322. }
  67323. bindStyle(svgEl, style);
  67324. setTransform(svgEl, el.transform);
  67325. if (style.text != null) {
  67326. svgTextDrawRectText(el, el.getBoundingRect());
  67327. }
  67328. };
  67329. /***************************************************
  67330. * IMAGE
  67331. **************************************************/
  67332. var svgImage = {};
  67333. svgImage.brush = function (el) {
  67334. var style = el.style;
  67335. var image = style.image;
  67336. if (image instanceof HTMLImageElement) {
  67337. var src = image.src;
  67338. image = src;
  67339. }
  67340. if (! image) {
  67341. return;
  67342. }
  67343. var x = style.x || 0;
  67344. var y = style.y || 0;
  67345. var dw = style.width;
  67346. var dh = style.height;
  67347. var svgEl = el.__svgEl;
  67348. if (! svgEl) {
  67349. svgEl = createElement('image');
  67350. el.__svgEl = svgEl;
  67351. }
  67352. if (image !== el.__imageSrc) {
  67353. attrXLink(svgEl, 'href', image);
  67354. // Caching image src
  67355. el.__imageSrc = image;
  67356. }
  67357. attr(svgEl, 'width', dw);
  67358. attr(svgEl, 'height', dh);
  67359. attr(svgEl, 'x', x);
  67360. attr(svgEl, 'y', y);
  67361. setTransform(svgEl, el.transform);
  67362. if (style.text != null) {
  67363. svgTextDrawRectText(el, el.getBoundingRect());
  67364. }
  67365. };
  67366. /***************************************************
  67367. * TEXT
  67368. **************************************************/
  67369. var svgText = {};
  67370. var tmpRect$3 = new BoundingRect();
  67371. var svgTextDrawRectText = function (el, rect, textRect) {
  67372. var style = el.style;
  67373. el.__dirty && normalizeTextStyle(style, true);
  67374. var text = style.text;
  67375. // Convert to string
  67376. if (text == null) {
  67377. // Draw no text only when text is set to null, but not ''
  67378. return;
  67379. }
  67380. else {
  67381. text += '';
  67382. }
  67383. var textSvgEl = el.__textSvgEl;
  67384. if (! textSvgEl) {
  67385. textSvgEl = createElement('text');
  67386. el.__textSvgEl = textSvgEl;
  67387. }
  67388. bindStyle(textSvgEl, style, true);
  67389. if (el instanceof Text || el.style.transformText) {
  67390. // Transform text with element
  67391. setTransform(textSvgEl, el.transform);
  67392. }
  67393. else {
  67394. if (el.transform) {
  67395. tmpRect$3.copy(rect);
  67396. tmpRect$3.applyTransform(el.transform);
  67397. rect = tmpRect$3;
  67398. }
  67399. else {
  67400. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  67401. rect.x = pos[0];
  67402. rect.y = pos[1];
  67403. }
  67404. }
  67405. var x;
  67406. var y;
  67407. var textPosition = style.textPosition;
  67408. var distance = style.textDistance;
  67409. var align = style.textAlign || 'left';
  67410. if (typeof style.fontSize === 'number') {
  67411. style.fontSize += 'px';
  67412. }
  67413. var font = style.font
  67414. || [
  67415. style.fontStyle || '',
  67416. style.fontWeight || '',
  67417. style.fontSize || '',
  67418. style.fontFamily || ''
  67419. ].join(' ')
  67420. || DEFAULT_FONT;
  67421. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  67422. textRect = getBoundingRect(text, font, align,
  67423. verticalAlign);
  67424. var lineHeight = textRect.lineHeight;
  67425. // Text position represented by coord
  67426. if (textPosition instanceof Array) {
  67427. x = rect.x + textPosition[0];
  67428. y = rect.y + textPosition[1];
  67429. }
  67430. else {
  67431. var newPos = adjustTextPositionOnRect(
  67432. textPosition, rect, distance
  67433. );
  67434. x = newPos.x;
  67435. y = newPos.y;
  67436. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  67437. align = newPos.textAlign;
  67438. }
  67439. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  67440. if (font) {
  67441. textSvgEl.style.font = font;
  67442. }
  67443. var textPadding = style.textPadding;
  67444. // Make baseline top
  67445. attr(textSvgEl, 'x', x);
  67446. attr(textSvgEl, 'y', y);
  67447. var textLines = text.split('\n');
  67448. var nTextLines = textLines.length;
  67449. var textAnchor = align;
  67450. // PENDING
  67451. if (textAnchor === 'left') {
  67452. textAnchor = 'start';
  67453. textPadding && (x += textPadding[3]);
  67454. }
  67455. else if (textAnchor === 'right') {
  67456. textAnchor = 'end';
  67457. textPadding && (x -= textPadding[1]);
  67458. }
  67459. else if (textAnchor === 'center') {
  67460. textAnchor = 'middle';
  67461. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  67462. }
  67463. var dy = 0;
  67464. if (verticalAlign === 'baseline') {
  67465. dy = -textRect.height + lineHeight;
  67466. textPadding && (dy -= textPadding[2]);
  67467. }
  67468. else if (verticalAlign === 'middle') {
  67469. dy = (-textRect.height + lineHeight) / 2;
  67470. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  67471. }
  67472. else {
  67473. textPadding && (dy += textPadding[0]);
  67474. }
  67475. // Font may affect position of each tspan elements
  67476. if (el.__text !== text || el.__textFont !== font) {
  67477. var tspanList = el.__tspanList || [];
  67478. el.__tspanList = tspanList;
  67479. for (var i = 0; i < nTextLines; i++) {
  67480. // Using cached tspan elements
  67481. var tspan = tspanList[i];
  67482. if (! tspan) {
  67483. tspan = tspanList[i] = createElement('tspan');
  67484. textSvgEl.appendChild(tspan);
  67485. attr(tspan, 'alignment-baseline', verticalAlign);
  67486. attr(tspan, 'text-anchor', textAnchor);
  67487. }
  67488. else {
  67489. tspan.innerHTML = '';
  67490. }
  67491. attr(tspan, 'x', x);
  67492. attr(tspan, 'y', y + i * lineHeight + dy);
  67493. tspan.appendChild(document.createTextNode(textLines[i]));
  67494. }
  67495. // Remove unsed tspan elements
  67496. for (; i < tspanList.length; i++) {
  67497. textSvgEl.removeChild(tspanList[i]);
  67498. }
  67499. tspanList.length = nTextLines;
  67500. el.__text = text;
  67501. el.__textFont = font;
  67502. }
  67503. else if (el.__tspanList.length) {
  67504. // Update span x and y
  67505. var len = el.__tspanList.length;
  67506. for (var i = 0; i < len; ++i) {
  67507. var tspan = el.__tspanList[i];
  67508. if (tspan) {
  67509. attr(tspan, 'x', x);
  67510. attr(tspan, 'y', y + i * lineHeight + dy);
  67511. }
  67512. }
  67513. }
  67514. };
  67515. function getVerticalAlignForSvg(verticalAlign) {
  67516. if (verticalAlign === 'middle') {
  67517. return 'middle';
  67518. }
  67519. else if (verticalAlign === 'bottom') {
  67520. return 'baseline';
  67521. }
  67522. else {
  67523. return 'hanging';
  67524. }
  67525. }
  67526. svgText.drawRectText = svgTextDrawRectText;
  67527. svgText.brush = function (el) {
  67528. var style = el.style;
  67529. if (style.text != null) {
  67530. // 强制设置 textPosition
  67531. style.textPosition = [0, 0];
  67532. svgTextDrawRectText(el, {
  67533. x: style.x || 0, y: style.y || 0,
  67534. width: 0, height: 0
  67535. }, el.getBoundingRect());
  67536. }
  67537. };
  67538. // Myers' Diff Algorithm
  67539. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  67540. function Diff() {}
  67541. Diff.prototype = {
  67542. diff: function (oldArr, newArr, equals) {
  67543. if (!equals) {
  67544. equals = function (a, b) {
  67545. return a === b;
  67546. };
  67547. }
  67548. this.equals = equals;
  67549. var self = this;
  67550. oldArr = oldArr.slice();
  67551. newArr = newArr.slice();
  67552. // Allow subclasses to massage the input prior to running
  67553. var newLen = newArr.length;
  67554. var oldLen = oldArr.length;
  67555. var editLength = 1;
  67556. var maxEditLength = newLen + oldLen;
  67557. var bestPath = [{ newPos: -1, components: [] }];
  67558. // Seed editLength = 0, i.e. the content starts with the same values
  67559. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  67560. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  67561. var indices = [];
  67562. for (var i = 0; i < newArr.length; i++) {
  67563. indices.push(i);
  67564. }
  67565. // Identity per the equality and tokenizer
  67566. return [{
  67567. indices: indices, count: newArr.length
  67568. }];
  67569. }
  67570. // Main worker method. checks all permutations of a given edit length for acceptance.
  67571. function execEditLength() {
  67572. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  67573. var basePath;
  67574. var addPath = bestPath[diagonalPath - 1];
  67575. var removePath = bestPath[diagonalPath + 1];
  67576. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  67577. if (addPath) {
  67578. // No one else is going to attempt to use this value, clear it
  67579. bestPath[diagonalPath - 1] = undefined;
  67580. }
  67581. var canAdd = addPath && addPath.newPos + 1 < newLen;
  67582. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  67583. if (!canAdd && !canRemove) {
  67584. // If this path is a terminal then prune
  67585. bestPath[diagonalPath] = undefined;
  67586. continue;
  67587. }
  67588. // Select the diagonal that we want to branch from. We select the prior
  67589. // path whose position in the new string is the farthest from the origin
  67590. // and does not pass the bounds of the diff graph
  67591. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  67592. basePath = clonePath(removePath);
  67593. self.pushComponent(basePath.components, undefined, true);
  67594. }
  67595. else {
  67596. basePath = addPath; // No need to clone, we've pulled it from the list
  67597. basePath.newPos++;
  67598. self.pushComponent(basePath.components, true, undefined);
  67599. }
  67600. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  67601. // If we have hit the end of both strings, then we are done
  67602. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  67603. return buildValues(self, basePath.components, newArr, oldArr);
  67604. }
  67605. else {
  67606. // Otherwise track this path as a potential candidate and continue.
  67607. bestPath[diagonalPath] = basePath;
  67608. }
  67609. }
  67610. editLength++;
  67611. }
  67612. while (editLength <= maxEditLength) {
  67613. var ret = execEditLength();
  67614. if (ret) {
  67615. return ret;
  67616. }
  67617. }
  67618. },
  67619. pushComponent: function (components, added, removed) {
  67620. var last = components[components.length - 1];
  67621. if (last && last.added === added && last.removed === removed) {
  67622. // We need to clone here as the component clone operation is just
  67623. // as shallow array clone
  67624. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  67625. }
  67626. else {
  67627. components.push({count: 1, added: added, removed: removed });
  67628. }
  67629. },
  67630. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  67631. var newLen = newArr.length;
  67632. var oldLen = oldArr.length;
  67633. var newPos = basePath.newPos;
  67634. var oldPos = newPos - diagonalPath;
  67635. var commonCount = 0;
  67636. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  67637. newPos++;
  67638. oldPos++;
  67639. commonCount++;
  67640. }
  67641. if (commonCount) {
  67642. basePath.components.push({count: commonCount});
  67643. }
  67644. basePath.newPos = newPos;
  67645. return oldPos;
  67646. },
  67647. tokenize: function (value) {
  67648. return value.slice();
  67649. },
  67650. join: function (value) {
  67651. return value.slice();
  67652. }
  67653. };
  67654. function buildValues(diff, components, newArr, oldArr) {
  67655. var componentPos = 0;
  67656. var componentLen = components.length;
  67657. var newPos = 0;
  67658. var oldPos = 0;
  67659. for (; componentPos < componentLen; componentPos++) {
  67660. var component = components[componentPos];
  67661. if (!component.removed) {
  67662. var indices = [];
  67663. for (var i = newPos; i < newPos + component.count; i++) {
  67664. indices.push(i);
  67665. }
  67666. component.indices = indices;
  67667. newPos += component.count;
  67668. // Common case
  67669. if (!component.added) {
  67670. oldPos += component.count;
  67671. }
  67672. }
  67673. else {
  67674. var indices = [];
  67675. for (var i = oldPos; i < oldPos + component.count; i++) {
  67676. indices.push(i);
  67677. }
  67678. component.indices = indices;
  67679. oldPos += component.count;
  67680. }
  67681. }
  67682. return components;
  67683. }
  67684. function clonePath(path) {
  67685. return { newPos: path.newPos, components: path.components.slice(0) };
  67686. }
  67687. var arrayDiff = new Diff();
  67688. var arrayDiff$1 = function (oldArr, newArr, callback) {
  67689. return arrayDiff.diff(oldArr, newArr, callback);
  67690. };
  67691. /**
  67692. * @file Manages elements that can be defined in <defs> in SVG,
  67693. * e.g., gradients, clip path, etc.
  67694. * @author Zhang Wenli
  67695. */
  67696. var MARK_UNUSED = '0';
  67697. var MARK_USED = '1';
  67698. /**
  67699. * Manages elements that can be defined in <defs> in SVG,
  67700. * e.g., gradients, clip path, etc.
  67701. *
  67702. * @class
  67703. * @param {number} zrId zrender instance id
  67704. * @param {SVGElement} svgRoot root of SVG document
  67705. * @param {string|string[]} tagNames possible tag names
  67706. * @param {string} markLabel label name to make if the element
  67707. * is used
  67708. */
  67709. function Definable(
  67710. zrId,
  67711. svgRoot,
  67712. tagNames,
  67713. markLabel,
  67714. domName
  67715. ) {
  67716. this._zrId = zrId;
  67717. this._svgRoot = svgRoot;
  67718. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  67719. this._markLabel = markLabel;
  67720. this._domName = domName || '_dom';
  67721. this.nextId = 0;
  67722. }
  67723. Definable.prototype.createElement = createElement;
  67724. /**
  67725. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  67726. *
  67727. * @param {boolean} isForceCreating if need to create when not exists
  67728. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  67729. * exist and isForceCreating is false
  67730. */
  67731. Definable.prototype.getDefs = function (isForceCreating) {
  67732. var svgRoot = this._svgRoot;
  67733. var defs = this._svgRoot.getElementsByTagName('defs');
  67734. if (defs.length === 0) {
  67735. // Not exist
  67736. if (isForceCreating) {
  67737. defs = svgRoot.insertBefore(
  67738. this.createElement('defs'), // Create new tag
  67739. svgRoot.firstChild // Insert in the front of svg
  67740. );
  67741. if (!defs.contains) {
  67742. // IE doesn't support contains method
  67743. defs.contains = function (el) {
  67744. var children = defs.children;
  67745. if (!children) {
  67746. return false;
  67747. }
  67748. for (var i = children.length - 1; i >= 0; --i) {
  67749. if (children[i] === el) {
  67750. return true;
  67751. }
  67752. }
  67753. return false;
  67754. };
  67755. }
  67756. return defs;
  67757. }
  67758. else {
  67759. return null;
  67760. }
  67761. }
  67762. else {
  67763. return defs[0];
  67764. }
  67765. };
  67766. /**
  67767. * Update DOM element if necessary.
  67768. *
  67769. * @param {Object|string} element style element. e.g., for gradient,
  67770. * it may be '#ccc' or {type: 'linear', ...}
  67771. * @param {Function|undefined} onUpdate update callback
  67772. */
  67773. Definable.prototype.update = function (element, onUpdate) {
  67774. if (!element) {
  67775. return;
  67776. }
  67777. var defs = this.getDefs(false);
  67778. if (element[this._domName] && defs.contains(element[this._domName])) {
  67779. // Update DOM
  67780. if (typeof onUpdate === 'function') {
  67781. onUpdate(element);
  67782. }
  67783. }
  67784. else {
  67785. // No previous dom, create new
  67786. var dom = this.add(element);
  67787. if (dom) {
  67788. element[this._domName] = dom;
  67789. }
  67790. }
  67791. };
  67792. /**
  67793. * Add gradient dom to defs
  67794. *
  67795. * @param {SVGElement} dom DOM to be added to <defs>
  67796. */
  67797. Definable.prototype.addDom = function (dom) {
  67798. var defs = this.getDefs(true);
  67799. defs.appendChild(dom);
  67800. };
  67801. /**
  67802. * Remove DOM of a given element.
  67803. *
  67804. * @param {SVGElement} element element to remove dom
  67805. */
  67806. Definable.prototype.removeDom = function (element) {
  67807. var defs = this.getDefs(false);
  67808. if (defs && element[this._domName]) {
  67809. defs.removeChild(element[this._domName]);
  67810. element[this._domName] = null;
  67811. }
  67812. };
  67813. /**
  67814. * Get DOMs of this element.
  67815. *
  67816. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  67817. */
  67818. Definable.prototype.getDoms = function () {
  67819. var defs = this.getDefs(false);
  67820. if (!defs) {
  67821. // No dom when defs is not defined
  67822. return [];
  67823. }
  67824. var doms = [];
  67825. each$1(this._tagNames, function (tagName) {
  67826. var tags = defs.getElementsByTagName(tagName);
  67827. // Note that tags is HTMLCollection, which is array-like
  67828. // rather than real array.
  67829. // So `doms.concat(tags)` add tags as one object.
  67830. doms = doms.concat([].slice.call(tags));
  67831. });
  67832. return doms;
  67833. };
  67834. /**
  67835. * Mark DOMs to be unused before painting, and clear unused ones at the end
  67836. * of the painting.
  67837. */
  67838. Definable.prototype.markAllUnused = function () {
  67839. var doms = this.getDoms();
  67840. var that = this;
  67841. each$1(doms, function (dom) {
  67842. dom[that._markLabel] = MARK_UNUSED;
  67843. });
  67844. };
  67845. /**
  67846. * Mark a single DOM to be used.
  67847. *
  67848. * @param {SVGElement} dom DOM to mark
  67849. */
  67850. Definable.prototype.markUsed = function (dom) {
  67851. if (dom) {
  67852. dom[this._markLabel] = MARK_USED;
  67853. }
  67854. };
  67855. /**
  67856. * Remove unused DOMs defined in <defs>
  67857. */
  67858. Definable.prototype.removeUnused = function () {
  67859. var defs = this.getDefs(false);
  67860. if (!defs) {
  67861. // Nothing to remove
  67862. return;
  67863. }
  67864. var doms = this.getDoms();
  67865. var that = this;
  67866. each$1(doms, function (dom) {
  67867. if (dom[that._markLabel] !== MARK_USED) {
  67868. // Remove gradient
  67869. defs.removeChild(dom);
  67870. }
  67871. });
  67872. };
  67873. /**
  67874. * Get SVG proxy.
  67875. *
  67876. * @param {Displayable} displayable displayable element
  67877. * @return {Path|Image|Text} svg proxy of given element
  67878. */
  67879. Definable.prototype.getSvgProxy = function (displayable) {
  67880. if (displayable instanceof Path) {
  67881. return svgPath;
  67882. }
  67883. else if (displayable instanceof ZImage) {
  67884. return svgImage;
  67885. }
  67886. else if (displayable instanceof Text) {
  67887. return svgText;
  67888. }
  67889. else {
  67890. return svgPath;
  67891. }
  67892. };
  67893. /**
  67894. * Get text SVG element.
  67895. *
  67896. * @param {Displayable} displayable displayable element
  67897. * @return {SVGElement} SVG element of text
  67898. */
  67899. Definable.prototype.getTextSvgElement = function (displayable) {
  67900. return displayable.__textSvgEl;
  67901. };
  67902. /**
  67903. * Get SVG element.
  67904. *
  67905. * @param {Displayable} displayable displayable element
  67906. * @return {SVGElement} SVG element
  67907. */
  67908. Definable.prototype.getSvgElement = function (displayable) {
  67909. return displayable.__svgEl;
  67910. };
  67911. /**
  67912. * @file Manages SVG gradient elements.
  67913. * @author Zhang Wenli
  67914. */
  67915. /**
  67916. * Manages SVG gradient elements.
  67917. *
  67918. * @class
  67919. * @extends Definable
  67920. * @param {number} zrId zrender instance id
  67921. * @param {SVGElement} svgRoot root of SVG document
  67922. */
  67923. function GradientManager(zrId, svgRoot) {
  67924. Definable.call(
  67925. this,
  67926. zrId,
  67927. svgRoot,
  67928. ['linearGradient', 'radialGradient'],
  67929. '__gradient_in_use__'
  67930. );
  67931. }
  67932. inherits(GradientManager, Definable);
  67933. /**
  67934. * Create new gradient DOM for fill or stroke if not exist,
  67935. * but will not update gradient if exists.
  67936. *
  67937. * @param {SvgElement} svgElement SVG element to paint
  67938. * @param {Displayable} displayable zrender displayable element
  67939. */
  67940. GradientManager.prototype.addWithoutUpdate = function (
  67941. svgElement,
  67942. displayable
  67943. ) {
  67944. if (displayable && displayable.style) {
  67945. var that = this;
  67946. each$1(['fill', 'stroke'], function (fillOrStroke) {
  67947. if (displayable.style[fillOrStroke]
  67948. && (displayable.style[fillOrStroke].type === 'linear'
  67949. || displayable.style[fillOrStroke].type === 'radial')
  67950. ) {
  67951. var gradient = displayable.style[fillOrStroke];
  67952. var defs = that.getDefs(true);
  67953. // Create dom in <defs> if not exists
  67954. var dom;
  67955. if (gradient._dom) {
  67956. // Gradient exists
  67957. dom = gradient._dom;
  67958. if (!defs.contains(gradient._dom)) {
  67959. // _dom is no longer in defs, recreate
  67960. that.addDom(dom);
  67961. }
  67962. }
  67963. else {
  67964. // New dom
  67965. dom = that.add(gradient);
  67966. }
  67967. that.markUsed(displayable);
  67968. var id = dom.getAttribute('id');
  67969. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  67970. }
  67971. });
  67972. }
  67973. };
  67974. /**
  67975. * Add a new gradient tag in <defs>
  67976. *
  67977. * @param {Gradient} gradient zr gradient instance
  67978. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  67979. * created DOM
  67980. */
  67981. GradientManager.prototype.add = function (gradient) {
  67982. var dom;
  67983. if (gradient.type === 'linear') {
  67984. dom = this.createElement('linearGradient');
  67985. }
  67986. else if (gradient.type === 'radial') {
  67987. dom = this.createElement('radialGradient');
  67988. }
  67989. else {
  67990. zrLog('Illegal gradient type.');
  67991. return null;
  67992. }
  67993. // Set dom id with gradient id, since each gradient instance
  67994. // will have no more than one dom element.
  67995. // id may exists before for those dirty elements, in which case
  67996. // id should remain the same, and other attributes should be
  67997. // updated.
  67998. gradient.id = gradient.id || this.nextId++;
  67999. dom.setAttribute('id', 'zr' + this._zrId
  68000. + '-gradient-' + gradient.id);
  68001. this.updateDom(gradient, dom);
  68002. this.addDom(dom);
  68003. return dom;
  68004. };
  68005. /**
  68006. * Update gradient.
  68007. *
  68008. * @param {Gradient} gradient zr gradient instance
  68009. */
  68010. GradientManager.prototype.update = function (gradient) {
  68011. var that = this;
  68012. Definable.prototype.update.call(this, gradient, function () {
  68013. var type = gradient.type;
  68014. var tagName = gradient._dom.tagName;
  68015. if (type === 'linear' && tagName === 'linearGradient'
  68016. || type === 'radial' && tagName === 'radialGradient'
  68017. ) {
  68018. // Gradient type is not changed, update gradient
  68019. that.updateDom(gradient, gradient._dom);
  68020. }
  68021. else {
  68022. // Remove and re-create if type is changed
  68023. that.removeDom(gradient);
  68024. that.add(gradient);
  68025. }
  68026. });
  68027. };
  68028. /**
  68029. * Update gradient dom
  68030. *
  68031. * @param {Gradient} gradient zr gradient instance
  68032. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  68033. * DOM to update
  68034. */
  68035. GradientManager.prototype.updateDom = function (gradient, dom) {
  68036. if (gradient.type === 'linear') {
  68037. dom.setAttribute('x1', gradient.x);
  68038. dom.setAttribute('y1', gradient.y);
  68039. dom.setAttribute('x2', gradient.x2);
  68040. dom.setAttribute('y2', gradient.y2);
  68041. }
  68042. else if (gradient.type === 'radial') {
  68043. dom.setAttribute('cx', gradient.x);
  68044. dom.setAttribute('cy', gradient.y);
  68045. dom.setAttribute('r', gradient.r);
  68046. }
  68047. else {
  68048. zrLog('Illegal gradient type.');
  68049. return;
  68050. }
  68051. if (gradient.global) {
  68052. // x1, x2, y1, y2 in range of 0 to canvas width or height
  68053. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  68054. }
  68055. else {
  68056. // x1, x2, y1, y2 in range of 0 to 1
  68057. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  68058. }
  68059. // Remove color stops if exists
  68060. dom.innerHTML = '';
  68061. // Add color stops
  68062. var colors = gradient.colorStops;
  68063. for (var i = 0, len = colors.length; i < len; ++i) {
  68064. var stop = this.createElement('stop');
  68065. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  68066. stop.setAttribute('stop-color', colors[i].color);
  68067. dom.appendChild(stop);
  68068. }
  68069. // Store dom element in gradient, to avoid creating multiple
  68070. // dom instances for the same gradient element
  68071. gradient._dom = dom;
  68072. };
  68073. /**
  68074. * Mark a single gradient to be used
  68075. *
  68076. * @param {Displayable} displayable displayable element
  68077. */
  68078. GradientManager.prototype.markUsed = function (displayable) {
  68079. if (displayable.style) {
  68080. var gradient = displayable.style.fill;
  68081. if (gradient && gradient._dom) {
  68082. Definable.prototype.markUsed.call(this, gradient._dom);
  68083. }
  68084. gradient = displayable.style.stroke;
  68085. if (gradient && gradient._dom) {
  68086. Definable.prototype.markUsed.call(this, gradient._dom);
  68087. }
  68088. }
  68089. };
  68090. /**
  68091. * @file Manages SVG clipPath elements.
  68092. * @author Zhang Wenli
  68093. */
  68094. /**
  68095. * Manages SVG clipPath elements.
  68096. *
  68097. * @class
  68098. * @extends Definable
  68099. * @param {number} zrId zrender instance id
  68100. * @param {SVGElement} svgRoot root of SVG document
  68101. */
  68102. function ClippathManager(zrId, svgRoot) {
  68103. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  68104. }
  68105. inherits(ClippathManager, Definable);
  68106. /**
  68107. * Update clipPath.
  68108. *
  68109. * @param {Displayable} displayable displayable element
  68110. */
  68111. ClippathManager.prototype.update = function (displayable) {
  68112. var svgEl = this.getSvgElement(displayable);
  68113. if (svgEl) {
  68114. this.updateDom(svgEl, displayable.__clipPaths, false);
  68115. }
  68116. var textEl = this.getTextSvgElement(displayable);
  68117. if (textEl) {
  68118. // Make another clipPath for text, since it's transform
  68119. // matrix is not the same with svgElement
  68120. this.updateDom(textEl, displayable.__clipPaths, true);
  68121. }
  68122. this.markUsed(displayable);
  68123. };
  68124. /**
  68125. * Create an SVGElement of displayable and create a <clipPath> of its
  68126. * clipPath
  68127. *
  68128. * @param {Displayable} parentEl parent element
  68129. * @param {ClipPath[]} clipPaths clipPaths of parent element
  68130. * @param {boolean} isText if parent element is Text
  68131. */
  68132. ClippathManager.prototype.updateDom = function (
  68133. parentEl,
  68134. clipPaths,
  68135. isText
  68136. ) {
  68137. if (clipPaths && clipPaths.length > 0) {
  68138. // Has clipPath, create <clipPath> with the first clipPath
  68139. var defs = this.getDefs(true);
  68140. var clipPath = clipPaths[0];
  68141. var clipPathEl;
  68142. var id;
  68143. var dom = isText ? '_textDom' : '_dom';
  68144. if (clipPath[dom]) {
  68145. // Use a dom that is already in <defs>
  68146. id = clipPath[dom].getAttribute('id');
  68147. clipPathEl = clipPath[dom];
  68148. // Use a dom that is already in <defs>
  68149. if (!defs.contains(clipPathEl)) {
  68150. // This happens when set old clipPath that has
  68151. // been previously removed
  68152. defs.appendChild(clipPathEl);
  68153. }
  68154. }
  68155. else {
  68156. // New <clipPath>
  68157. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  68158. ++this.nextId;
  68159. clipPathEl = this.createElement('clipPath');
  68160. clipPathEl.setAttribute('id', id);
  68161. defs.appendChild(clipPathEl);
  68162. clipPath[dom] = clipPathEl;
  68163. }
  68164. // Build path and add to <clipPath>
  68165. var svgProxy = this.getSvgProxy(clipPath);
  68166. if (clipPath.transform
  68167. && clipPath.parent.invTransform
  68168. && !isText
  68169. ) {
  68170. /**
  68171. * If a clipPath has a parent with transform, the transform
  68172. * of parent should not be considered when setting transform
  68173. * of clipPath. So we need to transform back from parent's
  68174. * transform, which is done by multiplying parent's inverse
  68175. * transform.
  68176. */
  68177. // Store old transform
  68178. var transform = Array.prototype.slice.call(
  68179. clipPath.transform
  68180. );
  68181. // Transform back from parent, and brush path
  68182. mul$1(
  68183. clipPath.transform,
  68184. clipPath.parent.invTransform,
  68185. clipPath.transform
  68186. );
  68187. svgProxy.brush(clipPath);
  68188. // Set back transform of clipPath
  68189. clipPath.transform = transform;
  68190. }
  68191. else {
  68192. svgProxy.brush(clipPath);
  68193. }
  68194. var pathEl = this.getSvgElement(clipPath);
  68195. clipPathEl.innerHTML = '';
  68196. /**
  68197. * Use `cloneNode()` here to appendChild to multiple parents,
  68198. * which may happend when Text and other shapes are using the same
  68199. * clipPath. Since Text will create an extra clipPath DOM due to
  68200. * different transform rules.
  68201. */
  68202. clipPathEl.appendChild(pathEl.cloneNode());
  68203. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  68204. if (clipPaths.length > 1) {
  68205. // Make the other clipPaths recursively
  68206. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  68207. }
  68208. }
  68209. else {
  68210. // No clipPath
  68211. if (parentEl) {
  68212. parentEl.setAttribute('clip-path', 'none');
  68213. }
  68214. }
  68215. };
  68216. /**
  68217. * Mark a single clipPath to be used
  68218. *
  68219. * @param {Displayable} displayable displayable element
  68220. */
  68221. ClippathManager.prototype.markUsed = function (displayable) {
  68222. var that = this;
  68223. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  68224. each$1(displayable.__clipPaths, function (clipPath) {
  68225. if (clipPath._dom) {
  68226. Definable.prototype.markUsed.call(that, clipPath._dom);
  68227. }
  68228. if (clipPath._textDom) {
  68229. Definable.prototype.markUsed.call(that, clipPath._textDom);
  68230. }
  68231. });
  68232. }
  68233. };
  68234. /**
  68235. * @file Manages SVG shadow elements.
  68236. * @author Zhang Wenli
  68237. */
  68238. /**
  68239. * Manages SVG shadow elements.
  68240. *
  68241. * @class
  68242. * @extends Definable
  68243. * @param {number} zrId zrender instance id
  68244. * @param {SVGElement} svgRoot root of SVG document
  68245. */
  68246. function ShadowManager(zrId, svgRoot) {
  68247. Definable.call(
  68248. this,
  68249. zrId,
  68250. svgRoot,
  68251. ['filter'],
  68252. '__filter_in_use__',
  68253. '_shadowDom'
  68254. );
  68255. }
  68256. inherits(ShadowManager, Definable);
  68257. /**
  68258. * Create new shadow DOM for fill or stroke if not exist,
  68259. * but will not update shadow if exists.
  68260. *
  68261. * @param {SvgElement} svgElement SVG element to paint
  68262. * @param {Displayable} displayable zrender displayable element
  68263. */
  68264. ShadowManager.prototype.addWithoutUpdate = function (
  68265. svgElement,
  68266. displayable
  68267. ) {
  68268. if (displayable && hasShadow(displayable.style)) {
  68269. var style = displayable.style;
  68270. // Create dom in <defs> if not exists
  68271. var dom;
  68272. if (style._shadowDom) {
  68273. // Gradient exists
  68274. dom = style._shadowDom;
  68275. var defs = this.getDefs(true);
  68276. if (!defs.contains(style._shadowDom)) {
  68277. // _shadowDom is no longer in defs, recreate
  68278. this.addDom(dom);
  68279. }
  68280. }
  68281. else {
  68282. // New dom
  68283. dom = this.add(displayable);
  68284. }
  68285. this.markUsed(displayable);
  68286. var id = dom.getAttribute('id');
  68287. svgElement.style.filter = 'url(#' + id + ')';
  68288. }
  68289. };
  68290. /**
  68291. * Add a new shadow tag in <defs>
  68292. *
  68293. * @param {Displayable} displayable zrender displayable element
  68294. * @return {SVGFilterElement} created DOM
  68295. */
  68296. ShadowManager.prototype.add = function (displayable) {
  68297. var dom = this.createElement('filter');
  68298. var style = displayable.style;
  68299. // Set dom id with shadow id, since each shadow instance
  68300. // will have no more than one dom element.
  68301. // id may exists before for those dirty elements, in which case
  68302. // id should remain the same, and other attributes should be
  68303. // updated.
  68304. style._shadowDomId = style._shadowDomId || this.nextId++;
  68305. dom.setAttribute('id', 'zr' + this._zrId
  68306. + '-shadow-' + style._shadowDomId);
  68307. this.updateDom(displayable, dom);
  68308. this.addDom(dom);
  68309. return dom;
  68310. };
  68311. /**
  68312. * Update shadow.
  68313. *
  68314. * @param {Displayable} displayable zrender displayable element
  68315. */
  68316. ShadowManager.prototype.update = function (svgElement, displayable) {
  68317. var style = displayable.style;
  68318. if (hasShadow(style)) {
  68319. var that = this;
  68320. Definable.prototype.update.call(this, displayable, function (style) {
  68321. that.updateDom(displayable, style._shadowDom);
  68322. });
  68323. }
  68324. else {
  68325. // Remove shadow
  68326. this.remove(svgElement, style);
  68327. }
  68328. };
  68329. /**
  68330. * Remove DOM and clear parent filter
  68331. */
  68332. ShadowManager.prototype.remove = function (svgElement, style) {
  68333. if (style._shadowDomId != null) {
  68334. this.removeDom(style);
  68335. svgElement.style.filter = '';
  68336. }
  68337. };
  68338. /**
  68339. * Update shadow dom
  68340. *
  68341. * @param {Displayable} displayable zrender displayable element
  68342. * @param {SVGFilterElement} dom DOM to update
  68343. */
  68344. ShadowManager.prototype.updateDom = function (displayable, dom) {
  68345. var domChild = dom.getElementsByTagName('feDropShadow');
  68346. if (domChild.length === 0) {
  68347. domChild = this.createElement('feDropShadow');
  68348. }
  68349. else {
  68350. domChild = domChild[0];
  68351. }
  68352. var style = displayable.style;
  68353. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  68354. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  68355. // TODO: textBoxShadowBlur is not supported yet
  68356. var offsetX, offsetY, blur, color;
  68357. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  68358. offsetX = style.shadowOffsetX || 0;
  68359. offsetY = style.shadowOffsetY || 0;
  68360. blur = style.shadowBlur;
  68361. color = style.shadowColor;
  68362. }
  68363. else if (style.textShadowBlur) {
  68364. offsetX = style.textShadowOffsetX || 0;
  68365. offsetY = style.textShadowOffsetY || 0;
  68366. blur = style.textShadowBlur;
  68367. color = style.textShadowColor;
  68368. }
  68369. else {
  68370. // Remove shadow
  68371. this.removeDom(dom, style);
  68372. return;
  68373. }
  68374. domChild.setAttribute('dx', offsetX / scaleX);
  68375. domChild.setAttribute('dy', offsetY / scaleY);
  68376. domChild.setAttribute('flood-color', color);
  68377. // Divide by two here so that it looks the same as in canvas
  68378. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  68379. var stdDx = blur / 2 / scaleX;
  68380. var stdDy = blur / 2 / scaleY;
  68381. var stdDeviation = stdDx + ' ' + stdDy;
  68382. domChild.setAttribute('stdDeviation', stdDeviation);
  68383. // Fix filter clipping problem
  68384. dom.setAttribute('x', '-100%');
  68385. dom.setAttribute('y', '-100%');
  68386. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  68387. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  68388. dom.appendChild(domChild);
  68389. // Store dom element in shadow, to avoid creating multiple
  68390. // dom instances for the same shadow element
  68391. style._shadowDom = dom;
  68392. };
  68393. /**
  68394. * Mark a single shadow to be used
  68395. *
  68396. * @param {Displayable} displayable displayable element
  68397. */
  68398. ShadowManager.prototype.markUsed = function (displayable) {
  68399. var style = displayable.style;
  68400. if (style && style._shadowDom) {
  68401. Definable.prototype.markUsed.call(this, style._shadowDom);
  68402. }
  68403. };
  68404. function hasShadow(style) {
  68405. // TODO: textBoxShadowBlur is not supported yet
  68406. return style
  68407. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  68408. || style.textShadowBlur || style.textShadowOffsetX
  68409. || style.textShadowOffsetY);
  68410. }
  68411. /**
  68412. * SVG Painter
  68413. * @module zrender/svg/Painter
  68414. */
  68415. function parseInt10$2(val) {
  68416. return parseInt(val, 10);
  68417. }
  68418. function getSvgProxy(el) {
  68419. if (el instanceof Path) {
  68420. return svgPath;
  68421. }
  68422. else if (el instanceof ZImage) {
  68423. return svgImage;
  68424. }
  68425. else if (el instanceof Text) {
  68426. return svgText;
  68427. }
  68428. else {
  68429. return svgPath;
  68430. }
  68431. }
  68432. function checkParentAvailable(parent, child) {
  68433. return child && parent && child.parentNode !== parent;
  68434. }
  68435. function insertAfter(parent, child, prevSibling) {
  68436. if (checkParentAvailable(parent, child) && prevSibling) {
  68437. var nextSibling = prevSibling.nextSibling;
  68438. nextSibling ? parent.insertBefore(child, nextSibling)
  68439. : parent.appendChild(child);
  68440. }
  68441. }
  68442. function prepend(parent, child) {
  68443. if (checkParentAvailable(parent, child)) {
  68444. var firstChild = parent.firstChild;
  68445. firstChild ? parent.insertBefore(child, firstChild)
  68446. : parent.appendChild(child);
  68447. }
  68448. }
  68449. function remove$1(parent, child) {
  68450. if (child && parent && child.parentNode === parent) {
  68451. parent.removeChild(child);
  68452. }
  68453. }
  68454. function getTextSvgElement(displayable) {
  68455. return displayable.__textSvgEl;
  68456. }
  68457. function getSvgElement(displayable) {
  68458. return displayable.__svgEl;
  68459. }
  68460. /**
  68461. * @alias module:zrender/svg/Painter
  68462. * @constructor
  68463. * @param {HTMLElement} root 绘图容器
  68464. * @param {module:zrender/Storage} storage
  68465. * @param {Object} opts
  68466. */
  68467. var SVGPainter = function (root, storage, opts, zrId) {
  68468. this.root = root;
  68469. this.storage = storage;
  68470. this._opts = opts = extend({}, opts || {});
  68471. var svgRoot = createElement('svg');
  68472. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  68473. svgRoot.setAttribute('version', '1.1');
  68474. svgRoot.setAttribute('baseProfile', 'full');
  68475. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  68476. this.gradientManager = new GradientManager(zrId, svgRoot);
  68477. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  68478. this.shadowManager = new ShadowManager(zrId, svgRoot);
  68479. var viewport = document.createElement('div');
  68480. viewport.style.cssText = 'overflow:hidden;position:relative';
  68481. this._svgRoot = svgRoot;
  68482. this._viewport = viewport;
  68483. root.appendChild(viewport);
  68484. viewport.appendChild(svgRoot);
  68485. this.resize(opts.width, opts.height);
  68486. this._visibleList = [];
  68487. };
  68488. SVGPainter.prototype = {
  68489. constructor: SVGPainter,
  68490. getType: function () {
  68491. return 'svg';
  68492. },
  68493. getViewportRoot: function () {
  68494. return this._viewport;
  68495. },
  68496. getViewportRootOffset: function () {
  68497. var viewportRoot = this.getViewportRoot();
  68498. if (viewportRoot) {
  68499. return {
  68500. offsetLeft: viewportRoot.offsetLeft || 0,
  68501. offsetTop: viewportRoot.offsetTop || 0
  68502. };
  68503. }
  68504. },
  68505. refresh: function () {
  68506. var list = this.storage.getDisplayList(true);
  68507. this._paintList(list);
  68508. },
  68509. _paintList: function (list) {
  68510. this.gradientManager.markAllUnused();
  68511. this.clipPathManager.markAllUnused();
  68512. this.shadowManager.markAllUnused();
  68513. var svgRoot = this._svgRoot;
  68514. var visibleList = this._visibleList;
  68515. var listLen = list.length;
  68516. var newVisibleList = [];
  68517. var i;
  68518. for (i = 0; i < listLen; i++) {
  68519. var displayable = list[i];
  68520. var svgProxy = getSvgProxy(displayable);
  68521. var svgElement = getSvgElement(displayable)
  68522. || getTextSvgElement(displayable);
  68523. if (!displayable.invisible) {
  68524. if (displayable.__dirty) {
  68525. svgProxy && svgProxy.brush(displayable);
  68526. // Update clipPath
  68527. this.clipPathManager.update(displayable);
  68528. // Update gradient and shadow
  68529. if (displayable.style) {
  68530. this.gradientManager
  68531. .update(displayable.style.fill);
  68532. this.gradientManager
  68533. .update(displayable.style.stroke);
  68534. this.shadowManager
  68535. .update(svgElement, displayable);
  68536. }
  68537. displayable.__dirty = false;
  68538. }
  68539. newVisibleList.push(displayable);
  68540. }
  68541. }
  68542. var diff = arrayDiff$1(visibleList, newVisibleList);
  68543. var prevSvgElement;
  68544. // First do remove, in case element moved to the head and do remove
  68545. // after add
  68546. for (i = 0; i < diff.length; i++) {
  68547. var item = diff[i];
  68548. if (item.removed) {
  68549. for (var k = 0; k < item.count; k++) {
  68550. var displayable = visibleList[item.indices[k]];
  68551. var svgElement = getSvgElement(displayable);
  68552. var textSvgElement = getTextSvgElement(displayable);
  68553. remove$1(svgRoot, svgElement);
  68554. remove$1(svgRoot, textSvgElement);
  68555. }
  68556. }
  68557. }
  68558. for (i = 0; i < diff.length; i++) {
  68559. var item = diff[i];
  68560. if (item.added) {
  68561. for (var k = 0; k < item.count; k++) {
  68562. var displayable = newVisibleList[item.indices[k]];
  68563. var svgElement = getSvgElement(displayable);
  68564. var textSvgElement = getTextSvgElement(displayable);
  68565. prevSvgElement
  68566. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  68567. : prepend(svgRoot, svgElement);
  68568. if (svgElement) {
  68569. insertAfter(svgRoot, textSvgElement, svgElement);
  68570. }
  68571. else if (prevSvgElement) {
  68572. insertAfter(
  68573. svgRoot, textSvgElement, prevSvgElement
  68574. );
  68575. }
  68576. else {
  68577. prepend(svgRoot, textSvgElement);
  68578. }
  68579. // Insert text
  68580. insertAfter(svgRoot, textSvgElement, svgElement);
  68581. prevSvgElement = textSvgElement || svgElement
  68582. || prevSvgElement;
  68583. this.gradientManager
  68584. .addWithoutUpdate(svgElement, displayable);
  68585. this.shadowManager
  68586. .addWithoutUpdate(prevSvgElement, displayable);
  68587. this.clipPathManager.markUsed(displayable);
  68588. }
  68589. }
  68590. else if (!item.removed) {
  68591. for (var k = 0; k < item.count; k++) {
  68592. var displayable = newVisibleList[item.indices[k]];
  68593. prevSvgElement
  68594. = svgElement
  68595. = getTextSvgElement(displayable)
  68596. || getSvgElement(displayable)
  68597. || prevSvgElement;
  68598. this.gradientManager.markUsed(displayable);
  68599. this.gradientManager
  68600. .addWithoutUpdate(svgElement, displayable);
  68601. this.shadowManager.markUsed(displayable);
  68602. this.shadowManager
  68603. .addWithoutUpdate(svgElement, displayable);
  68604. this.clipPathManager.markUsed(displayable);
  68605. }
  68606. }
  68607. }
  68608. this.gradientManager.removeUnused();
  68609. this.clipPathManager.removeUnused();
  68610. this.shadowManager.removeUnused();
  68611. this._visibleList = newVisibleList;
  68612. },
  68613. _getDefs: function (isForceCreating) {
  68614. var svgRoot = this._svgRoot;
  68615. var defs = this._svgRoot.getElementsByTagName('defs');
  68616. if (defs.length === 0) {
  68617. // Not exist
  68618. if (isForceCreating) {
  68619. var defs = svgRoot.insertBefore(
  68620. createElement('defs'), // Create new tag
  68621. svgRoot.firstChild // Insert in the front of svg
  68622. );
  68623. if (!defs.contains) {
  68624. // IE doesn't support contains method
  68625. defs.contains = function (el) {
  68626. var children = defs.children;
  68627. if (!children) {
  68628. return false;
  68629. }
  68630. for (var i = children.length - 1; i >= 0; --i) {
  68631. if (children[i] === el) {
  68632. return true;
  68633. }
  68634. }
  68635. return false;
  68636. };
  68637. }
  68638. return defs;
  68639. }
  68640. else {
  68641. return null;
  68642. }
  68643. }
  68644. else {
  68645. return defs[0];
  68646. }
  68647. },
  68648. resize: function (width, height) {
  68649. var viewport = this._viewport;
  68650. // FIXME Why ?
  68651. viewport.style.display = 'none';
  68652. // Save input w/h
  68653. var opts = this._opts;
  68654. width != null && (opts.width = width);
  68655. height != null && (opts.height = height);
  68656. width = this._getSize(0);
  68657. height = this._getSize(1);
  68658. viewport.style.display = '';
  68659. if (this._width !== width || this._height !== height) {
  68660. this._width = width;
  68661. this._height = height;
  68662. var viewportStyle = viewport.style;
  68663. viewportStyle.width = width + 'px';
  68664. viewportStyle.height = height + 'px';
  68665. var svgRoot = this._svgRoot;
  68666. // Set width by 'svgRoot.width = width' is invalid
  68667. svgRoot.setAttribute('width', width);
  68668. svgRoot.setAttribute('height', height);
  68669. }
  68670. },
  68671. /**
  68672. * 获取绘图区域宽度
  68673. */
  68674. getWidth: function () {
  68675. return this._width;
  68676. },
  68677. /**
  68678. * 获取绘图区域高度
  68679. */
  68680. getHeight: function () {
  68681. return this._height;
  68682. },
  68683. _getSize: function (whIdx) {
  68684. var opts = this._opts;
  68685. var wh = ['width', 'height'][whIdx];
  68686. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  68687. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  68688. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  68689. if (opts[wh] != null && opts[wh] !== 'auto') {
  68690. return parseFloat(opts[wh]);
  68691. }
  68692. var root = this.root;
  68693. // IE8 does not support getComputedStyle, but it use VML.
  68694. var stl = document.defaultView.getComputedStyle(root);
  68695. return (
  68696. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  68697. - (parseInt10$2(stl[plt]) || 0)
  68698. - (parseInt10$2(stl[prb]) || 0)
  68699. ) | 0;
  68700. },
  68701. dispose: function () {
  68702. this.root.innerHTML = '';
  68703. this._svgRoot
  68704. = this._viewport
  68705. = this.storage
  68706. = null;
  68707. },
  68708. clear: function () {
  68709. if (this._viewport) {
  68710. this.root.removeChild(this._viewport);
  68711. }
  68712. },
  68713. pathToSvg: function () {
  68714. this.refresh();
  68715. var html = this._svgRoot.outerHTML;
  68716. return 'data:img/svg+xml;utf-8,' + unescape(html);
  68717. }
  68718. };
  68719. // Not supported methods
  68720. function createMethodNotSupport$1(method) {
  68721. return function () {
  68722. zrLog('In SVG mode painter not support method "' + method + '"');
  68723. };
  68724. }
  68725. // Unsuppoted methods
  68726. each$1([
  68727. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  68728. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  68729. 'toDataURL', 'pathToImage'
  68730. ], function (name) {
  68731. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  68732. });
  68733. registerPainter('svg', SVGPainter);
  68734. // Import all charts and components
  68735. exports.version = version;
  68736. exports.dependencies = dependencies;
  68737. exports.PRIORITY = PRIORITY;
  68738. exports.init = init;
  68739. exports.connect = connect;
  68740. exports.disConnect = disConnect;
  68741. exports.disconnect = disconnect;
  68742. exports.dispose = dispose;
  68743. exports.getInstanceByDom = getInstanceByDom;
  68744. exports.getInstanceById = getInstanceById;
  68745. exports.registerTheme = registerTheme;
  68746. exports.registerPreprocessor = registerPreprocessor;
  68747. exports.registerProcessor = registerProcessor;
  68748. exports.registerPostUpdate = registerPostUpdate;
  68749. exports.registerAction = registerAction;
  68750. exports.registerCoordinateSystem = registerCoordinateSystem;
  68751. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  68752. exports.registerLayout = registerLayout;
  68753. exports.registerVisual = registerVisual;
  68754. exports.registerLoading = registerLoading;
  68755. exports.extendComponentModel = extendComponentModel;
  68756. exports.extendComponentView = extendComponentView;
  68757. exports.extendSeriesModel = extendSeriesModel;
  68758. exports.extendChartView = extendChartView;
  68759. exports.setCanvasCreator = setCanvasCreator;
  68760. exports.registerMap = registerMap;
  68761. exports.getMap = getMap;
  68762. exports.dataTool = dataTool;
  68763. exports.zrender = zrender;
  68764. exports.graphic = graphic;
  68765. exports.number = number;
  68766. exports.format = format;
  68767. exports.throttle = throttle;
  68768. exports.helper = helper;
  68769. exports.matrix = matrix;
  68770. exports.vector = vector;
  68771. exports.color = color;
  68772. exports.parseGeoJSON = parseGeoJson$1;
  68773. exports.parseGeoJson = parseGeoJson;
  68774. exports.util = ecUtil;
  68775. exports.List = List;
  68776. exports.Model = Model;
  68777. exports.Axis = Axis;
  68778. exports.env = env$1;
  68779. })));
  68780. //# sourceMappingURL=echarts-en.js.map