echarts.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531
  1. /*!
  2. * Copyright (c) https://github.com/apache/incubator-echarts
  3. * github: https://github.com/apache/incubator-echarts
  4. * license: Apachelicence 2.0
  5. * version: 4.0.4
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  9. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  10. (factory((global.echarts = {})));
  11. }(this, (function (exports) { 'use strict';
  12. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  13. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  14. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  15. // declaration is behind of the using position (for example in `Model.extent`,
  16. // And tools like rollup can not analysis the dependency if not import).
  17. var dev;
  18. // In browser
  19. if (typeof window !== 'undefined') {
  20. dev = window.__DEV__;
  21. }
  22. // In node
  23. else if (typeof global !== 'undefined') {
  24. dev = global.__DEV__;
  25. }
  26. if (typeof dev === 'undefined') {
  27. dev = true;
  28. }
  29. var __DEV__ = dev;
  30. /**
  31. * zrender: 生成唯一id
  32. *
  33. * @author errorrik (errorrik@gmail.com)
  34. */
  35. var idStart = 0x0907;
  36. var guid = function () {
  37. return idStart++;
  38. };
  39. /**
  40. * echarts设备环境识别
  41. *
  42. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  43. * @author firede[firede@firede.us]
  44. * @desc thanks zepto.
  45. */
  46. var env = {};
  47. if (typeof wx !== 'undefined') {
  48. // In Weixin Application
  49. env = {
  50. browser: {},
  51. os: {},
  52. node: false,
  53. wxa: true, // Weixin Application
  54. canvasSupported: true,
  55. svgSupported: false,
  56. touchEventsSupported: true
  57. };
  58. }
  59. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  60. // In worker
  61. env = {
  62. browser: {},
  63. os: {},
  64. node: false,
  65. worker: true,
  66. canvasSupported: true
  67. };
  68. }
  69. else if (typeof navigator === 'undefined') {
  70. // In node
  71. env = {
  72. browser: {},
  73. os: {},
  74. node: true,
  75. worker: false,
  76. // Assume canvas is supported
  77. canvasSupported: true,
  78. svgSupported: true
  79. };
  80. }
  81. else {
  82. env = detect(navigator.userAgent);
  83. }
  84. var env$1 = env;
  85. // Zepto.js
  86. // (c) 2010-2013 Thomas Fuchs
  87. // Zepto.js may be freely distributed under the MIT license.
  88. function detect(ua) {
  89. var os = {};
  90. var browser = {};
  91. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  92. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  93. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  94. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  95. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  96. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  97. // var touchpad = webos && ua.match(/TouchPad/);
  98. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  99. // var silk = ua.match(/Silk\/([\d._]+)/);
  100. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  101. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  102. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  103. // var playbook = ua.match(/PlayBook/);
  104. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  105. var firefox = ua.match(/Firefox\/([\d.]+)/);
  106. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  107. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  108. var ie = ua.match(/MSIE\s([\d.]+)/)
  109. // IE 11 Trident/7.0; rv:11.0
  110. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  111. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  112. var weChat = (/micromessenger/i).test(ua);
  113. // Todo: clean this up with a better OS/browser seperation:
  114. // - discern (more) between multiple browsers on android
  115. // - decide if kindle fire in silk mode is android or not
  116. // - Firefox on Android doesn't specify the Android version
  117. // - possibly devide in os, device and browser hashes
  118. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  119. // if (android) os.android = true, os.version = android[2];
  120. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  121. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  122. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  123. // if (webos) os.webos = true, os.version = webos[2];
  124. // if (touchpad) os.touchpad = true;
  125. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  126. // if (bb10) os.bb10 = true, os.version = bb10[2];
  127. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  128. // if (playbook) browser.playbook = true;
  129. // if (kindle) os.kindle = true, os.version = kindle[1];
  130. // if (silk) browser.silk = true, browser.version = silk[1];
  131. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  132. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  133. if (firefox) {
  134. browser.firefox = true;
  135. browser.version = firefox[1];
  136. }
  137. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  138. // if (webview) browser.webview = true;
  139. if (ie) {
  140. browser.ie = true;
  141. browser.version = ie[1];
  142. }
  143. if (edge) {
  144. browser.edge = true;
  145. browser.version = edge[1];
  146. }
  147. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  148. // not be set on win phone. So we do not consider Win Phone.
  149. if (weChat) {
  150. browser.weChat = true;
  151. }
  152. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  153. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  154. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  155. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  156. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  157. return {
  158. browser: browser,
  159. os: os,
  160. node: false,
  161. // 原生canvas支持,改极端点了
  162. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  163. canvasSupported: !!document.createElement('canvas').getContext,
  164. svgSupported: typeof SVGRect !== 'undefined',
  165. // works on most browsers
  166. // IE10/11 does not support touch event, and MS Edge supports them but not by
  167. // default, so we dont check navigator.maxTouchPoints for them here.
  168. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  169. // <http://caniuse.com/#search=pointer%20event>.
  170. pointerEventsSupported: 'onpointerdown' in window
  171. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  172. // events currently. So we dont use that on other browsers unless tested sufficiently.
  173. // Although IE 10 supports pointer event, it use old style and is different from the
  174. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  175. && (browser.edge || (browser.ie && browser.version >= 11))
  176. // passiveSupported: detectPassiveSupport()
  177. };
  178. }
  179. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  180. // function detectPassiveSupport() {
  181. // // Test via a getter in the options object to see if the passive property is accessed
  182. // var supportsPassive = false;
  183. // try {
  184. // var opts = Object.defineProperty({}, 'passive', {
  185. // get: function() {
  186. // supportsPassive = true;
  187. // }
  188. // });
  189. // window.addEventListener('testPassive', function() {}, opts);
  190. // } catch (e) {
  191. // }
  192. // return supportsPassive;
  193. // }
  194. /**
  195. * @module zrender/core/util
  196. */
  197. // 用于处理merge时无法遍历Date等对象的问题
  198. var BUILTIN_OBJECT = {
  199. '[object Function]': 1,
  200. '[object RegExp]': 1,
  201. '[object Date]': 1,
  202. '[object Error]': 1,
  203. '[object CanvasGradient]': 1,
  204. '[object CanvasPattern]': 1,
  205. // For node-canvas
  206. '[object Image]': 1,
  207. '[object Canvas]': 1
  208. };
  209. var TYPED_ARRAY = {
  210. '[object Int8Array]': 1,
  211. '[object Uint8Array]': 1,
  212. '[object Uint8ClampedArray]': 1,
  213. '[object Int16Array]': 1,
  214. '[object Uint16Array]': 1,
  215. '[object Int32Array]': 1,
  216. '[object Uint32Array]': 1,
  217. '[object Float32Array]': 1,
  218. '[object Float64Array]': 1
  219. };
  220. var objToString = Object.prototype.toString;
  221. var arrayProto = Array.prototype;
  222. var nativeForEach = arrayProto.forEach;
  223. var nativeFilter = arrayProto.filter;
  224. var nativeSlice = arrayProto.slice;
  225. var nativeMap = arrayProto.map;
  226. var nativeReduce = arrayProto.reduce;
  227. // Avoid assign to an exported variable, for transforming to cjs.
  228. var methods = {};
  229. function $override(name, fn) {
  230. // Clear ctx instance for different environment
  231. if (name === 'createCanvas') {
  232. _ctx = null;
  233. }
  234. methods[name] = fn;
  235. }
  236. /**
  237. * Those data types can be cloned:
  238. * Plain object, Array, TypedArray, number, string, null, undefined.
  239. * Those data types will be assgined using the orginal data:
  240. * BUILTIN_OBJECT
  241. * Instance of user defined class will be cloned to a plain object, without
  242. * properties in prototype.
  243. * Other data types is not supported (not sure what will happen).
  244. *
  245. * Caution: do not support clone Date, for performance consideration.
  246. * (There might be a large number of date in `series.data`).
  247. * So date should not be modified in and out of echarts.
  248. *
  249. * @param {*} source
  250. * @return {*} new
  251. */
  252. function clone(source) {
  253. if (source == null || typeof source != 'object') {
  254. return source;
  255. }
  256. var result = source;
  257. var typeStr = objToString.call(source);
  258. if (typeStr === '[object Array]') {
  259. if (!isPrimitive(source)) {
  260. result = [];
  261. for (var i = 0, len = source.length; i < len; i++) {
  262. result[i] = clone(source[i]);
  263. }
  264. }
  265. }
  266. else if (TYPED_ARRAY[typeStr]) {
  267. if (!isPrimitive(source)) {
  268. var Ctor = source.constructor;
  269. if (source.constructor.from) {
  270. result = Ctor.from(source);
  271. }
  272. else {
  273. result = new Ctor(source.length);
  274. for (var i = 0, len = source.length; i < len; i++) {
  275. result[i] = clone(source[i]);
  276. }
  277. }
  278. }
  279. }
  280. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  281. result = {};
  282. for (var key in source) {
  283. if (source.hasOwnProperty(key)) {
  284. result[key] = clone(source[key]);
  285. }
  286. }
  287. }
  288. return result;
  289. }
  290. /**
  291. * @memberOf module:zrender/core/util
  292. * @param {*} target
  293. * @param {*} source
  294. * @param {boolean} [overwrite=false]
  295. */
  296. function merge(target, source, overwrite) {
  297. // We should escapse that source is string
  298. // and enter for ... in ...
  299. if (!isObject$1(source) || !isObject$1(target)) {
  300. return overwrite ? clone(source) : target;
  301. }
  302. for (var key in source) {
  303. if (source.hasOwnProperty(key)) {
  304. var targetProp = target[key];
  305. var sourceProp = source[key];
  306. if (isObject$1(sourceProp)
  307. && isObject$1(targetProp)
  308. && !isArray(sourceProp)
  309. && !isArray(targetProp)
  310. && !isDom(sourceProp)
  311. && !isDom(targetProp)
  312. && !isBuiltInObject(sourceProp)
  313. && !isBuiltInObject(targetProp)
  314. && !isPrimitive(sourceProp)
  315. && !isPrimitive(targetProp)
  316. ) {
  317. // 如果需要递归覆盖,就递归调用merge
  318. merge(targetProp, sourceProp, overwrite);
  319. }
  320. else if (overwrite || !(key in target)) {
  321. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  322. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  323. target[key] = clone(source[key], true);
  324. }
  325. }
  326. }
  327. return target;
  328. }
  329. /**
  330. * @param {Array} targetAndSources The first item is target, and the rests are source.
  331. * @param {boolean} [overwrite=false]
  332. * @return {*} target
  333. */
  334. function mergeAll(targetAndSources, overwrite) {
  335. var result = targetAndSources[0];
  336. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  337. result = merge(result, targetAndSources[i], overwrite);
  338. }
  339. return result;
  340. }
  341. /**
  342. * @param {*} target
  343. * @param {*} source
  344. * @memberOf module:zrender/core/util
  345. */
  346. function extend(target, source) {
  347. for (var key in source) {
  348. if (source.hasOwnProperty(key)) {
  349. target[key] = source[key];
  350. }
  351. }
  352. return target;
  353. }
  354. /**
  355. * @param {*} target
  356. * @param {*} source
  357. * @param {boolean} [overlay=false]
  358. * @memberOf module:zrender/core/util
  359. */
  360. function defaults(target, source, overlay) {
  361. for (var key in source) {
  362. if (source.hasOwnProperty(key)
  363. && (overlay ? source[key] != null : target[key] == null)
  364. ) {
  365. target[key] = source[key];
  366. }
  367. }
  368. return target;
  369. }
  370. var createCanvas = function () {
  371. return methods.createCanvas();
  372. };
  373. methods.createCanvas = function () {
  374. return document.createElement('canvas');
  375. };
  376. // FIXME
  377. var _ctx;
  378. function getContext() {
  379. if (!_ctx) {
  380. // Use util.createCanvas instead of createCanvas
  381. // because createCanvas may be overwritten in different environment
  382. _ctx = createCanvas().getContext('2d');
  383. }
  384. return _ctx;
  385. }
  386. /**
  387. * 查询数组中元素的index
  388. * @memberOf module:zrender/core/util
  389. */
  390. function indexOf(array, value) {
  391. if (array) {
  392. if (array.indexOf) {
  393. return array.indexOf(value);
  394. }
  395. for (var i = 0, len = array.length; i < len; i++) {
  396. if (array[i] === value) {
  397. return i;
  398. }
  399. }
  400. }
  401. return -1;
  402. }
  403. /**
  404. * 构造类继承关系
  405. *
  406. * @memberOf module:zrender/core/util
  407. * @param {Function} clazz 源类
  408. * @param {Function} baseClazz 基类
  409. */
  410. function inherits(clazz, baseClazz) {
  411. var clazzPrototype = clazz.prototype;
  412. function F() {}
  413. F.prototype = baseClazz.prototype;
  414. clazz.prototype = new F();
  415. for (var prop in clazzPrototype) {
  416. clazz.prototype[prop] = clazzPrototype[prop];
  417. }
  418. clazz.prototype.constructor = clazz;
  419. clazz.superClass = baseClazz;
  420. }
  421. /**
  422. * @memberOf module:zrender/core/util
  423. * @param {Object|Function} target
  424. * @param {Object|Function} sorce
  425. * @param {boolean} overlay
  426. */
  427. function mixin(target, source, overlay) {
  428. target = 'prototype' in target ? target.prototype : target;
  429. source = 'prototype' in source ? source.prototype : source;
  430. defaults(target, source, overlay);
  431. }
  432. /**
  433. * Consider typed array.
  434. * @param {Array|TypedArray} data
  435. */
  436. function isArrayLike(data) {
  437. if (! data) {
  438. return;
  439. }
  440. if (typeof data == 'string') {
  441. return false;
  442. }
  443. return typeof data.length == 'number';
  444. }
  445. /**
  446. * 数组或对象遍历
  447. * @memberOf module:zrender/core/util
  448. * @param {Object|Array} obj
  449. * @param {Function} cb
  450. * @param {*} [context]
  451. */
  452. function each$1(obj, cb, context) {
  453. if (!(obj && cb)) {
  454. return;
  455. }
  456. if (obj.forEach && obj.forEach === nativeForEach) {
  457. obj.forEach(cb, context);
  458. }
  459. else if (obj.length === +obj.length) {
  460. for (var i = 0, len = obj.length; i < len; i++) {
  461. cb.call(context, obj[i], i, obj);
  462. }
  463. }
  464. else {
  465. for (var key in obj) {
  466. if (obj.hasOwnProperty(key)) {
  467. cb.call(context, obj[key], key, obj);
  468. }
  469. }
  470. }
  471. }
  472. /**
  473. * 数组映射
  474. * @memberOf module:zrender/core/util
  475. * @param {Array} obj
  476. * @param {Function} cb
  477. * @param {*} [context]
  478. * @return {Array}
  479. */
  480. function map(obj, cb, context) {
  481. if (!(obj && cb)) {
  482. return;
  483. }
  484. if (obj.map && obj.map === nativeMap) {
  485. return obj.map(cb, context);
  486. }
  487. else {
  488. var result = [];
  489. for (var i = 0, len = obj.length; i < len; i++) {
  490. result.push(cb.call(context, obj[i], i, obj));
  491. }
  492. return result;
  493. }
  494. }
  495. /**
  496. * @memberOf module:zrender/core/util
  497. * @param {Array} obj
  498. * @param {Function} cb
  499. * @param {Object} [memo]
  500. * @param {*} [context]
  501. * @return {Array}
  502. */
  503. function reduce(obj, cb, memo, context) {
  504. if (!(obj && cb)) {
  505. return;
  506. }
  507. if (obj.reduce && obj.reduce === nativeReduce) {
  508. return obj.reduce(cb, memo, context);
  509. }
  510. else {
  511. for (var i = 0, len = obj.length; i < len; i++) {
  512. memo = cb.call(context, memo, obj[i], i, obj);
  513. }
  514. return memo;
  515. }
  516. }
  517. /**
  518. * 数组过滤
  519. * @memberOf module:zrender/core/util
  520. * @param {Array} obj
  521. * @param {Function} cb
  522. * @param {*} [context]
  523. * @return {Array}
  524. */
  525. function filter(obj, cb, context) {
  526. if (!(obj && cb)) {
  527. return;
  528. }
  529. if (obj.filter && obj.filter === nativeFilter) {
  530. return obj.filter(cb, context);
  531. }
  532. else {
  533. var result = [];
  534. for (var i = 0, len = obj.length; i < len; i++) {
  535. if (cb.call(context, obj[i], i, obj)) {
  536. result.push(obj[i]);
  537. }
  538. }
  539. return result;
  540. }
  541. }
  542. /**
  543. * 数组项查找
  544. * @memberOf module:zrender/core/util
  545. * @param {Array} obj
  546. * @param {Function} cb
  547. * @param {*} [context]
  548. * @return {*}
  549. */
  550. function find(obj, cb, context) {
  551. if (!(obj && cb)) {
  552. return;
  553. }
  554. for (var i = 0, len = obj.length; i < len; i++) {
  555. if (cb.call(context, obj[i], i, obj)) {
  556. return obj[i];
  557. }
  558. }
  559. }
  560. /**
  561. * @memberOf module:zrender/core/util
  562. * @param {Function} func
  563. * @param {*} context
  564. * @return {Function}
  565. */
  566. function bind(func, context) {
  567. var args = nativeSlice.call(arguments, 2);
  568. return function () {
  569. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  570. };
  571. }
  572. /**
  573. * @memberOf module:zrender/core/util
  574. * @param {Function} func
  575. * @return {Function}
  576. */
  577. function curry(func) {
  578. var args = nativeSlice.call(arguments, 1);
  579. return function () {
  580. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  581. };
  582. }
  583. /**
  584. * @memberOf module:zrender/core/util
  585. * @param {*} value
  586. * @return {boolean}
  587. */
  588. function isArray(value) {
  589. return objToString.call(value) === '[object Array]';
  590. }
  591. /**
  592. * @memberOf module:zrender/core/util
  593. * @param {*} value
  594. * @return {boolean}
  595. */
  596. function isFunction$1(value) {
  597. return typeof value === 'function';
  598. }
  599. /**
  600. * @memberOf module:zrender/core/util
  601. * @param {*} value
  602. * @return {boolean}
  603. */
  604. function isString(value) {
  605. return objToString.call(value) === '[object String]';
  606. }
  607. /**
  608. * @memberOf module:zrender/core/util
  609. * @param {*} value
  610. * @return {boolean}
  611. */
  612. function isObject$1(value) {
  613. // Avoid a V8 JIT bug in Chrome 19-20.
  614. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  615. var type = typeof value;
  616. return type === 'function' || (!!value && type == 'object');
  617. }
  618. /**
  619. * @memberOf module:zrender/core/util
  620. * @param {*} value
  621. * @return {boolean}
  622. */
  623. function isBuiltInObject(value) {
  624. return !!BUILTIN_OBJECT[objToString.call(value)];
  625. }
  626. /**
  627. * @memberOf module:zrender/core/util
  628. * @param {*} value
  629. * @return {boolean}
  630. */
  631. function isTypedArray(value) {
  632. return !!TYPED_ARRAY[objToString.call(value)];
  633. }
  634. /**
  635. * @memberOf module:zrender/core/util
  636. * @param {*} value
  637. * @return {boolean}
  638. */
  639. function isDom(value) {
  640. return typeof value === 'object'
  641. && typeof value.nodeType === 'number'
  642. && typeof value.ownerDocument === 'object';
  643. }
  644. /**
  645. * Whether is exactly NaN. Notice isNaN('a') returns true.
  646. * @param {*} value
  647. * @return {boolean}
  648. */
  649. function eqNaN(value) {
  650. return value !== value;
  651. }
  652. /**
  653. * If value1 is not null, then return value1, otherwise judget rest of values.
  654. * Low performance.
  655. * @memberOf module:zrender/core/util
  656. * @return {*} Final value
  657. */
  658. function retrieve(values) {
  659. for (var i = 0, len = arguments.length; i < len; i++) {
  660. if (arguments[i] != null) {
  661. return arguments[i];
  662. }
  663. }
  664. }
  665. function retrieve2(value0, value1) {
  666. return value0 != null
  667. ? value0
  668. : value1;
  669. }
  670. function retrieve3(value0, value1, value2) {
  671. return value0 != null
  672. ? value0
  673. : value1 != null
  674. ? value1
  675. : value2;
  676. }
  677. /**
  678. * @memberOf module:zrender/core/util
  679. * @param {Array} arr
  680. * @param {number} startIndex
  681. * @param {number} endIndex
  682. * @return {Array}
  683. */
  684. function slice() {
  685. return Function.call.apply(nativeSlice, arguments);
  686. }
  687. /**
  688. * Normalize css liked array configuration
  689. * e.g.
  690. * 3 => [3, 3, 3, 3]
  691. * [4, 2] => [4, 2, 4, 2]
  692. * [4, 3, 2] => [4, 3, 2, 3]
  693. * @param {number|Array.<number>} val
  694. * @return {Array.<number>}
  695. */
  696. function normalizeCssArray(val) {
  697. if (typeof (val) === 'number') {
  698. return [val, val, val, val];
  699. }
  700. var len = val.length;
  701. if (len === 2) {
  702. // vertical | horizontal
  703. return [val[0], val[1], val[0], val[1]];
  704. }
  705. else if (len === 3) {
  706. // top | horizontal | bottom
  707. return [val[0], val[1], val[2], val[1]];
  708. }
  709. return val;
  710. }
  711. /**
  712. * @memberOf module:zrender/core/util
  713. * @param {boolean} condition
  714. * @param {string} message
  715. */
  716. function assert$1(condition, message) {
  717. if (!condition) {
  718. throw new Error(message);
  719. }
  720. }
  721. /**
  722. * @memberOf module:zrender/core/util
  723. * @param {string} str string to be trimed
  724. * @return {string} trimed string
  725. */
  726. function trim(str) {
  727. if (str == null) {
  728. return null;
  729. }
  730. else if (typeof str.trim === 'function') {
  731. return str.trim();
  732. }
  733. else {
  734. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  735. }
  736. }
  737. var primitiveKey = '__ec_primitive__';
  738. /**
  739. * Set an object as primitive to be ignored traversing children in clone or merge
  740. */
  741. function setAsPrimitive(obj) {
  742. obj[primitiveKey] = true;
  743. }
  744. function isPrimitive(obj) {
  745. return obj[primitiveKey];
  746. }
  747. /**
  748. * @constructor
  749. * @param {Object} obj Only apply `ownProperty`.
  750. */
  751. function HashMap(obj) {
  752. var isArr = isArray(obj);
  753. var thisMap = this;
  754. (obj instanceof HashMap)
  755. ? obj.each(visit)
  756. : (obj && each$1(obj, visit));
  757. function visit(value, key) {
  758. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  759. }
  760. }
  761. // Add prefix to avoid conflict with Object.prototype.
  762. HashMap.prototype = {
  763. constructor: HashMap,
  764. // Do not provide `has` method to avoid defining what is `has`.
  765. // (We usually treat `null` and `undefined` as the same, different
  766. // from ES6 Map).
  767. get: function (key) {
  768. return this.hasOwnProperty(key) ? this[key] : null;
  769. },
  770. set: function (key, value) {
  771. // Comparing with invocation chaining, `return value` is more commonly
  772. // used in this case: `var someVal = map.set('a', genVal());`
  773. return (this[key] = value);
  774. },
  775. // Although util.each can be performed on this hashMap directly, user
  776. // should not use the exposed keys, who are prefixed.
  777. each: function (cb, context) {
  778. context !== void 0 && (cb = bind(cb, context));
  779. for (var key in this) {
  780. this.hasOwnProperty(key) && cb(this[key], key);
  781. }
  782. },
  783. // Do not use this method if performance sensitive.
  784. removeKey: function (key) {
  785. delete this[key];
  786. }
  787. };
  788. function createHashMap(obj) {
  789. return new HashMap(obj);
  790. }
  791. function concatArray(a, b) {
  792. var newArray = new a.constructor(a.length + b.length);
  793. for (var i = 0; i < a.length; i++) {
  794. newArray[i] = a[i];
  795. }
  796. var offset = a.length;
  797. for (i = 0; i < b.length; i++) {
  798. newArray[i + offset] = b[i];
  799. }
  800. return newArray;
  801. }
  802. function noop() {}
  803. var zrUtil = (Object.freeze || Object)({
  804. $override: $override,
  805. clone: clone,
  806. merge: merge,
  807. mergeAll: mergeAll,
  808. extend: extend,
  809. defaults: defaults,
  810. createCanvas: createCanvas,
  811. getContext: getContext,
  812. indexOf: indexOf,
  813. inherits: inherits,
  814. mixin: mixin,
  815. isArrayLike: isArrayLike,
  816. each: each$1,
  817. map: map,
  818. reduce: reduce,
  819. filter: filter,
  820. find: find,
  821. bind: bind,
  822. curry: curry,
  823. isArray: isArray,
  824. isFunction: isFunction$1,
  825. isString: isString,
  826. isObject: isObject$1,
  827. isBuiltInObject: isBuiltInObject,
  828. isTypedArray: isTypedArray,
  829. isDom: isDom,
  830. eqNaN: eqNaN,
  831. retrieve: retrieve,
  832. retrieve2: retrieve2,
  833. retrieve3: retrieve3,
  834. slice: slice,
  835. normalizeCssArray: normalizeCssArray,
  836. assert: assert$1,
  837. trim: trim,
  838. setAsPrimitive: setAsPrimitive,
  839. isPrimitive: isPrimitive,
  840. createHashMap: createHashMap,
  841. concatArray: concatArray,
  842. noop: noop
  843. });
  844. var ArrayCtor = typeof Float32Array === 'undefined'
  845. ? Array
  846. : Float32Array;
  847. /**
  848. * 创建一个向量
  849. * @param {number} [x=0]
  850. * @param {number} [y=0]
  851. * @return {Vector2}
  852. */
  853. function create(x, y) {
  854. var out = new ArrayCtor(2);
  855. if (x == null) {
  856. x = 0;
  857. }
  858. if (y == null) {
  859. y = 0;
  860. }
  861. out[0] = x;
  862. out[1] = y;
  863. return out;
  864. }
  865. /**
  866. * 复制向量数据
  867. * @param {Vector2} out
  868. * @param {Vector2} v
  869. * @return {Vector2}
  870. */
  871. function copy(out, v) {
  872. out[0] = v[0];
  873. out[1] = v[1];
  874. return out;
  875. }
  876. /**
  877. * 克隆一个向量
  878. * @param {Vector2} v
  879. * @return {Vector2}
  880. */
  881. function clone$1(v) {
  882. var out = new ArrayCtor(2);
  883. out[0] = v[0];
  884. out[1] = v[1];
  885. return out;
  886. }
  887. /**
  888. * 设置向量的两个项
  889. * @param {Vector2} out
  890. * @param {number} a
  891. * @param {number} b
  892. * @return {Vector2} 结果
  893. */
  894. function set(out, a, b) {
  895. out[0] = a;
  896. out[1] = b;
  897. return out;
  898. }
  899. /**
  900. * 向量相加
  901. * @param {Vector2} out
  902. * @param {Vector2} v1
  903. * @param {Vector2} v2
  904. */
  905. function add(out, v1, v2) {
  906. out[0] = v1[0] + v2[0];
  907. out[1] = v1[1] + v2[1];
  908. return out;
  909. }
  910. /**
  911. * 向量缩放后相加
  912. * @param {Vector2} out
  913. * @param {Vector2} v1
  914. * @param {Vector2} v2
  915. * @param {number} a
  916. */
  917. function scaleAndAdd(out, v1, v2, a) {
  918. out[0] = v1[0] + v2[0] * a;
  919. out[1] = v1[1] + v2[1] * a;
  920. return out;
  921. }
  922. /**
  923. * 向量相减
  924. * @param {Vector2} out
  925. * @param {Vector2} v1
  926. * @param {Vector2} v2
  927. */
  928. function sub(out, v1, v2) {
  929. out[0] = v1[0] - v2[0];
  930. out[1] = v1[1] - v2[1];
  931. return out;
  932. }
  933. /**
  934. * 向量长度
  935. * @param {Vector2} v
  936. * @return {number}
  937. */
  938. function len(v) {
  939. return Math.sqrt(lenSquare(v));
  940. }
  941. var length = len; // jshint ignore:line
  942. /**
  943. * 向量长度平方
  944. * @param {Vector2} v
  945. * @return {number}
  946. */
  947. function lenSquare(v) {
  948. return v[0] * v[0] + v[1] * v[1];
  949. }
  950. var lengthSquare = lenSquare;
  951. /**
  952. * 向量乘法
  953. * @param {Vector2} out
  954. * @param {Vector2} v1
  955. * @param {Vector2} v2
  956. */
  957. function mul(out, v1, v2) {
  958. out[0] = v1[0] * v2[0];
  959. out[1] = v1[1] * v2[1];
  960. return out;
  961. }
  962. /**
  963. * 向量除法
  964. * @param {Vector2} out
  965. * @param {Vector2} v1
  966. * @param {Vector2} v2
  967. */
  968. function div(out, v1, v2) {
  969. out[0] = v1[0] / v2[0];
  970. out[1] = v1[1] / v2[1];
  971. return out;
  972. }
  973. /**
  974. * 向量点乘
  975. * @param {Vector2} v1
  976. * @param {Vector2} v2
  977. * @return {number}
  978. */
  979. function dot(v1, v2) {
  980. return v1[0] * v2[0] + v1[1] * v2[1];
  981. }
  982. /**
  983. * 向量缩放
  984. * @param {Vector2} out
  985. * @param {Vector2} v
  986. * @param {number} s
  987. */
  988. function scale(out, v, s) {
  989. out[0] = v[0] * s;
  990. out[1] = v[1] * s;
  991. return out;
  992. }
  993. /**
  994. * 向量归一化
  995. * @param {Vector2} out
  996. * @param {Vector2} v
  997. */
  998. function normalize(out, v) {
  999. var d = len(v);
  1000. if (d === 0) {
  1001. out[0] = 0;
  1002. out[1] = 0;
  1003. }
  1004. else {
  1005. out[0] = v[0] / d;
  1006. out[1] = v[1] / d;
  1007. }
  1008. return out;
  1009. }
  1010. /**
  1011. * 计算向量间距离
  1012. * @param {Vector2} v1
  1013. * @param {Vector2} v2
  1014. * @return {number}
  1015. */
  1016. function distance(v1, v2) {
  1017. return Math.sqrt(
  1018. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1019. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1020. );
  1021. }
  1022. var dist = distance;
  1023. /**
  1024. * 向量距离平方
  1025. * @param {Vector2} v1
  1026. * @param {Vector2} v2
  1027. * @return {number}
  1028. */
  1029. function distanceSquare(v1, v2) {
  1030. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1031. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1032. }
  1033. var distSquare = distanceSquare;
  1034. /**
  1035. * 求负向量
  1036. * @param {Vector2} out
  1037. * @param {Vector2} v
  1038. */
  1039. function negate(out, v) {
  1040. out[0] = -v[0];
  1041. out[1] = -v[1];
  1042. return out;
  1043. }
  1044. /**
  1045. * 插值两个点
  1046. * @param {Vector2} out
  1047. * @param {Vector2} v1
  1048. * @param {Vector2} v2
  1049. * @param {number} t
  1050. */
  1051. function lerp(out, v1, v2, t) {
  1052. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1053. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1054. return out;
  1055. }
  1056. /**
  1057. * 矩阵左乘向量
  1058. * @param {Vector2} out
  1059. * @param {Vector2} v
  1060. * @param {Vector2} m
  1061. */
  1062. function applyTransform(out, v, m) {
  1063. var x = v[0];
  1064. var y = v[1];
  1065. out[0] = m[0] * x + m[2] * y + m[4];
  1066. out[1] = m[1] * x + m[3] * y + m[5];
  1067. return out;
  1068. }
  1069. /**
  1070. * 求两个向量最小值
  1071. * @param {Vector2} out
  1072. * @param {Vector2} v1
  1073. * @param {Vector2} v2
  1074. */
  1075. function min(out, v1, v2) {
  1076. out[0] = Math.min(v1[0], v2[0]);
  1077. out[1] = Math.min(v1[1], v2[1]);
  1078. return out;
  1079. }
  1080. /**
  1081. * 求两个向量最大值
  1082. * @param {Vector2} out
  1083. * @param {Vector2} v1
  1084. * @param {Vector2} v2
  1085. */
  1086. function max(out, v1, v2) {
  1087. out[0] = Math.max(v1[0], v2[0]);
  1088. out[1] = Math.max(v1[1], v2[1]);
  1089. return out;
  1090. }
  1091. var vector = (Object.freeze || Object)({
  1092. create: create,
  1093. copy: copy,
  1094. clone: clone$1,
  1095. set: set,
  1096. add: add,
  1097. scaleAndAdd: scaleAndAdd,
  1098. sub: sub,
  1099. len: len,
  1100. length: length,
  1101. lenSquare: lenSquare,
  1102. lengthSquare: lengthSquare,
  1103. mul: mul,
  1104. div: div,
  1105. dot: dot,
  1106. scale: scale,
  1107. normalize: normalize,
  1108. distance: distance,
  1109. dist: dist,
  1110. distanceSquare: distanceSquare,
  1111. distSquare: distSquare,
  1112. negate: negate,
  1113. lerp: lerp,
  1114. applyTransform: applyTransform,
  1115. min: min,
  1116. max: max
  1117. });
  1118. // TODO Draggable for group
  1119. // FIXME Draggable on element which has parent rotation or scale
  1120. function Draggable() {
  1121. this.on('mousedown', this._dragStart, this);
  1122. this.on('mousemove', this._drag, this);
  1123. this.on('mouseup', this._dragEnd, this);
  1124. this.on('globalout', this._dragEnd, this);
  1125. // this._dropTarget = null;
  1126. // this._draggingTarget = null;
  1127. // this._x = 0;
  1128. // this._y = 0;
  1129. }
  1130. Draggable.prototype = {
  1131. constructor: Draggable,
  1132. _dragStart: function (e) {
  1133. var draggingTarget = e.target;
  1134. if (draggingTarget && draggingTarget.draggable) {
  1135. this._draggingTarget = draggingTarget;
  1136. draggingTarget.dragging = true;
  1137. this._x = e.offsetX;
  1138. this._y = e.offsetY;
  1139. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1140. }
  1141. },
  1142. _drag: function (e) {
  1143. var draggingTarget = this._draggingTarget;
  1144. if (draggingTarget) {
  1145. var x = e.offsetX;
  1146. var y = e.offsetY;
  1147. var dx = x - this._x;
  1148. var dy = y - this._y;
  1149. this._x = x;
  1150. this._y = y;
  1151. draggingTarget.drift(dx, dy, e);
  1152. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1153. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1154. var lastDropTarget = this._dropTarget;
  1155. this._dropTarget = dropTarget;
  1156. if (draggingTarget !== dropTarget) {
  1157. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1158. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1159. }
  1160. if (dropTarget && dropTarget !== lastDropTarget) {
  1161. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1162. }
  1163. }
  1164. }
  1165. },
  1166. _dragEnd: function (e) {
  1167. var draggingTarget = this._draggingTarget;
  1168. if (draggingTarget) {
  1169. draggingTarget.dragging = false;
  1170. }
  1171. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1172. if (this._dropTarget) {
  1173. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1174. }
  1175. this._draggingTarget = null;
  1176. this._dropTarget = null;
  1177. }
  1178. };
  1179. function param(target, e) {
  1180. return {target: target, topTarget: e && e.topTarget};
  1181. }
  1182. /**
  1183. * 事件扩展
  1184. * @module zrender/mixin/Eventful
  1185. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1186. * pissang (https://www.github.com/pissang)
  1187. */
  1188. var arrySlice = Array.prototype.slice;
  1189. /**
  1190. * 事件分发器
  1191. * @alias module:zrender/mixin/Eventful
  1192. * @constructor
  1193. */
  1194. var Eventful = function () {
  1195. this._$handlers = {};
  1196. };
  1197. Eventful.prototype = {
  1198. constructor: Eventful,
  1199. /**
  1200. * 单次触发绑定,trigger后销毁
  1201. *
  1202. * @param {string} event 事件名
  1203. * @param {Function} handler 响应函数
  1204. * @param {Object} context
  1205. */
  1206. one: function (event, handler, context) {
  1207. var _h = this._$handlers;
  1208. if (!handler || !event) {
  1209. return this;
  1210. }
  1211. if (!_h[event]) {
  1212. _h[event] = [];
  1213. }
  1214. for (var i = 0; i < _h[event].length; i++) {
  1215. if (_h[event][i].h === handler) {
  1216. return this;
  1217. }
  1218. }
  1219. _h[event].push({
  1220. h: handler,
  1221. one: true,
  1222. ctx: context || this
  1223. });
  1224. return this;
  1225. },
  1226. /**
  1227. * 绑定事件
  1228. * @param {string} event 事件名
  1229. * @param {Function} handler 事件处理函数
  1230. * @param {Object} [context]
  1231. */
  1232. on: function (event, handler, context) {
  1233. var _h = this._$handlers;
  1234. if (!handler || !event) {
  1235. return this;
  1236. }
  1237. if (!_h[event]) {
  1238. _h[event] = [];
  1239. }
  1240. for (var i = 0; i < _h[event].length; i++) {
  1241. if (_h[event][i].h === handler) {
  1242. return this;
  1243. }
  1244. }
  1245. _h[event].push({
  1246. h: handler,
  1247. one: false,
  1248. ctx: context || this
  1249. });
  1250. return this;
  1251. },
  1252. /**
  1253. * 是否绑定了事件
  1254. * @param {string} event
  1255. * @return {boolean}
  1256. */
  1257. isSilent: function (event) {
  1258. var _h = this._$handlers;
  1259. return _h[event] && _h[event].length;
  1260. },
  1261. /**
  1262. * 解绑事件
  1263. * @param {string} event 事件名
  1264. * @param {Function} [handler] 事件处理函数
  1265. */
  1266. off: function (event, handler) {
  1267. var _h = this._$handlers;
  1268. if (!event) {
  1269. this._$handlers = {};
  1270. return this;
  1271. }
  1272. if (handler) {
  1273. if (_h[event]) {
  1274. var newList = [];
  1275. for (var i = 0, l = _h[event].length; i < l; i++) {
  1276. if (_h[event][i]['h'] != handler) {
  1277. newList.push(_h[event][i]);
  1278. }
  1279. }
  1280. _h[event] = newList;
  1281. }
  1282. if (_h[event] && _h[event].length === 0) {
  1283. delete _h[event];
  1284. }
  1285. }
  1286. else {
  1287. delete _h[event];
  1288. }
  1289. return this;
  1290. },
  1291. /**
  1292. * 事件分发
  1293. *
  1294. * @param {string} type 事件类型
  1295. */
  1296. trigger: function (type) {
  1297. if (this._$handlers[type]) {
  1298. var args = arguments;
  1299. var argLen = args.length;
  1300. if (argLen > 3) {
  1301. args = arrySlice.call(args, 1);
  1302. }
  1303. var _h = this._$handlers[type];
  1304. var len = _h.length;
  1305. for (var i = 0; i < len;) {
  1306. // Optimize advise from backbone
  1307. switch (argLen) {
  1308. case 1:
  1309. _h[i]['h'].call(_h[i]['ctx']);
  1310. break;
  1311. case 2:
  1312. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1313. break;
  1314. case 3:
  1315. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1316. break;
  1317. default:
  1318. // have more than 2 given arguments
  1319. _h[i]['h'].apply(_h[i]['ctx'], args);
  1320. break;
  1321. }
  1322. if (_h[i]['one']) {
  1323. _h.splice(i, 1);
  1324. len--;
  1325. }
  1326. else {
  1327. i++;
  1328. }
  1329. }
  1330. }
  1331. return this;
  1332. },
  1333. /**
  1334. * 带有context的事件分发, 最后一个参数是事件回调的context
  1335. * @param {string} type 事件类型
  1336. */
  1337. triggerWithContext: function (type) {
  1338. if (this._$handlers[type]) {
  1339. var args = arguments;
  1340. var argLen = args.length;
  1341. if (argLen > 4) {
  1342. args = arrySlice.call(args, 1, args.length - 1);
  1343. }
  1344. var ctx = args[args.length - 1];
  1345. var _h = this._$handlers[type];
  1346. var len = _h.length;
  1347. for (var i = 0; i < len;) {
  1348. // Optimize advise from backbone
  1349. switch (argLen) {
  1350. case 1:
  1351. _h[i]['h'].call(ctx);
  1352. break;
  1353. case 2:
  1354. _h[i]['h'].call(ctx, args[1]);
  1355. break;
  1356. case 3:
  1357. _h[i]['h'].call(ctx, args[1], args[2]);
  1358. break;
  1359. default:
  1360. // have more than 2 given arguments
  1361. _h[i]['h'].apply(ctx, args);
  1362. break;
  1363. }
  1364. if (_h[i]['one']) {
  1365. _h.splice(i, 1);
  1366. len--;
  1367. }
  1368. else {
  1369. i++;
  1370. }
  1371. }
  1372. }
  1373. return this;
  1374. }
  1375. };
  1376. var SILENT = 'silent';
  1377. function makeEventPacket(eveType, targetInfo, event) {
  1378. return {
  1379. type: eveType,
  1380. event: event,
  1381. // target can only be an element that is not silent.
  1382. target: targetInfo.target,
  1383. // topTarget can be a silent element.
  1384. topTarget: targetInfo.topTarget,
  1385. cancelBubble: false,
  1386. offsetX: event.zrX,
  1387. offsetY: event.zrY,
  1388. gestureEvent: event.gestureEvent,
  1389. pinchX: event.pinchX,
  1390. pinchY: event.pinchY,
  1391. pinchScale: event.pinchScale,
  1392. wheelDelta: event.zrDelta,
  1393. zrByTouch: event.zrByTouch,
  1394. which: event.which
  1395. };
  1396. }
  1397. function EmptyProxy () {}
  1398. EmptyProxy.prototype.dispose = function () {};
  1399. var handlerNames = [
  1400. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1401. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1402. ];
  1403. /**
  1404. * @alias module:zrender/Handler
  1405. * @constructor
  1406. * @extends module:zrender/mixin/Eventful
  1407. * @param {module:zrender/Storage} storage Storage instance.
  1408. * @param {module:zrender/Painter} painter Painter instance.
  1409. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1410. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1411. */
  1412. var Handler = function(storage, painter, proxy, painterRoot) {
  1413. Eventful.call(this);
  1414. this.storage = storage;
  1415. this.painter = painter;
  1416. this.painterRoot = painterRoot;
  1417. proxy = proxy || new EmptyProxy();
  1418. /**
  1419. * Proxy of event. can be Dom, WebGLSurface, etc.
  1420. */
  1421. this.proxy = null;
  1422. /**
  1423. * {target, topTarget, x, y}
  1424. * @private
  1425. * @type {Object}
  1426. */
  1427. this._hovered = {};
  1428. /**
  1429. * @private
  1430. * @type {Date}
  1431. */
  1432. this._lastTouchMoment;
  1433. /**
  1434. * @private
  1435. * @type {number}
  1436. */
  1437. this._lastX;
  1438. /**
  1439. * @private
  1440. * @type {number}
  1441. */
  1442. this._lastY;
  1443. Draggable.call(this);
  1444. this.setHandlerProxy(proxy);
  1445. };
  1446. Handler.prototype = {
  1447. constructor: Handler,
  1448. setHandlerProxy: function (proxy) {
  1449. if (this.proxy) {
  1450. this.proxy.dispose();
  1451. }
  1452. if (proxy) {
  1453. each$1(handlerNames, function (name) {
  1454. proxy.on && proxy.on(name, this[name], this);
  1455. }, this);
  1456. // Attach handler
  1457. proxy.handler = this;
  1458. }
  1459. this.proxy = proxy;
  1460. },
  1461. mousemove: function (event) {
  1462. var x = event.zrX;
  1463. var y = event.zrY;
  1464. var lastHovered = this._hovered;
  1465. var lastHoveredTarget = lastHovered.target;
  1466. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1467. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1468. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1469. // See #6198.
  1470. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1471. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1472. lastHoveredTarget = lastHovered.target;
  1473. }
  1474. var hovered = this._hovered = this.findHover(x, y);
  1475. var hoveredTarget = hovered.target;
  1476. var proxy = this.proxy;
  1477. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1478. // Mouse out on previous hovered element
  1479. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1480. this.dispatchToElement(lastHovered, 'mouseout', event);
  1481. }
  1482. // Mouse moving on one element
  1483. this.dispatchToElement(hovered, 'mousemove', event);
  1484. // Mouse over on a new element
  1485. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1486. this.dispatchToElement(hovered, 'mouseover', event);
  1487. }
  1488. },
  1489. mouseout: function (event) {
  1490. this.dispatchToElement(this._hovered, 'mouseout', event);
  1491. // There might be some doms created by upper layer application
  1492. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1493. // dom created by echarts), where 'globalout' event should not
  1494. // be triggered when mouse enters these doms. (But 'mouseout'
  1495. // should be triggered at the original hovered element as usual).
  1496. var element = event.toElement || event.relatedTarget;
  1497. var innerDom;
  1498. do {
  1499. element = element && element.parentNode;
  1500. }
  1501. while (element && element.nodeType != 9 && !(
  1502. innerDom = element === this.painterRoot
  1503. ));
  1504. !innerDom && this.trigger('globalout', {event: event});
  1505. },
  1506. /**
  1507. * Resize
  1508. */
  1509. resize: function (event) {
  1510. this._hovered = {};
  1511. },
  1512. /**
  1513. * Dispatch event
  1514. * @param {string} eventName
  1515. * @param {event=} eventArgs
  1516. */
  1517. dispatch: function (eventName, eventArgs) {
  1518. var handler = this[eventName];
  1519. handler && handler.call(this, eventArgs);
  1520. },
  1521. /**
  1522. * Dispose
  1523. */
  1524. dispose: function () {
  1525. this.proxy.dispose();
  1526. this.storage =
  1527. this.proxy =
  1528. this.painter = null;
  1529. },
  1530. /**
  1531. * 设置默认的cursor style
  1532. * @param {string} [cursorStyle='default'] 例如 crosshair
  1533. */
  1534. setCursorStyle: function (cursorStyle) {
  1535. var proxy = this.proxy;
  1536. proxy.setCursor && proxy.setCursor(cursorStyle);
  1537. },
  1538. /**
  1539. * 事件分发代理
  1540. *
  1541. * @private
  1542. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1543. * @param {string} eventName 事件名称
  1544. * @param {Object} event 事件对象
  1545. */
  1546. dispatchToElement: function (targetInfo, eventName, event) {
  1547. targetInfo = targetInfo || {};
  1548. var el = targetInfo.target;
  1549. if (el && el.silent) {
  1550. return;
  1551. }
  1552. var eventHandler = 'on' + eventName;
  1553. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1554. while (el) {
  1555. el[eventHandler]
  1556. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1557. el.trigger(eventName, eventPacket);
  1558. el = el.parent;
  1559. if (eventPacket.cancelBubble) {
  1560. break;
  1561. }
  1562. }
  1563. if (!eventPacket.cancelBubble) {
  1564. // 冒泡到顶级 zrender 对象
  1565. this.trigger(eventName, eventPacket);
  1566. // 分发事件到用户自定义层
  1567. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1568. this.painter && this.painter.eachOtherLayer(function (layer) {
  1569. if (typeof(layer[eventHandler]) == 'function') {
  1570. layer[eventHandler].call(layer, eventPacket);
  1571. }
  1572. if (layer.trigger) {
  1573. layer.trigger(eventName, eventPacket);
  1574. }
  1575. });
  1576. }
  1577. },
  1578. /**
  1579. * @private
  1580. * @param {number} x
  1581. * @param {number} y
  1582. * @param {module:zrender/graphic/Displayable} exclude
  1583. * @return {model:zrender/Element}
  1584. * @method
  1585. */
  1586. findHover: function(x, y, exclude) {
  1587. var list = this.storage.getDisplayList();
  1588. var out = {x: x, y: y};
  1589. for (var i = list.length - 1; i >= 0 ; i--) {
  1590. var hoverCheckResult;
  1591. if (list[i] !== exclude
  1592. // getDisplayList may include ignored item in VML mode
  1593. && !list[i].ignore
  1594. && (hoverCheckResult = isHover(list[i], x, y))
  1595. ) {
  1596. !out.topTarget && (out.topTarget = list[i]);
  1597. if (hoverCheckResult !== SILENT) {
  1598. out.target = list[i];
  1599. break;
  1600. }
  1601. }
  1602. }
  1603. return out;
  1604. }
  1605. };
  1606. // Common handlers
  1607. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1608. Handler.prototype[name] = function (event) {
  1609. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1610. var hovered = this.findHover(event.zrX, event.zrY);
  1611. var hoveredTarget = hovered.target;
  1612. if (name === 'mousedown') {
  1613. this._downEl = hoveredTarget;
  1614. this._downPoint = [event.zrX, event.zrY];
  1615. // In case click triggered before mouseup
  1616. this._upEl = hoveredTarget;
  1617. }
  1618. else if (name === 'mouseup') {
  1619. this._upEl = hoveredTarget;
  1620. }
  1621. else if (name === 'click') {
  1622. if (this._downEl !== this._upEl
  1623. // Original click event is triggered on the whole canvas element,
  1624. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1625. // which should be filtered, otherwise it will bring trouble to
  1626. // pan and zoom.
  1627. || !this._downPoint
  1628. // Arbitrary value
  1629. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1630. ) {
  1631. return;
  1632. }
  1633. this._downPoint = null;
  1634. }
  1635. this.dispatchToElement(hovered, name, event);
  1636. };
  1637. });
  1638. function isHover(displayable, x, y) {
  1639. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1640. var el = displayable;
  1641. var isSilent;
  1642. while (el) {
  1643. // If clipped by ancestor.
  1644. // FIXME: If clipPath has neither stroke nor fill,
  1645. // el.clipPath.contain(x, y) will always return false.
  1646. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1647. return false;
  1648. }
  1649. if (el.silent) {
  1650. isSilent = true;
  1651. }
  1652. el = el.parent;
  1653. }
  1654. return isSilent ? SILENT : true;
  1655. }
  1656. return false;
  1657. }
  1658. mixin(Handler, Eventful);
  1659. mixin(Handler, Draggable);
  1660. /**
  1661. * 3x2矩阵操作类
  1662. * @exports zrender/tool/matrix
  1663. */
  1664. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1665. ? Array
  1666. : Float32Array;
  1667. /**
  1668. * Create a identity matrix.
  1669. * @return {Float32Array|Array.<number>}
  1670. */
  1671. function create$1() {
  1672. var out = new ArrayCtor$1(6);
  1673. identity(out);
  1674. return out;
  1675. }
  1676. /**
  1677. * 设置矩阵为单位矩阵
  1678. * @param {Float32Array|Array.<number>} out
  1679. */
  1680. function identity(out) {
  1681. out[0] = 1;
  1682. out[1] = 0;
  1683. out[2] = 0;
  1684. out[3] = 1;
  1685. out[4] = 0;
  1686. out[5] = 0;
  1687. return out;
  1688. }
  1689. /**
  1690. * 复制矩阵
  1691. * @param {Float32Array|Array.<number>} out
  1692. * @param {Float32Array|Array.<number>} m
  1693. */
  1694. function copy$1(out, m) {
  1695. out[0] = m[0];
  1696. out[1] = m[1];
  1697. out[2] = m[2];
  1698. out[3] = m[3];
  1699. out[4] = m[4];
  1700. out[5] = m[5];
  1701. return out;
  1702. }
  1703. /**
  1704. * 矩阵相乘
  1705. * @param {Float32Array|Array.<number>} out
  1706. * @param {Float32Array|Array.<number>} m1
  1707. * @param {Float32Array|Array.<number>} m2
  1708. */
  1709. function mul$1(out, m1, m2) {
  1710. // Consider matrix.mul(m, m2, m);
  1711. // where out is the same as m2.
  1712. // So use temp variable to escape error.
  1713. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1714. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1715. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1716. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1717. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1718. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1719. out[0] = out0;
  1720. out[1] = out1;
  1721. out[2] = out2;
  1722. out[3] = out3;
  1723. out[4] = out4;
  1724. out[5] = out5;
  1725. return out;
  1726. }
  1727. /**
  1728. * 平移变换
  1729. * @param {Float32Array|Array.<number>} out
  1730. * @param {Float32Array|Array.<number>} a
  1731. * @param {Float32Array|Array.<number>} v
  1732. */
  1733. function translate(out, a, v) {
  1734. out[0] = a[0];
  1735. out[1] = a[1];
  1736. out[2] = a[2];
  1737. out[3] = a[3];
  1738. out[4] = a[4] + v[0];
  1739. out[5] = a[5] + v[1];
  1740. return out;
  1741. }
  1742. /**
  1743. * 旋转变换
  1744. * @param {Float32Array|Array.<number>} out
  1745. * @param {Float32Array|Array.<number>} a
  1746. * @param {number} rad
  1747. */
  1748. function rotate(out, a, rad) {
  1749. var aa = a[0];
  1750. var ac = a[2];
  1751. var atx = a[4];
  1752. var ab = a[1];
  1753. var ad = a[3];
  1754. var aty = a[5];
  1755. var st = Math.sin(rad);
  1756. var ct = Math.cos(rad);
  1757. out[0] = aa * ct + ab * st;
  1758. out[1] = -aa * st + ab * ct;
  1759. out[2] = ac * ct + ad * st;
  1760. out[3] = -ac * st + ct * ad;
  1761. out[4] = ct * atx + st * aty;
  1762. out[5] = ct * aty - st * atx;
  1763. return out;
  1764. }
  1765. /**
  1766. * 缩放变换
  1767. * @param {Float32Array|Array.<number>} out
  1768. * @param {Float32Array|Array.<number>} a
  1769. * @param {Float32Array|Array.<number>} v
  1770. */
  1771. function scale$1(out, a, v) {
  1772. var vx = v[0];
  1773. var vy = v[1];
  1774. out[0] = a[0] * vx;
  1775. out[1] = a[1] * vy;
  1776. out[2] = a[2] * vx;
  1777. out[3] = a[3] * vy;
  1778. out[4] = a[4] * vx;
  1779. out[5] = a[5] * vy;
  1780. return out;
  1781. }
  1782. /**
  1783. * 求逆矩阵
  1784. * @param {Float32Array|Array.<number>} out
  1785. * @param {Float32Array|Array.<number>} a
  1786. */
  1787. function invert(out, a) {
  1788. var aa = a[0];
  1789. var ac = a[2];
  1790. var atx = a[4];
  1791. var ab = a[1];
  1792. var ad = a[3];
  1793. var aty = a[5];
  1794. var det = aa * ad - ab * ac;
  1795. if (!det) {
  1796. return null;
  1797. }
  1798. det = 1.0 / det;
  1799. out[0] = ad * det;
  1800. out[1] = -ab * det;
  1801. out[2] = -ac * det;
  1802. out[3] = aa * det;
  1803. out[4] = (ac * aty - ad * atx) * det;
  1804. out[5] = (ab * atx - aa * aty) * det;
  1805. return out;
  1806. }
  1807. /**
  1808. * Clone a new matrix.
  1809. * @param {Float32Array|Array.<number>} a
  1810. */
  1811. function clone$2(a) {
  1812. var b = create$1();
  1813. copy$1(b, a);
  1814. return b;
  1815. }
  1816. var matrix = (Object.freeze || Object)({
  1817. create: create$1,
  1818. identity: identity,
  1819. copy: copy$1,
  1820. mul: mul$1,
  1821. translate: translate,
  1822. rotate: rotate,
  1823. scale: scale$1,
  1824. invert: invert,
  1825. clone: clone$2
  1826. });
  1827. /**
  1828. * 提供变换扩展
  1829. * @module zrender/mixin/Transformable
  1830. * @author pissang (https://www.github.com/pissang)
  1831. */
  1832. var mIdentity = identity;
  1833. var EPSILON = 5e-5;
  1834. function isNotAroundZero(val) {
  1835. return val > EPSILON || val < -EPSILON;
  1836. }
  1837. /**
  1838. * @alias module:zrender/mixin/Transformable
  1839. * @constructor
  1840. */
  1841. var Transformable = function (opts) {
  1842. opts = opts || {};
  1843. // If there are no given position, rotation, scale
  1844. if (!opts.position) {
  1845. /**
  1846. * 平移
  1847. * @type {Array.<number>}
  1848. * @default [0, 0]
  1849. */
  1850. this.position = [0, 0];
  1851. }
  1852. if (opts.rotation == null) {
  1853. /**
  1854. * 旋转
  1855. * @type {Array.<number>}
  1856. * @default 0
  1857. */
  1858. this.rotation = 0;
  1859. }
  1860. if (!opts.scale) {
  1861. /**
  1862. * 缩放
  1863. * @type {Array.<number>}
  1864. * @default [1, 1]
  1865. */
  1866. this.scale = [1, 1];
  1867. }
  1868. /**
  1869. * 旋转和缩放的原点
  1870. * @type {Array.<number>}
  1871. * @default null
  1872. */
  1873. this.origin = this.origin || null;
  1874. };
  1875. var transformableProto = Transformable.prototype;
  1876. transformableProto.transform = null;
  1877. /**
  1878. * 判断是否需要有坐标变换
  1879. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1880. */
  1881. transformableProto.needLocalTransform = function () {
  1882. return isNotAroundZero(this.rotation)
  1883. || isNotAroundZero(this.position[0])
  1884. || isNotAroundZero(this.position[1])
  1885. || isNotAroundZero(this.scale[0] - 1)
  1886. || isNotAroundZero(this.scale[1] - 1);
  1887. };
  1888. transformableProto.updateTransform = function () {
  1889. var parent = this.parent;
  1890. var parentHasTransform = parent && parent.transform;
  1891. var needLocalTransform = this.needLocalTransform();
  1892. var m = this.transform;
  1893. if (!(needLocalTransform || parentHasTransform)) {
  1894. m && mIdentity(m);
  1895. return;
  1896. }
  1897. m = m || create$1();
  1898. if (needLocalTransform) {
  1899. this.getLocalTransform(m);
  1900. }
  1901. else {
  1902. mIdentity(m);
  1903. }
  1904. // 应用父节点变换
  1905. if (parentHasTransform) {
  1906. if (needLocalTransform) {
  1907. mul$1(m, parent.transform, m);
  1908. }
  1909. else {
  1910. copy$1(m, parent.transform);
  1911. }
  1912. }
  1913. // 保存这个变换矩阵
  1914. this.transform = m;
  1915. this.invTransform = this.invTransform || create$1();
  1916. invert(this.invTransform, m);
  1917. };
  1918. transformableProto.getLocalTransform = function (m) {
  1919. return Transformable.getLocalTransform(this, m);
  1920. };
  1921. /**
  1922. * 将自己的transform应用到context上
  1923. * @param {CanvasRenderingContext2D} ctx
  1924. */
  1925. transformableProto.setTransform = function (ctx) {
  1926. var m = this.transform;
  1927. var dpr = ctx.dpr || 1;
  1928. if (m) {
  1929. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1930. }
  1931. else {
  1932. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1933. }
  1934. };
  1935. transformableProto.restoreTransform = function (ctx) {
  1936. var dpr = ctx.dpr || 1;
  1937. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1938. };
  1939. var tmpTransform = [];
  1940. /**
  1941. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1942. */
  1943. transformableProto.decomposeTransform = function () {
  1944. if (!this.transform) {
  1945. return;
  1946. }
  1947. var parent = this.parent;
  1948. var m = this.transform;
  1949. if (parent && parent.transform) {
  1950. // Get local transform and decompose them to position, scale, rotation
  1951. mul$1(tmpTransform, parent.invTransform, m);
  1952. m = tmpTransform;
  1953. }
  1954. var sx = m[0] * m[0] + m[1] * m[1];
  1955. var sy = m[2] * m[2] + m[3] * m[3];
  1956. var position = this.position;
  1957. var scale$$1 = this.scale;
  1958. if (isNotAroundZero(sx - 1)) {
  1959. sx = Math.sqrt(sx);
  1960. }
  1961. if (isNotAroundZero(sy - 1)) {
  1962. sy = Math.sqrt(sy);
  1963. }
  1964. if (m[0] < 0) {
  1965. sx = -sx;
  1966. }
  1967. if (m[3] < 0) {
  1968. sy = -sy;
  1969. }
  1970. position[0] = m[4];
  1971. position[1] = m[5];
  1972. scale$$1[0] = sx;
  1973. scale$$1[1] = sy;
  1974. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1975. };
  1976. /**
  1977. * Get global scale
  1978. * @return {Array.<number>}
  1979. */
  1980. transformableProto.getGlobalScale = function () {
  1981. var m = this.transform;
  1982. if (!m) {
  1983. return [1, 1];
  1984. }
  1985. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1986. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1987. if (m[0] < 0) {
  1988. sx = -sx;
  1989. }
  1990. if (m[3] < 0) {
  1991. sy = -sy;
  1992. }
  1993. return [sx, sy];
  1994. };
  1995. /**
  1996. * 变换坐标位置到 shape 的局部坐标空间
  1997. * @method
  1998. * @param {number} x
  1999. * @param {number} y
  2000. * @return {Array.<number>}
  2001. */
  2002. transformableProto.transformCoordToLocal = function (x, y) {
  2003. var v2 = [x, y];
  2004. var invTransform = this.invTransform;
  2005. if (invTransform) {
  2006. applyTransform(v2, v2, invTransform);
  2007. }
  2008. return v2;
  2009. };
  2010. /**
  2011. * 变换局部坐标位置到全局坐标空间
  2012. * @method
  2013. * @param {number} x
  2014. * @param {number} y
  2015. * @return {Array.<number>}
  2016. */
  2017. transformableProto.transformCoordToGlobal = function (x, y) {
  2018. var v2 = [x, y];
  2019. var transform = this.transform;
  2020. if (transform) {
  2021. applyTransform(v2, v2, transform);
  2022. }
  2023. return v2;
  2024. };
  2025. /**
  2026. * @static
  2027. * @param {Object} target
  2028. * @param {Array.<number>} target.origin
  2029. * @param {number} target.rotation
  2030. * @param {Array.<number>} target.position
  2031. * @param {Array.<number>} [m]
  2032. */
  2033. Transformable.getLocalTransform = function (target, m) {
  2034. m = m || [];
  2035. mIdentity(m);
  2036. var origin = target.origin;
  2037. var scale$$1 = target.scale || [1, 1];
  2038. var rotation = target.rotation || 0;
  2039. var position = target.position || [0, 0];
  2040. if (origin) {
  2041. // Translate to origin
  2042. m[4] -= origin[0];
  2043. m[5] -= origin[1];
  2044. }
  2045. scale$1(m, m, scale$$1);
  2046. if (rotation) {
  2047. rotate(m, m, rotation);
  2048. }
  2049. if (origin) {
  2050. // Translate back from origin
  2051. m[4] += origin[0];
  2052. m[5] += origin[1];
  2053. }
  2054. m[4] += position[0];
  2055. m[5] += position[1];
  2056. return m;
  2057. };
  2058. /**
  2059. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2060. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2061. * @exports zrender/animation/easing
  2062. */
  2063. var easing = {
  2064. /**
  2065. * @param {number} k
  2066. * @return {number}
  2067. */
  2068. linear: function (k) {
  2069. return k;
  2070. },
  2071. /**
  2072. * @param {number} k
  2073. * @return {number}
  2074. */
  2075. quadraticIn: function (k) {
  2076. return k * k;
  2077. },
  2078. /**
  2079. * @param {number} k
  2080. * @return {number}
  2081. */
  2082. quadraticOut: function (k) {
  2083. return k * (2 - k);
  2084. },
  2085. /**
  2086. * @param {number} k
  2087. * @return {number}
  2088. */
  2089. quadraticInOut: function (k) {
  2090. if ((k *= 2) < 1) {
  2091. return 0.5 * k * k;
  2092. }
  2093. return -0.5 * (--k * (k - 2) - 1);
  2094. },
  2095. // 三次方的缓动(t^3)
  2096. /**
  2097. * @param {number} k
  2098. * @return {number}
  2099. */
  2100. cubicIn: function (k) {
  2101. return k * k * k;
  2102. },
  2103. /**
  2104. * @param {number} k
  2105. * @return {number}
  2106. */
  2107. cubicOut: function (k) {
  2108. return --k * k * k + 1;
  2109. },
  2110. /**
  2111. * @param {number} k
  2112. * @return {number}
  2113. */
  2114. cubicInOut: function (k) {
  2115. if ((k *= 2) < 1) {
  2116. return 0.5 * k * k * k;
  2117. }
  2118. return 0.5 * ((k -= 2) * k * k + 2);
  2119. },
  2120. // 四次方的缓动(t^4)
  2121. /**
  2122. * @param {number} k
  2123. * @return {number}
  2124. */
  2125. quarticIn: function (k) {
  2126. return k * k * k * k;
  2127. },
  2128. /**
  2129. * @param {number} k
  2130. * @return {number}
  2131. */
  2132. quarticOut: function (k) {
  2133. return 1 - (--k * k * k * k);
  2134. },
  2135. /**
  2136. * @param {number} k
  2137. * @return {number}
  2138. */
  2139. quarticInOut: function (k) {
  2140. if ((k *= 2) < 1) {
  2141. return 0.5 * k * k * k * k;
  2142. }
  2143. return -0.5 * ((k -= 2) * k * k * k - 2);
  2144. },
  2145. // 五次方的缓动(t^5)
  2146. /**
  2147. * @param {number} k
  2148. * @return {number}
  2149. */
  2150. quinticIn: function (k) {
  2151. return k * k * k * k * k;
  2152. },
  2153. /**
  2154. * @param {number} k
  2155. * @return {number}
  2156. */
  2157. quinticOut: function (k) {
  2158. return --k * k * k * k * k + 1;
  2159. },
  2160. /**
  2161. * @param {number} k
  2162. * @return {number}
  2163. */
  2164. quinticInOut: function (k) {
  2165. if ((k *= 2) < 1) {
  2166. return 0.5 * k * k * k * k * k;
  2167. }
  2168. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2169. },
  2170. // 正弦曲线的缓动(sin(t))
  2171. /**
  2172. * @param {number} k
  2173. * @return {number}
  2174. */
  2175. sinusoidalIn: function (k) {
  2176. return 1 - Math.cos(k * Math.PI / 2);
  2177. },
  2178. /**
  2179. * @param {number} k
  2180. * @return {number}
  2181. */
  2182. sinusoidalOut: function (k) {
  2183. return Math.sin(k * Math.PI / 2);
  2184. },
  2185. /**
  2186. * @param {number} k
  2187. * @return {number}
  2188. */
  2189. sinusoidalInOut: function (k) {
  2190. return 0.5 * (1 - Math.cos(Math.PI * k));
  2191. },
  2192. // 指数曲线的缓动(2^t)
  2193. /**
  2194. * @param {number} k
  2195. * @return {number}
  2196. */
  2197. exponentialIn: function (k) {
  2198. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2199. },
  2200. /**
  2201. * @param {number} k
  2202. * @return {number}
  2203. */
  2204. exponentialOut: function (k) {
  2205. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2206. },
  2207. /**
  2208. * @param {number} k
  2209. * @return {number}
  2210. */
  2211. exponentialInOut: function (k) {
  2212. if (k === 0) {
  2213. return 0;
  2214. }
  2215. if (k === 1) {
  2216. return 1;
  2217. }
  2218. if ((k *= 2) < 1) {
  2219. return 0.5 * Math.pow(1024, k - 1);
  2220. }
  2221. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2222. },
  2223. // 圆形曲线的缓动(sqrt(1-t^2))
  2224. /**
  2225. * @param {number} k
  2226. * @return {number}
  2227. */
  2228. circularIn: function (k) {
  2229. return 1 - Math.sqrt(1 - k * k);
  2230. },
  2231. /**
  2232. * @param {number} k
  2233. * @return {number}
  2234. */
  2235. circularOut: function (k) {
  2236. return Math.sqrt(1 - (--k * k));
  2237. },
  2238. /**
  2239. * @param {number} k
  2240. * @return {number}
  2241. */
  2242. circularInOut: function (k) {
  2243. if ((k *= 2) < 1) {
  2244. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2245. }
  2246. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2247. },
  2248. // 创建类似于弹簧在停止前来回振荡的动画
  2249. /**
  2250. * @param {number} k
  2251. * @return {number}
  2252. */
  2253. elasticIn: function (k) {
  2254. var s;
  2255. var a = 0.1;
  2256. var p = 0.4;
  2257. if (k === 0) {
  2258. return 0;
  2259. }
  2260. if (k === 1) {
  2261. return 1;
  2262. }
  2263. if (!a || a < 1) {
  2264. a = 1; s = p / 4;
  2265. }
  2266. else {
  2267. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2268. }
  2269. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2270. Math.sin((k - s) * (2 * Math.PI) / p));
  2271. },
  2272. /**
  2273. * @param {number} k
  2274. * @return {number}
  2275. */
  2276. elasticOut: function (k) {
  2277. var s;
  2278. var a = 0.1;
  2279. var p = 0.4;
  2280. if (k === 0) {
  2281. return 0;
  2282. }
  2283. if (k === 1) {
  2284. return 1;
  2285. }
  2286. if (!a || a < 1) {
  2287. a = 1; s = p / 4;
  2288. }
  2289. else {
  2290. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2291. }
  2292. return (a * Math.pow(2, -10 * k) *
  2293. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2294. },
  2295. /**
  2296. * @param {number} k
  2297. * @return {number}
  2298. */
  2299. elasticInOut: function (k) {
  2300. var s;
  2301. var a = 0.1;
  2302. var p = 0.4;
  2303. if (k === 0) {
  2304. return 0;
  2305. }
  2306. if (k === 1) {
  2307. return 1;
  2308. }
  2309. if (!a || a < 1) {
  2310. a = 1; s = p / 4;
  2311. }
  2312. else {
  2313. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2314. }
  2315. if ((k *= 2) < 1) {
  2316. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2317. * Math.sin((k - s) * (2 * Math.PI) / p));
  2318. }
  2319. return a * Math.pow(2, -10 * (k -= 1))
  2320. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2321. },
  2322. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2323. /**
  2324. * @param {number} k
  2325. * @return {number}
  2326. */
  2327. backIn: function (k) {
  2328. var s = 1.70158;
  2329. return k * k * ((s + 1) * k - s);
  2330. },
  2331. /**
  2332. * @param {number} k
  2333. * @return {number}
  2334. */
  2335. backOut: function (k) {
  2336. var s = 1.70158;
  2337. return --k * k * ((s + 1) * k + s) + 1;
  2338. },
  2339. /**
  2340. * @param {number} k
  2341. * @return {number}
  2342. */
  2343. backInOut: function (k) {
  2344. var s = 1.70158 * 1.525;
  2345. if ((k *= 2) < 1) {
  2346. return 0.5 * (k * k * ((s + 1) * k - s));
  2347. }
  2348. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2349. },
  2350. // 创建弹跳效果
  2351. /**
  2352. * @param {number} k
  2353. * @return {number}
  2354. */
  2355. bounceIn: function (k) {
  2356. return 1 - easing.bounceOut(1 - k);
  2357. },
  2358. /**
  2359. * @param {number} k
  2360. * @return {number}
  2361. */
  2362. bounceOut: function (k) {
  2363. if (k < (1 / 2.75)) {
  2364. return 7.5625 * k * k;
  2365. }
  2366. else if (k < (2 / 2.75)) {
  2367. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2368. }
  2369. else if (k < (2.5 / 2.75)) {
  2370. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2371. }
  2372. else {
  2373. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2374. }
  2375. },
  2376. /**
  2377. * @param {number} k
  2378. * @return {number}
  2379. */
  2380. bounceInOut: function (k) {
  2381. if (k < 0.5) {
  2382. return easing.bounceIn(k * 2) * 0.5;
  2383. }
  2384. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2385. }
  2386. };
  2387. /**
  2388. * 动画主控制器
  2389. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2390. * @config life(1000) 动画时长
  2391. * @config delay(0) 动画延迟时间
  2392. * @config loop(true)
  2393. * @config gap(0) 循环的间隔时间
  2394. * @config onframe
  2395. * @config easing(optional)
  2396. * @config ondestroy(optional)
  2397. * @config onrestart(optional)
  2398. *
  2399. * TODO pause
  2400. */
  2401. function Clip(options) {
  2402. this._target = options.target;
  2403. // 生命周期
  2404. this._life = options.life || 1000;
  2405. // 延时
  2406. this._delay = options.delay || 0;
  2407. // 开始时间
  2408. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2409. this._initialized = false;
  2410. // 是否循环
  2411. this.loop = options.loop == null ? false : options.loop;
  2412. this.gap = options.gap || 0;
  2413. this.easing = options.easing || 'Linear';
  2414. this.onframe = options.onframe;
  2415. this.ondestroy = options.ondestroy;
  2416. this.onrestart = options.onrestart;
  2417. this._pausedTime = 0;
  2418. this._paused = false;
  2419. }
  2420. Clip.prototype = {
  2421. constructor: Clip,
  2422. step: function (globalTime, deltaTime) {
  2423. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2424. // PENDING
  2425. if (!this._initialized) {
  2426. this._startTime = globalTime + this._delay;
  2427. this._initialized = true;
  2428. }
  2429. if (this._paused) {
  2430. this._pausedTime += deltaTime;
  2431. return;
  2432. }
  2433. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2434. // 还没开始
  2435. if (percent < 0) {
  2436. return;
  2437. }
  2438. percent = Math.min(percent, 1);
  2439. var easing$$1 = this.easing;
  2440. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2441. var schedule = typeof easingFunc === 'function'
  2442. ? easingFunc(percent)
  2443. : percent;
  2444. this.fire('frame', schedule);
  2445. // 结束
  2446. if (percent == 1) {
  2447. if (this.loop) {
  2448. this.restart (globalTime);
  2449. // 重新开始周期
  2450. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2451. return 'restart';
  2452. }
  2453. // 动画完成将这个控制器标识为待删除
  2454. // 在Animation.update中进行批量删除
  2455. this._needsRemove = true;
  2456. return 'destroy';
  2457. }
  2458. return null;
  2459. },
  2460. restart: function (globalTime) {
  2461. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2462. this._startTime = globalTime - remainder + this.gap;
  2463. this._pausedTime = 0;
  2464. this._needsRemove = false;
  2465. },
  2466. fire: function (eventType, arg) {
  2467. eventType = 'on' + eventType;
  2468. if (this[eventType]) {
  2469. this[eventType](this._target, arg);
  2470. }
  2471. },
  2472. pause: function () {
  2473. this._paused = true;
  2474. },
  2475. resume: function () {
  2476. this._paused = false;
  2477. }
  2478. };
  2479. // Simple LRU cache use doubly linked list
  2480. // @module zrender/core/LRU
  2481. /**
  2482. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2483. * @constructor
  2484. */
  2485. var LinkedList = function () {
  2486. /**
  2487. * @type {module:zrender/core/LRU~Entry}
  2488. */
  2489. this.head = null;
  2490. /**
  2491. * @type {module:zrender/core/LRU~Entry}
  2492. */
  2493. this.tail = null;
  2494. this._len = 0;
  2495. };
  2496. var linkedListProto = LinkedList.prototype;
  2497. /**
  2498. * Insert a new value at the tail
  2499. * @param {} val
  2500. * @return {module:zrender/core/LRU~Entry}
  2501. */
  2502. linkedListProto.insert = function (val) {
  2503. var entry = new Entry(val);
  2504. this.insertEntry(entry);
  2505. return entry;
  2506. };
  2507. /**
  2508. * Insert an entry at the tail
  2509. * @param {module:zrender/core/LRU~Entry} entry
  2510. */
  2511. linkedListProto.insertEntry = function (entry) {
  2512. if (!this.head) {
  2513. this.head = this.tail = entry;
  2514. }
  2515. else {
  2516. this.tail.next = entry;
  2517. entry.prev = this.tail;
  2518. entry.next = null;
  2519. this.tail = entry;
  2520. }
  2521. this._len++;
  2522. };
  2523. /**
  2524. * Remove entry.
  2525. * @param {module:zrender/core/LRU~Entry} entry
  2526. */
  2527. linkedListProto.remove = function (entry) {
  2528. var prev = entry.prev;
  2529. var next = entry.next;
  2530. if (prev) {
  2531. prev.next = next;
  2532. }
  2533. else {
  2534. // Is head
  2535. this.head = next;
  2536. }
  2537. if (next) {
  2538. next.prev = prev;
  2539. }
  2540. else {
  2541. // Is tail
  2542. this.tail = prev;
  2543. }
  2544. entry.next = entry.prev = null;
  2545. this._len--;
  2546. };
  2547. /**
  2548. * @return {number}
  2549. */
  2550. linkedListProto.len = function () {
  2551. return this._len;
  2552. };
  2553. /**
  2554. * Clear list
  2555. */
  2556. linkedListProto.clear = function () {
  2557. this.head = this.tail = null;
  2558. this._len = 0;
  2559. };
  2560. /**
  2561. * @constructor
  2562. * @param {} val
  2563. */
  2564. var Entry = function (val) {
  2565. /**
  2566. * @type {}
  2567. */
  2568. this.value = val;
  2569. /**
  2570. * @type {module:zrender/core/LRU~Entry}
  2571. */
  2572. this.next;
  2573. /**
  2574. * @type {module:zrender/core/LRU~Entry}
  2575. */
  2576. this.prev;
  2577. };
  2578. /**
  2579. * LRU Cache
  2580. * @constructor
  2581. * @alias module:zrender/core/LRU
  2582. */
  2583. var LRU = function (maxSize) {
  2584. this._list = new LinkedList();
  2585. this._map = {};
  2586. this._maxSize = maxSize || 10;
  2587. this._lastRemovedEntry = null;
  2588. };
  2589. var LRUProto = LRU.prototype;
  2590. /**
  2591. * @param {string} key
  2592. * @param {} value
  2593. * @return {} Removed value
  2594. */
  2595. LRUProto.put = function (key, value) {
  2596. var list = this._list;
  2597. var map = this._map;
  2598. var removed = null;
  2599. if (map[key] == null) {
  2600. var len = list.len();
  2601. // Reuse last removed entry
  2602. var entry = this._lastRemovedEntry;
  2603. if (len >= this._maxSize && len > 0) {
  2604. // Remove the least recently used
  2605. var leastUsedEntry = list.head;
  2606. list.remove(leastUsedEntry);
  2607. delete map[leastUsedEntry.key];
  2608. removed = leastUsedEntry.value;
  2609. this._lastRemovedEntry = leastUsedEntry;
  2610. }
  2611. if (entry) {
  2612. entry.value = value;
  2613. }
  2614. else {
  2615. entry = new Entry(value);
  2616. }
  2617. entry.key = key;
  2618. list.insertEntry(entry);
  2619. map[key] = entry;
  2620. }
  2621. return removed;
  2622. };
  2623. /**
  2624. * @param {string} key
  2625. * @return {}
  2626. */
  2627. LRUProto.get = function (key) {
  2628. var entry = this._map[key];
  2629. var list = this._list;
  2630. if (entry != null) {
  2631. // Put the latest used entry in the tail
  2632. if (entry !== list.tail) {
  2633. list.remove(entry);
  2634. list.insertEntry(entry);
  2635. }
  2636. return entry.value;
  2637. }
  2638. };
  2639. /**
  2640. * Clear the cache
  2641. */
  2642. LRUProto.clear = function () {
  2643. this._list.clear();
  2644. this._map = {};
  2645. };
  2646. var kCSSColorTable = {
  2647. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2648. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2649. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2650. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2651. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2652. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2653. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2654. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2655. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2656. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2657. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2658. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2659. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2660. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2661. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2662. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2663. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2664. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2665. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2666. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2667. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2668. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2669. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2670. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2671. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2672. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2673. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2674. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2675. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2676. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2677. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2678. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2679. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2680. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2681. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2682. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2683. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2684. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2685. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2686. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2687. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2688. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2689. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2690. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2691. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2692. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2693. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2694. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2695. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2696. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2697. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2698. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2699. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2700. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2701. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2702. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2703. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2704. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2705. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2706. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2707. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2708. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2709. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2710. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2711. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2712. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2713. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2714. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2715. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2716. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2717. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2718. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2719. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2720. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2721. };
  2722. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2723. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2724. return i < 0 ? 0 : i > 255 ? 255 : i;
  2725. }
  2726. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2727. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2728. return i < 0 ? 0 : i > 360 ? 360 : i;
  2729. }
  2730. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2731. return f < 0 ? 0 : f > 1 ? 1 : f;
  2732. }
  2733. function parseCssInt(str) { // int or percentage.
  2734. if (str.length && str.charAt(str.length - 1) === '%') {
  2735. return clampCssByte(parseFloat(str) / 100 * 255);
  2736. }
  2737. return clampCssByte(parseInt(str, 10));
  2738. }
  2739. function parseCssFloat(str) { // float or percentage.
  2740. if (str.length && str.charAt(str.length - 1) === '%') {
  2741. return clampCssFloat(parseFloat(str) / 100);
  2742. }
  2743. return clampCssFloat(parseFloat(str));
  2744. }
  2745. function cssHueToRgb(m1, m2, h) {
  2746. if (h < 0) {
  2747. h += 1;
  2748. }
  2749. else if (h > 1) {
  2750. h -= 1;
  2751. }
  2752. if (h * 6 < 1) {
  2753. return m1 + (m2 - m1) * h * 6;
  2754. }
  2755. if (h * 2 < 1) {
  2756. return m2;
  2757. }
  2758. if (h * 3 < 2) {
  2759. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2760. }
  2761. return m1;
  2762. }
  2763. function lerpNumber(a, b, p) {
  2764. return a + (b - a) * p;
  2765. }
  2766. function setRgba(out, r, g, b, a) {
  2767. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2768. return out;
  2769. }
  2770. function copyRgba(out, a) {
  2771. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2772. return out;
  2773. }
  2774. var colorCache = new LRU(20);
  2775. var lastRemovedArr = null;
  2776. function putToCache(colorStr, rgbaArr) {
  2777. // Reuse removed array
  2778. if (lastRemovedArr) {
  2779. copyRgba(lastRemovedArr, rgbaArr);
  2780. }
  2781. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2782. }
  2783. /**
  2784. * @param {string} colorStr
  2785. * @param {Array.<number>} out
  2786. * @return {Array.<number>}
  2787. * @memberOf module:zrender/util/color
  2788. */
  2789. function parse(colorStr, rgbaArr) {
  2790. if (!colorStr) {
  2791. return;
  2792. }
  2793. rgbaArr = rgbaArr || [];
  2794. var cached = colorCache.get(colorStr);
  2795. if (cached) {
  2796. return copyRgba(rgbaArr, cached);
  2797. }
  2798. // colorStr may be not string
  2799. colorStr = colorStr + '';
  2800. // Remove all whitespace, not compliant, but should just be more accepting.
  2801. var str = colorStr.replace(/ /g, '').toLowerCase();
  2802. // Color keywords (and transparent) lookup.
  2803. if (str in kCSSColorTable) {
  2804. copyRgba(rgbaArr, kCSSColorTable[str]);
  2805. putToCache(colorStr, rgbaArr);
  2806. return rgbaArr;
  2807. }
  2808. // #abc and #abc123 syntax.
  2809. if (str.charAt(0) === '#') {
  2810. if (str.length === 4) {
  2811. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2812. if (!(iv >= 0 && iv <= 0xfff)) {
  2813. setRgba(rgbaArr, 0, 0, 0, 1);
  2814. return; // Covers NaN.
  2815. }
  2816. setRgba(rgbaArr,
  2817. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2818. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2819. (iv & 0xf) | ((iv & 0xf) << 4),
  2820. 1
  2821. );
  2822. putToCache(colorStr, rgbaArr);
  2823. return rgbaArr;
  2824. }
  2825. else if (str.length === 7) {
  2826. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2827. if (!(iv >= 0 && iv <= 0xffffff)) {
  2828. setRgba(rgbaArr, 0, 0, 0, 1);
  2829. return; // Covers NaN.
  2830. }
  2831. setRgba(rgbaArr,
  2832. (iv & 0xff0000) >> 16,
  2833. (iv & 0xff00) >> 8,
  2834. iv & 0xff,
  2835. 1
  2836. );
  2837. putToCache(colorStr, rgbaArr);
  2838. return rgbaArr;
  2839. }
  2840. return;
  2841. }
  2842. var op = str.indexOf('('), ep = str.indexOf(')');
  2843. if (op !== -1 && ep + 1 === str.length) {
  2844. var fname = str.substr(0, op);
  2845. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2846. var alpha = 1; // To allow case fallthrough.
  2847. switch (fname) {
  2848. case 'rgba':
  2849. if (params.length !== 4) {
  2850. setRgba(rgbaArr, 0, 0, 0, 1);
  2851. return;
  2852. }
  2853. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2854. // Fall through.
  2855. case 'rgb':
  2856. if (params.length !== 3) {
  2857. setRgba(rgbaArr, 0, 0, 0, 1);
  2858. return;
  2859. }
  2860. setRgba(rgbaArr,
  2861. parseCssInt(params[0]),
  2862. parseCssInt(params[1]),
  2863. parseCssInt(params[2]),
  2864. alpha
  2865. );
  2866. putToCache(colorStr, rgbaArr);
  2867. return rgbaArr;
  2868. case 'hsla':
  2869. if (params.length !== 4) {
  2870. setRgba(rgbaArr, 0, 0, 0, 1);
  2871. return;
  2872. }
  2873. params[3] = parseCssFloat(params[3]);
  2874. hsla2rgba(params, rgbaArr);
  2875. putToCache(colorStr, rgbaArr);
  2876. return rgbaArr;
  2877. case 'hsl':
  2878. if (params.length !== 3) {
  2879. setRgba(rgbaArr, 0, 0, 0, 1);
  2880. return;
  2881. }
  2882. hsla2rgba(params, rgbaArr);
  2883. putToCache(colorStr, rgbaArr);
  2884. return rgbaArr;
  2885. default:
  2886. return;
  2887. }
  2888. }
  2889. setRgba(rgbaArr, 0, 0, 0, 1);
  2890. return;
  2891. }
  2892. /**
  2893. * @param {Array.<number>} hsla
  2894. * @param {Array.<number>} rgba
  2895. * @return {Array.<number>} rgba
  2896. */
  2897. function hsla2rgba(hsla, rgba) {
  2898. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2899. // NOTE(deanm): According to the CSS spec s/l should only be
  2900. // percentages, but we don't bother and let float or percentage.
  2901. var s = parseCssFloat(hsla[1]);
  2902. var l = parseCssFloat(hsla[2]);
  2903. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2904. var m1 = l * 2 - m2;
  2905. rgba = rgba || [];
  2906. setRgba(rgba,
  2907. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2908. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2909. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2910. 1
  2911. );
  2912. if (hsla.length === 4) {
  2913. rgba[3] = hsla[3];
  2914. }
  2915. return rgba;
  2916. }
  2917. /**
  2918. * @param {Array.<number>} rgba
  2919. * @return {Array.<number>} hsla
  2920. */
  2921. function rgba2hsla(rgba) {
  2922. if (!rgba) {
  2923. return;
  2924. }
  2925. // RGB from 0 to 255
  2926. var R = rgba[0] / 255;
  2927. var G = rgba[1] / 255;
  2928. var B = rgba[2] / 255;
  2929. var vMin = Math.min(R, G, B); // Min. value of RGB
  2930. var vMax = Math.max(R, G, B); // Max. value of RGB
  2931. var delta = vMax - vMin; // Delta RGB value
  2932. var L = (vMax + vMin) / 2;
  2933. var H;
  2934. var S;
  2935. // HSL results from 0 to 1
  2936. if (delta === 0) {
  2937. H = 0;
  2938. S = 0;
  2939. }
  2940. else {
  2941. if (L < 0.5) {
  2942. S = delta / (vMax + vMin);
  2943. }
  2944. else {
  2945. S = delta / (2 - vMax - vMin);
  2946. }
  2947. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2948. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2949. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2950. if (R === vMax) {
  2951. H = deltaB - deltaG;
  2952. }
  2953. else if (G === vMax) {
  2954. H = (1 / 3) + deltaR - deltaB;
  2955. }
  2956. else if (B === vMax) {
  2957. H = (2 / 3) + deltaG - deltaR;
  2958. }
  2959. if (H < 0) {
  2960. H += 1;
  2961. }
  2962. if (H > 1) {
  2963. H -= 1;
  2964. }
  2965. }
  2966. var hsla = [H * 360, S, L];
  2967. if (rgba[3] != null) {
  2968. hsla.push(rgba[3]);
  2969. }
  2970. return hsla;
  2971. }
  2972. /**
  2973. * @param {string} color
  2974. * @param {number} level
  2975. * @return {string}
  2976. * @memberOf module:zrender/util/color
  2977. */
  2978. function lift(color, level) {
  2979. var colorArr = parse(color);
  2980. if (colorArr) {
  2981. for (var i = 0; i < 3; i++) {
  2982. if (level < 0) {
  2983. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2984. }
  2985. else {
  2986. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2987. }
  2988. if (colorArr[i] > 255) {
  2989. colorArr[i] = 255;
  2990. }
  2991. else if (color[i] < 0) {
  2992. colorArr[i] = 0;
  2993. }
  2994. }
  2995. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2996. }
  2997. }
  2998. /**
  2999. * @param {string} color
  3000. * @return {string}
  3001. * @memberOf module:zrender/util/color
  3002. */
  3003. function toHex(color) {
  3004. var colorArr = parse(color);
  3005. if (colorArr) {
  3006. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3007. }
  3008. }
  3009. /**
  3010. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3011. * @param {number} normalizedValue A float between 0 and 1.
  3012. * @param {Array.<Array.<number>>} colors List of rgba color array
  3013. * @param {Array.<number>} [out] Mapped gba color array
  3014. * @return {Array.<number>} will be null/undefined if input illegal.
  3015. */
  3016. function fastLerp(normalizedValue, colors, out) {
  3017. if (!(colors && colors.length)
  3018. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3019. ) {
  3020. return;
  3021. }
  3022. out = out || [];
  3023. var value = normalizedValue * (colors.length - 1);
  3024. var leftIndex = Math.floor(value);
  3025. var rightIndex = Math.ceil(value);
  3026. var leftColor = colors[leftIndex];
  3027. var rightColor = colors[rightIndex];
  3028. var dv = value - leftIndex;
  3029. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3030. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3031. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3032. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3033. return out;
  3034. }
  3035. /**
  3036. * @deprecated
  3037. */
  3038. var fastMapToColor = fastLerp;
  3039. /**
  3040. * @param {number} normalizedValue A float between 0 and 1.
  3041. * @param {Array.<string>} colors Color list.
  3042. * @param {boolean=} fullOutput Default false.
  3043. * @return {(string|Object)} Result color. If fullOutput,
  3044. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3045. * @memberOf module:zrender/util/color
  3046. */
  3047. function lerp$1(normalizedValue, colors, fullOutput) {
  3048. if (!(colors && colors.length)
  3049. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3050. ) {
  3051. return;
  3052. }
  3053. var value = normalizedValue * (colors.length - 1);
  3054. var leftIndex = Math.floor(value);
  3055. var rightIndex = Math.ceil(value);
  3056. var leftColor = parse(colors[leftIndex]);
  3057. var rightColor = parse(colors[rightIndex]);
  3058. var dv = value - leftIndex;
  3059. var color = stringify(
  3060. [
  3061. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3062. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3063. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3064. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3065. ],
  3066. 'rgba'
  3067. );
  3068. return fullOutput
  3069. ? {
  3070. color: color,
  3071. leftIndex: leftIndex,
  3072. rightIndex: rightIndex,
  3073. value: value
  3074. }
  3075. : color;
  3076. }
  3077. /**
  3078. * @deprecated
  3079. */
  3080. var mapToColor = lerp$1;
  3081. /**
  3082. * @param {string} color
  3083. * @param {number=} h 0 ~ 360, ignore when null.
  3084. * @param {number=} s 0 ~ 1, ignore when null.
  3085. * @param {number=} l 0 ~ 1, ignore when null.
  3086. * @return {string} Color string in rgba format.
  3087. * @memberOf module:zrender/util/color
  3088. */
  3089. function modifyHSL(color, h, s, l) {
  3090. color = parse(color);
  3091. if (color) {
  3092. color = rgba2hsla(color);
  3093. h != null && (color[0] = clampCssAngle(h));
  3094. s != null && (color[1] = parseCssFloat(s));
  3095. l != null && (color[2] = parseCssFloat(l));
  3096. return stringify(hsla2rgba(color), 'rgba');
  3097. }
  3098. }
  3099. /**
  3100. * @param {string} color
  3101. * @param {number=} alpha 0 ~ 1
  3102. * @return {string} Color string in rgba format.
  3103. * @memberOf module:zrender/util/color
  3104. */
  3105. function modifyAlpha(color, alpha) {
  3106. color = parse(color);
  3107. if (color && alpha != null) {
  3108. color[3] = clampCssFloat(alpha);
  3109. return stringify(color, 'rgba');
  3110. }
  3111. }
  3112. /**
  3113. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3114. * @param {string} type 'rgba', 'hsva', ...
  3115. * @return {string} Result color. (If input illegal, return undefined).
  3116. */
  3117. function stringify(arrColor, type) {
  3118. if (!arrColor || !arrColor.length) {
  3119. return;
  3120. }
  3121. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3122. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3123. colorStr += ',' + arrColor[3];
  3124. }
  3125. return type + '(' + colorStr + ')';
  3126. }
  3127. var color = (Object.freeze || Object)({
  3128. parse: parse,
  3129. lift: lift,
  3130. toHex: toHex,
  3131. fastLerp: fastLerp,
  3132. fastMapToColor: fastMapToColor,
  3133. lerp: lerp$1,
  3134. mapToColor: mapToColor,
  3135. modifyHSL: modifyHSL,
  3136. modifyAlpha: modifyAlpha,
  3137. stringify: stringify
  3138. });
  3139. /**
  3140. * @module echarts/animation/Animator
  3141. */
  3142. var arraySlice = Array.prototype.slice;
  3143. function defaultGetter(target, key) {
  3144. return target[key];
  3145. }
  3146. function defaultSetter(target, key, value) {
  3147. target[key] = value;
  3148. }
  3149. /**
  3150. * @param {number} p0
  3151. * @param {number} p1
  3152. * @param {number} percent
  3153. * @return {number}
  3154. */
  3155. function interpolateNumber(p0, p1, percent) {
  3156. return (p1 - p0) * percent + p0;
  3157. }
  3158. /**
  3159. * @param {string} p0
  3160. * @param {string} p1
  3161. * @param {number} percent
  3162. * @return {string}
  3163. */
  3164. function interpolateString(p0, p1, percent) {
  3165. return percent > 0.5 ? p1 : p0;
  3166. }
  3167. /**
  3168. * @param {Array} p0
  3169. * @param {Array} p1
  3170. * @param {number} percent
  3171. * @param {Array} out
  3172. * @param {number} arrDim
  3173. */
  3174. function interpolateArray(p0, p1, percent, out, arrDim) {
  3175. var len = p0.length;
  3176. if (arrDim == 1) {
  3177. for (var i = 0; i < len; i++) {
  3178. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3179. }
  3180. }
  3181. else {
  3182. var len2 = len && p0[0].length;
  3183. for (var i = 0; i < len; i++) {
  3184. for (var j = 0; j < len2; j++) {
  3185. out[i][j] = interpolateNumber(
  3186. p0[i][j], p1[i][j], percent
  3187. );
  3188. }
  3189. }
  3190. }
  3191. }
  3192. // arr0 is source array, arr1 is target array.
  3193. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3194. function fillArr(arr0, arr1, arrDim) {
  3195. var arr0Len = arr0.length;
  3196. var arr1Len = arr1.length;
  3197. if (arr0Len !== arr1Len) {
  3198. // FIXME Not work for TypedArray
  3199. var isPreviousLarger = arr0Len > arr1Len;
  3200. if (isPreviousLarger) {
  3201. // Cut the previous
  3202. arr0.length = arr1Len;
  3203. }
  3204. else {
  3205. // Fill the previous
  3206. for (var i = arr0Len; i < arr1Len; i++) {
  3207. arr0.push(
  3208. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3209. );
  3210. }
  3211. }
  3212. }
  3213. // Handling NaN value
  3214. var len2 = arr0[0] && arr0[0].length;
  3215. for (var i = 0; i < arr0.length; i++) {
  3216. if (arrDim === 1) {
  3217. if (isNaN(arr0[i])) {
  3218. arr0[i] = arr1[i];
  3219. }
  3220. }
  3221. else {
  3222. for (var j = 0; j < len2; j++) {
  3223. if (isNaN(arr0[i][j])) {
  3224. arr0[i][j] = arr1[i][j];
  3225. }
  3226. }
  3227. }
  3228. }
  3229. }
  3230. /**
  3231. * @param {Array} arr0
  3232. * @param {Array} arr1
  3233. * @param {number} arrDim
  3234. * @return {boolean}
  3235. */
  3236. function isArraySame(arr0, arr1, arrDim) {
  3237. if (arr0 === arr1) {
  3238. return true;
  3239. }
  3240. var len = arr0.length;
  3241. if (len !== arr1.length) {
  3242. return false;
  3243. }
  3244. if (arrDim === 1) {
  3245. for (var i = 0; i < len; i++) {
  3246. if (arr0[i] !== arr1[i]) {
  3247. return false;
  3248. }
  3249. }
  3250. }
  3251. else {
  3252. var len2 = arr0[0].length;
  3253. for (var i = 0; i < len; i++) {
  3254. for (var j = 0; j < len2; j++) {
  3255. if (arr0[i][j] !== arr1[i][j]) {
  3256. return false;
  3257. }
  3258. }
  3259. }
  3260. }
  3261. return true;
  3262. }
  3263. /**
  3264. * Catmull Rom interpolate array
  3265. * @param {Array} p0
  3266. * @param {Array} p1
  3267. * @param {Array} p2
  3268. * @param {Array} p3
  3269. * @param {number} t
  3270. * @param {number} t2
  3271. * @param {number} t3
  3272. * @param {Array} out
  3273. * @param {number} arrDim
  3274. */
  3275. function catmullRomInterpolateArray(
  3276. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3277. ) {
  3278. var len = p0.length;
  3279. if (arrDim == 1) {
  3280. for (var i = 0; i < len; i++) {
  3281. out[i] = catmullRomInterpolate(
  3282. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3283. );
  3284. }
  3285. }
  3286. else {
  3287. var len2 = p0[0].length;
  3288. for (var i = 0; i < len; i++) {
  3289. for (var j = 0; j < len2; j++) {
  3290. out[i][j] = catmullRomInterpolate(
  3291. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3292. t, t2, t3
  3293. );
  3294. }
  3295. }
  3296. }
  3297. }
  3298. /**
  3299. * Catmull Rom interpolate number
  3300. * @param {number} p0
  3301. * @param {number} p1
  3302. * @param {number} p2
  3303. * @param {number} p3
  3304. * @param {number} t
  3305. * @param {number} t2
  3306. * @param {number} t3
  3307. * @return {number}
  3308. */
  3309. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3310. var v0 = (p2 - p0) * 0.5;
  3311. var v1 = (p3 - p1) * 0.5;
  3312. return (2 * (p1 - p2) + v0 + v1) * t3
  3313. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3314. + v0 * t + p1;
  3315. }
  3316. function cloneValue(value) {
  3317. if (isArrayLike(value)) {
  3318. var len = value.length;
  3319. if (isArrayLike(value[0])) {
  3320. var ret = [];
  3321. for (var i = 0; i < len; i++) {
  3322. ret.push(arraySlice.call(value[i]));
  3323. }
  3324. return ret;
  3325. }
  3326. return arraySlice.call(value);
  3327. }
  3328. return value;
  3329. }
  3330. function rgba2String(rgba) {
  3331. rgba[0] = Math.floor(rgba[0]);
  3332. rgba[1] = Math.floor(rgba[1]);
  3333. rgba[2] = Math.floor(rgba[2]);
  3334. return 'rgba(' + rgba.join(',') + ')';
  3335. }
  3336. function getArrayDim(keyframes) {
  3337. var lastValue = keyframes[keyframes.length - 1].value;
  3338. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3339. }
  3340. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3341. var getter = animator._getter;
  3342. var setter = animator._setter;
  3343. var useSpline = easing === 'spline';
  3344. var trackLen = keyframes.length;
  3345. if (!trackLen) {
  3346. return;
  3347. }
  3348. // Guess data type
  3349. var firstVal = keyframes[0].value;
  3350. var isValueArray = isArrayLike(firstVal);
  3351. var isValueColor = false;
  3352. var isValueString = false;
  3353. // For vertices morphing
  3354. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3355. var trackMaxTime;
  3356. // Sort keyframe as ascending
  3357. keyframes.sort(function(a, b) {
  3358. return a.time - b.time;
  3359. });
  3360. trackMaxTime = keyframes[trackLen - 1].time;
  3361. // Percents of each keyframe
  3362. var kfPercents = [];
  3363. // Value of each keyframe
  3364. var kfValues = [];
  3365. var prevValue = keyframes[0].value;
  3366. var isAllValueEqual = true;
  3367. for (var i = 0; i < trackLen; i++) {
  3368. kfPercents.push(keyframes[i].time / trackMaxTime);
  3369. // Assume value is a color when it is a string
  3370. var value = keyframes[i].value;
  3371. // Check if value is equal, deep check if value is array
  3372. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3373. || (!isValueArray && value === prevValue))) {
  3374. isAllValueEqual = false;
  3375. }
  3376. prevValue = value;
  3377. // Try converting a string to a color array
  3378. if (typeof value == 'string') {
  3379. var colorArray = parse(value);
  3380. if (colorArray) {
  3381. value = colorArray;
  3382. isValueColor = true;
  3383. }
  3384. else {
  3385. isValueString = true;
  3386. }
  3387. }
  3388. kfValues.push(value);
  3389. }
  3390. if (!forceAnimate && isAllValueEqual) {
  3391. return;
  3392. }
  3393. var lastValue = kfValues[trackLen - 1];
  3394. // Polyfill array and NaN value
  3395. for (var i = 0; i < trackLen - 1; i++) {
  3396. if (isValueArray) {
  3397. fillArr(kfValues[i], lastValue, arrDim);
  3398. }
  3399. else {
  3400. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3401. kfValues[i] = lastValue;
  3402. }
  3403. }
  3404. }
  3405. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3406. // Cache the key of last frame to speed up when
  3407. // animation playback is sequency
  3408. var lastFrame = 0;
  3409. var lastFramePercent = 0;
  3410. var start;
  3411. var w;
  3412. var p0;
  3413. var p1;
  3414. var p2;
  3415. var p3;
  3416. if (isValueColor) {
  3417. var rgba = [0, 0, 0, 0];
  3418. }
  3419. var onframe = function (target, percent) {
  3420. // Find the range keyframes
  3421. // kf1-----kf2---------current--------kf3
  3422. // find kf2 and kf3 and do interpolation
  3423. var frame;
  3424. // In the easing function like elasticOut, percent may less than 0
  3425. if (percent < 0) {
  3426. frame = 0;
  3427. }
  3428. else if (percent < lastFramePercent) {
  3429. // Start from next key
  3430. // PENDING start from lastFrame ?
  3431. start = Math.min(lastFrame + 1, trackLen - 1);
  3432. for (frame = start; frame >= 0; frame--) {
  3433. if (kfPercents[frame] <= percent) {
  3434. break;
  3435. }
  3436. }
  3437. // PENDING really need to do this ?
  3438. frame = Math.min(frame, trackLen - 2);
  3439. }
  3440. else {
  3441. for (frame = lastFrame; frame < trackLen; frame++) {
  3442. if (kfPercents[frame] > percent) {
  3443. break;
  3444. }
  3445. }
  3446. frame = Math.min(frame - 1, trackLen - 2);
  3447. }
  3448. lastFrame = frame;
  3449. lastFramePercent = percent;
  3450. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3451. if (range === 0) {
  3452. return;
  3453. }
  3454. else {
  3455. w = (percent - kfPercents[frame]) / range;
  3456. }
  3457. if (useSpline) {
  3458. p1 = kfValues[frame];
  3459. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3460. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3461. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3462. if (isValueArray) {
  3463. catmullRomInterpolateArray(
  3464. p0, p1, p2, p3, w, w * w, w * w * w,
  3465. getter(target, propName),
  3466. arrDim
  3467. );
  3468. }
  3469. else {
  3470. var value;
  3471. if (isValueColor) {
  3472. value = catmullRomInterpolateArray(
  3473. p0, p1, p2, p3, w, w * w, w * w * w,
  3474. rgba, 1
  3475. );
  3476. value = rgba2String(rgba);
  3477. }
  3478. else if (isValueString) {
  3479. // String is step(0.5)
  3480. return interpolateString(p1, p2, w);
  3481. }
  3482. else {
  3483. value = catmullRomInterpolate(
  3484. p0, p1, p2, p3, w, w * w, w * w * w
  3485. );
  3486. }
  3487. setter(
  3488. target,
  3489. propName,
  3490. value
  3491. );
  3492. }
  3493. }
  3494. else {
  3495. if (isValueArray) {
  3496. interpolateArray(
  3497. kfValues[frame], kfValues[frame + 1], w,
  3498. getter(target, propName),
  3499. arrDim
  3500. );
  3501. }
  3502. else {
  3503. var value;
  3504. if (isValueColor) {
  3505. interpolateArray(
  3506. kfValues[frame], kfValues[frame + 1], w,
  3507. rgba, 1
  3508. );
  3509. value = rgba2String(rgba);
  3510. }
  3511. else if (isValueString) {
  3512. // String is step(0.5)
  3513. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3514. }
  3515. else {
  3516. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3517. }
  3518. setter(
  3519. target,
  3520. propName,
  3521. value
  3522. );
  3523. }
  3524. }
  3525. };
  3526. var clip = new Clip({
  3527. target: animator._target,
  3528. life: trackMaxTime,
  3529. loop: animator._loop,
  3530. delay: animator._delay,
  3531. onframe: onframe,
  3532. ondestroy: oneTrackDone
  3533. });
  3534. if (easing && easing !== 'spline') {
  3535. clip.easing = easing;
  3536. }
  3537. return clip;
  3538. }
  3539. /**
  3540. * @alias module:zrender/animation/Animator
  3541. * @constructor
  3542. * @param {Object} target
  3543. * @param {boolean} loop
  3544. * @param {Function} getter
  3545. * @param {Function} setter
  3546. */
  3547. var Animator = function(target, loop, getter, setter) {
  3548. this._tracks = {};
  3549. this._target = target;
  3550. this._loop = loop || false;
  3551. this._getter = getter || defaultGetter;
  3552. this._setter = setter || defaultSetter;
  3553. this._clipCount = 0;
  3554. this._delay = 0;
  3555. this._doneList = [];
  3556. this._onframeList = [];
  3557. this._clipList = [];
  3558. };
  3559. Animator.prototype = {
  3560. /**
  3561. * 设置动画关键帧
  3562. * @param {number} time 关键帧时间,单位是ms
  3563. * @param {Object} props 关键帧的属性值,key-value表示
  3564. * @return {module:zrender/animation/Animator}
  3565. */
  3566. when: function(time /* ms */, props) {
  3567. var tracks = this._tracks;
  3568. for (var propName in props) {
  3569. if (!props.hasOwnProperty(propName)) {
  3570. continue;
  3571. }
  3572. if (!tracks[propName]) {
  3573. tracks[propName] = [];
  3574. // Invalid value
  3575. var value = this._getter(this._target, propName);
  3576. if (value == null) {
  3577. // zrLog('Invalid property ' + propName);
  3578. continue;
  3579. }
  3580. // If time is 0
  3581. // Then props is given initialize value
  3582. // Else
  3583. // Initialize value from current prop value
  3584. if (time !== 0) {
  3585. tracks[propName].push({
  3586. time: 0,
  3587. value: cloneValue(value)
  3588. });
  3589. }
  3590. }
  3591. tracks[propName].push({
  3592. time: time,
  3593. value: props[propName]
  3594. });
  3595. }
  3596. return this;
  3597. },
  3598. /**
  3599. * 添加动画每一帧的回调函数
  3600. * @param {Function} callback
  3601. * @return {module:zrender/animation/Animator}
  3602. */
  3603. during: function (callback) {
  3604. this._onframeList.push(callback);
  3605. return this;
  3606. },
  3607. pause: function () {
  3608. for (var i = 0; i < this._clipList.length; i++) {
  3609. this._clipList[i].pause();
  3610. }
  3611. this._paused = true;
  3612. },
  3613. resume: function () {
  3614. for (var i = 0; i < this._clipList.length; i++) {
  3615. this._clipList[i].resume();
  3616. }
  3617. this._paused = false;
  3618. },
  3619. isPaused: function () {
  3620. return !!this._paused;
  3621. },
  3622. _doneCallback: function () {
  3623. // Clear all tracks
  3624. this._tracks = {};
  3625. // Clear all clips
  3626. this._clipList.length = 0;
  3627. var doneList = this._doneList;
  3628. var len = doneList.length;
  3629. for (var i = 0; i < len; i++) {
  3630. doneList[i].call(this);
  3631. }
  3632. },
  3633. /**
  3634. * 开始执行动画
  3635. * @param {string|Function} [easing]
  3636. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3637. * @param {boolean} forceAnimate
  3638. * @return {module:zrender/animation/Animator}
  3639. */
  3640. start: function (easing, forceAnimate) {
  3641. var self = this;
  3642. var clipCount = 0;
  3643. var oneTrackDone = function() {
  3644. clipCount--;
  3645. if (!clipCount) {
  3646. self._doneCallback();
  3647. }
  3648. };
  3649. var lastClip;
  3650. for (var propName in this._tracks) {
  3651. if (!this._tracks.hasOwnProperty(propName)) {
  3652. continue;
  3653. }
  3654. var clip = createTrackClip(
  3655. this, easing, oneTrackDone,
  3656. this._tracks[propName], propName, forceAnimate
  3657. );
  3658. if (clip) {
  3659. this._clipList.push(clip);
  3660. clipCount++;
  3661. // If start after added to animation
  3662. if (this.animation) {
  3663. this.animation.addClip(clip);
  3664. }
  3665. lastClip = clip;
  3666. }
  3667. }
  3668. // Add during callback on the last clip
  3669. if (lastClip) {
  3670. var oldOnFrame = lastClip.onframe;
  3671. lastClip.onframe = function (target, percent) {
  3672. oldOnFrame(target, percent);
  3673. for (var i = 0; i < self._onframeList.length; i++) {
  3674. self._onframeList[i](target, percent);
  3675. }
  3676. };
  3677. }
  3678. // This optimization will help the case that in the upper application
  3679. // the view may be refreshed frequently, where animation will be
  3680. // called repeatly but nothing changed.
  3681. if (!clipCount) {
  3682. this._doneCallback();
  3683. }
  3684. return this;
  3685. },
  3686. /**
  3687. * 停止动画
  3688. * @param {boolean} forwardToLast If move to last frame before stop
  3689. */
  3690. stop: function (forwardToLast) {
  3691. var clipList = this._clipList;
  3692. var animation = this.animation;
  3693. for (var i = 0; i < clipList.length; i++) {
  3694. var clip = clipList[i];
  3695. if (forwardToLast) {
  3696. // Move to last frame before stop
  3697. clip.onframe(this._target, 1);
  3698. }
  3699. animation && animation.removeClip(clip);
  3700. }
  3701. clipList.length = 0;
  3702. },
  3703. /**
  3704. * 设置动画延迟开始的时间
  3705. * @param {number} time 单位ms
  3706. * @return {module:zrender/animation/Animator}
  3707. */
  3708. delay: function (time) {
  3709. this._delay = time;
  3710. return this;
  3711. },
  3712. /**
  3713. * 添加动画结束的回调
  3714. * @param {Function} cb
  3715. * @return {module:zrender/animation/Animator}
  3716. */
  3717. done: function(cb) {
  3718. if (cb) {
  3719. this._doneList.push(cb);
  3720. }
  3721. return this;
  3722. },
  3723. /**
  3724. * @return {Array.<module:zrender/animation/Clip>}
  3725. */
  3726. getClips: function () {
  3727. return this._clipList;
  3728. }
  3729. };
  3730. var dpr = 1;
  3731. // If in browser environment
  3732. if (typeof window !== 'undefined') {
  3733. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3734. }
  3735. /**
  3736. * config默认配置项
  3737. * @exports zrender/config
  3738. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3739. */
  3740. /**
  3741. * debug日志选项:catchBrushException为true下有效
  3742. * 0 : 不生成debug数据,发布用
  3743. * 1 : 异常抛出,调试用
  3744. * 2 : 控制台输出,调试用
  3745. */
  3746. var debugMode = 0;
  3747. // retina 屏幕优化
  3748. var devicePixelRatio = dpr;
  3749. var log = function () {
  3750. };
  3751. if (debugMode === 1) {
  3752. log = function () {
  3753. for (var k in arguments) {
  3754. throw new Error(arguments[k]);
  3755. }
  3756. };
  3757. }
  3758. else if (debugMode > 1) {
  3759. log = function () {
  3760. for (var k in arguments) {
  3761. console.log(arguments[k]);
  3762. }
  3763. };
  3764. }
  3765. var zrLog = log;
  3766. /**
  3767. * @alias modue:zrender/mixin/Animatable
  3768. * @constructor
  3769. */
  3770. var Animatable = function () {
  3771. /**
  3772. * @type {Array.<module:zrender/animation/Animator>}
  3773. * @readOnly
  3774. */
  3775. this.animators = [];
  3776. };
  3777. Animatable.prototype = {
  3778. constructor: Animatable,
  3779. /**
  3780. * 动画
  3781. *
  3782. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3783. * @param {boolean} [loop] Whether to loop animation.
  3784. * @return {module:zrender/animation/Animator}
  3785. * @example:
  3786. * el.animate('style', false)
  3787. * .when(1000, {x: 10} )
  3788. * .done(function(){ // Animation done })
  3789. * .start()
  3790. */
  3791. animate: function (path, loop) {
  3792. var target;
  3793. var animatingShape = false;
  3794. var el = this;
  3795. var zr = this.__zr;
  3796. if (path) {
  3797. var pathSplitted = path.split('.');
  3798. var prop = el;
  3799. // If animating shape
  3800. animatingShape = pathSplitted[0] === 'shape';
  3801. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3802. if (!prop) {
  3803. continue;
  3804. }
  3805. prop = prop[pathSplitted[i]];
  3806. }
  3807. if (prop) {
  3808. target = prop;
  3809. }
  3810. }
  3811. else {
  3812. target = el;
  3813. }
  3814. if (!target) {
  3815. zrLog(
  3816. 'Property "'
  3817. + path
  3818. + '" is not existed in element '
  3819. + el.id
  3820. );
  3821. return;
  3822. }
  3823. var animators = el.animators;
  3824. var animator = new Animator(target, loop);
  3825. animator.during(function (target) {
  3826. el.dirty(animatingShape);
  3827. })
  3828. .done(function () {
  3829. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3830. animators.splice(indexOf(animators, animator), 1);
  3831. });
  3832. animators.push(animator);
  3833. // If animate after added to the zrender
  3834. if (zr) {
  3835. zr.animation.addAnimator(animator);
  3836. }
  3837. return animator;
  3838. },
  3839. /**
  3840. * 停止动画
  3841. * @param {boolean} forwardToLast If move to last frame before stop
  3842. */
  3843. stopAnimation: function (forwardToLast) {
  3844. var animators = this.animators;
  3845. var len = animators.length;
  3846. for (var i = 0; i < len; i++) {
  3847. animators[i].stop(forwardToLast);
  3848. }
  3849. animators.length = 0;
  3850. return this;
  3851. },
  3852. /**
  3853. * Caution: this method will stop previous animation.
  3854. * So do not use this method to one element twice before
  3855. * animation starts, unless you know what you are doing.
  3856. * @param {Object} target
  3857. * @param {number} [time=500] Time in ms
  3858. * @param {string} [easing='linear']
  3859. * @param {number} [delay=0]
  3860. * @param {Function} [callback]
  3861. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3862. * immediently when target values are the same as current values.
  3863. *
  3864. * @example
  3865. * // Animate position
  3866. * el.animateTo({
  3867. * position: [10, 10]
  3868. * }, function () { // done })
  3869. *
  3870. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3871. * el.animateTo({
  3872. * shape: {
  3873. * width: 500
  3874. * },
  3875. * style: {
  3876. * fill: 'red'
  3877. * }
  3878. * position: [10, 10]
  3879. * }, 100, 100, 'cubicOut', function () { // done })
  3880. */
  3881. // TODO Return animation key
  3882. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3883. // animateTo(target, time, easing, callback);
  3884. if (isString(delay)) {
  3885. callback = easing;
  3886. easing = delay;
  3887. delay = 0;
  3888. }
  3889. // animateTo(target, time, delay, callback);
  3890. else if (isFunction$1(easing)) {
  3891. callback = easing;
  3892. easing = 'linear';
  3893. delay = 0;
  3894. }
  3895. // animateTo(target, time, callback);
  3896. else if (isFunction$1(delay)) {
  3897. callback = delay;
  3898. delay = 0;
  3899. }
  3900. // animateTo(target, callback)
  3901. else if (isFunction$1(time)) {
  3902. callback = time;
  3903. time = 500;
  3904. }
  3905. // animateTo(target)
  3906. else if (!time) {
  3907. time = 500;
  3908. }
  3909. // Stop all previous animations
  3910. this.stopAnimation();
  3911. this._animateToShallow('', this, target, time, delay);
  3912. // Animators may be removed immediately after start
  3913. // if there is nothing to animate
  3914. var animators = this.animators.slice();
  3915. var count = animators.length;
  3916. function done() {
  3917. count--;
  3918. if (!count) {
  3919. callback && callback();
  3920. }
  3921. }
  3922. // No animators. This should be checked before animators[i].start(),
  3923. // because 'done' may be executed immediately if no need to animate.
  3924. if (!count) {
  3925. callback && callback();
  3926. }
  3927. // Start after all animators created
  3928. // Incase any animator is done immediately when all animation properties are not changed
  3929. for (var i = 0; i < animators.length; i++) {
  3930. animators[i]
  3931. .done(done)
  3932. .start(easing, forceAnimate);
  3933. }
  3934. },
  3935. /**
  3936. * @private
  3937. * @param {string} path=''
  3938. * @param {Object} source=this
  3939. * @param {Object} target
  3940. * @param {number} [time=500]
  3941. * @param {number} [delay=0]
  3942. *
  3943. * @example
  3944. * // Animate position
  3945. * el._animateToShallow({
  3946. * position: [10, 10]
  3947. * })
  3948. *
  3949. * // Animate shape, style and position in 100ms, delayed 100ms
  3950. * el._animateToShallow({
  3951. * shape: {
  3952. * width: 500
  3953. * },
  3954. * style: {
  3955. * fill: 'red'
  3956. * }
  3957. * position: [10, 10]
  3958. * }, 100, 100)
  3959. */
  3960. _animateToShallow: function (path, source, target, time, delay) {
  3961. var objShallow = {};
  3962. var propertyCount = 0;
  3963. for (var name in target) {
  3964. if (!target.hasOwnProperty(name)) {
  3965. continue;
  3966. }
  3967. if (source[name] != null) {
  3968. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3969. this._animateToShallow(
  3970. path ? path + '.' + name : name,
  3971. source[name],
  3972. target[name],
  3973. time,
  3974. delay
  3975. );
  3976. }
  3977. else {
  3978. objShallow[name] = target[name];
  3979. propertyCount++;
  3980. }
  3981. }
  3982. else if (target[name] != null) {
  3983. // Attr directly if not has property
  3984. // FIXME, if some property not needed for element ?
  3985. if (!path) {
  3986. this.attr(name, target[name]);
  3987. }
  3988. else { // Shape or style
  3989. var props = {};
  3990. props[path] = {};
  3991. props[path][name] = target[name];
  3992. this.attr(props);
  3993. }
  3994. }
  3995. }
  3996. if (propertyCount > 0) {
  3997. this.animate(path, false)
  3998. .when(time == null ? 500 : time, objShallow)
  3999. .delay(delay || 0);
  4000. }
  4001. return this;
  4002. }
  4003. };
  4004. /**
  4005. * @alias module:zrender/Element
  4006. * @constructor
  4007. * @extends {module:zrender/mixin/Animatable}
  4008. * @extends {module:zrender/mixin/Transformable}
  4009. * @extends {module:zrender/mixin/Eventful}
  4010. */
  4011. var Element = function (opts) { // jshint ignore:line
  4012. Transformable.call(this, opts);
  4013. Eventful.call(this, opts);
  4014. Animatable.call(this, opts);
  4015. /**
  4016. * 画布元素ID
  4017. * @type {string}
  4018. */
  4019. this.id = opts.id || guid();
  4020. };
  4021. Element.prototype = {
  4022. /**
  4023. * 元素类型
  4024. * Element type
  4025. * @type {string}
  4026. */
  4027. type: 'element',
  4028. /**
  4029. * 元素名字
  4030. * Element name
  4031. * @type {string}
  4032. */
  4033. name: '',
  4034. /**
  4035. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4036. * ZRender instance will be assigned when element is associated with zrender
  4037. * @name module:/zrender/Element#__zr
  4038. * @type {module:zrender/ZRender}
  4039. */
  4040. __zr: null,
  4041. /**
  4042. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4043. * If ignore drawing and events of the element object
  4044. * @name module:/zrender/Element#ignore
  4045. * @type {boolean}
  4046. * @default false
  4047. */
  4048. ignore: false,
  4049. /**
  4050. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4051. * 该路径会继承被裁减对象的变换
  4052. * @type {module:zrender/graphic/Path}
  4053. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4054. * @readOnly
  4055. */
  4056. clipPath: null,
  4057. /**
  4058. * 是否是 Group
  4059. * @type {boolean}
  4060. */
  4061. isGroup: false,
  4062. /**
  4063. * Drift element
  4064. * @param {number} dx dx on the global space
  4065. * @param {number} dy dy on the global space
  4066. */
  4067. drift: function (dx, dy) {
  4068. switch (this.draggable) {
  4069. case 'horizontal':
  4070. dy = 0;
  4071. break;
  4072. case 'vertical':
  4073. dx = 0;
  4074. break;
  4075. }
  4076. var m = this.transform;
  4077. if (!m) {
  4078. m = this.transform = [1, 0, 0, 1, 0, 0];
  4079. }
  4080. m[4] += dx;
  4081. m[5] += dy;
  4082. this.decomposeTransform();
  4083. this.dirty(false);
  4084. },
  4085. /**
  4086. * Hook before update
  4087. */
  4088. beforeUpdate: function () {},
  4089. /**
  4090. * Hook after update
  4091. */
  4092. afterUpdate: function () {},
  4093. /**
  4094. * Update each frame
  4095. */
  4096. update: function () {
  4097. this.updateTransform();
  4098. },
  4099. /**
  4100. * @param {Function} cb
  4101. * @param {} context
  4102. */
  4103. traverse: function (cb, context) {},
  4104. /**
  4105. * @protected
  4106. */
  4107. attrKV: function (key, value) {
  4108. if (key === 'position' || key === 'scale' || key === 'origin') {
  4109. // Copy the array
  4110. if (value) {
  4111. var target = this[key];
  4112. if (!target) {
  4113. target = this[key] = [];
  4114. }
  4115. target[0] = value[0];
  4116. target[1] = value[1];
  4117. }
  4118. }
  4119. else {
  4120. this[key] = value;
  4121. }
  4122. },
  4123. /**
  4124. * Hide the element
  4125. */
  4126. hide: function () {
  4127. this.ignore = true;
  4128. this.__zr && this.__zr.refresh();
  4129. },
  4130. /**
  4131. * Show the element
  4132. */
  4133. show: function () {
  4134. this.ignore = false;
  4135. this.__zr && this.__zr.refresh();
  4136. },
  4137. /**
  4138. * @param {string|Object} key
  4139. * @param {*} value
  4140. */
  4141. attr: function (key, value) {
  4142. if (typeof key === 'string') {
  4143. this.attrKV(key, value);
  4144. }
  4145. else if (isObject$1(key)) {
  4146. for (var name in key) {
  4147. if (key.hasOwnProperty(name)) {
  4148. this.attrKV(name, key[name]);
  4149. }
  4150. }
  4151. }
  4152. this.dirty(false);
  4153. return this;
  4154. },
  4155. /**
  4156. * @param {module:zrender/graphic/Path} clipPath
  4157. */
  4158. setClipPath: function (clipPath) {
  4159. var zr = this.__zr;
  4160. if (zr) {
  4161. clipPath.addSelfToZr(zr);
  4162. }
  4163. // Remove previous clip path
  4164. if (this.clipPath && this.clipPath !== clipPath) {
  4165. this.removeClipPath();
  4166. }
  4167. this.clipPath = clipPath;
  4168. clipPath.__zr = zr;
  4169. clipPath.__clipTarget = this;
  4170. this.dirty(false);
  4171. },
  4172. /**
  4173. */
  4174. removeClipPath: function () {
  4175. var clipPath = this.clipPath;
  4176. if (clipPath) {
  4177. if (clipPath.__zr) {
  4178. clipPath.removeSelfFromZr(clipPath.__zr);
  4179. }
  4180. clipPath.__zr = null;
  4181. clipPath.__clipTarget = null;
  4182. this.clipPath = null;
  4183. this.dirty(false);
  4184. }
  4185. },
  4186. /**
  4187. * Add self from zrender instance.
  4188. * Not recursively because it will be invoked when element added to storage.
  4189. * @param {module:zrender/ZRender} zr
  4190. */
  4191. addSelfToZr: function (zr) {
  4192. this.__zr = zr;
  4193. // 添加动画
  4194. var animators = this.animators;
  4195. if (animators) {
  4196. for (var i = 0; i < animators.length; i++) {
  4197. zr.animation.addAnimator(animators[i]);
  4198. }
  4199. }
  4200. if (this.clipPath) {
  4201. this.clipPath.addSelfToZr(zr);
  4202. }
  4203. },
  4204. /**
  4205. * Remove self from zrender instance.
  4206. * Not recursively because it will be invoked when element added to storage.
  4207. * @param {module:zrender/ZRender} zr
  4208. */
  4209. removeSelfFromZr: function (zr) {
  4210. this.__zr = null;
  4211. // 移除动画
  4212. var animators = this.animators;
  4213. if (animators) {
  4214. for (var i = 0; i < animators.length; i++) {
  4215. zr.animation.removeAnimator(animators[i]);
  4216. }
  4217. }
  4218. if (this.clipPath) {
  4219. this.clipPath.removeSelfFromZr(zr);
  4220. }
  4221. }
  4222. };
  4223. mixin(Element, Animatable);
  4224. mixin(Element, Transformable);
  4225. mixin(Element, Eventful);
  4226. /**
  4227. * @module echarts/core/BoundingRect
  4228. */
  4229. var v2ApplyTransform = applyTransform;
  4230. var mathMin = Math.min;
  4231. var mathMax = Math.max;
  4232. /**
  4233. * @alias module:echarts/core/BoundingRect
  4234. */
  4235. function BoundingRect(x, y, width, height) {
  4236. if (width < 0) {
  4237. x = x + width;
  4238. width = -width;
  4239. }
  4240. if (height < 0) {
  4241. y = y + height;
  4242. height = -height;
  4243. }
  4244. /**
  4245. * @type {number}
  4246. */
  4247. this.x = x;
  4248. /**
  4249. * @type {number}
  4250. */
  4251. this.y = y;
  4252. /**
  4253. * @type {number}
  4254. */
  4255. this.width = width;
  4256. /**
  4257. * @type {number}
  4258. */
  4259. this.height = height;
  4260. }
  4261. BoundingRect.prototype = {
  4262. constructor: BoundingRect,
  4263. /**
  4264. * @param {module:echarts/core/BoundingRect} other
  4265. */
  4266. union: function (other) {
  4267. var x = mathMin(other.x, this.x);
  4268. var y = mathMin(other.y, this.y);
  4269. this.width = mathMax(
  4270. other.x + other.width,
  4271. this.x + this.width
  4272. ) - x;
  4273. this.height = mathMax(
  4274. other.y + other.height,
  4275. this.y + this.height
  4276. ) - y;
  4277. this.x = x;
  4278. this.y = y;
  4279. },
  4280. /**
  4281. * @param {Array.<number>} m
  4282. * @methods
  4283. */
  4284. applyTransform: (function () {
  4285. var lt = [];
  4286. var rb = [];
  4287. var lb = [];
  4288. var rt = [];
  4289. return function (m) {
  4290. // In case usage like this
  4291. // el.getBoundingRect().applyTransform(el.transform)
  4292. // And element has no transform
  4293. if (!m) {
  4294. return;
  4295. }
  4296. lt[0] = lb[0] = this.x;
  4297. lt[1] = rt[1] = this.y;
  4298. rb[0] = rt[0] = this.x + this.width;
  4299. rb[1] = lb[1] = this.y + this.height;
  4300. v2ApplyTransform(lt, lt, m);
  4301. v2ApplyTransform(rb, rb, m);
  4302. v2ApplyTransform(lb, lb, m);
  4303. v2ApplyTransform(rt, rt, m);
  4304. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4305. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4306. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4307. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4308. this.width = maxX - this.x;
  4309. this.height = maxY - this.y;
  4310. };
  4311. })(),
  4312. /**
  4313. * Calculate matrix of transforming from self to target rect
  4314. * @param {module:zrender/core/BoundingRect} b
  4315. * @return {Array.<number>}
  4316. */
  4317. calculateTransform: function (b) {
  4318. var a = this;
  4319. var sx = b.width / a.width;
  4320. var sy = b.height / a.height;
  4321. var m = create$1();
  4322. // 矩阵右乘
  4323. translate(m, m, [-a.x, -a.y]);
  4324. scale$1(m, m, [sx, sy]);
  4325. translate(m, m, [b.x, b.y]);
  4326. return m;
  4327. },
  4328. /**
  4329. * @param {(module:echarts/core/BoundingRect|Object)} b
  4330. * @return {boolean}
  4331. */
  4332. intersect: function (b) {
  4333. if (!b) {
  4334. return false;
  4335. }
  4336. if (!(b instanceof BoundingRect)) {
  4337. // Normalize negative width/height.
  4338. b = BoundingRect.create(b);
  4339. }
  4340. var a = this;
  4341. var ax0 = a.x;
  4342. var ax1 = a.x + a.width;
  4343. var ay0 = a.y;
  4344. var ay1 = a.y + a.height;
  4345. var bx0 = b.x;
  4346. var bx1 = b.x + b.width;
  4347. var by0 = b.y;
  4348. var by1 = b.y + b.height;
  4349. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4350. },
  4351. contain: function (x, y) {
  4352. var rect = this;
  4353. return x >= rect.x
  4354. && x <= (rect.x + rect.width)
  4355. && y >= rect.y
  4356. && y <= (rect.y + rect.height);
  4357. },
  4358. /**
  4359. * @return {module:echarts/core/BoundingRect}
  4360. */
  4361. clone: function () {
  4362. return new BoundingRect(this.x, this.y, this.width, this.height);
  4363. },
  4364. /**
  4365. * Copy from another rect
  4366. */
  4367. copy: function (other) {
  4368. this.x = other.x;
  4369. this.y = other.y;
  4370. this.width = other.width;
  4371. this.height = other.height;
  4372. },
  4373. plain: function () {
  4374. return {
  4375. x: this.x,
  4376. y: this.y,
  4377. width: this.width,
  4378. height: this.height
  4379. };
  4380. }
  4381. };
  4382. /**
  4383. * @param {Object|module:zrender/core/BoundingRect} rect
  4384. * @param {number} rect.x
  4385. * @param {number} rect.y
  4386. * @param {number} rect.width
  4387. * @param {number} rect.height
  4388. * @return {module:zrender/core/BoundingRect}
  4389. */
  4390. BoundingRect.create = function (rect) {
  4391. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4392. };
  4393. /**
  4394. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4395. * @module zrender/graphic/Group
  4396. * @example
  4397. * var Group = require('zrender/container/Group');
  4398. * var Circle = require('zrender/graphic/shape/Circle');
  4399. * var g = new Group();
  4400. * g.position[0] = 100;
  4401. * g.position[1] = 100;
  4402. * g.add(new Circle({
  4403. * style: {
  4404. * x: 100,
  4405. * y: 100,
  4406. * r: 20,
  4407. * }
  4408. * }));
  4409. * zr.add(g);
  4410. */
  4411. /**
  4412. * @alias module:zrender/graphic/Group
  4413. * @constructor
  4414. * @extends module:zrender/mixin/Transformable
  4415. * @extends module:zrender/mixin/Eventful
  4416. */
  4417. var Group = function (opts) {
  4418. opts = opts || {};
  4419. Element.call(this, opts);
  4420. for (var key in opts) {
  4421. if (opts.hasOwnProperty(key)) {
  4422. this[key] = opts[key];
  4423. }
  4424. }
  4425. this._children = [];
  4426. this.__storage = null;
  4427. this.__dirty = true;
  4428. };
  4429. Group.prototype = {
  4430. constructor: Group,
  4431. isGroup: true,
  4432. /**
  4433. * @type {string}
  4434. */
  4435. type: 'group',
  4436. /**
  4437. * 所有子孙元素是否响应鼠标事件
  4438. * @name module:/zrender/container/Group#silent
  4439. * @type {boolean}
  4440. * @default false
  4441. */
  4442. silent: false,
  4443. /**
  4444. * @return {Array.<module:zrender/Element>}
  4445. */
  4446. children: function () {
  4447. return this._children.slice();
  4448. },
  4449. /**
  4450. * 获取指定 index 的儿子节点
  4451. * @param {number} idx
  4452. * @return {module:zrender/Element}
  4453. */
  4454. childAt: function (idx) {
  4455. return this._children[idx];
  4456. },
  4457. /**
  4458. * 获取指定名字的儿子节点
  4459. * @param {string} name
  4460. * @return {module:zrender/Element}
  4461. */
  4462. childOfName: function (name) {
  4463. var children = this._children;
  4464. for (var i = 0; i < children.length; i++) {
  4465. if (children[i].name === name) {
  4466. return children[i];
  4467. }
  4468. }
  4469. },
  4470. /**
  4471. * @return {number}
  4472. */
  4473. childCount: function () {
  4474. return this._children.length;
  4475. },
  4476. /**
  4477. * 添加子节点到最后
  4478. * @param {module:zrender/Element} child
  4479. */
  4480. add: function (child) {
  4481. if (child && child !== this && child.parent !== this) {
  4482. this._children.push(child);
  4483. this._doAdd(child);
  4484. }
  4485. return this;
  4486. },
  4487. /**
  4488. * 添加子节点在 nextSibling 之前
  4489. * @param {module:zrender/Element} child
  4490. * @param {module:zrender/Element} nextSibling
  4491. */
  4492. addBefore: function (child, nextSibling) {
  4493. if (child && child !== this && child.parent !== this
  4494. && nextSibling && nextSibling.parent === this) {
  4495. var children = this._children;
  4496. var idx = children.indexOf(nextSibling);
  4497. if (idx >= 0) {
  4498. children.splice(idx, 0, child);
  4499. this._doAdd(child);
  4500. }
  4501. }
  4502. return this;
  4503. },
  4504. _doAdd: function (child) {
  4505. if (child.parent) {
  4506. child.parent.remove(child);
  4507. }
  4508. child.parent = this;
  4509. var storage = this.__storage;
  4510. var zr = this.__zr;
  4511. if (storage && storage !== child.__storage) {
  4512. storage.addToStorage(child);
  4513. if (child instanceof Group) {
  4514. child.addChildrenToStorage(storage);
  4515. }
  4516. }
  4517. zr && zr.refresh();
  4518. },
  4519. /**
  4520. * 移除子节点
  4521. * @param {module:zrender/Element} child
  4522. */
  4523. remove: function (child) {
  4524. var zr = this.__zr;
  4525. var storage = this.__storage;
  4526. var children = this._children;
  4527. var idx = indexOf(children, child);
  4528. if (idx < 0) {
  4529. return this;
  4530. }
  4531. children.splice(idx, 1);
  4532. child.parent = null;
  4533. if (storage) {
  4534. storage.delFromStorage(child);
  4535. if (child instanceof Group) {
  4536. child.delChildrenFromStorage(storage);
  4537. }
  4538. }
  4539. zr && zr.refresh();
  4540. return this;
  4541. },
  4542. /**
  4543. * 移除所有子节点
  4544. */
  4545. removeAll: function () {
  4546. var children = this._children;
  4547. var storage = this.__storage;
  4548. var child;
  4549. var i;
  4550. for (i = 0; i < children.length; i++) {
  4551. child = children[i];
  4552. if (storage) {
  4553. storage.delFromStorage(child);
  4554. if (child instanceof Group) {
  4555. child.delChildrenFromStorage(storage);
  4556. }
  4557. }
  4558. child.parent = null;
  4559. }
  4560. children.length = 0;
  4561. return this;
  4562. },
  4563. /**
  4564. * 遍历所有子节点
  4565. * @param {Function} cb
  4566. * @param {} context
  4567. */
  4568. eachChild: function (cb, context) {
  4569. var children = this._children;
  4570. for (var i = 0; i < children.length; i++) {
  4571. var child = children[i];
  4572. cb.call(context, child, i);
  4573. }
  4574. return this;
  4575. },
  4576. /**
  4577. * 深度优先遍历所有子孙节点
  4578. * @param {Function} cb
  4579. * @param {} context
  4580. */
  4581. traverse: function (cb, context) {
  4582. for (var i = 0; i < this._children.length; i++) {
  4583. var child = this._children[i];
  4584. cb.call(context, child);
  4585. if (child.type === 'group') {
  4586. child.traverse(cb, context);
  4587. }
  4588. }
  4589. return this;
  4590. },
  4591. addChildrenToStorage: function (storage) {
  4592. for (var i = 0; i < this._children.length; i++) {
  4593. var child = this._children[i];
  4594. storage.addToStorage(child);
  4595. if (child instanceof Group) {
  4596. child.addChildrenToStorage(storage);
  4597. }
  4598. }
  4599. },
  4600. delChildrenFromStorage: function (storage) {
  4601. for (var i = 0; i < this._children.length; i++) {
  4602. var child = this._children[i];
  4603. storage.delFromStorage(child);
  4604. if (child instanceof Group) {
  4605. child.delChildrenFromStorage(storage);
  4606. }
  4607. }
  4608. },
  4609. dirty: function () {
  4610. this.__dirty = true;
  4611. this.__zr && this.__zr.refresh();
  4612. return this;
  4613. },
  4614. /**
  4615. * @return {module:zrender/core/BoundingRect}
  4616. */
  4617. getBoundingRect: function (includeChildren) {
  4618. // TODO Caching
  4619. var rect = null;
  4620. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4621. var children = includeChildren || this._children;
  4622. var tmpMat = [];
  4623. for (var i = 0; i < children.length; i++) {
  4624. var child = children[i];
  4625. if (child.ignore || child.invisible) {
  4626. continue;
  4627. }
  4628. var childRect = child.getBoundingRect();
  4629. var transform = child.getLocalTransform(tmpMat);
  4630. // TODO
  4631. // The boundingRect cacluated by transforming original
  4632. // rect may be bigger than the actual bundingRect when rotation
  4633. // is used. (Consider a circle rotated aginst its center, where
  4634. // the actual boundingRect should be the same as that not be
  4635. // rotated.) But we can not find better approach to calculate
  4636. // actual boundingRect yet, considering performance.
  4637. if (transform) {
  4638. tmpRect.copy(childRect);
  4639. tmpRect.applyTransform(transform);
  4640. rect = rect || tmpRect.clone();
  4641. rect.union(tmpRect);
  4642. }
  4643. else {
  4644. rect = rect || childRect.clone();
  4645. rect.union(childRect);
  4646. }
  4647. }
  4648. return rect || tmpRect;
  4649. }
  4650. };
  4651. inherits(Group, Element);
  4652. // https://github.com/mziccard/node-timsort
  4653. var DEFAULT_MIN_MERGE = 32;
  4654. var DEFAULT_MIN_GALLOPING = 7;
  4655. function minRunLength(n) {
  4656. var r = 0;
  4657. while (n >= DEFAULT_MIN_MERGE) {
  4658. r |= n & 1;
  4659. n >>= 1;
  4660. }
  4661. return n + r;
  4662. }
  4663. function makeAscendingRun(array, lo, hi, compare) {
  4664. var runHi = lo + 1;
  4665. if (runHi === hi) {
  4666. return 1;
  4667. }
  4668. if (compare(array[runHi++], array[lo]) < 0) {
  4669. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4670. runHi++;
  4671. }
  4672. reverseRun(array, lo, runHi);
  4673. }
  4674. else {
  4675. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4676. runHi++;
  4677. }
  4678. }
  4679. return runHi - lo;
  4680. }
  4681. function reverseRun(array, lo, hi) {
  4682. hi--;
  4683. while (lo < hi) {
  4684. var t = array[lo];
  4685. array[lo++] = array[hi];
  4686. array[hi--] = t;
  4687. }
  4688. }
  4689. function binaryInsertionSort(array, lo, hi, start, compare) {
  4690. if (start === lo) {
  4691. start++;
  4692. }
  4693. for (; start < hi; start++) {
  4694. var pivot = array[start];
  4695. var left = lo;
  4696. var right = start;
  4697. var mid;
  4698. while (left < right) {
  4699. mid = left + right >>> 1;
  4700. if (compare(pivot, array[mid]) < 0) {
  4701. right = mid;
  4702. }
  4703. else {
  4704. left = mid + 1;
  4705. }
  4706. }
  4707. var n = start - left;
  4708. switch (n) {
  4709. case 3:
  4710. array[left + 3] = array[left + 2];
  4711. case 2:
  4712. array[left + 2] = array[left + 1];
  4713. case 1:
  4714. array[left + 1] = array[left];
  4715. break;
  4716. default:
  4717. while (n > 0) {
  4718. array[left + n] = array[left + n - 1];
  4719. n--;
  4720. }
  4721. }
  4722. array[left] = pivot;
  4723. }
  4724. }
  4725. function gallopLeft(value, array, start, length, hint, compare) {
  4726. var lastOffset = 0;
  4727. var maxOffset = 0;
  4728. var offset = 1;
  4729. if (compare(value, array[start + hint]) > 0) {
  4730. maxOffset = length - hint;
  4731. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4732. lastOffset = offset;
  4733. offset = (offset << 1) + 1;
  4734. if (offset <= 0) {
  4735. offset = maxOffset;
  4736. }
  4737. }
  4738. if (offset > maxOffset) {
  4739. offset = maxOffset;
  4740. }
  4741. lastOffset += hint;
  4742. offset += hint;
  4743. }
  4744. else {
  4745. maxOffset = hint + 1;
  4746. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4747. lastOffset = offset;
  4748. offset = (offset << 1) + 1;
  4749. if (offset <= 0) {
  4750. offset = maxOffset;
  4751. }
  4752. }
  4753. if (offset > maxOffset) {
  4754. offset = maxOffset;
  4755. }
  4756. var tmp = lastOffset;
  4757. lastOffset = hint - offset;
  4758. offset = hint - tmp;
  4759. }
  4760. lastOffset++;
  4761. while (lastOffset < offset) {
  4762. var m = lastOffset + (offset - lastOffset >>> 1);
  4763. if (compare(value, array[start + m]) > 0) {
  4764. lastOffset = m + 1;
  4765. }
  4766. else {
  4767. offset = m;
  4768. }
  4769. }
  4770. return offset;
  4771. }
  4772. function gallopRight(value, array, start, length, hint, compare) {
  4773. var lastOffset = 0;
  4774. var maxOffset = 0;
  4775. var offset = 1;
  4776. if (compare(value, array[start + hint]) < 0) {
  4777. maxOffset = hint + 1;
  4778. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4779. lastOffset = offset;
  4780. offset = (offset << 1) + 1;
  4781. if (offset <= 0) {
  4782. offset = maxOffset;
  4783. }
  4784. }
  4785. if (offset > maxOffset) {
  4786. offset = maxOffset;
  4787. }
  4788. var tmp = lastOffset;
  4789. lastOffset = hint - offset;
  4790. offset = hint - tmp;
  4791. }
  4792. else {
  4793. maxOffset = length - hint;
  4794. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4795. lastOffset = offset;
  4796. offset = (offset << 1) + 1;
  4797. if (offset <= 0) {
  4798. offset = maxOffset;
  4799. }
  4800. }
  4801. if (offset > maxOffset) {
  4802. offset = maxOffset;
  4803. }
  4804. lastOffset += hint;
  4805. offset += hint;
  4806. }
  4807. lastOffset++;
  4808. while (lastOffset < offset) {
  4809. var m = lastOffset + (offset - lastOffset >>> 1);
  4810. if (compare(value, array[start + m]) < 0) {
  4811. offset = m;
  4812. }
  4813. else {
  4814. lastOffset = m + 1;
  4815. }
  4816. }
  4817. return offset;
  4818. }
  4819. function TimSort(array, compare) {
  4820. var minGallop = DEFAULT_MIN_GALLOPING;
  4821. var runStart;
  4822. var runLength;
  4823. var stackSize = 0;
  4824. var tmp = [];
  4825. runStart = [];
  4826. runLength = [];
  4827. function pushRun(_runStart, _runLength) {
  4828. runStart[stackSize] = _runStart;
  4829. runLength[stackSize] = _runLength;
  4830. stackSize += 1;
  4831. }
  4832. function mergeRuns() {
  4833. while (stackSize > 1) {
  4834. var n = stackSize - 2;
  4835. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4836. if (runLength[n - 1] < runLength[n + 1]) {
  4837. n--;
  4838. }
  4839. }
  4840. else if (runLength[n] > runLength[n + 1]) {
  4841. break;
  4842. }
  4843. mergeAt(n);
  4844. }
  4845. }
  4846. function forceMergeRuns() {
  4847. while (stackSize > 1) {
  4848. var n = stackSize - 2;
  4849. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4850. n--;
  4851. }
  4852. mergeAt(n);
  4853. }
  4854. }
  4855. function mergeAt(i) {
  4856. var start1 = runStart[i];
  4857. var length1 = runLength[i];
  4858. var start2 = runStart[i + 1];
  4859. var length2 = runLength[i + 1];
  4860. runLength[i] = length1 + length2;
  4861. if (i === stackSize - 3) {
  4862. runStart[i + 1] = runStart[i + 2];
  4863. runLength[i + 1] = runLength[i + 2];
  4864. }
  4865. stackSize--;
  4866. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4867. start1 += k;
  4868. length1 -= k;
  4869. if (length1 === 0) {
  4870. return;
  4871. }
  4872. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4873. if (length2 === 0) {
  4874. return;
  4875. }
  4876. if (length1 <= length2) {
  4877. mergeLow(start1, length1, start2, length2);
  4878. }
  4879. else {
  4880. mergeHigh(start1, length1, start2, length2);
  4881. }
  4882. }
  4883. function mergeLow(start1, length1, start2, length2) {
  4884. var i = 0;
  4885. for (i = 0; i < length1; i++) {
  4886. tmp[i] = array[start1 + i];
  4887. }
  4888. var cursor1 = 0;
  4889. var cursor2 = start2;
  4890. var dest = start1;
  4891. array[dest++] = array[cursor2++];
  4892. if (--length2 === 0) {
  4893. for (i = 0; i < length1; i++) {
  4894. array[dest + i] = tmp[cursor1 + i];
  4895. }
  4896. return;
  4897. }
  4898. if (length1 === 1) {
  4899. for (i = 0; i < length2; i++) {
  4900. array[dest + i] = array[cursor2 + i];
  4901. }
  4902. array[dest + length2] = tmp[cursor1];
  4903. return;
  4904. }
  4905. var _minGallop = minGallop;
  4906. var count1, count2, exit;
  4907. while (1) {
  4908. count1 = 0;
  4909. count2 = 0;
  4910. exit = false;
  4911. do {
  4912. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4913. array[dest++] = array[cursor2++];
  4914. count2++;
  4915. count1 = 0;
  4916. if (--length2 === 0) {
  4917. exit = true;
  4918. break;
  4919. }
  4920. }
  4921. else {
  4922. array[dest++] = tmp[cursor1++];
  4923. count1++;
  4924. count2 = 0;
  4925. if (--length1 === 1) {
  4926. exit = true;
  4927. break;
  4928. }
  4929. }
  4930. } while ((count1 | count2) < _minGallop);
  4931. if (exit) {
  4932. break;
  4933. }
  4934. do {
  4935. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4936. if (count1 !== 0) {
  4937. for (i = 0; i < count1; i++) {
  4938. array[dest + i] = tmp[cursor1 + i];
  4939. }
  4940. dest += count1;
  4941. cursor1 += count1;
  4942. length1 -= count1;
  4943. if (length1 <= 1) {
  4944. exit = true;
  4945. break;
  4946. }
  4947. }
  4948. array[dest++] = array[cursor2++];
  4949. if (--length2 === 0) {
  4950. exit = true;
  4951. break;
  4952. }
  4953. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4954. if (count2 !== 0) {
  4955. for (i = 0; i < count2; i++) {
  4956. array[dest + i] = array[cursor2 + i];
  4957. }
  4958. dest += count2;
  4959. cursor2 += count2;
  4960. length2 -= count2;
  4961. if (length2 === 0) {
  4962. exit = true;
  4963. break;
  4964. }
  4965. }
  4966. array[dest++] = tmp[cursor1++];
  4967. if (--length1 === 1) {
  4968. exit = true;
  4969. break;
  4970. }
  4971. _minGallop--;
  4972. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4973. if (exit) {
  4974. break;
  4975. }
  4976. if (_minGallop < 0) {
  4977. _minGallop = 0;
  4978. }
  4979. _minGallop += 2;
  4980. }
  4981. minGallop = _minGallop;
  4982. minGallop < 1 && (minGallop = 1);
  4983. if (length1 === 1) {
  4984. for (i = 0; i < length2; i++) {
  4985. array[dest + i] = array[cursor2 + i];
  4986. }
  4987. array[dest + length2] = tmp[cursor1];
  4988. }
  4989. else if (length1 === 0) {
  4990. throw new Error();
  4991. // throw new Error('mergeLow preconditions were not respected');
  4992. }
  4993. else {
  4994. for (i = 0; i < length1; i++) {
  4995. array[dest + i] = tmp[cursor1 + i];
  4996. }
  4997. }
  4998. }
  4999. function mergeHigh (start1, length1, start2, length2) {
  5000. var i = 0;
  5001. for (i = 0; i < length2; i++) {
  5002. tmp[i] = array[start2 + i];
  5003. }
  5004. var cursor1 = start1 + length1 - 1;
  5005. var cursor2 = length2 - 1;
  5006. var dest = start2 + length2 - 1;
  5007. var customCursor = 0;
  5008. var customDest = 0;
  5009. array[dest--] = array[cursor1--];
  5010. if (--length1 === 0) {
  5011. customCursor = dest - (length2 - 1);
  5012. for (i = 0; i < length2; i++) {
  5013. array[customCursor + i] = tmp[i];
  5014. }
  5015. return;
  5016. }
  5017. if (length2 === 1) {
  5018. dest -= length1;
  5019. cursor1 -= length1;
  5020. customDest = dest + 1;
  5021. customCursor = cursor1 + 1;
  5022. for (i = length1 - 1; i >= 0; i--) {
  5023. array[customDest + i] = array[customCursor + i];
  5024. }
  5025. array[dest] = tmp[cursor2];
  5026. return;
  5027. }
  5028. var _minGallop = minGallop;
  5029. while (true) {
  5030. var count1 = 0;
  5031. var count2 = 0;
  5032. var exit = false;
  5033. do {
  5034. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5035. array[dest--] = array[cursor1--];
  5036. count1++;
  5037. count2 = 0;
  5038. if (--length1 === 0) {
  5039. exit = true;
  5040. break;
  5041. }
  5042. }
  5043. else {
  5044. array[dest--] = tmp[cursor2--];
  5045. count2++;
  5046. count1 = 0;
  5047. if (--length2 === 1) {
  5048. exit = true;
  5049. break;
  5050. }
  5051. }
  5052. } while ((count1 | count2) < _minGallop);
  5053. if (exit) {
  5054. break;
  5055. }
  5056. do {
  5057. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5058. if (count1 !== 0) {
  5059. dest -= count1;
  5060. cursor1 -= count1;
  5061. length1 -= count1;
  5062. customDest = dest + 1;
  5063. customCursor = cursor1 + 1;
  5064. for (i = count1 - 1; i >= 0; i--) {
  5065. array[customDest + i] = array[customCursor + i];
  5066. }
  5067. if (length1 === 0) {
  5068. exit = true;
  5069. break;
  5070. }
  5071. }
  5072. array[dest--] = tmp[cursor2--];
  5073. if (--length2 === 1) {
  5074. exit = true;
  5075. break;
  5076. }
  5077. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5078. if (count2 !== 0) {
  5079. dest -= count2;
  5080. cursor2 -= count2;
  5081. length2 -= count2;
  5082. customDest = dest + 1;
  5083. customCursor = cursor2 + 1;
  5084. for (i = 0; i < count2; i++) {
  5085. array[customDest + i] = tmp[customCursor + i];
  5086. }
  5087. if (length2 <= 1) {
  5088. exit = true;
  5089. break;
  5090. }
  5091. }
  5092. array[dest--] = array[cursor1--];
  5093. if (--length1 === 0) {
  5094. exit = true;
  5095. break;
  5096. }
  5097. _minGallop--;
  5098. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5099. if (exit) {
  5100. break;
  5101. }
  5102. if (_minGallop < 0) {
  5103. _minGallop = 0;
  5104. }
  5105. _minGallop += 2;
  5106. }
  5107. minGallop = _minGallop;
  5108. if (minGallop < 1) {
  5109. minGallop = 1;
  5110. }
  5111. if (length2 === 1) {
  5112. dest -= length1;
  5113. cursor1 -= length1;
  5114. customDest = dest + 1;
  5115. customCursor = cursor1 + 1;
  5116. for (i = length1 - 1; i >= 0; i--) {
  5117. array[customDest + i] = array[customCursor + i];
  5118. }
  5119. array[dest] = tmp[cursor2];
  5120. }
  5121. else if (length2 === 0) {
  5122. throw new Error();
  5123. // throw new Error('mergeHigh preconditions were not respected');
  5124. }
  5125. else {
  5126. customCursor = dest - (length2 - 1);
  5127. for (i = 0; i < length2; i++) {
  5128. array[customCursor + i] = tmp[i];
  5129. }
  5130. }
  5131. }
  5132. this.mergeRuns = mergeRuns;
  5133. this.forceMergeRuns = forceMergeRuns;
  5134. this.pushRun = pushRun;
  5135. }
  5136. function sort(array, compare, lo, hi) {
  5137. if (!lo) {
  5138. lo = 0;
  5139. }
  5140. if (!hi) {
  5141. hi = array.length;
  5142. }
  5143. var remaining = hi - lo;
  5144. if (remaining < 2) {
  5145. return;
  5146. }
  5147. var runLength = 0;
  5148. if (remaining < DEFAULT_MIN_MERGE) {
  5149. runLength = makeAscendingRun(array, lo, hi, compare);
  5150. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5151. return;
  5152. }
  5153. var ts = new TimSort(array, compare);
  5154. var minRun = minRunLength(remaining);
  5155. do {
  5156. runLength = makeAscendingRun(array, lo, hi, compare);
  5157. if (runLength < minRun) {
  5158. var force = remaining;
  5159. if (force > minRun) {
  5160. force = minRun;
  5161. }
  5162. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5163. runLength = force;
  5164. }
  5165. ts.pushRun(lo, runLength);
  5166. ts.mergeRuns();
  5167. remaining -= runLength;
  5168. lo += runLength;
  5169. } while (remaining !== 0);
  5170. ts.forceMergeRuns();
  5171. }
  5172. // Use timsort because in most case elements are partially sorted
  5173. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5174. function shapeCompareFunc(a, b) {
  5175. if (a.zlevel === b.zlevel) {
  5176. if (a.z === b.z) {
  5177. // if (a.z2 === b.z2) {
  5178. // // FIXME Slow has renderidx compare
  5179. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5180. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5181. // return a.__renderidx - b.__renderidx;
  5182. // }
  5183. return a.z2 - b.z2;
  5184. }
  5185. return a.z - b.z;
  5186. }
  5187. return a.zlevel - b.zlevel;
  5188. }
  5189. /**
  5190. * 内容仓库 (M)
  5191. * @alias module:zrender/Storage
  5192. * @constructor
  5193. */
  5194. var Storage = function () { // jshint ignore:line
  5195. this._roots = [];
  5196. this._displayList = [];
  5197. this._displayListLen = 0;
  5198. };
  5199. Storage.prototype = {
  5200. constructor: Storage,
  5201. /**
  5202. * @param {Function} cb
  5203. *
  5204. */
  5205. traverse: function (cb, context) {
  5206. for (var i = 0; i < this._roots.length; i++) {
  5207. this._roots[i].traverse(cb, context);
  5208. }
  5209. },
  5210. /**
  5211. * 返回所有图形的绘制队列
  5212. * @param {boolean} [update=false] 是否在返回前更新该数组
  5213. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5214. *
  5215. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5216. * @return {Array.<module:zrender/graphic/Displayable>}
  5217. */
  5218. getDisplayList: function (update, includeIgnore) {
  5219. includeIgnore = includeIgnore || false;
  5220. if (update) {
  5221. this.updateDisplayList(includeIgnore);
  5222. }
  5223. return this._displayList;
  5224. },
  5225. /**
  5226. * 更新图形的绘制队列。
  5227. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5228. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5229. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5230. */
  5231. updateDisplayList: function (includeIgnore) {
  5232. this._displayListLen = 0;
  5233. var roots = this._roots;
  5234. var displayList = this._displayList;
  5235. for (var i = 0, len = roots.length; i < len; i++) {
  5236. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5237. }
  5238. displayList.length = this._displayListLen;
  5239. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5240. },
  5241. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5242. if (el.ignore && !includeIgnore) {
  5243. return;
  5244. }
  5245. el.beforeUpdate();
  5246. if (el.__dirty) {
  5247. el.update();
  5248. }
  5249. el.afterUpdate();
  5250. var userSetClipPath = el.clipPath;
  5251. if (userSetClipPath) {
  5252. // FIXME 效率影响
  5253. if (clipPaths) {
  5254. clipPaths = clipPaths.slice();
  5255. }
  5256. else {
  5257. clipPaths = [];
  5258. }
  5259. var currentClipPath = userSetClipPath;
  5260. var parentClipPath = el;
  5261. // Recursively add clip path
  5262. while (currentClipPath) {
  5263. // clipPath 的变换是基于使用这个 clipPath 的元素
  5264. currentClipPath.parent = parentClipPath;
  5265. currentClipPath.updateTransform();
  5266. clipPaths.push(currentClipPath);
  5267. parentClipPath = currentClipPath;
  5268. currentClipPath = currentClipPath.clipPath;
  5269. }
  5270. }
  5271. if (el.isGroup) {
  5272. var children = el._children;
  5273. for (var i = 0; i < children.length; i++) {
  5274. var child = children[i];
  5275. // Force to mark as dirty if group is dirty
  5276. // FIXME __dirtyPath ?
  5277. if (el.__dirty) {
  5278. child.__dirty = true;
  5279. }
  5280. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5281. }
  5282. // Mark group clean here
  5283. el.__dirty = false;
  5284. }
  5285. else {
  5286. el.__clipPaths = clipPaths;
  5287. this._displayList[this._displayListLen++] = el;
  5288. }
  5289. },
  5290. /**
  5291. * 添加图形(Shape)或者组(Group)到根节点
  5292. * @param {module:zrender/Element} el
  5293. */
  5294. addRoot: function (el) {
  5295. if (el.__storage === this) {
  5296. return;
  5297. }
  5298. if (el instanceof Group) {
  5299. el.addChildrenToStorage(this);
  5300. }
  5301. this.addToStorage(el);
  5302. this._roots.push(el);
  5303. },
  5304. /**
  5305. * 删除指定的图形(Shape)或者组(Group)
  5306. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5307. */
  5308. delRoot: function (el) {
  5309. if (el == null) {
  5310. // 不指定el清空
  5311. for (var i = 0; i < this._roots.length; i++) {
  5312. var root = this._roots[i];
  5313. if (root instanceof Group) {
  5314. root.delChildrenFromStorage(this);
  5315. }
  5316. }
  5317. this._roots = [];
  5318. this._displayList = [];
  5319. this._displayListLen = 0;
  5320. return;
  5321. }
  5322. if (el instanceof Array) {
  5323. for (var i = 0, l = el.length; i < l; i++) {
  5324. this.delRoot(el[i]);
  5325. }
  5326. return;
  5327. }
  5328. var idx = indexOf(this._roots, el);
  5329. if (idx >= 0) {
  5330. this.delFromStorage(el);
  5331. this._roots.splice(idx, 1);
  5332. if (el instanceof Group) {
  5333. el.delChildrenFromStorage(this);
  5334. }
  5335. }
  5336. },
  5337. addToStorage: function (el) {
  5338. if (el) {
  5339. el.__storage = this;
  5340. el.dirty(false);
  5341. }
  5342. return this;
  5343. },
  5344. delFromStorage: function (el) {
  5345. if (el) {
  5346. el.__storage = null;
  5347. }
  5348. return this;
  5349. },
  5350. /**
  5351. * 清空并且释放Storage
  5352. */
  5353. dispose: function () {
  5354. this._renderList =
  5355. this._roots = null;
  5356. },
  5357. displayableSortFunc: shapeCompareFunc
  5358. };
  5359. var SHADOW_PROPS = {
  5360. 'shadowBlur': 1,
  5361. 'shadowOffsetX': 1,
  5362. 'shadowOffsetY': 1,
  5363. 'textShadowBlur': 1,
  5364. 'textShadowOffsetX': 1,
  5365. 'textShadowOffsetY': 1,
  5366. 'textBoxShadowBlur': 1,
  5367. 'textBoxShadowOffsetX': 1,
  5368. 'textBoxShadowOffsetY': 1
  5369. };
  5370. var fixShadow = function (ctx, propName, value) {
  5371. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5372. return value *= ctx.dpr;
  5373. }
  5374. return value;
  5375. };
  5376. var STYLE_COMMON_PROPS = [
  5377. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5378. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5379. ];
  5380. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5381. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5382. var Style = function (opts, host) {
  5383. this.extendFrom(opts, false);
  5384. this.host = host;
  5385. };
  5386. function createLinearGradient(ctx, obj, rect) {
  5387. var x = obj.x == null ? 0 : obj.x;
  5388. var x2 = obj.x2 == null ? 1 : obj.x2;
  5389. var y = obj.y == null ? 0 : obj.y;
  5390. var y2 = obj.y2 == null ? 0 : obj.y2;
  5391. if (!obj.global) {
  5392. x = x * rect.width + rect.x;
  5393. x2 = x2 * rect.width + rect.x;
  5394. y = y * rect.height + rect.y;
  5395. y2 = y2 * rect.height + rect.y;
  5396. }
  5397. // Fix NaN when rect is Infinity
  5398. x = isNaN(x) ? 0 : x;
  5399. x2 = isNaN(x2) ? 1 : x2;
  5400. y = isNaN(y) ? 0 : y;
  5401. y2 = isNaN(y2) ? 0 : y2;
  5402. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5403. return canvasGradient;
  5404. }
  5405. function createRadialGradient(ctx, obj, rect) {
  5406. var width = rect.width;
  5407. var height = rect.height;
  5408. var min = Math.min(width, height);
  5409. var x = obj.x == null ? 0.5 : obj.x;
  5410. var y = obj.y == null ? 0.5 : obj.y;
  5411. var r = obj.r == null ? 0.5 : obj.r;
  5412. if (!obj.global) {
  5413. x = x * width + rect.x;
  5414. y = y * height + rect.y;
  5415. r = r * min;
  5416. }
  5417. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5418. return canvasGradient;
  5419. }
  5420. Style.prototype = {
  5421. constructor: Style,
  5422. /**
  5423. * @type {module:zrender/graphic/Displayable}
  5424. */
  5425. host: null,
  5426. /**
  5427. * @type {string}
  5428. */
  5429. fill: '#000',
  5430. /**
  5431. * @type {string}
  5432. */
  5433. stroke: null,
  5434. /**
  5435. * @type {number}
  5436. */
  5437. opacity: 1,
  5438. /**
  5439. * @type {Array.<number>}
  5440. */
  5441. lineDash: null,
  5442. /**
  5443. * @type {number}
  5444. */
  5445. lineDashOffset: 0,
  5446. /**
  5447. * @type {number}
  5448. */
  5449. shadowBlur: 0,
  5450. /**
  5451. * @type {number}
  5452. */
  5453. shadowOffsetX: 0,
  5454. /**
  5455. * @type {number}
  5456. */
  5457. shadowOffsetY: 0,
  5458. /**
  5459. * @type {number}
  5460. */
  5461. lineWidth: 1,
  5462. /**
  5463. * If stroke ignore scale
  5464. * @type {Boolean}
  5465. */
  5466. strokeNoScale: false,
  5467. // Bounding rect text configuration
  5468. // Not affected by element transform
  5469. /**
  5470. * @type {string}
  5471. */
  5472. text: null,
  5473. /**
  5474. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5475. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5476. * So do not visit it directly in upper application (like echarts),
  5477. * but use `contain/text#makeFont` instead.
  5478. * @type {string}
  5479. */
  5480. font: null,
  5481. /**
  5482. * The same as font. Use font please.
  5483. * @deprecated
  5484. * @type {string}
  5485. */
  5486. textFont: null,
  5487. /**
  5488. * It helps merging respectively, rather than parsing an entire font string.
  5489. * @type {string}
  5490. */
  5491. fontStyle: null,
  5492. /**
  5493. * It helps merging respectively, rather than parsing an entire font string.
  5494. * @type {string}
  5495. */
  5496. fontWeight: null,
  5497. /**
  5498. * It helps merging respectively, rather than parsing an entire font string.
  5499. * Should be 12 but not '12px'.
  5500. * @type {number}
  5501. */
  5502. fontSize: null,
  5503. /**
  5504. * It helps merging respectively, rather than parsing an entire font string.
  5505. * @type {string}
  5506. */
  5507. fontFamily: null,
  5508. /**
  5509. * Reserved for special functinality, like 'hr'.
  5510. * @type {string}
  5511. */
  5512. textTag: null,
  5513. /**
  5514. * @type {string}
  5515. */
  5516. textFill: '#000',
  5517. /**
  5518. * @type {string}
  5519. */
  5520. textStroke: null,
  5521. /**
  5522. * @type {number}
  5523. */
  5524. textWidth: null,
  5525. /**
  5526. * Only for textBackground.
  5527. * @type {number}
  5528. */
  5529. textHeight: null,
  5530. /**
  5531. * textStroke may be set as some color as a default
  5532. * value in upper applicaion, where the default value
  5533. * of textStrokeWidth should be 0 to make sure that
  5534. * user can choose to do not use text stroke.
  5535. * @type {number}
  5536. */
  5537. textStrokeWidth: 0,
  5538. /**
  5539. * @type {number}
  5540. */
  5541. textLineHeight: null,
  5542. /**
  5543. * 'inside', 'left', 'right', 'top', 'bottom'
  5544. * [x, y]
  5545. * Based on x, y of rect.
  5546. * @type {string|Array.<number>}
  5547. * @default 'inside'
  5548. */
  5549. textPosition: 'inside',
  5550. /**
  5551. * If not specified, use the boundingRect of a `displayable`.
  5552. * @type {Object}
  5553. */
  5554. textRect: null,
  5555. /**
  5556. * [x, y]
  5557. * @type {Array.<number>}
  5558. */
  5559. textOffset: null,
  5560. /**
  5561. * @type {string}
  5562. */
  5563. textAlign: null,
  5564. /**
  5565. * @type {string}
  5566. */
  5567. textVerticalAlign: null,
  5568. /**
  5569. * @type {number}
  5570. */
  5571. textDistance: 5,
  5572. /**
  5573. * @type {string}
  5574. */
  5575. textShadowColor: 'transparent',
  5576. /**
  5577. * @type {number}
  5578. */
  5579. textShadowBlur: 0,
  5580. /**
  5581. * @type {number}
  5582. */
  5583. textShadowOffsetX: 0,
  5584. /**
  5585. * @type {number}
  5586. */
  5587. textShadowOffsetY: 0,
  5588. /**
  5589. * @type {string}
  5590. */
  5591. textBoxShadowColor: 'transparent',
  5592. /**
  5593. * @type {number}
  5594. */
  5595. textBoxShadowBlur: 0,
  5596. /**
  5597. * @type {number}
  5598. */
  5599. textBoxShadowOffsetX: 0,
  5600. /**
  5601. * @type {number}
  5602. */
  5603. textBoxShadowOffsetY: 0,
  5604. /**
  5605. * Whether transform text.
  5606. * Only useful in Path and Image element
  5607. * @type {boolean}
  5608. */
  5609. transformText: false,
  5610. /**
  5611. * Text rotate around position of Path or Image
  5612. * Only useful in Path and Image element and transformText is false.
  5613. */
  5614. textRotation: 0,
  5615. /**
  5616. * Text origin of text rotation, like [10, 40].
  5617. * Based on x, y of rect.
  5618. * Useful in label rotation of circular symbol.
  5619. * By default, this origin is textPosition.
  5620. * Can be 'center'.
  5621. * @type {string|Array.<number>}
  5622. */
  5623. textOrigin: null,
  5624. /**
  5625. * @type {string}
  5626. */
  5627. textBackgroundColor: null,
  5628. /**
  5629. * @type {string}
  5630. */
  5631. textBorderColor: null,
  5632. /**
  5633. * @type {number}
  5634. */
  5635. textBorderWidth: 0,
  5636. /**
  5637. * @type {number}
  5638. */
  5639. textBorderRadius: 0,
  5640. /**
  5641. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5642. * @type {number|Array.<number>}
  5643. */
  5644. textPadding: null,
  5645. /**
  5646. * Text styles for rich text.
  5647. * @type {Object}
  5648. */
  5649. rich: null,
  5650. /**
  5651. * {outerWidth, outerHeight, ellipsis, placeholder}
  5652. * @type {Object}
  5653. */
  5654. truncate: null,
  5655. /**
  5656. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5657. * @type {string}
  5658. */
  5659. blend: null,
  5660. /**
  5661. * @param {CanvasRenderingContext2D} ctx
  5662. */
  5663. bind: function (ctx, el, prevEl) {
  5664. var style = this;
  5665. var prevStyle = prevEl && prevEl.style;
  5666. var firstDraw = !prevStyle;
  5667. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5668. var prop = STYLE_COMMON_PROPS[i];
  5669. var styleName = prop[0];
  5670. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5671. // FIXME Invalid property value will cause style leak from previous element.
  5672. ctx[styleName] =
  5673. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5674. }
  5675. }
  5676. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5677. ctx.fillStyle = style.fill;
  5678. }
  5679. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5680. ctx.strokeStyle = style.stroke;
  5681. }
  5682. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5683. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5684. }
  5685. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5686. ctx.globalCompositeOperation = style.blend || 'source-over';
  5687. }
  5688. if (this.hasStroke()) {
  5689. var lineWidth = style.lineWidth;
  5690. ctx.lineWidth = lineWidth / (
  5691. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5692. );
  5693. }
  5694. },
  5695. hasFill: function () {
  5696. var fill = this.fill;
  5697. return fill != null && fill !== 'none';
  5698. },
  5699. hasStroke: function () {
  5700. var stroke = this.stroke;
  5701. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5702. },
  5703. /**
  5704. * Extend from other style
  5705. * @param {zrender/graphic/Style} otherStyle
  5706. * @param {boolean} overwrite true: overwrirte any way.
  5707. * false: overwrite only when !target.hasOwnProperty
  5708. * others: overwrite when property is not null/undefined.
  5709. */
  5710. extendFrom: function (otherStyle, overwrite) {
  5711. if (otherStyle) {
  5712. for (var name in otherStyle) {
  5713. if (otherStyle.hasOwnProperty(name)
  5714. && (overwrite === true
  5715. || (
  5716. overwrite === false
  5717. ? !this.hasOwnProperty(name)
  5718. : otherStyle[name] != null
  5719. )
  5720. )
  5721. ) {
  5722. this[name] = otherStyle[name];
  5723. }
  5724. }
  5725. }
  5726. },
  5727. /**
  5728. * Batch setting style with a given object
  5729. * @param {Object|string} obj
  5730. * @param {*} [obj]
  5731. */
  5732. set: function (obj, value) {
  5733. if (typeof obj === 'string') {
  5734. this[obj] = value;
  5735. }
  5736. else {
  5737. this.extendFrom(obj, true);
  5738. }
  5739. },
  5740. /**
  5741. * Clone
  5742. * @return {zrender/graphic/Style} [description]
  5743. */
  5744. clone: function () {
  5745. var newStyle = new this.constructor();
  5746. newStyle.extendFrom(this, true);
  5747. return newStyle;
  5748. },
  5749. getGradient: function (ctx, obj, rect) {
  5750. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5751. var canvasGradient = method(ctx, obj, rect);
  5752. var colorStops = obj.colorStops;
  5753. for (var i = 0; i < colorStops.length; i++) {
  5754. canvasGradient.addColorStop(
  5755. colorStops[i].offset, colorStops[i].color
  5756. );
  5757. }
  5758. return canvasGradient;
  5759. }
  5760. };
  5761. var styleProto = Style.prototype;
  5762. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5763. var prop = STYLE_COMMON_PROPS[i];
  5764. if (!(prop[0] in styleProto)) {
  5765. styleProto[prop[0]] = prop[1];
  5766. }
  5767. }
  5768. // Provide for others
  5769. Style.getGradient = styleProto.getGradient;
  5770. var Pattern = function (image, repeat) {
  5771. // Should do nothing more in this constructor. Because gradient can be
  5772. // declard by `color: {image: ...}`, where this constructor will not be called.
  5773. this.image = image;
  5774. this.repeat = repeat;
  5775. // Can be cloned
  5776. this.type = 'pattern';
  5777. };
  5778. Pattern.prototype.getCanvasPattern = function (ctx) {
  5779. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5780. };
  5781. /**
  5782. * @module zrender/Layer
  5783. * @author pissang(https://www.github.com/pissang)
  5784. */
  5785. function returnFalse() {
  5786. return false;
  5787. }
  5788. /**
  5789. * 创建dom
  5790. *
  5791. * @inner
  5792. * @param {string} id dom id 待用
  5793. * @param {Painter} painter painter instance
  5794. * @param {number} number
  5795. */
  5796. function createDom(id, painter, dpr) {
  5797. var newDom = createCanvas();
  5798. var width = painter.getWidth();
  5799. var height = painter.getHeight();
  5800. var newDomStyle = newDom.style;
  5801. if (newDomStyle) { // In node or some other non-browser environment
  5802. newDomStyle.position = 'absolute';
  5803. newDomStyle.left = 0;
  5804. newDomStyle.top = 0;
  5805. newDomStyle.width = width + 'px';
  5806. newDomStyle.height = height + 'px';
  5807. newDom.setAttribute('data-zr-dom-id', id);
  5808. }
  5809. newDom.width = width * dpr;
  5810. newDom.height = height * dpr;
  5811. return newDom;
  5812. }
  5813. /**
  5814. * @alias module:zrender/Layer
  5815. * @constructor
  5816. * @extends module:zrender/mixin/Transformable
  5817. * @param {string} id
  5818. * @param {module:zrender/Painter} painter
  5819. * @param {number} [dpr]
  5820. */
  5821. var Layer = function(id, painter, dpr) {
  5822. var dom;
  5823. dpr = dpr || devicePixelRatio;
  5824. if (typeof id === 'string') {
  5825. dom = createDom(id, painter, dpr);
  5826. }
  5827. // Not using isDom because in node it will return false
  5828. else if (isObject$1(id)) {
  5829. dom = id;
  5830. id = dom.id;
  5831. }
  5832. this.id = id;
  5833. this.dom = dom;
  5834. var domStyle = dom.style;
  5835. if (domStyle) { // Not in node
  5836. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5837. domStyle['-webkit-user-select'] = 'none';
  5838. domStyle['user-select'] = 'none';
  5839. domStyle['-webkit-touch-callout'] = 'none';
  5840. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5841. domStyle['padding'] = 0;
  5842. domStyle['margin'] = 0;
  5843. domStyle['border-width'] = 0;
  5844. }
  5845. this.domBack = null;
  5846. this.ctxBack = null;
  5847. this.painter = painter;
  5848. this.config = null;
  5849. // Configs
  5850. /**
  5851. * 每次清空画布的颜色
  5852. * @type {string}
  5853. * @default 0
  5854. */
  5855. this.clearColor = 0;
  5856. /**
  5857. * 是否开启动态模糊
  5858. * @type {boolean}
  5859. * @default false
  5860. */
  5861. this.motionBlur = false;
  5862. /**
  5863. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5864. * @type {number}
  5865. * @default 0.7
  5866. */
  5867. this.lastFrameAlpha = 0.7;
  5868. /**
  5869. * Layer dpr
  5870. * @type {number}
  5871. */
  5872. this.dpr = dpr;
  5873. };
  5874. Layer.prototype = {
  5875. constructor: Layer,
  5876. __dirty: true,
  5877. __used: false,
  5878. __drawIndex: 0,
  5879. __startIndex: 0,
  5880. __endIndex: 0,
  5881. incremental: false,
  5882. getElementCount: function () {
  5883. return this.__endIndex - this.__startIndex;
  5884. },
  5885. initContext: function () {
  5886. this.ctx = this.dom.getContext('2d');
  5887. this.ctx.dpr = this.dpr;
  5888. },
  5889. createBackBuffer: function () {
  5890. var dpr = this.dpr;
  5891. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5892. this.ctxBack = this.domBack.getContext('2d');
  5893. if (dpr != 1) {
  5894. this.ctxBack.scale(dpr, dpr);
  5895. }
  5896. },
  5897. /**
  5898. * @param {number} width
  5899. * @param {number} height
  5900. */
  5901. resize: function (width, height) {
  5902. var dpr = this.dpr;
  5903. var dom = this.dom;
  5904. var domStyle = dom.style;
  5905. var domBack = this.domBack;
  5906. if (domStyle) {
  5907. domStyle.width = width + 'px';
  5908. domStyle.height = height + 'px';
  5909. }
  5910. dom.width = width * dpr;
  5911. dom.height = height * dpr;
  5912. if (domBack) {
  5913. domBack.width = width * dpr;
  5914. domBack.height = height * dpr;
  5915. if (dpr != 1) {
  5916. this.ctxBack.scale(dpr, dpr);
  5917. }
  5918. }
  5919. },
  5920. /**
  5921. * 清空该层画布
  5922. * @param {boolean} [clearAll]=false Clear all with out motion blur
  5923. * @param {Color} [clearColor]
  5924. */
  5925. clear: function (clearAll, clearColor) {
  5926. var dom = this.dom;
  5927. var ctx = this.ctx;
  5928. var width = dom.width;
  5929. var height = dom.height;
  5930. var clearColor = clearColor || this.clearColor;
  5931. var haveMotionBLur = this.motionBlur && !clearAll;
  5932. var lastFrameAlpha = this.lastFrameAlpha;
  5933. var dpr = this.dpr;
  5934. if (haveMotionBLur) {
  5935. if (!this.domBack) {
  5936. this.createBackBuffer();
  5937. }
  5938. this.ctxBack.globalCompositeOperation = 'copy';
  5939. this.ctxBack.drawImage(
  5940. dom, 0, 0,
  5941. width / dpr,
  5942. height / dpr
  5943. );
  5944. }
  5945. ctx.clearRect(0, 0, width, height);
  5946. if (clearColor && clearColor !== 'transparent') {
  5947. var clearColorGradientOrPattern;
  5948. // Gradient
  5949. if (clearColor.colorStops) {
  5950. // Cache canvas gradient
  5951. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5952. x: 0,
  5953. y: 0,
  5954. width: width,
  5955. height: height
  5956. });
  5957. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5958. }
  5959. // Pattern
  5960. else if (clearColor.image) {
  5961. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5962. }
  5963. ctx.save();
  5964. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5965. ctx.fillRect(0, 0, width, height);
  5966. ctx.restore();
  5967. }
  5968. if (haveMotionBLur) {
  5969. var domBack = this.domBack;
  5970. ctx.save();
  5971. ctx.globalAlpha = lastFrameAlpha;
  5972. ctx.drawImage(domBack, 0, 0, width, height);
  5973. ctx.restore();
  5974. }
  5975. }
  5976. };
  5977. var requestAnimationFrame = (
  5978. typeof window !== 'undefined'
  5979. && (
  5980. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5981. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5982. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5983. || window.mozRequestAnimationFrame
  5984. || window.webkitRequestAnimationFrame
  5985. )
  5986. ) || function (func) {
  5987. setTimeout(func, 16);
  5988. };
  5989. var globalImageCache = new LRU(50);
  5990. /**
  5991. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5992. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5993. */
  5994. function findExistImage(newImageOrSrc) {
  5995. if (typeof newImageOrSrc === 'string') {
  5996. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5997. return cachedImgObj && cachedImgObj.image;
  5998. }
  5999. else {
  6000. return newImageOrSrc;
  6001. }
  6002. }
  6003. /**
  6004. * Caution: User should cache loaded images, but not just count on LRU.
  6005. * Consider if required images more than LRU size, will dead loop occur?
  6006. *
  6007. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6008. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6009. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6010. * @param {Function} [cb] params: (image, cbPayload)
  6011. * @param {Object} [cbPayload] Payload on cb calling.
  6012. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6013. */
  6014. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6015. if (!newImageOrSrc) {
  6016. return image;
  6017. }
  6018. else if (typeof newImageOrSrc === 'string') {
  6019. // Image should not be loaded repeatly.
  6020. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6021. return image;
  6022. }
  6023. // Only when there is no existent image or existent image src
  6024. // is different, this method is responsible for load.
  6025. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6026. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6027. if (cachedImgObj) {
  6028. image = cachedImgObj.image;
  6029. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6030. }
  6031. else {
  6032. !image && (image = new Image());
  6033. image.onload = imageOnLoad;
  6034. globalImageCache.put(
  6035. newImageOrSrc,
  6036. image.__cachedImgObj = {
  6037. image: image,
  6038. pending: [pendingWrap]
  6039. }
  6040. );
  6041. image.src = image.__zrImageSrc = newImageOrSrc;
  6042. }
  6043. return image;
  6044. }
  6045. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6046. else {
  6047. return newImageOrSrc;
  6048. }
  6049. }
  6050. function imageOnLoad() {
  6051. var cachedImgObj = this.__cachedImgObj;
  6052. this.onload = this.__cachedImgObj = null;
  6053. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6054. var pendingWrap = cachedImgObj.pending[i];
  6055. var cb = pendingWrap.cb;
  6056. cb && cb(this, pendingWrap.cbPayload);
  6057. pendingWrap.hostEl.dirty();
  6058. }
  6059. cachedImgObj.pending.length = 0;
  6060. }
  6061. function isImageReady(image) {
  6062. return image && image.width && image.height;
  6063. }
  6064. var textWidthCache = {};
  6065. var textWidthCacheCounter = 0;
  6066. var TEXT_CACHE_MAX = 5000;
  6067. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6068. var DEFAULT_FONT = '12px sans-serif';
  6069. // Avoid assign to an exported variable, for transforming to cjs.
  6070. var methods$1 = {};
  6071. function $override$1(name, fn) {
  6072. methods$1[name] = fn;
  6073. }
  6074. /**
  6075. * @public
  6076. * @param {string} text
  6077. * @param {string} font
  6078. * @return {number} width
  6079. */
  6080. function getWidth(text, font) {
  6081. font = font || DEFAULT_FONT;
  6082. var key = text + ':' + font;
  6083. if (textWidthCache[key]) {
  6084. return textWidthCache[key];
  6085. }
  6086. var textLines = (text + '').split('\n');
  6087. var width = 0;
  6088. for (var i = 0, l = textLines.length; i < l; i++) {
  6089. // textContain.measureText may be overrided in SVG or VML
  6090. width = Math.max(measureText(textLines[i], font).width, width);
  6091. }
  6092. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6093. textWidthCacheCounter = 0;
  6094. textWidthCache = {};
  6095. }
  6096. textWidthCacheCounter++;
  6097. textWidthCache[key] = width;
  6098. return width;
  6099. }
  6100. /**
  6101. * @public
  6102. * @param {string} text
  6103. * @param {string} font
  6104. * @param {string} [textAlign='left']
  6105. * @param {string} [textVerticalAlign='top']
  6106. * @param {Array.<number>} [textPadding]
  6107. * @param {Object} [rich]
  6108. * @param {Object} [truncate]
  6109. * @return {Object} {x, y, width, height, lineHeight}
  6110. */
  6111. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6112. return rich
  6113. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6114. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6115. }
  6116. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6117. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6118. var outerWidth = getWidth(text, font);
  6119. if (textPadding) {
  6120. outerWidth += textPadding[1] + textPadding[3];
  6121. }
  6122. var outerHeight = contentBlock.outerHeight;
  6123. var x = adjustTextX(0, outerWidth, textAlign);
  6124. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6125. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6126. rect.lineHeight = contentBlock.lineHeight;
  6127. return rect;
  6128. }
  6129. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6130. var contentBlock = parseRichText(text, {
  6131. rich: rich,
  6132. truncate: truncate,
  6133. font: font,
  6134. textAlign: textAlign,
  6135. textPadding: textPadding
  6136. });
  6137. var outerWidth = contentBlock.outerWidth;
  6138. var outerHeight = contentBlock.outerHeight;
  6139. var x = adjustTextX(0, outerWidth, textAlign);
  6140. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6141. return new BoundingRect(x, y, outerWidth, outerHeight);
  6142. }
  6143. /**
  6144. * @public
  6145. * @param {number} x
  6146. * @param {number} width
  6147. * @param {string} [textAlign='left']
  6148. * @return {number} Adjusted x.
  6149. */
  6150. function adjustTextX(x, width, textAlign) {
  6151. // FIXME Right to left language
  6152. if (textAlign === 'right') {
  6153. x -= width;
  6154. }
  6155. else if (textAlign === 'center') {
  6156. x -= width / 2;
  6157. }
  6158. return x;
  6159. }
  6160. /**
  6161. * @public
  6162. * @param {number} y
  6163. * @param {number} height
  6164. * @param {string} [textVerticalAlign='top']
  6165. * @return {number} Adjusted y.
  6166. */
  6167. function adjustTextY(y, height, textVerticalAlign) {
  6168. if (textVerticalAlign === 'middle') {
  6169. y -= height / 2;
  6170. }
  6171. else if (textVerticalAlign === 'bottom') {
  6172. y -= height;
  6173. }
  6174. return y;
  6175. }
  6176. /**
  6177. * @public
  6178. * @param {stirng} textPosition
  6179. * @param {Object} rect {x, y, width, height}
  6180. * @param {number} distance
  6181. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6182. */
  6183. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6184. var x = rect.x;
  6185. var y = rect.y;
  6186. var height = rect.height;
  6187. var width = rect.width;
  6188. var halfHeight = height / 2;
  6189. var textAlign = 'left';
  6190. var textVerticalAlign = 'top';
  6191. switch (textPosition) {
  6192. case 'left':
  6193. x -= distance;
  6194. y += halfHeight;
  6195. textAlign = 'right';
  6196. textVerticalAlign = 'middle';
  6197. break;
  6198. case 'right':
  6199. x += distance + width;
  6200. y += halfHeight;
  6201. textVerticalAlign = 'middle';
  6202. break;
  6203. case 'top':
  6204. x += width / 2;
  6205. y -= distance;
  6206. textAlign = 'center';
  6207. textVerticalAlign = 'bottom';
  6208. break;
  6209. case 'bottom':
  6210. x += width / 2;
  6211. y += height + distance;
  6212. textAlign = 'center';
  6213. break;
  6214. case 'inside':
  6215. x += width / 2;
  6216. y += halfHeight;
  6217. textAlign = 'center';
  6218. textVerticalAlign = 'middle';
  6219. break;
  6220. case 'insideLeft':
  6221. x += distance;
  6222. y += halfHeight;
  6223. textVerticalAlign = 'middle';
  6224. break;
  6225. case 'insideRight':
  6226. x += width - distance;
  6227. y += halfHeight;
  6228. textAlign = 'right';
  6229. textVerticalAlign = 'middle';
  6230. break;
  6231. case 'insideTop':
  6232. x += width / 2;
  6233. y += distance;
  6234. textAlign = 'center';
  6235. break;
  6236. case 'insideBottom':
  6237. x += width / 2;
  6238. y += height - distance;
  6239. textAlign = 'center';
  6240. textVerticalAlign = 'bottom';
  6241. break;
  6242. case 'insideTopLeft':
  6243. x += distance;
  6244. y += distance;
  6245. break;
  6246. case 'insideTopRight':
  6247. x += width - distance;
  6248. y += distance;
  6249. textAlign = 'right';
  6250. break;
  6251. case 'insideBottomLeft':
  6252. x += distance;
  6253. y += height - distance;
  6254. textVerticalAlign = 'bottom';
  6255. break;
  6256. case 'insideBottomRight':
  6257. x += width - distance;
  6258. y += height - distance;
  6259. textAlign = 'right';
  6260. textVerticalAlign = 'bottom';
  6261. break;
  6262. }
  6263. return {
  6264. x: x,
  6265. y: y,
  6266. textAlign: textAlign,
  6267. textVerticalAlign: textVerticalAlign
  6268. };
  6269. }
  6270. /**
  6271. * Show ellipsis if overflow.
  6272. *
  6273. * @public
  6274. * @param {string} text
  6275. * @param {string} containerWidth
  6276. * @param {string} font
  6277. * @param {number} [ellipsis='...']
  6278. * @param {Object} [options]
  6279. * @param {number} [options.maxIterations=3]
  6280. * @param {number} [options.minChar=0] If truncate result are less
  6281. * then minChar, ellipsis will not show, which is
  6282. * better for user hint in some cases.
  6283. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6284. * @return {string}
  6285. */
  6286. function truncateText(text, containerWidth, font, ellipsis, options) {
  6287. if (!containerWidth) {
  6288. return '';
  6289. }
  6290. var textLines = (text + '').split('\n');
  6291. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6292. // FIXME
  6293. // It is not appropriate that every line has '...' when truncate multiple lines.
  6294. for (var i = 0, len = textLines.length; i < len; i++) {
  6295. textLines[i] = truncateSingleLine(textLines[i], options);
  6296. }
  6297. return textLines.join('\n');
  6298. }
  6299. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6300. options = extend({}, options);
  6301. options.font = font;
  6302. var ellipsis = retrieve2(ellipsis, '...');
  6303. options.maxIterations = retrieve2(options.maxIterations, 2);
  6304. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6305. // FIXME
  6306. // Other languages?
  6307. options.cnCharWidth = getWidth('国', font);
  6308. // FIXME
  6309. // Consider proportional font?
  6310. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6311. options.placeholder = retrieve2(options.placeholder, '');
  6312. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6313. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6314. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6315. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6316. contentWidth -= ascCharWidth;
  6317. }
  6318. var ellipsisWidth = getWidth(ellipsis);
  6319. if (ellipsisWidth > contentWidth) {
  6320. ellipsis = '';
  6321. ellipsisWidth = 0;
  6322. }
  6323. contentWidth = containerWidth - ellipsisWidth;
  6324. options.ellipsis = ellipsis;
  6325. options.ellipsisWidth = ellipsisWidth;
  6326. options.contentWidth = contentWidth;
  6327. options.containerWidth = containerWidth;
  6328. return options;
  6329. }
  6330. function truncateSingleLine(textLine, options) {
  6331. var containerWidth = options.containerWidth;
  6332. var font = options.font;
  6333. var contentWidth = options.contentWidth;
  6334. if (!containerWidth) {
  6335. return '';
  6336. }
  6337. var lineWidth = getWidth(textLine, font);
  6338. if (lineWidth <= containerWidth) {
  6339. return textLine;
  6340. }
  6341. for (var j = 0;; j++) {
  6342. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6343. textLine += options.ellipsis;
  6344. break;
  6345. }
  6346. var subLength = j === 0
  6347. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6348. : lineWidth > 0
  6349. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6350. : 0;
  6351. textLine = textLine.substr(0, subLength);
  6352. lineWidth = getWidth(textLine, font);
  6353. }
  6354. if (textLine === '') {
  6355. textLine = options.placeholder;
  6356. }
  6357. return textLine;
  6358. }
  6359. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6360. var width = 0;
  6361. var i = 0;
  6362. for (var len = text.length; i < len && width < contentWidth; i++) {
  6363. var charCode = text.charCodeAt(i);
  6364. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6365. }
  6366. return i;
  6367. }
  6368. /**
  6369. * @public
  6370. * @param {string} font
  6371. * @return {number} line height
  6372. */
  6373. function getLineHeight(font) {
  6374. // FIXME A rough approach.
  6375. return getWidth('国', font);
  6376. }
  6377. /**
  6378. * @public
  6379. * @param {string} text
  6380. * @param {string} font
  6381. * @return {Object} width
  6382. */
  6383. function measureText(text, font) {
  6384. return methods$1.measureText(text, font);
  6385. }
  6386. // Avoid assign to an exported variable, for transforming to cjs.
  6387. methods$1.measureText = function (text, font) {
  6388. var ctx = getContext();
  6389. ctx.font = font || DEFAULT_FONT;
  6390. return ctx.measureText(text);
  6391. };
  6392. /**
  6393. * @public
  6394. * @param {string} text
  6395. * @param {string} font
  6396. * @param {Object} [truncate]
  6397. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6398. * Notice: for performance, do not calculate outerWidth util needed.
  6399. */
  6400. function parsePlainText(text, font, padding, truncate) {
  6401. text != null && (text += '');
  6402. var lineHeight = getLineHeight(font);
  6403. var lines = text ? text.split('\n') : [];
  6404. var height = lines.length * lineHeight;
  6405. var outerHeight = height;
  6406. if (padding) {
  6407. outerHeight += padding[0] + padding[2];
  6408. }
  6409. if (text && truncate) {
  6410. var truncOuterHeight = truncate.outerHeight;
  6411. var truncOuterWidth = truncate.outerWidth;
  6412. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6413. text = '';
  6414. lines = [];
  6415. }
  6416. else if (truncOuterWidth != null) {
  6417. var options = prepareTruncateOptions(
  6418. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6419. font,
  6420. truncate.ellipsis,
  6421. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6422. );
  6423. // FIXME
  6424. // It is not appropriate that every line has '...' when truncate multiple lines.
  6425. for (var i = 0, len = lines.length; i < len; i++) {
  6426. lines[i] = truncateSingleLine(lines[i], options);
  6427. }
  6428. }
  6429. }
  6430. return {
  6431. lines: lines,
  6432. height: height,
  6433. outerHeight: outerHeight,
  6434. lineHeight: lineHeight
  6435. };
  6436. }
  6437. /**
  6438. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6439. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6440. *
  6441. * @public
  6442. * @param {string} text
  6443. * @param {Object} style
  6444. * @return {Object} block
  6445. * {
  6446. * width,
  6447. * height,
  6448. * lines: [{
  6449. * lineHeight,
  6450. * width,
  6451. * tokens: [[{
  6452. * styleName,
  6453. * text,
  6454. * width, // include textPadding
  6455. * height, // include textPadding
  6456. * textWidth, // pure text width
  6457. * textHeight, // pure text height
  6458. * lineHeihgt,
  6459. * font,
  6460. * textAlign,
  6461. * textVerticalAlign
  6462. * }], [...], ...]
  6463. * }, ...]
  6464. * }
  6465. * If styleName is undefined, it is plain text.
  6466. */
  6467. function parseRichText(text, style) {
  6468. var contentBlock = {lines: [], width: 0, height: 0};
  6469. text != null && (text += '');
  6470. if (!text) {
  6471. return contentBlock;
  6472. }
  6473. var lastIndex = STYLE_REG.lastIndex = 0;
  6474. var result;
  6475. while ((result = STYLE_REG.exec(text)) != null) {
  6476. var matchedIndex = result.index;
  6477. if (matchedIndex > lastIndex) {
  6478. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6479. }
  6480. pushTokens(contentBlock, result[2], result[1]);
  6481. lastIndex = STYLE_REG.lastIndex;
  6482. }
  6483. if (lastIndex < text.length) {
  6484. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6485. }
  6486. var lines = contentBlock.lines;
  6487. var contentHeight = 0;
  6488. var contentWidth = 0;
  6489. // For `textWidth: 100%`
  6490. var pendingList = [];
  6491. var stlPadding = style.textPadding;
  6492. var truncate = style.truncate;
  6493. var truncateWidth = truncate && truncate.outerWidth;
  6494. var truncateHeight = truncate && truncate.outerHeight;
  6495. if (stlPadding) {
  6496. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6497. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6498. }
  6499. // Calculate layout info of tokens.
  6500. for (var i = 0; i < lines.length; i++) {
  6501. var line = lines[i];
  6502. var lineHeight = 0;
  6503. var lineWidth = 0;
  6504. for (var j = 0; j < line.tokens.length; j++) {
  6505. var token = line.tokens[j];
  6506. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6507. // textPadding should not inherit from style.
  6508. var textPadding = token.textPadding = tokenStyle.textPadding;
  6509. // textFont has been asigned to font by `normalizeStyle`.
  6510. var font = token.font = tokenStyle.font || style.font;
  6511. // textHeight can be used when textVerticalAlign is specified in token.
  6512. var tokenHeight = token.textHeight = retrieve2(
  6513. // textHeight should not be inherited, consider it can be specified
  6514. // as box height of the block.
  6515. tokenStyle.textHeight, getLineHeight(font)
  6516. );
  6517. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6518. token.height = tokenHeight;
  6519. token.lineHeight = retrieve3(
  6520. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6521. );
  6522. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6523. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6524. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6525. return {lines: [], width: 0, height: 0};
  6526. }
  6527. token.textWidth = getWidth(token.text, font);
  6528. var tokenWidth = tokenStyle.textWidth;
  6529. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6530. // Percent width, can be `100%`, can be used in drawing separate
  6531. // line when box width is needed to be auto.
  6532. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6533. token.percentWidth = tokenWidth;
  6534. pendingList.push(token);
  6535. tokenWidth = 0;
  6536. // Do not truncate in this case, because there is no user case
  6537. // and it is too complicated.
  6538. }
  6539. else {
  6540. if (tokenWidthNotSpecified) {
  6541. tokenWidth = token.textWidth;
  6542. // FIXME: If image is not loaded and textWidth is not specified, calling
  6543. // `getBoundingRect()` will not get correct result.
  6544. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6545. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6546. // Use cases:
  6547. // (1) If image is not loaded, it will be loaded at render phase and call
  6548. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6549. // image, and then the right size will be calculated here at the next tick.
  6550. // See `graphic/helper/text.js`.
  6551. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6552. // use `imageHelper.findExistImage` to find cached image.
  6553. // `imageHelper.findExistImage` will always be called here before
  6554. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6555. // which ensures that image will not be rendered before correct size calcualted.
  6556. if (bgImg) {
  6557. bgImg = findExistImage(bgImg);
  6558. if (isImageReady(bgImg)) {
  6559. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6560. }
  6561. }
  6562. }
  6563. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6564. tokenWidth += paddingW;
  6565. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6566. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6567. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6568. token.text = '';
  6569. token.textWidth = tokenWidth = 0;
  6570. }
  6571. else {
  6572. token.text = truncateText(
  6573. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6574. {minChar: truncate.minChar}
  6575. );
  6576. token.textWidth = getWidth(token.text, font);
  6577. tokenWidth = token.textWidth + paddingW;
  6578. }
  6579. }
  6580. }
  6581. lineWidth += (token.width = tokenWidth);
  6582. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6583. }
  6584. line.width = lineWidth;
  6585. line.lineHeight = lineHeight;
  6586. contentHeight += lineHeight;
  6587. contentWidth = Math.max(contentWidth, lineWidth);
  6588. }
  6589. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6590. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6591. if (stlPadding) {
  6592. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6593. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6594. }
  6595. for (var i = 0; i < pendingList.length; i++) {
  6596. var token = pendingList[i];
  6597. var percentWidth = token.percentWidth;
  6598. // Should not base on outerWidth, because token can not be placed out of padding.
  6599. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6600. }
  6601. return contentBlock;
  6602. }
  6603. function pushTokens(block, str, styleName) {
  6604. var isEmptyStr = str === '';
  6605. var strs = str.split('\n');
  6606. var lines = block.lines;
  6607. for (var i = 0; i < strs.length; i++) {
  6608. var text = strs[i];
  6609. var token = {
  6610. styleName: styleName,
  6611. text: text,
  6612. isLineHolder: !text && !isEmptyStr
  6613. };
  6614. // The first token should be appended to the last line.
  6615. if (!i) {
  6616. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6617. // Consider cases:
  6618. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6619. // (which is a placeholder) should be replaced by new token.
  6620. // (2) A image backage, where token likes {a|}.
  6621. // (3) A redundant '' will affect textAlign in line.
  6622. // (4) tokens with the same tplName should not be merged, because
  6623. // they should be displayed in different box (with border and padding).
  6624. var tokensLen = tokens.length;
  6625. (tokensLen === 1 && tokens[0].isLineHolder)
  6626. ? (tokens[0] = token)
  6627. // Consider text is '', only insert when it is the "lineHolder" or
  6628. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6629. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6630. }
  6631. // Other tokens always start a new line.
  6632. else {
  6633. // If there is '', insert it as a placeholder.
  6634. lines.push({tokens: [token]});
  6635. }
  6636. }
  6637. }
  6638. function makeFont(style) {
  6639. // FIXME in node-canvas fontWeight is before fontStyle
  6640. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6641. var font = (style.fontSize || style.fontFamily) && [
  6642. style.fontStyle,
  6643. style.fontWeight,
  6644. (style.fontSize || 12) + 'px',
  6645. // If font properties are defined, `fontFamily` should not be ignored.
  6646. style.fontFamily || 'sans-serif'
  6647. ].join(' ');
  6648. return font && trim(font) || style.textFont || style.font;
  6649. }
  6650. function buildPath(ctx, shape) {
  6651. var x = shape.x;
  6652. var y = shape.y;
  6653. var width = shape.width;
  6654. var height = shape.height;
  6655. var r = shape.r;
  6656. var r1;
  6657. var r2;
  6658. var r3;
  6659. var r4;
  6660. // Convert width and height to positive for better borderRadius
  6661. if (width < 0) {
  6662. x = x + width;
  6663. width = -width;
  6664. }
  6665. if (height < 0) {
  6666. y = y + height;
  6667. height = -height;
  6668. }
  6669. if (typeof r === 'number') {
  6670. r1 = r2 = r3 = r4 = r;
  6671. }
  6672. else if (r instanceof Array) {
  6673. if (r.length === 1) {
  6674. r1 = r2 = r3 = r4 = r[0];
  6675. }
  6676. else if (r.length === 2) {
  6677. r1 = r3 = r[0];
  6678. r2 = r4 = r[1];
  6679. }
  6680. else if (r.length === 3) {
  6681. r1 = r[0];
  6682. r2 = r4 = r[1];
  6683. r3 = r[2];
  6684. }
  6685. else {
  6686. r1 = r[0];
  6687. r2 = r[1];
  6688. r3 = r[2];
  6689. r4 = r[3];
  6690. }
  6691. }
  6692. else {
  6693. r1 = r2 = r3 = r4 = 0;
  6694. }
  6695. var total;
  6696. if (r1 + r2 > width) {
  6697. total = r1 + r2;
  6698. r1 *= width / total;
  6699. r2 *= width / total;
  6700. }
  6701. if (r3 + r4 > width) {
  6702. total = r3 + r4;
  6703. r3 *= width / total;
  6704. r4 *= width / total;
  6705. }
  6706. if (r2 + r3 > height) {
  6707. total = r2 + r3;
  6708. r2 *= height / total;
  6709. r3 *= height / total;
  6710. }
  6711. if (r1 + r4 > height) {
  6712. total = r1 + r4;
  6713. r1 *= height / total;
  6714. r4 *= height / total;
  6715. }
  6716. ctx.moveTo(x + r1, y);
  6717. ctx.lineTo(x + width - r2, y);
  6718. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6719. ctx.lineTo(x + width, y + height - r3);
  6720. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6721. ctx.lineTo(x + r4, y + height);
  6722. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6723. ctx.lineTo(x, y + r1);
  6724. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6725. }
  6726. // TODO: Have not support 'start', 'end' yet.
  6727. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6728. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6729. /**
  6730. * @param {module:zrender/graphic/Style} style
  6731. * @return {module:zrender/graphic/Style} The input style.
  6732. */
  6733. function normalizeTextStyle(style) {
  6734. normalizeStyle(style);
  6735. each$1(style.rich, normalizeStyle);
  6736. return style;
  6737. }
  6738. function normalizeStyle(style) {
  6739. if (style) {
  6740. style.font = makeFont(style);
  6741. var textAlign = style.textAlign;
  6742. textAlign === 'middle' && (textAlign = 'center');
  6743. style.textAlign = (
  6744. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6745. ) ? textAlign : 'left';
  6746. // Compatible with textBaseline.
  6747. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6748. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6749. style.textVerticalAlign = (
  6750. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6751. ) ? textVerticalAlign : 'top';
  6752. var textPadding = style.textPadding;
  6753. if (textPadding) {
  6754. style.textPadding = normalizeCssArray(style.textPadding);
  6755. }
  6756. }
  6757. }
  6758. /**
  6759. * @param {CanvasRenderingContext2D} ctx
  6760. * @param {string} text
  6761. * @param {module:zrender/graphic/Style} style
  6762. * @param {Object|boolean} [rect] {x, y, width, height}
  6763. * If set false, rect text is not used.
  6764. */
  6765. function renderText(hostEl, ctx, text, style, rect) {
  6766. style.rich
  6767. ? renderRichText(hostEl, ctx, text, style, rect)
  6768. : renderPlainText(hostEl, ctx, text, style, rect);
  6769. }
  6770. function renderPlainText(hostEl, ctx, text, style, rect) {
  6771. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6772. var textPadding = style.textPadding;
  6773. var contentBlock = hostEl.__textCotentBlock;
  6774. if (!contentBlock || hostEl.__dirty) {
  6775. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6776. text, font, textPadding, style.truncate
  6777. );
  6778. }
  6779. var outerHeight = contentBlock.outerHeight;
  6780. var textLines = contentBlock.lines;
  6781. var lineHeight = contentBlock.lineHeight;
  6782. var boxPos = getBoxPosition(outerHeight, style, rect);
  6783. var baseX = boxPos.baseX;
  6784. var baseY = boxPos.baseY;
  6785. var textAlign = boxPos.textAlign;
  6786. var textVerticalAlign = boxPos.textVerticalAlign;
  6787. // Origin of textRotation should be the base point of text drawing.
  6788. applyTextRotation(ctx, style, rect, baseX, baseY);
  6789. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6790. var textX = baseX;
  6791. var textY = boxY;
  6792. var needDrawBg = needDrawBackground(style);
  6793. if (needDrawBg || textPadding) {
  6794. // Consider performance, do not call getTextWidth util necessary.
  6795. var textWidth = getWidth(text, font);
  6796. var outerWidth = textWidth;
  6797. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6798. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6799. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6800. if (textPadding) {
  6801. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6802. textY += textPadding[0];
  6803. }
  6804. }
  6805. setCtx(ctx, 'textAlign', textAlign || 'left');
  6806. // Force baseline to be "middle". Otherwise, if using "top", the
  6807. // text will offset downward a little bit in font "Microsoft YaHei".
  6808. setCtx(ctx, 'textBaseline', 'middle');
  6809. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6810. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6811. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6812. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6813. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6814. // `textBaseline` is set as 'middle'.
  6815. textY += lineHeight / 2;
  6816. var textStrokeWidth = style.textStrokeWidth;
  6817. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6818. var textFill = getFill(style.textFill);
  6819. if (textStroke) {
  6820. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6821. setCtx(ctx, 'strokeStyle', textStroke);
  6822. }
  6823. if (textFill) {
  6824. setCtx(ctx, 'fillStyle', textFill);
  6825. }
  6826. for (var i = 0; i < textLines.length; i++) {
  6827. // Fill after stroke so the outline will not cover the main part.
  6828. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6829. textFill && ctx.fillText(textLines[i], textX, textY);
  6830. textY += lineHeight;
  6831. }
  6832. }
  6833. function renderRichText(hostEl, ctx, text, style, rect) {
  6834. var contentBlock = hostEl.__textCotentBlock;
  6835. if (!contentBlock || hostEl.__dirty) {
  6836. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6837. }
  6838. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6839. }
  6840. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6841. var contentWidth = contentBlock.width;
  6842. var outerWidth = contentBlock.outerWidth;
  6843. var outerHeight = contentBlock.outerHeight;
  6844. var textPadding = style.textPadding;
  6845. var boxPos = getBoxPosition(outerHeight, style, rect);
  6846. var baseX = boxPos.baseX;
  6847. var baseY = boxPos.baseY;
  6848. var textAlign = boxPos.textAlign;
  6849. var textVerticalAlign = boxPos.textVerticalAlign;
  6850. // Origin of textRotation should be the base point of text drawing.
  6851. applyTextRotation(ctx, style, rect, baseX, baseY);
  6852. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6853. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6854. var xLeft = boxX;
  6855. var lineTop = boxY;
  6856. if (textPadding) {
  6857. xLeft += textPadding[3];
  6858. lineTop += textPadding[0];
  6859. }
  6860. var xRight = xLeft + contentWidth;
  6861. needDrawBackground(style) && drawBackground(
  6862. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6863. );
  6864. for (var i = 0; i < contentBlock.lines.length; i++) {
  6865. var line = contentBlock.lines[i];
  6866. var tokens = line.tokens;
  6867. var tokenCount = tokens.length;
  6868. var lineHeight = line.lineHeight;
  6869. var usedWidth = line.width;
  6870. var leftIndex = 0;
  6871. var lineXLeft = xLeft;
  6872. var lineXRight = xRight;
  6873. var rightIndex = tokenCount - 1;
  6874. var token;
  6875. while (
  6876. leftIndex < tokenCount
  6877. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6878. ) {
  6879. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6880. usedWidth -= token.width;
  6881. lineXLeft += token.width;
  6882. leftIndex++;
  6883. }
  6884. while (
  6885. rightIndex >= 0
  6886. && (token = tokens[rightIndex], token.textAlign === 'right')
  6887. ) {
  6888. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6889. usedWidth -= token.width;
  6890. lineXRight -= token.width;
  6891. rightIndex--;
  6892. }
  6893. // The other tokens are placed as textAlign 'center' if there is enough space.
  6894. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6895. while (leftIndex <= rightIndex) {
  6896. token = tokens[leftIndex];
  6897. // Consider width specified by user, use 'center' rather than 'left'.
  6898. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6899. lineXLeft += token.width;
  6900. leftIndex++;
  6901. }
  6902. lineTop += lineHeight;
  6903. }
  6904. }
  6905. function applyTextRotation(ctx, style, rect, x, y) {
  6906. // textRotation only apply in RectText.
  6907. if (rect && style.textRotation) {
  6908. var origin = style.textOrigin;
  6909. if (origin === 'center') {
  6910. x = rect.width / 2 + rect.x;
  6911. y = rect.height / 2 + rect.y;
  6912. }
  6913. else if (origin) {
  6914. x = origin[0] + rect.x;
  6915. y = origin[1] + rect.y;
  6916. }
  6917. ctx.translate(x, y);
  6918. // Positive: anticlockwise
  6919. ctx.rotate(-style.textRotation);
  6920. ctx.translate(-x, -y);
  6921. }
  6922. }
  6923. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6924. var tokenStyle = style.rich[token.styleName] || {};
  6925. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6926. // the bias of "Microsoft YaHei".
  6927. var textVerticalAlign = token.textVerticalAlign;
  6928. var y = lineTop + lineHeight / 2;
  6929. if (textVerticalAlign === 'top') {
  6930. y = lineTop + token.height / 2;
  6931. }
  6932. else if (textVerticalAlign === 'bottom') {
  6933. y = lineTop + lineHeight - token.height / 2;
  6934. }
  6935. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6936. hostEl,
  6937. ctx,
  6938. tokenStyle,
  6939. textAlign === 'right'
  6940. ? x - token.width
  6941. : textAlign === 'center'
  6942. ? x - token.width / 2
  6943. : x,
  6944. y - token.height / 2,
  6945. token.width,
  6946. token.height
  6947. );
  6948. var textPadding = token.textPadding;
  6949. if (textPadding) {
  6950. x = getTextXForPadding(x, textAlign, textPadding);
  6951. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6952. }
  6953. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6954. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6955. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6956. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6957. setCtx(ctx, 'textAlign', textAlign);
  6958. // Force baseline to be "middle". Otherwise, if using "top", the
  6959. // text will offset downward a little bit in font "Microsoft YaHei".
  6960. setCtx(ctx, 'textBaseline', 'middle');
  6961. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6962. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6963. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6964. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6965. // Fill after stroke so the outline will not cover the main part.
  6966. if (textStroke) {
  6967. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6968. setCtx(ctx, 'strokeStyle', textStroke);
  6969. ctx.strokeText(token.text, x, y);
  6970. }
  6971. if (textFill) {
  6972. setCtx(ctx, 'fillStyle', textFill);
  6973. ctx.fillText(token.text, x, y);
  6974. }
  6975. }
  6976. function needDrawBackground(style) {
  6977. return style.textBackgroundColor
  6978. || (style.textBorderWidth && style.textBorderColor);
  6979. }
  6980. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6981. // shape: {x, y, width, height}
  6982. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6983. var textBackgroundColor = style.textBackgroundColor;
  6984. var textBorderWidth = style.textBorderWidth;
  6985. var textBorderColor = style.textBorderColor;
  6986. var isPlainBg = isString(textBackgroundColor);
  6987. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6988. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6989. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6990. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6991. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6992. ctx.beginPath();
  6993. var textBorderRadius = style.textBorderRadius;
  6994. if (!textBorderRadius) {
  6995. ctx.rect(x, y, width, height);
  6996. }
  6997. else {
  6998. buildPath(ctx, {
  6999. x: x, y: y, width: width, height: height, r: textBorderRadius
  7000. });
  7001. }
  7002. ctx.closePath();
  7003. }
  7004. if (isPlainBg) {
  7005. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7006. ctx.fill();
  7007. }
  7008. else if (isObject$1(textBackgroundColor)) {
  7009. var image = textBackgroundColor.image;
  7010. image = createOrUpdateImage(
  7011. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7012. );
  7013. if (image && isImageReady(image)) {
  7014. ctx.drawImage(image, x, y, width, height);
  7015. }
  7016. }
  7017. if (textBorderWidth && textBorderColor) {
  7018. setCtx(ctx, 'lineWidth', textBorderWidth);
  7019. setCtx(ctx, 'strokeStyle', textBorderColor);
  7020. ctx.stroke();
  7021. }
  7022. }
  7023. function onBgImageLoaded(image, textBackgroundColor) {
  7024. // Replace image, so that `contain/text.js#parseRichText`
  7025. // will get correct result in next tick.
  7026. textBackgroundColor.image = image;
  7027. }
  7028. function getBoxPosition(blockHeiht, style, rect) {
  7029. var baseX = style.x || 0;
  7030. var baseY = style.y || 0;
  7031. var textAlign = style.textAlign;
  7032. var textVerticalAlign = style.textVerticalAlign;
  7033. // Text position represented by coord
  7034. if (rect) {
  7035. var textPosition = style.textPosition;
  7036. if (textPosition instanceof Array) {
  7037. // Percent
  7038. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7039. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7040. }
  7041. else {
  7042. var res = adjustTextPositionOnRect(
  7043. textPosition, rect, style.textDistance
  7044. );
  7045. baseX = res.x;
  7046. baseY = res.y;
  7047. // Default align and baseline when has textPosition
  7048. textAlign = textAlign || res.textAlign;
  7049. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7050. }
  7051. // textOffset is only support in RectText, otherwise
  7052. // we have to adjust boundingRect for textOffset.
  7053. var textOffset = style.textOffset;
  7054. if (textOffset) {
  7055. baseX += textOffset[0];
  7056. baseY += textOffset[1];
  7057. }
  7058. }
  7059. return {
  7060. baseX: baseX,
  7061. baseY: baseY,
  7062. textAlign: textAlign,
  7063. textVerticalAlign: textVerticalAlign
  7064. };
  7065. }
  7066. function setCtx(ctx, prop, value) {
  7067. ctx[prop] = fixShadow(ctx, prop, value);
  7068. return ctx[prop];
  7069. }
  7070. /**
  7071. * @param {string} [stroke] If specified, do not check style.textStroke.
  7072. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7073. * @param {number} style
  7074. */
  7075. function getStroke(stroke, lineWidth) {
  7076. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7077. ? null
  7078. // TODO pattern and gradient?
  7079. : (stroke.image || stroke.colorStops)
  7080. ? '#000'
  7081. : stroke;
  7082. }
  7083. function getFill(fill) {
  7084. return (fill == null || fill === 'none')
  7085. ? null
  7086. // TODO pattern and gradient?
  7087. : (fill.image || fill.colorStops)
  7088. ? '#000'
  7089. : fill;
  7090. }
  7091. function parsePercent(value, maxValue) {
  7092. if (typeof value === 'string') {
  7093. if (value.lastIndexOf('%') >= 0) {
  7094. return parseFloat(value) / 100 * maxValue;
  7095. }
  7096. return parseFloat(value);
  7097. }
  7098. return value;
  7099. }
  7100. function getTextXForPadding(x, textAlign, textPadding) {
  7101. return textAlign === 'right'
  7102. ? (x - textPadding[1])
  7103. : textAlign === 'center'
  7104. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7105. : (x + textPadding[3]);
  7106. }
  7107. /**
  7108. * @param {string} text
  7109. * @param {module:zrender/Style} style
  7110. * @return {boolean}
  7111. */
  7112. function needDrawText(text, style) {
  7113. return text != null
  7114. && (text
  7115. || style.textBackgroundColor
  7116. || (style.textBorderWidth && style.textBorderColor)
  7117. || style.textPadding
  7118. );
  7119. }
  7120. /**
  7121. * Mixin for drawing text in a element bounding rect
  7122. * @module zrender/mixin/RectText
  7123. */
  7124. var tmpRect$1 = new BoundingRect();
  7125. var RectText = function () {};
  7126. RectText.prototype = {
  7127. constructor: RectText,
  7128. /**
  7129. * Draw text in a rect with specified position.
  7130. * @param {CanvasRenderingContext2D} ctx
  7131. * @param {Object} rect Displayable rect
  7132. */
  7133. drawRectText: function (ctx, rect) {
  7134. var style = this.style;
  7135. rect = style.textRect || rect;
  7136. // Optimize, avoid normalize every time.
  7137. this.__dirty && normalizeTextStyle(style, true);
  7138. var text = style.text;
  7139. // Convert to string
  7140. text != null && (text += '');
  7141. if (!needDrawText(text, style)) {
  7142. return;
  7143. }
  7144. // FIXME
  7145. ctx.save();
  7146. // Transform rect to view space
  7147. var transform = this.transform;
  7148. if (!style.transformText) {
  7149. if (transform) {
  7150. tmpRect$1.copy(rect);
  7151. tmpRect$1.applyTransform(transform);
  7152. rect = tmpRect$1;
  7153. }
  7154. }
  7155. else {
  7156. this.setTransform(ctx);
  7157. }
  7158. // transformText and textRotation can not be used at the same time.
  7159. renderText(this, ctx, text, style, rect);
  7160. ctx.restore();
  7161. }
  7162. };
  7163. /**
  7164. * 可绘制的图形基类
  7165. * Base class of all displayable graphic objects
  7166. * @module zrender/graphic/Displayable
  7167. */
  7168. /**
  7169. * @alias module:zrender/graphic/Displayable
  7170. * @extends module:zrender/Element
  7171. * @extends module:zrender/graphic/mixin/RectText
  7172. */
  7173. function Displayable(opts) {
  7174. opts = opts || {};
  7175. Element.call(this, opts);
  7176. // Extend properties
  7177. for (var name in opts) {
  7178. if (
  7179. opts.hasOwnProperty(name) &&
  7180. name !== 'style'
  7181. ) {
  7182. this[name] = opts[name];
  7183. }
  7184. }
  7185. /**
  7186. * @type {module:zrender/graphic/Style}
  7187. */
  7188. this.style = new Style(opts.style, this);
  7189. this._rect = null;
  7190. // Shapes for cascade clipping.
  7191. this.__clipPaths = [];
  7192. // FIXME Stateful must be mixined after style is setted
  7193. // Stateful.call(this, opts);
  7194. }
  7195. Displayable.prototype = {
  7196. constructor: Displayable,
  7197. type: 'displayable',
  7198. /**
  7199. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7200. * Dirty flag. From which painter will determine if this displayable object needs brush
  7201. * @name module:zrender/graphic/Displayable#__dirty
  7202. * @type {boolean}
  7203. */
  7204. __dirty: true,
  7205. /**
  7206. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7207. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7208. * @name module:/zrender/graphic/Displayable#invisible
  7209. * @type {boolean}
  7210. * @default false
  7211. */
  7212. invisible: false,
  7213. /**
  7214. * @name module:/zrender/graphic/Displayable#z
  7215. * @type {number}
  7216. * @default 0
  7217. */
  7218. z: 0,
  7219. /**
  7220. * @name module:/zrender/graphic/Displayable#z
  7221. * @type {number}
  7222. * @default 0
  7223. */
  7224. z2: 0,
  7225. /**
  7226. * z层level,决定绘画在哪层canvas中
  7227. * @name module:/zrender/graphic/Displayable#zlevel
  7228. * @type {number}
  7229. * @default 0
  7230. */
  7231. zlevel: 0,
  7232. /**
  7233. * 是否可拖拽
  7234. * @name module:/zrender/graphic/Displayable#draggable
  7235. * @type {boolean}
  7236. * @default false
  7237. */
  7238. draggable: false,
  7239. /**
  7240. * 是否正在拖拽
  7241. * @name module:/zrender/graphic/Displayable#draggable
  7242. * @type {boolean}
  7243. * @default false
  7244. */
  7245. dragging: false,
  7246. /**
  7247. * 是否相应鼠标事件
  7248. * @name module:/zrender/graphic/Displayable#silent
  7249. * @type {boolean}
  7250. * @default false
  7251. */
  7252. silent: false,
  7253. /**
  7254. * If enable culling
  7255. * @type {boolean}
  7256. * @default false
  7257. */
  7258. culling: false,
  7259. /**
  7260. * Mouse cursor when hovered
  7261. * @name module:/zrender/graphic/Displayable#cursor
  7262. * @type {string}
  7263. */
  7264. cursor: 'pointer',
  7265. /**
  7266. * If hover area is bounding rect
  7267. * @name module:/zrender/graphic/Displayable#rectHover
  7268. * @type {string}
  7269. */
  7270. rectHover: false,
  7271. /**
  7272. * Render the element progressively when the value >= 0,
  7273. * usefull for large data.
  7274. * @type {boolean}
  7275. */
  7276. progressive: false,
  7277. /**
  7278. * @type {boolean}
  7279. */
  7280. incremental: false,
  7281. // inplace is used with incremental
  7282. inplace: false,
  7283. beforeBrush: function (ctx) {},
  7284. afterBrush: function (ctx) {},
  7285. /**
  7286. * 图形绘制方法
  7287. * @param {CanvasRenderingContext2D} ctx
  7288. */
  7289. // Interface
  7290. brush: function (ctx, prevEl) {},
  7291. /**
  7292. * 获取最小包围盒
  7293. * @return {module:zrender/core/BoundingRect}
  7294. */
  7295. // Interface
  7296. getBoundingRect: function () {},
  7297. /**
  7298. * 判断坐标 x, y 是否在图形上
  7299. * If displayable element contain coord x, y
  7300. * @param {number} x
  7301. * @param {number} y
  7302. * @return {boolean}
  7303. */
  7304. contain: function (x, y) {
  7305. return this.rectContain(x, y);
  7306. },
  7307. /**
  7308. * @param {Function} cb
  7309. * @param {} context
  7310. */
  7311. traverse: function (cb, context) {
  7312. cb.call(context, this);
  7313. },
  7314. /**
  7315. * 判断坐标 x, y 是否在图形的包围盒上
  7316. * If bounding rect of element contain coord x, y
  7317. * @param {number} x
  7318. * @param {number} y
  7319. * @return {boolean}
  7320. */
  7321. rectContain: function (x, y) {
  7322. var coord = this.transformCoordToLocal(x, y);
  7323. var rect = this.getBoundingRect();
  7324. return rect.contain(coord[0], coord[1]);
  7325. },
  7326. /**
  7327. * 标记图形元素为脏,并且在下一帧重绘
  7328. * Mark displayable element dirty and refresh next frame
  7329. */
  7330. dirty: function () {
  7331. this.__dirty = true;
  7332. this._rect = null;
  7333. this.__zr && this.__zr.refresh();
  7334. },
  7335. /**
  7336. * 图形是否会触发事件
  7337. * If displayable object binded any event
  7338. * @return {boolean}
  7339. */
  7340. // TODO, 通过 bind 绑定的事件
  7341. // isSilent: function () {
  7342. // return !(
  7343. // this.hoverable || this.draggable
  7344. // || this.onmousemove || this.onmouseover || this.onmouseout
  7345. // || this.onmousedown || this.onmouseup || this.onclick
  7346. // || this.ondragenter || this.ondragover || this.ondragleave
  7347. // || this.ondrop
  7348. // );
  7349. // },
  7350. /**
  7351. * Alias for animate('style')
  7352. * @param {boolean} loop
  7353. */
  7354. animateStyle: function (loop) {
  7355. return this.animate('style', loop);
  7356. },
  7357. attrKV: function (key, value) {
  7358. if (key !== 'style') {
  7359. Element.prototype.attrKV.call(this, key, value);
  7360. }
  7361. else {
  7362. this.style.set(value);
  7363. }
  7364. },
  7365. /**
  7366. * @param {Object|string} key
  7367. * @param {*} value
  7368. */
  7369. setStyle: function (key, value) {
  7370. this.style.set(key, value);
  7371. this.dirty(false);
  7372. return this;
  7373. },
  7374. /**
  7375. * Use given style object
  7376. * @param {Object} obj
  7377. */
  7378. useStyle: function (obj) {
  7379. this.style = new Style(obj, this);
  7380. this.dirty(false);
  7381. return this;
  7382. }
  7383. };
  7384. inherits(Displayable, Element);
  7385. mixin(Displayable, RectText);
  7386. /**
  7387. * @alias zrender/graphic/Image
  7388. * @extends module:zrender/graphic/Displayable
  7389. * @constructor
  7390. * @param {Object} opts
  7391. */
  7392. function ZImage(opts) {
  7393. Displayable.call(this, opts);
  7394. }
  7395. ZImage.prototype = {
  7396. constructor: ZImage,
  7397. type: 'image',
  7398. brush: function (ctx, prevEl) {
  7399. var style = this.style;
  7400. var src = style.image;
  7401. // Must bind each time
  7402. style.bind(ctx, this, prevEl);
  7403. var image = this._image = createOrUpdateImage(
  7404. src,
  7405. this._image,
  7406. this,
  7407. this.onload
  7408. );
  7409. if (!image || !isImageReady(image)) {
  7410. return;
  7411. }
  7412. // 图片已经加载完成
  7413. // if (image.nodeName.toUpperCase() == 'IMG') {
  7414. // if (!image.complete) {
  7415. // return;
  7416. // }
  7417. // }
  7418. // Else is canvas
  7419. var x = style.x || 0;
  7420. var y = style.y || 0;
  7421. var width = style.width;
  7422. var height = style.height;
  7423. var aspect = image.width / image.height;
  7424. if (width == null && height != null) {
  7425. // Keep image/height ratio
  7426. width = height * aspect;
  7427. }
  7428. else if (height == null && width != null) {
  7429. height = width / aspect;
  7430. }
  7431. else if (width == null && height == null) {
  7432. width = image.width;
  7433. height = image.height;
  7434. }
  7435. // 设置transform
  7436. this.setTransform(ctx);
  7437. if (style.sWidth && style.sHeight) {
  7438. var sx = style.sx || 0;
  7439. var sy = style.sy || 0;
  7440. ctx.drawImage(
  7441. image,
  7442. sx, sy, style.sWidth, style.sHeight,
  7443. x, y, width, height
  7444. );
  7445. }
  7446. else if (style.sx && style.sy) {
  7447. var sx = style.sx;
  7448. var sy = style.sy;
  7449. var sWidth = width - sx;
  7450. var sHeight = height - sy;
  7451. ctx.drawImage(
  7452. image,
  7453. sx, sy, sWidth, sHeight,
  7454. x, y, width, height
  7455. );
  7456. }
  7457. else {
  7458. ctx.drawImage(image, x, y, width, height);
  7459. }
  7460. // Draw rect text
  7461. if (style.text != null) {
  7462. // Only restore transform when needs draw text.
  7463. this.restoreTransform(ctx);
  7464. this.drawRectText(ctx, this.getBoundingRect());
  7465. }
  7466. },
  7467. getBoundingRect: function () {
  7468. var style = this.style;
  7469. if (! this._rect) {
  7470. this._rect = new BoundingRect(
  7471. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7472. );
  7473. }
  7474. return this._rect;
  7475. }
  7476. };
  7477. inherits(ZImage, Displayable);
  7478. var HOVER_LAYER_ZLEVEL = 1e5;
  7479. var CANVAS_ZLEVEL = 314159;
  7480. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7481. var INCREMENTAL_INC = 0.001;
  7482. function parseInt10(val) {
  7483. return parseInt(val, 10);
  7484. }
  7485. function isLayerValid(layer) {
  7486. if (!layer) {
  7487. return false;
  7488. }
  7489. if (layer.__builtin__) {
  7490. return true;
  7491. }
  7492. if (typeof(layer.resize) !== 'function'
  7493. || typeof(layer.refresh) !== 'function'
  7494. ) {
  7495. return false;
  7496. }
  7497. return true;
  7498. }
  7499. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7500. var viewRect = new BoundingRect(0, 0, 0, 0);
  7501. function isDisplayableCulled(el, width, height) {
  7502. tmpRect.copy(el.getBoundingRect());
  7503. if (el.transform) {
  7504. tmpRect.applyTransform(el.transform);
  7505. }
  7506. viewRect.width = width;
  7507. viewRect.height = height;
  7508. return !tmpRect.intersect(viewRect);
  7509. }
  7510. function isClipPathChanged(clipPaths, prevClipPaths) {
  7511. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7512. return false;
  7513. }
  7514. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7515. return true;
  7516. }
  7517. for (var i = 0; i < clipPaths.length; i++) {
  7518. if (clipPaths[i] !== prevClipPaths[i]) {
  7519. return true;
  7520. }
  7521. }
  7522. }
  7523. function doClip(clipPaths, ctx) {
  7524. for (var i = 0; i < clipPaths.length; i++) {
  7525. var clipPath = clipPaths[i];
  7526. clipPath.setTransform(ctx);
  7527. ctx.beginPath();
  7528. clipPath.buildPath(ctx, clipPath.shape);
  7529. ctx.clip();
  7530. // Transform back
  7531. clipPath.restoreTransform(ctx);
  7532. }
  7533. }
  7534. function createRoot(width, height) {
  7535. var domRoot = document.createElement('div');
  7536. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7537. domRoot.style.cssText = [
  7538. 'position:relative',
  7539. 'overflow:hidden',
  7540. 'width:' + width + 'px',
  7541. 'height:' + height + 'px',
  7542. 'padding:0',
  7543. 'margin:0',
  7544. 'border-width:0'
  7545. ].join(';') + ';';
  7546. return domRoot;
  7547. }
  7548. /**
  7549. * @alias module:zrender/Painter
  7550. * @constructor
  7551. * @param {HTMLElement} root 绘图容器
  7552. * @param {module:zrender/Storage} storage
  7553. * @param {Object} opts
  7554. */
  7555. var Painter = function (root, storage, opts) {
  7556. this.type = 'canvas';
  7557. // In node environment using node-canvas
  7558. var singleCanvas = !root.nodeName // In node ?
  7559. || root.nodeName.toUpperCase() === 'CANVAS';
  7560. this._opts = opts = extend({}, opts || {});
  7561. /**
  7562. * @type {number}
  7563. */
  7564. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7565. /**
  7566. * @type {boolean}
  7567. * @private
  7568. */
  7569. this._singleCanvas = singleCanvas;
  7570. /**
  7571. * 绘图容器
  7572. * @type {HTMLElement}
  7573. */
  7574. this.root = root;
  7575. var rootStyle = root.style;
  7576. if (rootStyle) {
  7577. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7578. rootStyle['-webkit-user-select'] =
  7579. rootStyle['user-select'] =
  7580. rootStyle['-webkit-touch-callout'] = 'none';
  7581. root.innerHTML = '';
  7582. }
  7583. /**
  7584. * @type {module:zrender/Storage}
  7585. */
  7586. this.storage = storage;
  7587. /**
  7588. * @type {Array.<number>}
  7589. * @private
  7590. */
  7591. var zlevelList = this._zlevelList = [];
  7592. /**
  7593. * @type {Object.<string, module:zrender/Layer>}
  7594. * @private
  7595. */
  7596. var layers = this._layers = {};
  7597. /**
  7598. * @type {Object.<string, Object>}
  7599. * @private
  7600. */
  7601. this._layerConfig = {};
  7602. /**
  7603. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7604. */
  7605. this._needsManuallyCompositing = false;
  7606. if (!singleCanvas) {
  7607. this._width = this._getSize(0);
  7608. this._height = this._getSize(1);
  7609. var domRoot = this._domRoot = createRoot(
  7610. this._width, this._height
  7611. );
  7612. root.appendChild(domRoot);
  7613. }
  7614. else {
  7615. var width = root.width;
  7616. var height = root.height;
  7617. if (opts.width != null) {
  7618. width = opts.width;
  7619. }
  7620. if (opts.height != null) {
  7621. height = opts.height;
  7622. }
  7623. this.dpr = opts.devicePixelRatio || 1;
  7624. // Use canvas width and height directly
  7625. root.width = width * this.dpr;
  7626. root.height = height * this.dpr;
  7627. this._width = width;
  7628. this._height = height;
  7629. // Create layer if only one given canvas
  7630. // Device can be specified to create a high dpi image.
  7631. var mainLayer = new Layer(root, this, this.dpr);
  7632. mainLayer.__builtin__ = true;
  7633. mainLayer.initContext();
  7634. // FIXME Use canvas width and height
  7635. // mainLayer.resize(width, height);
  7636. layers[CANVAS_ZLEVEL] = mainLayer;
  7637. // Not use common zlevel.
  7638. zlevelList.push(CANVAS_ZLEVEL);
  7639. this._domRoot = root;
  7640. }
  7641. /**
  7642. * @type {module:zrender/Layer}
  7643. * @private
  7644. */
  7645. this._hoverlayer = null;
  7646. this._hoverElements = [];
  7647. };
  7648. Painter.prototype = {
  7649. constructor: Painter,
  7650. getType: function () {
  7651. return 'canvas';
  7652. },
  7653. /**
  7654. * If painter use a single canvas
  7655. * @return {boolean}
  7656. */
  7657. isSingleCanvas: function () {
  7658. return this._singleCanvas;
  7659. },
  7660. /**
  7661. * @return {HTMLDivElement}
  7662. */
  7663. getViewportRoot: function () {
  7664. return this._domRoot;
  7665. },
  7666. getViewportRootOffset: function () {
  7667. var viewportRoot = this.getViewportRoot();
  7668. if (viewportRoot) {
  7669. return {
  7670. offsetLeft: viewportRoot.offsetLeft || 0,
  7671. offsetTop: viewportRoot.offsetTop || 0
  7672. };
  7673. }
  7674. },
  7675. /**
  7676. * 刷新
  7677. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7678. */
  7679. refresh: function (paintAll) {
  7680. var list = this.storage.getDisplayList(true);
  7681. var zlevelList = this._zlevelList;
  7682. this._redrawId = Math.random();
  7683. this._paintList(list, paintAll, this._redrawId);
  7684. // Paint custum layers
  7685. for (var i = 0; i < zlevelList.length; i++) {
  7686. var z = zlevelList[i];
  7687. var layer = this._layers[z];
  7688. if (!layer.__builtin__ && layer.refresh) {
  7689. var clearColor = i === 0 ? this._backgroundColor : null;
  7690. layer.refresh(clearColor);
  7691. }
  7692. }
  7693. this.refreshHover();
  7694. return this;
  7695. },
  7696. addHover: function (el, hoverStyle) {
  7697. if (el.__hoverMir) {
  7698. return;
  7699. }
  7700. var elMirror = new el.constructor({
  7701. style: el.style,
  7702. shape: el.shape
  7703. });
  7704. elMirror.__from = el;
  7705. el.__hoverMir = elMirror;
  7706. elMirror.setStyle(hoverStyle);
  7707. this._hoverElements.push(elMirror);
  7708. },
  7709. removeHover: function (el) {
  7710. var elMirror = el.__hoverMir;
  7711. var hoverElements = this._hoverElements;
  7712. var idx = indexOf(hoverElements, elMirror);
  7713. if (idx >= 0) {
  7714. hoverElements.splice(idx, 1);
  7715. }
  7716. el.__hoverMir = null;
  7717. },
  7718. clearHover: function (el) {
  7719. var hoverElements = this._hoverElements;
  7720. for (var i = 0; i < hoverElements.length; i++) {
  7721. var from = hoverElements[i].__from;
  7722. if (from) {
  7723. from.__hoverMir = null;
  7724. }
  7725. }
  7726. hoverElements.length = 0;
  7727. },
  7728. refreshHover: function () {
  7729. var hoverElements = this._hoverElements;
  7730. var len = hoverElements.length;
  7731. var hoverLayer = this._hoverlayer;
  7732. hoverLayer && hoverLayer.clear();
  7733. if (!len) {
  7734. return;
  7735. }
  7736. sort(hoverElements, this.storage.displayableSortFunc);
  7737. // Use a extream large zlevel
  7738. // FIXME?
  7739. if (!hoverLayer) {
  7740. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7741. }
  7742. var scope = {};
  7743. hoverLayer.ctx.save();
  7744. for (var i = 0; i < len;) {
  7745. var el = hoverElements[i];
  7746. var originalEl = el.__from;
  7747. // Original el is removed
  7748. // PENDING
  7749. if (!(originalEl && originalEl.__zr)) {
  7750. hoverElements.splice(i, 1);
  7751. originalEl.__hoverMir = null;
  7752. len--;
  7753. continue;
  7754. }
  7755. i++;
  7756. // Use transform
  7757. // FIXME style and shape ?
  7758. if (!originalEl.invisible) {
  7759. el.transform = originalEl.transform;
  7760. el.invTransform = originalEl.invTransform;
  7761. el.__clipPaths = originalEl.__clipPaths;
  7762. // el.
  7763. this._doPaintEl(el, hoverLayer, true, scope);
  7764. }
  7765. }
  7766. hoverLayer.ctx.restore();
  7767. },
  7768. getHoverLayer: function () {
  7769. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7770. },
  7771. _paintList: function (list, paintAll, redrawId) {
  7772. if (this._redrawId !== redrawId) {
  7773. return;
  7774. }
  7775. paintAll = paintAll || false;
  7776. this._updateLayerStatus(list);
  7777. var finished = this._doPaintList(list, paintAll);
  7778. if (this._needsManuallyCompositing) {
  7779. this._compositeManually();
  7780. }
  7781. if (!finished) {
  7782. var self = this;
  7783. requestAnimationFrame(function () {
  7784. self._paintList(list, paintAll, redrawId);
  7785. });
  7786. }
  7787. },
  7788. _compositeManually: function () {
  7789. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7790. var width = this._domRoot.width;
  7791. var height = this._domRoot.height;
  7792. ctx.clearRect(0, 0, width, height);
  7793. // PENDING, If only builtin layer?
  7794. this.eachBuiltinLayer(function (layer) {
  7795. if (layer.virtual) {
  7796. ctx.drawImage(layer.dom, 0, 0, width, height);
  7797. }
  7798. });
  7799. },
  7800. _doPaintList: function (list, paintAll) {
  7801. var layerList = [];
  7802. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7803. var zlevel = this._zlevelList[zi];
  7804. var layer = this._layers[zlevel];
  7805. if (layer.__builtin__
  7806. && layer !== this._hoverlayer
  7807. && (layer.__dirty || paintAll)
  7808. ) {
  7809. layerList.push(layer);
  7810. }
  7811. }
  7812. var finished = true;
  7813. for (var k = 0; k < layerList.length; k++) {
  7814. var layer = layerList[k];
  7815. var ctx = layer.ctx;
  7816. var scope = {};
  7817. ctx.save();
  7818. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7819. var useTimer = !paintAll && layer.incremental && Date.now;
  7820. var startTime = useTimer && Date.now();
  7821. var clearColor = layer.zlevel === this._zlevelList[0]
  7822. ? this._backgroundColor : null;
  7823. // All elements in this layer are cleared.
  7824. if (layer.__startIndex === layer.__endIndex) {
  7825. layer.clear(false, clearColor);
  7826. }
  7827. else if (start === layer.__startIndex) {
  7828. var firstEl = list[start];
  7829. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7830. layer.clear(false, clearColor);
  7831. }
  7832. }
  7833. if (start === -1) {
  7834. console.error('For some unknown reason. drawIndex is -1');
  7835. start = layer.__startIndex;
  7836. }
  7837. for (var i = start; i < layer.__endIndex; i++) {
  7838. var el = list[i];
  7839. this._doPaintEl(el, layer, paintAll, scope);
  7840. el.__dirty = false;
  7841. if (useTimer) {
  7842. // Date.now can be executed in 13,025,305 ops/second.
  7843. var dTime = Date.now() - startTime;
  7844. // Give 15 millisecond to draw.
  7845. // The rest elements will be drawn in the next frame.
  7846. if (dTime > 15) {
  7847. break;
  7848. }
  7849. }
  7850. }
  7851. layer.__drawIndex = i;
  7852. if (layer.__drawIndex < layer.__endIndex) {
  7853. finished = false;
  7854. }
  7855. if (scope.prevElClipPaths) {
  7856. // Needs restore the state. If last drawn element is in the clipping area.
  7857. ctx.restore();
  7858. }
  7859. ctx.restore();
  7860. }
  7861. if (env$1.wxa) {
  7862. // Flush for weixin application
  7863. each$1(this._layers, function (layer) {
  7864. if (layer && layer.ctx && layer.ctx.draw) {
  7865. layer.ctx.draw();
  7866. }
  7867. });
  7868. }
  7869. return finished;
  7870. },
  7871. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7872. var ctx = currentLayer.ctx;
  7873. var m = el.transform;
  7874. if (
  7875. (currentLayer.__dirty || forcePaint)
  7876. // Ignore invisible element
  7877. && !el.invisible
  7878. // Ignore transparent element
  7879. && el.style.opacity !== 0
  7880. // Ignore scale 0 element, in some environment like node-canvas
  7881. // Draw a scale 0 element can cause all following draw wrong
  7882. // And setTransform with scale 0 will cause set back transform failed.
  7883. && !(m && !m[0] && !m[3])
  7884. // Ignore culled element
  7885. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7886. ) {
  7887. var clipPaths = el.__clipPaths;
  7888. // Optimize when clipping on group with several elements
  7889. if (!scope.prevElClipPaths
  7890. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7891. ) {
  7892. // If has previous clipping state, restore from it
  7893. if (scope.prevElClipPaths) {
  7894. currentLayer.ctx.restore();
  7895. scope.prevElClipPaths = null;
  7896. // Reset prevEl since context has been restored
  7897. scope.prevEl = null;
  7898. }
  7899. // New clipping state
  7900. if (clipPaths) {
  7901. ctx.save();
  7902. doClip(clipPaths, ctx);
  7903. scope.prevElClipPaths = clipPaths;
  7904. }
  7905. }
  7906. el.beforeBrush && el.beforeBrush(ctx);
  7907. el.brush(ctx, scope.prevEl || null);
  7908. scope.prevEl = el;
  7909. el.afterBrush && el.afterBrush(ctx);
  7910. }
  7911. },
  7912. /**
  7913. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7914. * @param {number} zlevel
  7915. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7916. * @return {module:zrender/Layer}
  7917. */
  7918. getLayer: function (zlevel, virtual) {
  7919. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7920. zlevel = CANVAS_ZLEVEL;
  7921. }
  7922. var layer = this._layers[zlevel];
  7923. if (!layer) {
  7924. // Create a new layer
  7925. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7926. layer.zlevel = zlevel;
  7927. layer.__builtin__ = true;
  7928. if (this._layerConfig[zlevel]) {
  7929. merge(layer, this._layerConfig[zlevel], true);
  7930. }
  7931. if (virtual) {
  7932. layer.virtual = virtual;
  7933. }
  7934. this.insertLayer(zlevel, layer);
  7935. // Context is created after dom inserted to document
  7936. // Or excanvas will get 0px clientWidth and clientHeight
  7937. layer.initContext();
  7938. }
  7939. return layer;
  7940. },
  7941. insertLayer: function (zlevel, layer) {
  7942. var layersMap = this._layers;
  7943. var zlevelList = this._zlevelList;
  7944. var len = zlevelList.length;
  7945. var prevLayer = null;
  7946. var i = -1;
  7947. var domRoot = this._domRoot;
  7948. if (layersMap[zlevel]) {
  7949. zrLog('ZLevel ' + zlevel + ' has been used already');
  7950. return;
  7951. }
  7952. // Check if is a valid layer
  7953. if (!isLayerValid(layer)) {
  7954. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7955. return;
  7956. }
  7957. if (len > 0 && zlevel > zlevelList[0]) {
  7958. for (i = 0; i < len - 1; i++) {
  7959. if (
  7960. zlevelList[i] < zlevel
  7961. && zlevelList[i + 1] > zlevel
  7962. ) {
  7963. break;
  7964. }
  7965. }
  7966. prevLayer = layersMap[zlevelList[i]];
  7967. }
  7968. zlevelList.splice(i + 1, 0, zlevel);
  7969. layersMap[zlevel] = layer;
  7970. // Vitual layer will not directly show on the screen.
  7971. // (It can be a WebGL layer and assigned to a ZImage element)
  7972. // But it still under management of zrender.
  7973. if (!layer.virtual) {
  7974. if (prevLayer) {
  7975. var prevDom = prevLayer.dom;
  7976. if (prevDom.nextSibling) {
  7977. domRoot.insertBefore(
  7978. layer.dom,
  7979. prevDom.nextSibling
  7980. );
  7981. }
  7982. else {
  7983. domRoot.appendChild(layer.dom);
  7984. }
  7985. }
  7986. else {
  7987. if (domRoot.firstChild) {
  7988. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7989. }
  7990. else {
  7991. domRoot.appendChild(layer.dom);
  7992. }
  7993. }
  7994. }
  7995. },
  7996. // Iterate each layer
  7997. eachLayer: function (cb, context) {
  7998. var zlevelList = this._zlevelList;
  7999. var z;
  8000. var i;
  8001. for (i = 0; i < zlevelList.length; i++) {
  8002. z = zlevelList[i];
  8003. cb.call(context, this._layers[z], z);
  8004. }
  8005. },
  8006. // Iterate each buildin layer
  8007. eachBuiltinLayer: function (cb, context) {
  8008. var zlevelList = this._zlevelList;
  8009. var layer;
  8010. var z;
  8011. var i;
  8012. for (i = 0; i < zlevelList.length; i++) {
  8013. z = zlevelList[i];
  8014. layer = this._layers[z];
  8015. if (layer.__builtin__) {
  8016. cb.call(context, layer, z);
  8017. }
  8018. }
  8019. },
  8020. // Iterate each other layer except buildin layer
  8021. eachOtherLayer: function (cb, context) {
  8022. var zlevelList = this._zlevelList;
  8023. var layer;
  8024. var z;
  8025. var i;
  8026. for (i = 0; i < zlevelList.length; i++) {
  8027. z = zlevelList[i];
  8028. layer = this._layers[z];
  8029. if (!layer.__builtin__) {
  8030. cb.call(context, layer, z);
  8031. }
  8032. }
  8033. },
  8034. /**
  8035. * 获取所有已创建的层
  8036. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8037. */
  8038. getLayers: function () {
  8039. return this._layers;
  8040. },
  8041. _updateLayerStatus: function (list) {
  8042. this.eachBuiltinLayer(function (layer, z) {
  8043. layer.__dirty = layer.__used = false;
  8044. });
  8045. function updatePrevLayer(idx) {
  8046. if (prevLayer) {
  8047. if (prevLayer.__endIndex !== idx) {
  8048. prevLayer.__dirty = true;
  8049. }
  8050. prevLayer.__endIndex = idx;
  8051. }
  8052. }
  8053. if (this._singleCanvas) {
  8054. for (var i = 1; i < list.length; i++) {
  8055. var el = list[i];
  8056. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8057. this._needsManuallyCompositing = true;
  8058. break;
  8059. }
  8060. }
  8061. }
  8062. var prevLayer = null;
  8063. var incrementalLayerCount = 0;
  8064. for (var i = 0; i < list.length; i++) {
  8065. var el = list[i];
  8066. var zlevel = el.zlevel;
  8067. var layer;
  8068. // PENDING If change one incremental element style ?
  8069. // TODO Where there are non-incremental elements between incremental elements.
  8070. if (el.incremental) {
  8071. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8072. layer.incremental = true;
  8073. incrementalLayerCount = 1;
  8074. }
  8075. else {
  8076. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8077. }
  8078. if (!layer.__builtin__) {
  8079. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8080. }
  8081. if (layer !== prevLayer) {
  8082. layer.__used = true;
  8083. if (layer.__startIndex !== i) {
  8084. layer.__dirty = true;
  8085. }
  8086. layer.__startIndex = i;
  8087. if (!layer.incremental) {
  8088. layer.__drawIndex = i;
  8089. }
  8090. else {
  8091. // Mark layer draw index needs to update.
  8092. layer.__drawIndex = -1;
  8093. }
  8094. updatePrevLayer(i);
  8095. prevLayer = layer;
  8096. }
  8097. if (el.__dirty) {
  8098. layer.__dirty = true;
  8099. if (layer.incremental && layer.__drawIndex < 0) {
  8100. // Start draw from the first dirty element.
  8101. layer.__drawIndex = i;
  8102. }
  8103. }
  8104. }
  8105. updatePrevLayer(i);
  8106. this.eachBuiltinLayer(function (layer, z) {
  8107. // Used in last frame but not in this frame. Needs clear
  8108. if (!layer.__used && layer.getElementCount() > 0) {
  8109. layer.__dirty = true;
  8110. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8111. }
  8112. // For incremental layer. In case start index changed and no elements are dirty.
  8113. if (layer.__dirty && layer.__drawIndex < 0) {
  8114. layer.__drawIndex = layer.__startIndex;
  8115. }
  8116. });
  8117. },
  8118. /**
  8119. * 清除hover层外所有内容
  8120. */
  8121. clear: function () {
  8122. this.eachBuiltinLayer(this._clearLayer);
  8123. return this;
  8124. },
  8125. _clearLayer: function (layer) {
  8126. layer.clear();
  8127. },
  8128. setBackgroundColor: function (backgroundColor) {
  8129. this._backgroundColor = backgroundColor;
  8130. },
  8131. /**
  8132. * 修改指定zlevel的绘制参数
  8133. *
  8134. * @param {string} zlevel
  8135. * @param {Object} config 配置对象
  8136. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8137. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8138. * @param {number} [config.lastFrameAlpha=0.7]
  8139. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8140. */
  8141. configLayer: function (zlevel, config) {
  8142. if (config) {
  8143. var layerConfig = this._layerConfig;
  8144. if (!layerConfig[zlevel]) {
  8145. layerConfig[zlevel] = config;
  8146. }
  8147. else {
  8148. merge(layerConfig[zlevel], config, true);
  8149. }
  8150. for (var i = 0; i < this._zlevelList.length; i++) {
  8151. var _zlevel = this._zlevelList[i];
  8152. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8153. var layer = this._layers[_zlevel];
  8154. merge(layer, layerConfig[zlevel], true);
  8155. }
  8156. }
  8157. }
  8158. },
  8159. /**
  8160. * 删除指定层
  8161. * @param {number} zlevel 层所在的zlevel
  8162. */
  8163. delLayer: function (zlevel) {
  8164. var layers = this._layers;
  8165. var zlevelList = this._zlevelList;
  8166. var layer = layers[zlevel];
  8167. if (!layer) {
  8168. return;
  8169. }
  8170. layer.dom.parentNode.removeChild(layer.dom);
  8171. delete layers[zlevel];
  8172. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8173. },
  8174. /**
  8175. * 区域大小变化后重绘
  8176. */
  8177. resize: function (width, height) {
  8178. if (!this._domRoot.style) { // Maybe in node or worker
  8179. if (width == null || height == null) {
  8180. return;
  8181. }
  8182. this._width = width;
  8183. this._height = height;
  8184. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8185. }
  8186. else {
  8187. var domRoot = this._domRoot;
  8188. // FIXME Why ?
  8189. domRoot.style.display = 'none';
  8190. // Save input w/h
  8191. var opts = this._opts;
  8192. width != null && (opts.width = width);
  8193. height != null && (opts.height = height);
  8194. width = this._getSize(0);
  8195. height = this._getSize(1);
  8196. domRoot.style.display = '';
  8197. // 优化没有实际改变的resize
  8198. if (this._width != width || height != this._height) {
  8199. domRoot.style.width = width + 'px';
  8200. domRoot.style.height = height + 'px';
  8201. for (var id in this._layers) {
  8202. if (this._layers.hasOwnProperty(id)) {
  8203. this._layers[id].resize(width, height);
  8204. }
  8205. }
  8206. each$1(this._progressiveLayers, function (layer) {
  8207. layer.resize(width, height);
  8208. });
  8209. this.refresh(true);
  8210. }
  8211. this._width = width;
  8212. this._height = height;
  8213. }
  8214. return this;
  8215. },
  8216. /**
  8217. * 清除单独的一个层
  8218. * @param {number} zlevel
  8219. */
  8220. clearLayer: function (zlevel) {
  8221. var layer = this._layers[zlevel];
  8222. if (layer) {
  8223. layer.clear();
  8224. }
  8225. },
  8226. /**
  8227. * 释放
  8228. */
  8229. dispose: function () {
  8230. this.root.innerHTML = '';
  8231. this.root =
  8232. this.storage =
  8233. this._domRoot =
  8234. this._layers = null;
  8235. },
  8236. /**
  8237. * Get canvas which has all thing rendered
  8238. * @param {Object} opts
  8239. * @param {string} [opts.backgroundColor]
  8240. * @param {number} [opts.pixelRatio]
  8241. */
  8242. getRenderedCanvas: function (opts) {
  8243. opts = opts || {};
  8244. if (this._singleCanvas && !this._compositeManually) {
  8245. return this._layers[CANVAS_ZLEVEL].dom;
  8246. }
  8247. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8248. imageLayer.initContext();
  8249. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8250. if (opts.pixelRatio <= this.dpr) {
  8251. this.refresh();
  8252. var width = imageLayer.dom.width;
  8253. var height = imageLayer.dom.height;
  8254. var ctx = imageLayer.ctx;
  8255. this.eachLayer(function (layer) {
  8256. if (layer.__builtin__) {
  8257. ctx.drawImage(layer.dom, 0, 0, width, height);
  8258. }
  8259. else if (layer.renderToCanvas) {
  8260. imageLayer.ctx.save();
  8261. layer.renderToCanvas(imageLayer.ctx);
  8262. imageLayer.ctx.restore();
  8263. }
  8264. });
  8265. }
  8266. else {
  8267. // PENDING, echarts-gl and incremental rendering.
  8268. var scope = {};
  8269. var displayList = this.storage.getDisplayList(true);
  8270. for (var i = 0; i < displayList.length; i++) {
  8271. var el = displayList[i];
  8272. this._doPaintEl(el, imageLayer, true, scope);
  8273. }
  8274. }
  8275. return imageLayer.dom;
  8276. },
  8277. /**
  8278. * 获取绘图区域宽度
  8279. */
  8280. getWidth: function () {
  8281. return this._width;
  8282. },
  8283. /**
  8284. * 获取绘图区域高度
  8285. */
  8286. getHeight: function () {
  8287. return this._height;
  8288. },
  8289. _getSize: function (whIdx) {
  8290. var opts = this._opts;
  8291. var wh = ['width', 'height'][whIdx];
  8292. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8293. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8294. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8295. if (opts[wh] != null && opts[wh] !== 'auto') {
  8296. return parseFloat(opts[wh]);
  8297. }
  8298. var root = this.root;
  8299. // IE8 does not support getComputedStyle, but it use VML.
  8300. var stl = document.defaultView.getComputedStyle(root);
  8301. return (
  8302. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8303. - (parseInt10(stl[plt]) || 0)
  8304. - (parseInt10(stl[prb]) || 0)
  8305. ) | 0;
  8306. },
  8307. pathToImage: function (path, dpr) {
  8308. dpr = dpr || this.dpr;
  8309. var canvas = document.createElement('canvas');
  8310. var ctx = canvas.getContext('2d');
  8311. var rect = path.getBoundingRect();
  8312. var style = path.style;
  8313. var shadowBlurSize = style.shadowBlur * dpr;
  8314. var shadowOffsetX = style.shadowOffsetX * dpr;
  8315. var shadowOffsetY = style.shadowOffsetY * dpr;
  8316. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8317. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8318. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8319. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8320. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8321. var width = rect.width + leftMargin + rightMargin;
  8322. var height = rect.height + topMargin + bottomMargin;
  8323. canvas.width = width * dpr;
  8324. canvas.height = height * dpr;
  8325. ctx.scale(dpr, dpr);
  8326. ctx.clearRect(0, 0, width, height);
  8327. ctx.dpr = dpr;
  8328. var pathTransform = {
  8329. position: path.position,
  8330. rotation: path.rotation,
  8331. scale: path.scale
  8332. };
  8333. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8334. path.rotation = 0;
  8335. path.scale = [1, 1];
  8336. path.updateTransform();
  8337. if (path) {
  8338. path.brush(ctx);
  8339. }
  8340. var ImageShape = ZImage;
  8341. var imgShape = new ImageShape({
  8342. style: {
  8343. x: 0,
  8344. y: 0,
  8345. image: canvas
  8346. }
  8347. });
  8348. if (pathTransform.position != null) {
  8349. imgShape.position = path.position = pathTransform.position;
  8350. }
  8351. if (pathTransform.rotation != null) {
  8352. imgShape.rotation = path.rotation = pathTransform.rotation;
  8353. }
  8354. if (pathTransform.scale != null) {
  8355. imgShape.scale = path.scale = pathTransform.scale;
  8356. }
  8357. return imgShape;
  8358. }
  8359. };
  8360. /**
  8361. * 事件辅助类
  8362. * @module zrender/core/event
  8363. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8364. */
  8365. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8366. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8367. function getBoundingClientRect(el) {
  8368. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8369. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8370. }
  8371. // `calculate` is optional, default false
  8372. function clientToLocal(el, e, out, calculate) {
  8373. out = out || {};
  8374. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8375. // to the padding edge of the target element. The only browser using this convention
  8376. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8377. // not support the properties.
  8378. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8379. // In zr painter.dom, padding edge equals to border edge.
  8380. // FIXME
  8381. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8382. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8383. // is too complex. So css-transfrom dont support in this case temporarily.
  8384. if (calculate || !env$1.canvasSupported) {
  8385. defaultGetZrXY(el, e, out);
  8386. }
  8387. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8388. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8389. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8390. // zoom-factor, overflow / opacity layers, transforms ...)
  8391. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8392. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8393. // BTW3, In ff, offsetX/offsetY is always 0.
  8394. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8395. out.zrX = e.layerX;
  8396. out.zrY = e.layerY;
  8397. }
  8398. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8399. else if (e.offsetX != null) {
  8400. out.zrX = e.offsetX;
  8401. out.zrY = e.offsetY;
  8402. }
  8403. // For some other device, e.g., IOS safari.
  8404. else {
  8405. defaultGetZrXY(el, e, out);
  8406. }
  8407. return out;
  8408. }
  8409. function defaultGetZrXY(el, e, out) {
  8410. // This well-known method below does not support css transform.
  8411. var box = getBoundingClientRect(el);
  8412. out.zrX = e.clientX - box.left;
  8413. out.zrY = e.clientY - box.top;
  8414. }
  8415. /**
  8416. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8417. * `calculate` is optional, default false.
  8418. */
  8419. function normalizeEvent(el, e, calculate) {
  8420. e = e || window.event;
  8421. if (e.zrX != null) {
  8422. return e;
  8423. }
  8424. var eventType = e.type;
  8425. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8426. if (!isTouch) {
  8427. clientToLocal(el, e, e, calculate);
  8428. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8429. }
  8430. else {
  8431. var touch = eventType != 'touchend'
  8432. ? e.targetTouches[0]
  8433. : e.changedTouches[0];
  8434. touch && clientToLocal(el, touch, e, calculate);
  8435. }
  8436. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8437. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8438. // If e.which has been defined, if may be readonly,
  8439. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8440. var button = e.button;
  8441. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8442. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8443. }
  8444. return e;
  8445. }
  8446. /**
  8447. * @param {HTMLElement} el
  8448. * @param {string} name
  8449. * @param {Function} handler
  8450. */
  8451. function addEventListener(el, name, handler) {
  8452. if (isDomLevel2) {
  8453. // Reproduct the console warning:
  8454. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  8455. // Consider marking event handler as 'passive' to make the page more responsive.
  8456. // Just set console log level: verbose in chrome dev tool.
  8457. // then the warning log will be printed when addEventListener called.
  8458. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  8459. // We have not yet found a neat way to using passive. Because in zrender the dom event
  8460. // listener delegate all of the upper events of element. Some of those events need
  8461. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  8462. // Before passive can be adopted, these issues should be considered:
  8463. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  8464. // passive or not.
  8465. // (2) How to tread that some zrender event listener is passive, and some is not. If
  8466. // we use other way but not preventDefault of mousewheel and touchmove, browser
  8467. // compatibility should be handled.
  8468. // var opts = (env.passiveSupported && name === 'mousewheel')
  8469. // ? {passive: true}
  8470. // // By default, the third param of el.addEventListener is `capture: false`.
  8471. // : void 0;
  8472. // el.addEventListener(name, handler /* , opts */);
  8473. el.addEventListener(name, handler);
  8474. }
  8475. else {
  8476. el.attachEvent('on' + name, handler);
  8477. }
  8478. }
  8479. function removeEventListener(el, name, handler) {
  8480. if (isDomLevel2) {
  8481. el.removeEventListener(name, handler);
  8482. }
  8483. else {
  8484. el.detachEvent('on' + name, handler);
  8485. }
  8486. }
  8487. /**
  8488. * preventDefault and stopPropagation.
  8489. * Notice: do not do that in zrender. Upper application
  8490. * do that if necessary.
  8491. *
  8492. * @memberOf module:zrender/core/event
  8493. * @method
  8494. * @param {Event} e : event对象
  8495. */
  8496. var stop = isDomLevel2
  8497. ? function (e) {
  8498. e.preventDefault();
  8499. e.stopPropagation();
  8500. e.cancelBubble = true;
  8501. }
  8502. : function (e) {
  8503. e.returnValue = false;
  8504. e.cancelBubble = true;
  8505. };
  8506. function notLeftMouse(e) {
  8507. // If e.which is undefined, considered as left mouse event.
  8508. return e.which > 1;
  8509. }
  8510. /**
  8511. * 动画主类, 调度和管理所有动画控制器
  8512. *
  8513. * @module zrender/animation/Animation
  8514. * @author pissang(https://github.com/pissang)
  8515. */
  8516. // TODO Additive animation
  8517. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8518. // https://developer.apple.com/videos/wwdc2014/#236
  8519. /**
  8520. * @typedef {Object} IZRenderStage
  8521. * @property {Function} update
  8522. */
  8523. /**
  8524. * @alias module:zrender/animation/Animation
  8525. * @constructor
  8526. * @param {Object} [options]
  8527. * @param {Function} [options.onframe]
  8528. * @param {IZRenderStage} [options.stage]
  8529. * @example
  8530. * var animation = new Animation();
  8531. * var obj = {
  8532. * x: 100,
  8533. * y: 100
  8534. * };
  8535. * animation.animate(node.position)
  8536. * .when(1000, {
  8537. * x: 500,
  8538. * y: 500
  8539. * })
  8540. * .when(2000, {
  8541. * x: 100,
  8542. * y: 100
  8543. * })
  8544. * .start('spline');
  8545. */
  8546. var Animation = function (options) {
  8547. options = options || {};
  8548. this.stage = options.stage || {};
  8549. this.onframe = options.onframe || function() {};
  8550. // private properties
  8551. this._clips = [];
  8552. this._running = false;
  8553. this._time;
  8554. this._pausedTime;
  8555. this._pauseStart;
  8556. this._paused = false;
  8557. Eventful.call(this);
  8558. };
  8559. Animation.prototype = {
  8560. constructor: Animation,
  8561. /**
  8562. * 添加 clip
  8563. * @param {module:zrender/animation/Clip} clip
  8564. */
  8565. addClip: function (clip) {
  8566. this._clips.push(clip);
  8567. },
  8568. /**
  8569. * 添加 animator
  8570. * @param {module:zrender/animation/Animator} animator
  8571. */
  8572. addAnimator: function (animator) {
  8573. animator.animation = this;
  8574. var clips = animator.getClips();
  8575. for (var i = 0; i < clips.length; i++) {
  8576. this.addClip(clips[i]);
  8577. }
  8578. },
  8579. /**
  8580. * 删除动画片段
  8581. * @param {module:zrender/animation/Clip} clip
  8582. */
  8583. removeClip: function(clip) {
  8584. var idx = indexOf(this._clips, clip);
  8585. if (idx >= 0) {
  8586. this._clips.splice(idx, 1);
  8587. }
  8588. },
  8589. /**
  8590. * 删除动画片段
  8591. * @param {module:zrender/animation/Animator} animator
  8592. */
  8593. removeAnimator: function (animator) {
  8594. var clips = animator.getClips();
  8595. for (var i = 0; i < clips.length; i++) {
  8596. this.removeClip(clips[i]);
  8597. }
  8598. animator.animation = null;
  8599. },
  8600. _update: function() {
  8601. var time = new Date().getTime() - this._pausedTime;
  8602. var delta = time - this._time;
  8603. var clips = this._clips;
  8604. var len = clips.length;
  8605. var deferredEvents = [];
  8606. var deferredClips = [];
  8607. for (var i = 0; i < len; i++) {
  8608. var clip = clips[i];
  8609. var e = clip.step(time, delta);
  8610. // Throw out the events need to be called after
  8611. // stage.update, like destroy
  8612. if (e) {
  8613. deferredEvents.push(e);
  8614. deferredClips.push(clip);
  8615. }
  8616. }
  8617. // Remove the finished clip
  8618. for (var i = 0; i < len;) {
  8619. if (clips[i]._needsRemove) {
  8620. clips[i] = clips[len - 1];
  8621. clips.pop();
  8622. len--;
  8623. }
  8624. else {
  8625. i++;
  8626. }
  8627. }
  8628. len = deferredEvents.length;
  8629. for (var i = 0; i < len; i++) {
  8630. deferredClips[i].fire(deferredEvents[i]);
  8631. }
  8632. this._time = time;
  8633. this.onframe(delta);
  8634. // 'frame' should be triggered before stage, because upper application
  8635. // depends on the sequence (e.g., echarts-stream and finish
  8636. // event judge)
  8637. this.trigger('frame', delta);
  8638. if (this.stage.update) {
  8639. this.stage.update();
  8640. }
  8641. },
  8642. _startLoop: function () {
  8643. var self = this;
  8644. this._running = true;
  8645. function step() {
  8646. if (self._running) {
  8647. requestAnimationFrame(step);
  8648. !self._paused && self._update();
  8649. }
  8650. }
  8651. requestAnimationFrame(step);
  8652. },
  8653. /**
  8654. * Start animation.
  8655. */
  8656. start: function () {
  8657. this._time = new Date().getTime();
  8658. this._pausedTime = 0;
  8659. this._startLoop();
  8660. },
  8661. /**
  8662. * Stop animation.
  8663. */
  8664. stop: function () {
  8665. this._running = false;
  8666. },
  8667. /**
  8668. * Pause animation.
  8669. */
  8670. pause: function () {
  8671. if (!this._paused) {
  8672. this._pauseStart = new Date().getTime();
  8673. this._paused = true;
  8674. }
  8675. },
  8676. /**
  8677. * Resume animation.
  8678. */
  8679. resume: function () {
  8680. if (this._paused) {
  8681. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8682. this._paused = false;
  8683. }
  8684. },
  8685. /**
  8686. * Clear animation.
  8687. */
  8688. clear: function () {
  8689. this._clips = [];
  8690. },
  8691. /**
  8692. * Whether animation finished.
  8693. */
  8694. isFinished: function () {
  8695. return !this._clips.length;
  8696. },
  8697. /**
  8698. * Creat animator for a target, whose props can be animated.
  8699. *
  8700. * @param {Object} target
  8701. * @param {Object} options
  8702. * @param {boolean} [options.loop=false] Whether loop animation.
  8703. * @param {Function} [options.getter=null] Get value from target.
  8704. * @param {Function} [options.setter=null] Set value to target.
  8705. * @return {module:zrender/animation/Animation~Animator}
  8706. */
  8707. // TODO Gap
  8708. animate: function (target, options) {
  8709. options = options || {};
  8710. var animator = new Animator(
  8711. target,
  8712. options.loop,
  8713. options.getter,
  8714. options.setter
  8715. );
  8716. this.addAnimator(animator);
  8717. return animator;
  8718. }
  8719. };
  8720. mixin(Animation, Eventful);
  8721. /**
  8722. * Only implements needed gestures for mobile.
  8723. */
  8724. var GestureMgr = function () {
  8725. /**
  8726. * @private
  8727. * @type {Array.<Object>}
  8728. */
  8729. this._track = [];
  8730. };
  8731. GestureMgr.prototype = {
  8732. constructor: GestureMgr,
  8733. recognize: function (event, target, root) {
  8734. this._doTrack(event, target, root);
  8735. return this._recognize(event);
  8736. },
  8737. clear: function () {
  8738. this._track.length = 0;
  8739. return this;
  8740. },
  8741. _doTrack: function (event, target, root) {
  8742. var touches = event.touches;
  8743. if (!touches) {
  8744. return;
  8745. }
  8746. var trackItem = {
  8747. points: [],
  8748. touches: [],
  8749. target: target,
  8750. event: event
  8751. };
  8752. for (var i = 0, len = touches.length; i < len; i++) {
  8753. var touch = touches[i];
  8754. var pos = clientToLocal(root, touch, {});
  8755. trackItem.points.push([pos.zrX, pos.zrY]);
  8756. trackItem.touches.push(touch);
  8757. }
  8758. this._track.push(trackItem);
  8759. },
  8760. _recognize: function (event) {
  8761. for (var eventName in recognizers) {
  8762. if (recognizers.hasOwnProperty(eventName)) {
  8763. var gestureInfo = recognizers[eventName](this._track, event);
  8764. if (gestureInfo) {
  8765. return gestureInfo;
  8766. }
  8767. }
  8768. }
  8769. }
  8770. };
  8771. function dist$1(pointPair) {
  8772. var dx = pointPair[1][0] - pointPair[0][0];
  8773. var dy = pointPair[1][1] - pointPair[0][1];
  8774. return Math.sqrt(dx * dx + dy * dy);
  8775. }
  8776. function center(pointPair) {
  8777. return [
  8778. (pointPair[0][0] + pointPair[1][0]) / 2,
  8779. (pointPair[0][1] + pointPair[1][1]) / 2
  8780. ];
  8781. }
  8782. var recognizers = {
  8783. pinch: function (track, event) {
  8784. var trackLen = track.length;
  8785. if (!trackLen) {
  8786. return;
  8787. }
  8788. var pinchEnd = (track[trackLen - 1] || {}).points;
  8789. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8790. if (pinchPre
  8791. && pinchPre.length > 1
  8792. && pinchEnd
  8793. && pinchEnd.length > 1
  8794. ) {
  8795. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8796. !isFinite(pinchScale) && (pinchScale = 1);
  8797. event.pinchScale = pinchScale;
  8798. var pinchCenter = center(pinchEnd);
  8799. event.pinchX = pinchCenter[0];
  8800. event.pinchY = pinchCenter[1];
  8801. return {
  8802. type: 'pinch',
  8803. target: track[0].target,
  8804. event: event
  8805. };
  8806. }
  8807. }
  8808. // Only pinch currently.
  8809. };
  8810. var TOUCH_CLICK_DELAY = 300;
  8811. var mouseHandlerNames = [
  8812. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8813. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8814. ];
  8815. var touchHandlerNames = [
  8816. 'touchstart', 'touchend', 'touchmove'
  8817. ];
  8818. var pointerEventNames = {
  8819. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8820. };
  8821. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8822. var nm = name.replace('mouse', 'pointer');
  8823. return pointerEventNames[nm] ? nm : name;
  8824. });
  8825. function eventNameFix(name) {
  8826. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8827. }
  8828. function processGesture(proxy, event, stage) {
  8829. var gestureMgr = proxy._gestureMgr;
  8830. stage === 'start' && gestureMgr.clear();
  8831. var gestureInfo = gestureMgr.recognize(
  8832. event,
  8833. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8834. proxy.dom
  8835. );
  8836. stage === 'end' && gestureMgr.clear();
  8837. // Do not do any preventDefault here. Upper application do that if necessary.
  8838. if (gestureInfo) {
  8839. var type = gestureInfo.type;
  8840. event.gestureEvent = type;
  8841. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8842. }
  8843. }
  8844. // function onMSGestureChange(proxy, event) {
  8845. // if (event.translationX || event.translationY) {
  8846. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8847. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8848. // }
  8849. // if (event.scale !== 1) {
  8850. // event.pinchX = event.offsetX;
  8851. // event.pinchY = event.offsetY;
  8852. // event.pinchScale = event.scale;
  8853. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8854. // }
  8855. // }
  8856. /**
  8857. * Prevent mouse event from being dispatched after Touch Events action
  8858. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8859. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8860. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8861. * Result: Blocking Mouse Events for 700ms.
  8862. */
  8863. function setTouchTimer(instance) {
  8864. instance._touching = true;
  8865. clearTimeout(instance._touchTimer);
  8866. instance._touchTimer = setTimeout(function () {
  8867. instance._touching = false;
  8868. }, 700);
  8869. }
  8870. var domHandlers = {
  8871. /**
  8872. * Mouse move handler
  8873. * @inner
  8874. * @param {Event} event
  8875. */
  8876. mousemove: function (event) {
  8877. event = normalizeEvent(this.dom, event);
  8878. this.trigger('mousemove', event);
  8879. },
  8880. /**
  8881. * Mouse out handler
  8882. * @inner
  8883. * @param {Event} event
  8884. */
  8885. mouseout: function (event) {
  8886. event = normalizeEvent(this.dom, event);
  8887. var element = event.toElement || event.relatedTarget;
  8888. if (element != this.dom) {
  8889. while (element && element.nodeType != 9) {
  8890. // 忽略包含在root中的dom引起的mouseOut
  8891. if (element === this.dom) {
  8892. return;
  8893. }
  8894. element = element.parentNode;
  8895. }
  8896. }
  8897. this.trigger('mouseout', event);
  8898. },
  8899. /**
  8900. * Touch开始响应函数
  8901. * @inner
  8902. * @param {Event} event
  8903. */
  8904. touchstart: function (event) {
  8905. // Default mouse behaviour should not be disabled here.
  8906. // For example, page may needs to be slided.
  8907. event = normalizeEvent(this.dom, event);
  8908. // Mark touch, which is useful in distinguish touch and
  8909. // mouse event in upper applicatoin.
  8910. event.zrByTouch = true;
  8911. this._lastTouchMoment = new Date();
  8912. processGesture(this, event, 'start');
  8913. // In touch device, trigger `mousemove`(`mouseover`) should
  8914. // be triggered, and must before `mousedown` triggered.
  8915. domHandlers.mousemove.call(this, event);
  8916. domHandlers.mousedown.call(this, event);
  8917. setTouchTimer(this);
  8918. },
  8919. /**
  8920. * Touch移动响应函数
  8921. * @inner
  8922. * @param {Event} event
  8923. */
  8924. touchmove: function (event) {
  8925. event = normalizeEvent(this.dom, event);
  8926. // Mark touch, which is useful in distinguish touch and
  8927. // mouse event in upper applicatoin.
  8928. event.zrByTouch = true;
  8929. processGesture(this, event, 'change');
  8930. // Mouse move should always be triggered no matter whether
  8931. // there is gestrue event, because mouse move and pinch may
  8932. // be used at the same time.
  8933. domHandlers.mousemove.call(this, event);
  8934. setTouchTimer(this);
  8935. },
  8936. /**
  8937. * Touch结束响应函数
  8938. * @inner
  8939. * @param {Event} event
  8940. */
  8941. touchend: function (event) {
  8942. event = normalizeEvent(this.dom, event);
  8943. // Mark touch, which is useful in distinguish touch and
  8944. // mouse event in upper applicatoin.
  8945. event.zrByTouch = true;
  8946. processGesture(this, event, 'end');
  8947. domHandlers.mouseup.call(this, event);
  8948. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8949. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8950. // we can conveniently implement "hover style" in both PC and touch device just
  8951. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8952. // to remove "hover style" on an element, without any additional code for
  8953. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8954. // style" will remain for user view)
  8955. // click event should always be triggered no matter whether
  8956. // there is gestrue event. System click can not be prevented.
  8957. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8958. domHandlers.click.call(this, event);
  8959. }
  8960. setTouchTimer(this);
  8961. },
  8962. pointerdown: function (event) {
  8963. domHandlers.mousedown.call(this, event);
  8964. // if (useMSGuesture(this, event)) {
  8965. // this._msGesture.addPointer(event.pointerId);
  8966. // }
  8967. },
  8968. pointermove: function (event) {
  8969. // FIXME
  8970. // pointermove is so sensitive that it always triggered when
  8971. // tap(click) on touch screen, which affect some judgement in
  8972. // upper application. So, we dont support mousemove on MS touch
  8973. // device yet.
  8974. if (!isPointerFromTouch(event)) {
  8975. domHandlers.mousemove.call(this, event);
  8976. }
  8977. },
  8978. pointerup: function (event) {
  8979. domHandlers.mouseup.call(this, event);
  8980. },
  8981. pointerout: function (event) {
  8982. // pointerout will be triggered when tap on touch screen
  8983. // (IE11+/Edge on MS Surface) after click event triggered,
  8984. // which is inconsistent with the mousout behavior we defined
  8985. // in touchend. So we unify them.
  8986. // (check domHandlers.touchend for detailed explanation)
  8987. if (!isPointerFromTouch(event)) {
  8988. domHandlers.mouseout.call(this, event);
  8989. }
  8990. }
  8991. };
  8992. function isPointerFromTouch(event) {
  8993. var pointerType = event.pointerType;
  8994. return pointerType === 'pen' || pointerType === 'touch';
  8995. }
  8996. // function useMSGuesture(handlerProxy, event) {
  8997. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8998. // }
  8999. // Common handlers
  9000. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9001. domHandlers[name] = function (event) {
  9002. event = normalizeEvent(this.dom, event);
  9003. this.trigger(name, event);
  9004. };
  9005. });
  9006. /**
  9007. * 为控制类实例初始化dom 事件处理函数
  9008. *
  9009. * @inner
  9010. * @param {module:zrender/Handler} instance 控制类实例
  9011. */
  9012. function initDomHandler(instance) {
  9013. each$1(touchHandlerNames, function (name) {
  9014. instance._handlers[name] = bind(domHandlers[name], instance);
  9015. });
  9016. each$1(pointerHandlerNames, function (name) {
  9017. instance._handlers[name] = bind(domHandlers[name], instance);
  9018. });
  9019. each$1(mouseHandlerNames, function (name) {
  9020. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9021. });
  9022. function makeMouseHandler(fn, instance) {
  9023. return function () {
  9024. if (instance._touching) {
  9025. return;
  9026. }
  9027. return fn.apply(instance, arguments);
  9028. };
  9029. }
  9030. }
  9031. function HandlerDomProxy(dom) {
  9032. Eventful.call(this);
  9033. this.dom = dom;
  9034. /**
  9035. * @private
  9036. * @type {boolean}
  9037. */
  9038. this._touching = false;
  9039. /**
  9040. * @private
  9041. * @type {number}
  9042. */
  9043. this._touchTimer;
  9044. /**
  9045. * @private
  9046. * @type {module:zrender/core/GestureMgr}
  9047. */
  9048. this._gestureMgr = new GestureMgr();
  9049. this._handlers = {};
  9050. initDomHandler(this);
  9051. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9052. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9053. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9054. // at the same time.
  9055. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9056. // screen, which do not occurs in pointer event.
  9057. // So we use pointer event to both detect touch gesture and mouse behavior.
  9058. mountHandlers(pointerHandlerNames, this);
  9059. // FIXME
  9060. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9061. // which does not prevent defuault behavior occasionally (which may cause view port
  9062. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9063. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9064. // touch screen. And we only support click behavior on MS touch screen now.
  9065. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9066. // We dont support touch on IE on win7.
  9067. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9068. // if (typeof MSGesture === 'function') {
  9069. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9070. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9071. // }
  9072. }
  9073. else {
  9074. if (env$1.touchEventsSupported) {
  9075. mountHandlers(touchHandlerNames, this);
  9076. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9077. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9078. }
  9079. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9080. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9081. // mouse event can not be handle in those devices.
  9082. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9083. // mouseevent after touch event triggered, see `setTouchTimer`.
  9084. mountHandlers(mouseHandlerNames, this);
  9085. }
  9086. function mountHandlers(handlerNames, instance) {
  9087. each$1(handlerNames, function (name) {
  9088. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9089. }, instance);
  9090. }
  9091. }
  9092. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9093. handlerDomProxyProto.dispose = function () {
  9094. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9095. for (var i = 0; i < handlerNames.length; i++) {
  9096. var name = handlerNames[i];
  9097. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9098. }
  9099. };
  9100. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9101. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9102. };
  9103. mixin(HandlerDomProxy, Eventful);
  9104. /*!
  9105. * ZRender, a high performance 2d drawing library.
  9106. *
  9107. * Copyright (c) 2013, Baidu Inc.
  9108. * All rights reserved.
  9109. *
  9110. * LICENSE
  9111. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9112. */
  9113. var useVML = !env$1.canvasSupported;
  9114. var painterCtors = {
  9115. canvas: Painter
  9116. };
  9117. var instances$1 = {}; // ZRender实例map索引
  9118. /**
  9119. * @type {string}
  9120. */
  9121. var version$1 = '4.0.3';
  9122. /**
  9123. * Initializing a zrender instance
  9124. * @param {HTMLElement} dom
  9125. * @param {Object} opts
  9126. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9127. * @param {number} [opts.devicePixelRatio]
  9128. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9129. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9130. * @return {module:zrender/ZRender}
  9131. */
  9132. function init$1(dom, opts) {
  9133. var zr = new ZRender(guid(), dom, opts);
  9134. instances$1[zr.id] = zr;
  9135. return zr;
  9136. }
  9137. /**
  9138. * Dispose zrender instance
  9139. * @param {module:zrender/ZRender} zr
  9140. */
  9141. function dispose$1(zr) {
  9142. if (zr) {
  9143. zr.dispose();
  9144. }
  9145. else {
  9146. for (var key in instances$1) {
  9147. if (instances$1.hasOwnProperty(key)) {
  9148. instances$1[key].dispose();
  9149. }
  9150. }
  9151. instances$1 = {};
  9152. }
  9153. return this;
  9154. }
  9155. /**
  9156. * Get zrender instance by id
  9157. * @param {string} id zrender instance id
  9158. * @return {module:zrender/ZRender}
  9159. */
  9160. function getInstance(id) {
  9161. return instances$1[id];
  9162. }
  9163. function registerPainter(name, Ctor) {
  9164. painterCtors[name] = Ctor;
  9165. }
  9166. function delInstance(id) {
  9167. delete instances$1[id];
  9168. }
  9169. /**
  9170. * @module zrender/ZRender
  9171. */
  9172. /**
  9173. * @constructor
  9174. * @alias module:zrender/ZRender
  9175. * @param {string} id
  9176. * @param {HTMLElement} dom
  9177. * @param {Object} opts
  9178. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9179. * @param {number} [opts.devicePixelRatio]
  9180. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9181. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9182. */
  9183. var ZRender = function (id, dom, opts) {
  9184. opts = opts || {};
  9185. /**
  9186. * @type {HTMLDomElement}
  9187. */
  9188. this.dom = dom;
  9189. /**
  9190. * @type {string}
  9191. */
  9192. this.id = id;
  9193. var self = this;
  9194. var storage = new Storage();
  9195. var rendererType = opts.renderer;
  9196. // TODO WebGL
  9197. if (useVML) {
  9198. if (!painterCtors.vml) {
  9199. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9200. }
  9201. rendererType = 'vml';
  9202. }
  9203. else if (!rendererType || !painterCtors[rendererType]) {
  9204. rendererType = 'canvas';
  9205. }
  9206. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9207. this.storage = storage;
  9208. this.painter = painter;
  9209. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9210. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9211. /**
  9212. * @type {module:zrender/animation/Animation}
  9213. */
  9214. this.animation = new Animation({
  9215. stage: {
  9216. update: bind(this.flush, this)
  9217. }
  9218. });
  9219. this.animation.start();
  9220. /**
  9221. * @type {boolean}
  9222. * @private
  9223. */
  9224. this._needsRefresh;
  9225. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9226. // FIXME 有点ugly
  9227. var oldDelFromStorage = storage.delFromStorage;
  9228. var oldAddToStorage = storage.addToStorage;
  9229. storage.delFromStorage = function (el) {
  9230. oldDelFromStorage.call(storage, el);
  9231. el && el.removeSelfFromZr(self);
  9232. };
  9233. storage.addToStorage = function (el) {
  9234. oldAddToStorage.call(storage, el);
  9235. el.addSelfToZr(self);
  9236. };
  9237. };
  9238. ZRender.prototype = {
  9239. constructor: ZRender,
  9240. /**
  9241. * 获取实例唯一标识
  9242. * @return {string}
  9243. */
  9244. getId: function () {
  9245. return this.id;
  9246. },
  9247. /**
  9248. * 添加元素
  9249. * @param {module:zrender/Element} el
  9250. */
  9251. add: function (el) {
  9252. this.storage.addRoot(el);
  9253. this._needsRefresh = true;
  9254. },
  9255. /**
  9256. * 删除元素
  9257. * @param {module:zrender/Element} el
  9258. */
  9259. remove: function (el) {
  9260. this.storage.delRoot(el);
  9261. this._needsRefresh = true;
  9262. },
  9263. /**
  9264. * Change configuration of layer
  9265. * @param {string} zLevel
  9266. * @param {Object} config
  9267. * @param {string} [config.clearColor=0] Clear color
  9268. * @param {string} [config.motionBlur=false] If enable motion blur
  9269. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9270. */
  9271. configLayer: function (zLevel, config) {
  9272. if (this.painter.configLayer) {
  9273. this.painter.configLayer(zLevel, config);
  9274. }
  9275. this._needsRefresh = true;
  9276. },
  9277. /**
  9278. * Set background color
  9279. * @param {string} backgroundColor
  9280. */
  9281. setBackgroundColor: function (backgroundColor) {
  9282. if (this.painter.setBackgroundColor) {
  9283. this.painter.setBackgroundColor(backgroundColor);
  9284. }
  9285. this._needsRefresh = true;
  9286. },
  9287. /**
  9288. * Repaint the canvas immediately
  9289. */
  9290. refreshImmediately: function () {
  9291. // var start = new Date();
  9292. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9293. // Or it will cause zrender refreshes again and again.
  9294. this._needsRefresh = false;
  9295. this.painter.refresh();
  9296. /**
  9297. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9298. */
  9299. this._needsRefresh = false;
  9300. // var end = new Date();
  9301. // var log = document.getElementById('log');
  9302. // if (log) {
  9303. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9304. // }
  9305. },
  9306. /**
  9307. * Mark and repaint the canvas in the next frame of browser
  9308. */
  9309. refresh: function() {
  9310. this._needsRefresh = true;
  9311. },
  9312. /**
  9313. * Perform all refresh
  9314. */
  9315. flush: function () {
  9316. var triggerRendered;
  9317. if (this._needsRefresh) {
  9318. triggerRendered = true;
  9319. this.refreshImmediately();
  9320. }
  9321. if (this._needsRefreshHover) {
  9322. triggerRendered = true;
  9323. this.refreshHoverImmediately();
  9324. }
  9325. triggerRendered && this.trigger('rendered');
  9326. },
  9327. /**
  9328. * Add element to hover layer
  9329. * @param {module:zrender/Element} el
  9330. * @param {Object} style
  9331. */
  9332. addHover: function (el, style) {
  9333. if (this.painter.addHover) {
  9334. this.painter.addHover(el, style);
  9335. this.refreshHover();
  9336. }
  9337. },
  9338. /**
  9339. * Add element from hover layer
  9340. * @param {module:zrender/Element} el
  9341. */
  9342. removeHover: function (el) {
  9343. if (this.painter.removeHover) {
  9344. this.painter.removeHover(el);
  9345. this.refreshHover();
  9346. }
  9347. },
  9348. /**
  9349. * Clear all hover elements in hover layer
  9350. * @param {module:zrender/Element} el
  9351. */
  9352. clearHover: function () {
  9353. if (this.painter.clearHover) {
  9354. this.painter.clearHover();
  9355. this.refreshHover();
  9356. }
  9357. },
  9358. /**
  9359. * Refresh hover in next frame
  9360. */
  9361. refreshHover: function () {
  9362. this._needsRefreshHover = true;
  9363. },
  9364. /**
  9365. * Refresh hover immediately
  9366. */
  9367. refreshHoverImmediately: function () {
  9368. this._needsRefreshHover = false;
  9369. this.painter.refreshHover && this.painter.refreshHover();
  9370. },
  9371. /**
  9372. * Resize the canvas.
  9373. * Should be invoked when container size is changed
  9374. * @param {Object} [opts]
  9375. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9376. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9377. */
  9378. resize: function(opts) {
  9379. opts = opts || {};
  9380. this.painter.resize(opts.width, opts.height);
  9381. this.handler.resize();
  9382. },
  9383. /**
  9384. * Stop and clear all animation immediately
  9385. */
  9386. clearAnimation: function () {
  9387. this.animation.clear();
  9388. },
  9389. /**
  9390. * Get container width
  9391. */
  9392. getWidth: function() {
  9393. return this.painter.getWidth();
  9394. },
  9395. /**
  9396. * Get container height
  9397. */
  9398. getHeight: function() {
  9399. return this.painter.getHeight();
  9400. },
  9401. /**
  9402. * Export the canvas as Base64 URL
  9403. * @param {string} type
  9404. * @param {string} [backgroundColor='#fff']
  9405. * @return {string} Base64 URL
  9406. */
  9407. // toDataURL: function(type, backgroundColor) {
  9408. // return this.painter.getRenderedCanvas({
  9409. // backgroundColor: backgroundColor
  9410. // }).toDataURL(type);
  9411. // },
  9412. /**
  9413. * Converting a path to image.
  9414. * It has much better performance of drawing image rather than drawing a vector path.
  9415. * @param {module:zrender/graphic/Path} e
  9416. * @param {number} width
  9417. * @param {number} height
  9418. */
  9419. pathToImage: function(e, dpr) {
  9420. return this.painter.pathToImage(e, dpr);
  9421. },
  9422. /**
  9423. * Set default cursor
  9424. * @param {string} [cursorStyle='default'] 例如 crosshair
  9425. */
  9426. setCursorStyle: function (cursorStyle) {
  9427. this.handler.setCursorStyle(cursorStyle);
  9428. },
  9429. /**
  9430. * Find hovered element
  9431. * @param {number} x
  9432. * @param {number} y
  9433. * @return {Object} {target, topTarget}
  9434. */
  9435. findHover: function (x, y) {
  9436. return this.handler.findHover(x, y);
  9437. },
  9438. /**
  9439. * Bind event
  9440. *
  9441. * @param {string} eventName Event name
  9442. * @param {Function} eventHandler Handler function
  9443. * @param {Object} [context] Context object
  9444. */
  9445. on: function(eventName, eventHandler, context) {
  9446. this.handler.on(eventName, eventHandler, context);
  9447. },
  9448. /**
  9449. * Unbind event
  9450. * @param {string} eventName Event name
  9451. * @param {Function} [eventHandler] Handler function
  9452. */
  9453. off: function(eventName, eventHandler) {
  9454. this.handler.off(eventName, eventHandler);
  9455. },
  9456. /**
  9457. * Trigger event manually
  9458. *
  9459. * @param {string} eventName Event name
  9460. * @param {event=} event Event object
  9461. */
  9462. trigger: function (eventName, event) {
  9463. this.handler.trigger(eventName, event);
  9464. },
  9465. /**
  9466. * Clear all objects and the canvas.
  9467. */
  9468. clear: function () {
  9469. this.storage.delRoot();
  9470. this.painter.clear();
  9471. },
  9472. /**
  9473. * Dispose self.
  9474. */
  9475. dispose: function () {
  9476. this.animation.stop();
  9477. this.clear();
  9478. this.storage.dispose();
  9479. this.painter.dispose();
  9480. this.handler.dispose();
  9481. this.animation =
  9482. this.storage =
  9483. this.painter =
  9484. this.handler = null;
  9485. delInstance(this.id);
  9486. }
  9487. };
  9488. var zrender = (Object.freeze || Object)({
  9489. version: version$1,
  9490. init: init$1,
  9491. dispose: dispose$1,
  9492. getInstance: getInstance,
  9493. registerPainter: registerPainter
  9494. });
  9495. var each$2 = each$1;
  9496. var isObject$2 = isObject$1;
  9497. var isArray$1 = isArray;
  9498. /**
  9499. * Make the name displayable. But we should
  9500. * make sure it is not duplicated with user
  9501. * specified name, so use '\0';
  9502. */
  9503. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9504. /**
  9505. * If value is not array, then translate it to array.
  9506. * @param {*} value
  9507. * @return {Array} [value] or value
  9508. */
  9509. function normalizeToArray(value) {
  9510. return value instanceof Array
  9511. ? value
  9512. : value == null
  9513. ? []
  9514. : [value];
  9515. }
  9516. /**
  9517. * Sync default option between normal and emphasis like `position` and `show`
  9518. * In case some one will write code like
  9519. * label: {
  9520. * show: false,
  9521. * position: 'outside',
  9522. * fontSize: 18
  9523. * },
  9524. * emphasis: {
  9525. * label: { show: true }
  9526. * }
  9527. * @param {Object} opt
  9528. * @param {string} key
  9529. * @param {Array.<string>} subOpts
  9530. */
  9531. function defaultEmphasis(opt, key, subOpts) {
  9532. if (opt) {
  9533. opt[key] = opt[key] || {};
  9534. opt.emphasis = opt.emphasis || {};
  9535. opt.emphasis[key] = opt.emphasis[key] || {};
  9536. // Default emphasis option from normal
  9537. for (var i = 0, len = subOpts.length; i < len; i++) {
  9538. var subOptName = subOpts[i];
  9539. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9540. && opt[key].hasOwnProperty(subOptName)
  9541. ) {
  9542. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9543. }
  9544. }
  9545. }
  9546. }
  9547. var TEXT_STYLE_OPTIONS = [
  9548. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9549. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9550. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9551. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9552. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9553. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9554. ];
  9555. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9556. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9557. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9558. // // FIXME: deprecated, check and remove it.
  9559. // 'textStyle'
  9560. // ]);
  9561. /**
  9562. * The method do not ensure performance.
  9563. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9564. * This helper method retieves value from data.
  9565. * @param {string|number|Date|Array|Object} dataItem
  9566. * @return {number|string|Date|Array.<number|string|Date>}
  9567. */
  9568. function getDataItemValue(dataItem) {
  9569. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9570. ? dataItem.value : dataItem;
  9571. }
  9572. /**
  9573. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9574. * This helper method determine if dataItem has extra option besides value
  9575. * @param {string|number|Date|Array|Object} dataItem
  9576. */
  9577. function isDataItemOption(dataItem) {
  9578. return isObject$2(dataItem)
  9579. && !(dataItem instanceof Array);
  9580. // // markLine data can be array
  9581. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9582. }
  9583. /**
  9584. * Mapping to exists for merge.
  9585. *
  9586. * @public
  9587. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9588. * @param {Object|Array.<Object>} newCptOptions
  9589. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9590. * index of which is the same as exists.
  9591. */
  9592. function mappingToExists(exists, newCptOptions) {
  9593. // Mapping by the order by original option (but not order of
  9594. // new option) in merge mode. Because we should ensure
  9595. // some specified index (like xAxisIndex) is consistent with
  9596. // original option, which is easy to understand, espatially in
  9597. // media query. And in most case, merge option is used to
  9598. // update partial option but not be expected to change order.
  9599. newCptOptions = (newCptOptions || []).slice();
  9600. var result = map(exists || [], function (obj, index) {
  9601. return {exist: obj};
  9602. });
  9603. // Mapping by id or name if specified.
  9604. each$2(newCptOptions, function (cptOption, index) {
  9605. if (!isObject$2(cptOption)) {
  9606. return;
  9607. }
  9608. // id has highest priority.
  9609. for (var i = 0; i < result.length; i++) {
  9610. if (!result[i].option // Consider name: two map to one.
  9611. && cptOption.id != null
  9612. && result[i].exist.id === cptOption.id + ''
  9613. ) {
  9614. result[i].option = cptOption;
  9615. newCptOptions[index] = null;
  9616. return;
  9617. }
  9618. }
  9619. for (var i = 0; i < result.length; i++) {
  9620. var exist = result[i].exist;
  9621. if (!result[i].option // Consider name: two map to one.
  9622. // Can not match when both ids exist but different.
  9623. && (exist.id == null || cptOption.id == null)
  9624. && cptOption.name != null
  9625. && !isIdInner(cptOption)
  9626. && !isIdInner(exist)
  9627. && exist.name === cptOption.name + ''
  9628. ) {
  9629. result[i].option = cptOption;
  9630. newCptOptions[index] = null;
  9631. return;
  9632. }
  9633. }
  9634. });
  9635. // Otherwise mapping by index.
  9636. each$2(newCptOptions, function (cptOption, index) {
  9637. if (!isObject$2(cptOption)) {
  9638. return;
  9639. }
  9640. var i = 0;
  9641. for (; i < result.length; i++) {
  9642. var exist = result[i].exist;
  9643. if (!result[i].option
  9644. // Existing model that already has id should be able to
  9645. // mapped to (because after mapping performed model may
  9646. // be assigned with a id, whish should not affect next
  9647. // mapping), except those has inner id.
  9648. && !isIdInner(exist)
  9649. // Caution:
  9650. // Do not overwrite id. But name can be overwritten,
  9651. // because axis use name as 'show label text'.
  9652. // 'exist' always has id and name and we dont
  9653. // need to check it.
  9654. && cptOption.id == null
  9655. ) {
  9656. result[i].option = cptOption;
  9657. break;
  9658. }
  9659. }
  9660. if (i >= result.length) {
  9661. result.push({option: cptOption});
  9662. }
  9663. });
  9664. return result;
  9665. }
  9666. /**
  9667. * Make id and name for mapping result (result of mappingToExists)
  9668. * into `keyInfo` field.
  9669. *
  9670. * @public
  9671. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9672. * which order is the same as exists.
  9673. * @return {Array.<Object>} The input.
  9674. */
  9675. function makeIdAndName(mapResult) {
  9676. // We use this id to hash component models and view instances
  9677. // in echarts. id can be specified by user, or auto generated.
  9678. // The id generation rule ensures new view instance are able
  9679. // to mapped to old instance when setOption are called in
  9680. // no-merge mode. So we generate model id by name and plus
  9681. // type in view id.
  9682. // name can be duplicated among components, which is convenient
  9683. // to specify multi components (like series) by one name.
  9684. // Ensure that each id is distinct.
  9685. var idMap = createHashMap();
  9686. each$2(mapResult, function (item, index) {
  9687. var existCpt = item.exist;
  9688. existCpt && idMap.set(existCpt.id, item);
  9689. });
  9690. each$2(mapResult, function (item, index) {
  9691. var opt = item.option;
  9692. assert$1(
  9693. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9694. 'id duplicates: ' + (opt && opt.id)
  9695. );
  9696. opt && opt.id != null && idMap.set(opt.id, item);
  9697. !item.keyInfo && (item.keyInfo = {});
  9698. });
  9699. // Make name and id.
  9700. each$2(mapResult, function (item, index) {
  9701. var existCpt = item.exist;
  9702. var opt = item.option;
  9703. var keyInfo = item.keyInfo;
  9704. if (!isObject$2(opt)) {
  9705. return;
  9706. }
  9707. // name can be overwitten. Consider case: axis.name = '20km'.
  9708. // But id generated by name will not be changed, which affect
  9709. // only in that case: setOption with 'not merge mode' and view
  9710. // instance will be recreated, which can be accepted.
  9711. keyInfo.name = opt.name != null
  9712. ? opt.name + ''
  9713. : existCpt
  9714. ? existCpt.name
  9715. // Avoid diffferent series has the same name,
  9716. // because name may be used like in color pallet.
  9717. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9718. if (existCpt) {
  9719. keyInfo.id = existCpt.id;
  9720. }
  9721. else if (opt.id != null) {
  9722. keyInfo.id = opt.id + '';
  9723. }
  9724. else {
  9725. // Consider this situatoin:
  9726. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9727. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9728. // Series with the same name between optionA and optionB
  9729. // should be mapped.
  9730. var idNum = 0;
  9731. do {
  9732. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9733. }
  9734. while (idMap.get(keyInfo.id));
  9735. }
  9736. idMap.set(keyInfo.id, item);
  9737. });
  9738. }
  9739. function isNameSpecified(componentModel) {
  9740. var name = componentModel.name;
  9741. // Is specified when `indexOf` get -1 or > 0.
  9742. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9743. }
  9744. /**
  9745. * @public
  9746. * @param {Object} cptOption
  9747. * @return {boolean}
  9748. */
  9749. function isIdInner(cptOption) {
  9750. return isObject$2(cptOption)
  9751. && cptOption.id
  9752. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9753. }
  9754. /**
  9755. * A helper for removing duplicate items between batchA and batchB,
  9756. * and in themselves, and categorize by series.
  9757. *
  9758. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9759. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9760. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9761. */
  9762. function compressBatches(batchA, batchB) {
  9763. var mapA = {};
  9764. var mapB = {};
  9765. makeMap(batchA || [], mapA);
  9766. makeMap(batchB || [], mapB, mapA);
  9767. return [mapToArray(mapA), mapToArray(mapB)];
  9768. function makeMap(sourceBatch, map$$1, otherMap) {
  9769. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9770. var seriesId = sourceBatch[i].seriesId;
  9771. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9772. var otherDataIndices = otherMap && otherMap[seriesId];
  9773. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9774. var dataIndex = dataIndices[j];
  9775. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9776. otherDataIndices[dataIndex] = null;
  9777. }
  9778. else {
  9779. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9780. }
  9781. }
  9782. }
  9783. }
  9784. function mapToArray(map$$1, isData) {
  9785. var result = [];
  9786. for (var i in map$$1) {
  9787. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9788. if (isData) {
  9789. result.push(+i);
  9790. }
  9791. else {
  9792. var dataIndices = mapToArray(map$$1[i], true);
  9793. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9794. }
  9795. }
  9796. }
  9797. return result;
  9798. }
  9799. }
  9800. /**
  9801. * @param {module:echarts/data/List} data
  9802. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9803. * each of which can be Array or primary type.
  9804. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9805. */
  9806. function queryDataIndex(data, payload) {
  9807. if (payload.dataIndexInside != null) {
  9808. return payload.dataIndexInside;
  9809. }
  9810. else if (payload.dataIndex != null) {
  9811. return isArray(payload.dataIndex)
  9812. ? map(payload.dataIndex, function (value) {
  9813. return data.indexOfRawIndex(value);
  9814. })
  9815. : data.indexOfRawIndex(payload.dataIndex);
  9816. }
  9817. else if (payload.name != null) {
  9818. return isArray(payload.name)
  9819. ? map(payload.name, function (value) {
  9820. return data.indexOfName(value);
  9821. })
  9822. : data.indexOfName(payload.name);
  9823. }
  9824. }
  9825. /**
  9826. * Enable property storage to any host object.
  9827. * Notice: Serialization is not supported.
  9828. *
  9829. * For example:
  9830. * var inner = zrUitl.makeInner();
  9831. *
  9832. * function some1(hostObj) {
  9833. * inner(hostObj).someProperty = 1212;
  9834. * ...
  9835. * }
  9836. * function some2() {
  9837. * var fields = inner(this);
  9838. * fields.someProperty1 = 1212;
  9839. * fields.someProperty2 = 'xx';
  9840. * ...
  9841. * }
  9842. *
  9843. * @return {Function}
  9844. */
  9845. function makeInner() {
  9846. // Consider different scope by es module import.
  9847. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9848. return function (hostObj) {
  9849. return hostObj[key] || (hostObj[key] = {});
  9850. };
  9851. }
  9852. var innerUniqueIndex = 0;
  9853. /**
  9854. * @param {module:echarts/model/Global} ecModel
  9855. * @param {string|Object} finder
  9856. * If string, e.g., 'geo', means {geoIndex: 0}.
  9857. * If Object, could contain some of these properties below:
  9858. * {
  9859. * seriesIndex, seriesId, seriesName,
  9860. * geoIndex, geoId, geoName,
  9861. * bmapIndex, bmapId, bmapName,
  9862. * xAxisIndex, xAxisId, xAxisName,
  9863. * yAxisIndex, yAxisId, yAxisName,
  9864. * gridIndex, gridId, gridName,
  9865. * ... (can be extended)
  9866. * }
  9867. * Each properties can be number|string|Array.<number>|Array.<string>
  9868. * For example, a finder could be
  9869. * {
  9870. * seriesIndex: 3,
  9871. * geoId: ['aa', 'cc'],
  9872. * gridName: ['xx', 'rr']
  9873. * }
  9874. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9875. * If nothing or null/undefined specified, return nothing.
  9876. * @param {Object} [opt]
  9877. * @param {string} [opt.defaultMainType]
  9878. * @param {Array.<string>} [opt.includeMainTypes]
  9879. * @return {Object} result like:
  9880. * {
  9881. * seriesModels: [seriesModel1, seriesModel2],
  9882. * seriesModel: seriesModel1, // The first model
  9883. * geoModels: [geoModel1, geoModel2],
  9884. * geoModel: geoModel1, // The first model
  9885. * ...
  9886. * }
  9887. */
  9888. function parseFinder(ecModel, finder, opt) {
  9889. if (isString(finder)) {
  9890. var obj = {};
  9891. obj[finder + 'Index'] = 0;
  9892. finder = obj;
  9893. }
  9894. var defaultMainType = opt && opt.defaultMainType;
  9895. if (defaultMainType
  9896. && !has(finder, defaultMainType + 'Index')
  9897. && !has(finder, defaultMainType + 'Id')
  9898. && !has(finder, defaultMainType + 'Name')
  9899. ) {
  9900. finder[defaultMainType + 'Index'] = 0;
  9901. }
  9902. var result = {};
  9903. each$2(finder, function (value, key) {
  9904. var value = finder[key];
  9905. // Exclude 'dataIndex' and other illgal keys.
  9906. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9907. result[key] = value;
  9908. return;
  9909. }
  9910. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9911. var mainType = parsedKey[1];
  9912. var queryType = (parsedKey[2] || '').toLowerCase();
  9913. if (!mainType
  9914. || !queryType
  9915. || value == null
  9916. || (queryType === 'index' && value === 'none')
  9917. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9918. ) {
  9919. return;
  9920. }
  9921. var queryParam = {mainType: mainType};
  9922. if (queryType !== 'index' || value !== 'all') {
  9923. queryParam[queryType] = value;
  9924. }
  9925. var models = ecModel.queryComponents(queryParam);
  9926. result[mainType + 'Models'] = models;
  9927. result[mainType + 'Model'] = models[0];
  9928. });
  9929. return result;
  9930. }
  9931. function has(obj, prop) {
  9932. return obj && obj.hasOwnProperty(prop);
  9933. }
  9934. function setAttribute(dom, key, value) {
  9935. dom.setAttribute
  9936. ? dom.setAttribute(key, value)
  9937. : (dom[key] = value);
  9938. }
  9939. function getAttribute(dom, key) {
  9940. return dom.getAttribute
  9941. ? dom.getAttribute(key)
  9942. : dom[key];
  9943. }
  9944. var TYPE_DELIMITER = '.';
  9945. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9946. /**
  9947. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9948. * @public
  9949. */
  9950. function parseClassType$1(componentType) {
  9951. var ret = {main: '', sub: ''};
  9952. if (componentType) {
  9953. componentType = componentType.split(TYPE_DELIMITER);
  9954. ret.main = componentType[0] || '';
  9955. ret.sub = componentType[1] || '';
  9956. }
  9957. return ret;
  9958. }
  9959. /**
  9960. * @public
  9961. */
  9962. function checkClassType(componentType) {
  9963. assert$1(
  9964. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9965. 'componentType "' + componentType + '" illegal'
  9966. );
  9967. }
  9968. /**
  9969. * @public
  9970. */
  9971. function enableClassExtend(RootClass, mandatoryMethods) {
  9972. RootClass.$constructor = RootClass;
  9973. RootClass.extend = function (proto) {
  9974. if (__DEV__) {
  9975. each$1(mandatoryMethods, function (method) {
  9976. if (!proto[method]) {
  9977. console.warn(
  9978. 'Method `' + method + '` should be implemented'
  9979. + (proto.type ? ' in ' + proto.type : '') + '.'
  9980. );
  9981. }
  9982. });
  9983. }
  9984. var superClass = this;
  9985. var ExtendedClass = function () {
  9986. if (!proto.$constructor) {
  9987. superClass.apply(this, arguments);
  9988. }
  9989. else {
  9990. proto.$constructor.apply(this, arguments);
  9991. }
  9992. };
  9993. extend(ExtendedClass.prototype, proto);
  9994. ExtendedClass.extend = this.extend;
  9995. ExtendedClass.superCall = superCall;
  9996. ExtendedClass.superApply = superApply;
  9997. inherits(ExtendedClass, this);
  9998. ExtendedClass.superClass = superClass;
  9999. return ExtendedClass;
  10000. };
  10001. }
  10002. var classBase = 0;
  10003. /**
  10004. * Can not use instanceof, consider different scope by
  10005. * cross domain or es module import in ec extensions.
  10006. * Mount a method "isInstance()" to Clz.
  10007. */
  10008. function enableClassCheck(Clz) {
  10009. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10010. Clz.prototype[classAttr] = true;
  10011. if (__DEV__) {
  10012. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10013. }
  10014. Clz.isInstance = function (obj) {
  10015. return !!(obj && obj[classAttr]);
  10016. };
  10017. }
  10018. // superCall should have class info, which can not be fetch from 'this'.
  10019. // Consider this case:
  10020. // class A has method f,
  10021. // class B inherits class A, overrides method f, f call superApply('f'),
  10022. // class C inherits class B, do not overrides method f,
  10023. // then when method of class C is called, dead loop occured.
  10024. function superCall(context, methodName) {
  10025. var args = slice(arguments, 2);
  10026. return this.superClass.prototype[methodName].apply(context, args);
  10027. }
  10028. function superApply(context, methodName, args) {
  10029. return this.superClass.prototype[methodName].apply(context, args);
  10030. }
  10031. /**
  10032. * @param {Object} entity
  10033. * @param {Object} options
  10034. * @param {boolean} [options.registerWhenExtend]
  10035. * @public
  10036. */
  10037. function enableClassManagement(entity, options) {
  10038. options = options || {};
  10039. /**
  10040. * Component model classes
  10041. * key: componentType,
  10042. * value:
  10043. * componentClass, when componentType is 'xxx'
  10044. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10045. * @type {Object}
  10046. */
  10047. var storage = {};
  10048. entity.registerClass = function (Clazz, componentType) {
  10049. if (componentType) {
  10050. checkClassType(componentType);
  10051. componentType = parseClassType$1(componentType);
  10052. if (!componentType.sub) {
  10053. if (__DEV__) {
  10054. if (storage[componentType.main]) {
  10055. console.warn(componentType.main + ' exists.');
  10056. }
  10057. }
  10058. storage[componentType.main] = Clazz;
  10059. }
  10060. else if (componentType.sub !== IS_CONTAINER) {
  10061. var container = makeContainer(componentType);
  10062. container[componentType.sub] = Clazz;
  10063. }
  10064. }
  10065. return Clazz;
  10066. };
  10067. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10068. var Clazz = storage[componentMainType];
  10069. if (Clazz && Clazz[IS_CONTAINER]) {
  10070. Clazz = subType ? Clazz[subType] : null;
  10071. }
  10072. if (throwWhenNotFound && !Clazz) {
  10073. throw new Error(
  10074. !subType
  10075. ? componentMainType + '.' + 'type should be specified.'
  10076. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10077. );
  10078. }
  10079. return Clazz;
  10080. };
  10081. entity.getClassesByMainType = function (componentType) {
  10082. componentType = parseClassType$1(componentType);
  10083. var result = [];
  10084. var obj = storage[componentType.main];
  10085. if (obj && obj[IS_CONTAINER]) {
  10086. each$1(obj, function (o, type) {
  10087. type !== IS_CONTAINER && result.push(o);
  10088. });
  10089. }
  10090. else {
  10091. result.push(obj);
  10092. }
  10093. return result;
  10094. };
  10095. entity.hasClass = function (componentType) {
  10096. // Just consider componentType.main.
  10097. componentType = parseClassType$1(componentType);
  10098. return !!storage[componentType.main];
  10099. };
  10100. /**
  10101. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10102. */
  10103. entity.getAllClassMainTypes = function () {
  10104. var types = [];
  10105. each$1(storage, function (obj, type) {
  10106. types.push(type);
  10107. });
  10108. return types;
  10109. };
  10110. /**
  10111. * If a main type is container and has sub types
  10112. * @param {string} mainType
  10113. * @return {boolean}
  10114. */
  10115. entity.hasSubTypes = function (componentType) {
  10116. componentType = parseClassType$1(componentType);
  10117. var obj = storage[componentType.main];
  10118. return obj && obj[IS_CONTAINER];
  10119. };
  10120. entity.parseClassType = parseClassType$1;
  10121. function makeContainer(componentType) {
  10122. var container = storage[componentType.main];
  10123. if (!container || !container[IS_CONTAINER]) {
  10124. container = storage[componentType.main] = {};
  10125. container[IS_CONTAINER] = true;
  10126. }
  10127. return container;
  10128. }
  10129. if (options.registerWhenExtend) {
  10130. var originalExtend = entity.extend;
  10131. if (originalExtend) {
  10132. entity.extend = function (proto) {
  10133. var ExtendedClass = originalExtend.call(this, proto);
  10134. return entity.registerClass(ExtendedClass, proto.type);
  10135. };
  10136. }
  10137. }
  10138. return entity;
  10139. }
  10140. /**
  10141. * @param {string|Array.<string>} properties
  10142. */
  10143. // TODO Parse shadow style
  10144. // TODO Only shallow path support
  10145. var makeStyleMapper = function (properties) {
  10146. // Normalize
  10147. for (var i = 0; i < properties.length; i++) {
  10148. if (!properties[i][1]) {
  10149. properties[i][1] = properties[i][0];
  10150. }
  10151. }
  10152. return function (model, excludes, includes) {
  10153. var style = {};
  10154. for (var i = 0; i < properties.length; i++) {
  10155. var propName = properties[i][1];
  10156. if ((excludes && indexOf(excludes, propName) >= 0)
  10157. || (includes && indexOf(includes, propName) < 0)
  10158. ) {
  10159. continue;
  10160. }
  10161. var val = model.getShallow(propName);
  10162. if (val != null) {
  10163. style[properties[i][0]] = val;
  10164. }
  10165. }
  10166. return style;
  10167. };
  10168. };
  10169. var getLineStyle = makeStyleMapper(
  10170. [
  10171. ['lineWidth', 'width'],
  10172. ['stroke', 'color'],
  10173. ['opacity'],
  10174. ['shadowBlur'],
  10175. ['shadowOffsetX'],
  10176. ['shadowOffsetY'],
  10177. ['shadowColor']
  10178. ]
  10179. );
  10180. var lineStyleMixin = {
  10181. getLineStyle: function (excludes) {
  10182. var style = getLineStyle(this, excludes);
  10183. var lineDash = this.getLineDash(style.lineWidth);
  10184. lineDash && (style.lineDash = lineDash);
  10185. return style;
  10186. },
  10187. getLineDash: function (lineWidth) {
  10188. if (lineWidth == null) {
  10189. lineWidth = 1;
  10190. }
  10191. var lineType = this.get('type');
  10192. var dotSize = Math.max(lineWidth, 2);
  10193. var dashSize = lineWidth * 4;
  10194. return (lineType === 'solid' || lineType == null) ? null
  10195. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10196. }
  10197. };
  10198. var getAreaStyle = makeStyleMapper(
  10199. [
  10200. ['fill', 'color'],
  10201. ['shadowBlur'],
  10202. ['shadowOffsetX'],
  10203. ['shadowOffsetY'],
  10204. ['opacity'],
  10205. ['shadowColor']
  10206. ]
  10207. );
  10208. var areaStyleMixin = {
  10209. getAreaStyle: function (excludes, includes) {
  10210. return getAreaStyle(this, excludes, includes);
  10211. }
  10212. };
  10213. /**
  10214. * 曲线辅助模块
  10215. * @module zrender/core/curve
  10216. * @author pissang(https://www.github.com/pissang)
  10217. */
  10218. var mathPow = Math.pow;
  10219. var mathSqrt$2 = Math.sqrt;
  10220. var EPSILON$1 = 1e-8;
  10221. var EPSILON_NUMERIC = 1e-4;
  10222. var THREE_SQRT = mathSqrt$2(3);
  10223. var ONE_THIRD = 1 / 3;
  10224. // 临时变量
  10225. var _v0 = create();
  10226. var _v1 = create();
  10227. var _v2 = create();
  10228. function isAroundZero(val) {
  10229. return val > -EPSILON$1 && val < EPSILON$1;
  10230. }
  10231. function isNotAroundZero$1(val) {
  10232. return val > EPSILON$1 || val < -EPSILON$1;
  10233. }
  10234. /**
  10235. * 计算三次贝塞尔值
  10236. * @memberOf module:zrender/core/curve
  10237. * @param {number} p0
  10238. * @param {number} p1
  10239. * @param {number} p2
  10240. * @param {number} p3
  10241. * @param {number} t
  10242. * @return {number}
  10243. */
  10244. function cubicAt(p0, p1, p2, p3, t) {
  10245. var onet = 1 - t;
  10246. return onet * onet * (onet * p0 + 3 * t * p1)
  10247. + t * t * (t * p3 + 3 * onet * p2);
  10248. }
  10249. /**
  10250. * 计算三次贝塞尔导数值
  10251. * @memberOf module:zrender/core/curve
  10252. * @param {number} p0
  10253. * @param {number} p1
  10254. * @param {number} p2
  10255. * @param {number} p3
  10256. * @param {number} t
  10257. * @return {number}
  10258. */
  10259. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10260. var onet = 1 - t;
  10261. return 3 * (
  10262. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10263. + (p3 - p2) * t * t
  10264. );
  10265. }
  10266. /**
  10267. * 计算三次贝塞尔方程根,使用盛金公式
  10268. * @memberOf module:zrender/core/curve
  10269. * @param {number} p0
  10270. * @param {number} p1
  10271. * @param {number} p2
  10272. * @param {number} p3
  10273. * @param {number} val
  10274. * @param {Array.<number>} roots
  10275. * @return {number} 有效根数目
  10276. */
  10277. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10278. // Evaluate roots of cubic functions
  10279. var a = p3 + 3 * (p1 - p2) - p0;
  10280. var b = 3 * (p2 - p1 * 2 + p0);
  10281. var c = 3 * (p1 - p0);
  10282. var d = p0 - val;
  10283. var A = b * b - 3 * a * c;
  10284. var B = b * c - 9 * a * d;
  10285. var C = c * c - 3 * b * d;
  10286. var n = 0;
  10287. if (isAroundZero(A) && isAroundZero(B)) {
  10288. if (isAroundZero(b)) {
  10289. roots[0] = 0;
  10290. }
  10291. else {
  10292. var t1 = -c / b; //t1, t2, t3, b is not zero
  10293. if (t1 >= 0 && t1 <= 1) {
  10294. roots[n++] = t1;
  10295. }
  10296. }
  10297. }
  10298. else {
  10299. var disc = B * B - 4 * A * C;
  10300. if (isAroundZero(disc)) {
  10301. var K = B / A;
  10302. var t1 = -b / a + K; // t1, a is not zero
  10303. var t2 = -K / 2; // t2, t3
  10304. if (t1 >= 0 && t1 <= 1) {
  10305. roots[n++] = t1;
  10306. }
  10307. if (t2 >= 0 && t2 <= 1) {
  10308. roots[n++] = t2;
  10309. }
  10310. }
  10311. else if (disc > 0) {
  10312. var discSqrt = mathSqrt$2(disc);
  10313. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10314. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10315. if (Y1 < 0) {
  10316. Y1 = -mathPow(-Y1, ONE_THIRD);
  10317. }
  10318. else {
  10319. Y1 = mathPow(Y1, ONE_THIRD);
  10320. }
  10321. if (Y2 < 0) {
  10322. Y2 = -mathPow(-Y2, ONE_THIRD);
  10323. }
  10324. else {
  10325. Y2 = mathPow(Y2, ONE_THIRD);
  10326. }
  10327. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10328. if (t1 >= 0 && t1 <= 1) {
  10329. roots[n++] = t1;
  10330. }
  10331. }
  10332. else {
  10333. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10334. var theta = Math.acos(T) / 3;
  10335. var ASqrt = mathSqrt$2(A);
  10336. var tmp = Math.cos(theta);
  10337. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10338. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10339. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10340. if (t1 >= 0 && t1 <= 1) {
  10341. roots[n++] = t1;
  10342. }
  10343. if (t2 >= 0 && t2 <= 1) {
  10344. roots[n++] = t2;
  10345. }
  10346. if (t3 >= 0 && t3 <= 1) {
  10347. roots[n++] = t3;
  10348. }
  10349. }
  10350. }
  10351. return n;
  10352. }
  10353. /**
  10354. * 计算三次贝塞尔方程极限值的位置
  10355. * @memberOf module:zrender/core/curve
  10356. * @param {number} p0
  10357. * @param {number} p1
  10358. * @param {number} p2
  10359. * @param {number} p3
  10360. * @param {Array.<number>} extrema
  10361. * @return {number} 有效数目
  10362. */
  10363. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10364. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10365. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10366. var c = 3 * p1 - 3 * p0;
  10367. var n = 0;
  10368. if (isAroundZero(a)) {
  10369. if (isNotAroundZero$1(b)) {
  10370. var t1 = -c / b;
  10371. if (t1 >= 0 && t1 <=1) {
  10372. extrema[n++] = t1;
  10373. }
  10374. }
  10375. }
  10376. else {
  10377. var disc = b * b - 4 * a * c;
  10378. if (isAroundZero(disc)) {
  10379. extrema[0] = -b / (2 * a);
  10380. }
  10381. else if (disc > 0) {
  10382. var discSqrt = mathSqrt$2(disc);
  10383. var t1 = (-b + discSqrt) / (2 * a);
  10384. var t2 = (-b - discSqrt) / (2 * a);
  10385. if (t1 >= 0 && t1 <= 1) {
  10386. extrema[n++] = t1;
  10387. }
  10388. if (t2 >= 0 && t2 <= 1) {
  10389. extrema[n++] = t2;
  10390. }
  10391. }
  10392. }
  10393. return n;
  10394. }
  10395. /**
  10396. * 细分三次贝塞尔曲线
  10397. * @memberOf module:zrender/core/curve
  10398. * @param {number} p0
  10399. * @param {number} p1
  10400. * @param {number} p2
  10401. * @param {number} p3
  10402. * @param {number} t
  10403. * @param {Array.<number>} out
  10404. */
  10405. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10406. var p01 = (p1 - p0) * t + p0;
  10407. var p12 = (p2 - p1) * t + p1;
  10408. var p23 = (p3 - p2) * t + p2;
  10409. var p012 = (p12 - p01) * t + p01;
  10410. var p123 = (p23 - p12) * t + p12;
  10411. var p0123 = (p123 - p012) * t + p012;
  10412. // Seg0
  10413. out[0] = p0;
  10414. out[1] = p01;
  10415. out[2] = p012;
  10416. out[3] = p0123;
  10417. // Seg1
  10418. out[4] = p0123;
  10419. out[5] = p123;
  10420. out[6] = p23;
  10421. out[7] = p3;
  10422. }
  10423. /**
  10424. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10425. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10426. * @param {number} x0
  10427. * @param {number} y0
  10428. * @param {number} x1
  10429. * @param {number} y1
  10430. * @param {number} x2
  10431. * @param {number} y2
  10432. * @param {number} x3
  10433. * @param {number} y3
  10434. * @param {number} x
  10435. * @param {number} y
  10436. * @param {Array.<number>} [out] 投射点
  10437. * @return {number}
  10438. */
  10439. function cubicProjectPoint(
  10440. x0, y0, x1, y1, x2, y2, x3, y3,
  10441. x, y, out
  10442. ) {
  10443. // http://pomax.github.io/bezierinfo/#projections
  10444. var t;
  10445. var interval = 0.005;
  10446. var d = Infinity;
  10447. var prev;
  10448. var next;
  10449. var d1;
  10450. var d2;
  10451. _v0[0] = x;
  10452. _v0[1] = y;
  10453. // 先粗略估计一下可能的最小距离的 t 值
  10454. // PENDING
  10455. for (var _t = 0; _t < 1; _t += 0.05) {
  10456. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10457. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10458. d1 = distSquare(_v0, _v1);
  10459. if (d1 < d) {
  10460. t = _t;
  10461. d = d1;
  10462. }
  10463. }
  10464. d = Infinity;
  10465. // At most 32 iteration
  10466. for (var i = 0; i < 32; i++) {
  10467. if (interval < EPSILON_NUMERIC) {
  10468. break;
  10469. }
  10470. prev = t - interval;
  10471. next = t + interval;
  10472. // t - interval
  10473. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10474. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10475. d1 = distSquare(_v1, _v0);
  10476. if (prev >= 0 && d1 < d) {
  10477. t = prev;
  10478. d = d1;
  10479. }
  10480. else {
  10481. // t + interval
  10482. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10483. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10484. d2 = distSquare(_v2, _v0);
  10485. if (next <= 1 && d2 < d) {
  10486. t = next;
  10487. d = d2;
  10488. }
  10489. else {
  10490. interval *= 0.5;
  10491. }
  10492. }
  10493. }
  10494. // t
  10495. if (out) {
  10496. out[0] = cubicAt(x0, x1, x2, x3, t);
  10497. out[1] = cubicAt(y0, y1, y2, y3, t);
  10498. }
  10499. // console.log(interval, i);
  10500. return mathSqrt$2(d);
  10501. }
  10502. /**
  10503. * 计算二次方贝塞尔值
  10504. * @param {number} p0
  10505. * @param {number} p1
  10506. * @param {number} p2
  10507. * @param {number} t
  10508. * @return {number}
  10509. */
  10510. function quadraticAt(p0, p1, p2, t) {
  10511. var onet = 1 - t;
  10512. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10513. }
  10514. /**
  10515. * 计算二次方贝塞尔导数值
  10516. * @param {number} p0
  10517. * @param {number} p1
  10518. * @param {number} p2
  10519. * @param {number} t
  10520. * @return {number}
  10521. */
  10522. function quadraticDerivativeAt(p0, p1, p2, t) {
  10523. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10524. }
  10525. /**
  10526. * 计算二次方贝塞尔方程根
  10527. * @param {number} p0
  10528. * @param {number} p1
  10529. * @param {number} p2
  10530. * @param {number} t
  10531. * @param {Array.<number>} roots
  10532. * @return {number} 有效根数目
  10533. */
  10534. function quadraticRootAt(p0, p1, p2, val, roots) {
  10535. var a = p0 - 2 * p1 + p2;
  10536. var b = 2 * (p1 - p0);
  10537. var c = p0 - val;
  10538. var n = 0;
  10539. if (isAroundZero(a)) {
  10540. if (isNotAroundZero$1(b)) {
  10541. var t1 = -c / b;
  10542. if (t1 >= 0 && t1 <= 1) {
  10543. roots[n++] = t1;
  10544. }
  10545. }
  10546. }
  10547. else {
  10548. var disc = b * b - 4 * a * c;
  10549. if (isAroundZero(disc)) {
  10550. var t1 = -b / (2 * a);
  10551. if (t1 >= 0 && t1 <= 1) {
  10552. roots[n++] = t1;
  10553. }
  10554. }
  10555. else if (disc > 0) {
  10556. var discSqrt = mathSqrt$2(disc);
  10557. var t1 = (-b + discSqrt) / (2 * a);
  10558. var t2 = (-b - discSqrt) / (2 * a);
  10559. if (t1 >= 0 && t1 <= 1) {
  10560. roots[n++] = t1;
  10561. }
  10562. if (t2 >= 0 && t2 <= 1) {
  10563. roots[n++] = t2;
  10564. }
  10565. }
  10566. }
  10567. return n;
  10568. }
  10569. /**
  10570. * 计算二次贝塞尔方程极限值
  10571. * @memberOf module:zrender/core/curve
  10572. * @param {number} p0
  10573. * @param {number} p1
  10574. * @param {number} p2
  10575. * @return {number}
  10576. */
  10577. function quadraticExtremum(p0, p1, p2) {
  10578. var divider = p0 + p2 - 2 * p1;
  10579. if (divider === 0) {
  10580. // p1 is center of p0 and p2
  10581. return 0.5;
  10582. }
  10583. else {
  10584. return (p0 - p1) / divider;
  10585. }
  10586. }
  10587. /**
  10588. * 细分二次贝塞尔曲线
  10589. * @memberOf module:zrender/core/curve
  10590. * @param {number} p0
  10591. * @param {number} p1
  10592. * @param {number} p2
  10593. * @param {number} t
  10594. * @param {Array.<number>} out
  10595. */
  10596. function quadraticSubdivide(p0, p1, p2, t, out) {
  10597. var p01 = (p1 - p0) * t + p0;
  10598. var p12 = (p2 - p1) * t + p1;
  10599. var p012 = (p12 - p01) * t + p01;
  10600. // Seg0
  10601. out[0] = p0;
  10602. out[1] = p01;
  10603. out[2] = p012;
  10604. // Seg1
  10605. out[3] = p012;
  10606. out[4] = p12;
  10607. out[5] = p2;
  10608. }
  10609. /**
  10610. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10611. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10612. * @param {number} x0
  10613. * @param {number} y0
  10614. * @param {number} x1
  10615. * @param {number} y1
  10616. * @param {number} x2
  10617. * @param {number} y2
  10618. * @param {number} x
  10619. * @param {number} y
  10620. * @param {Array.<number>} out 投射点
  10621. * @return {number}
  10622. */
  10623. function quadraticProjectPoint(
  10624. x0, y0, x1, y1, x2, y2,
  10625. x, y, out
  10626. ) {
  10627. // http://pomax.github.io/bezierinfo/#projections
  10628. var t;
  10629. var interval = 0.005;
  10630. var d = Infinity;
  10631. _v0[0] = x;
  10632. _v0[1] = y;
  10633. // 先粗略估计一下可能的最小距离的 t 值
  10634. // PENDING
  10635. for (var _t = 0; _t < 1; _t += 0.05) {
  10636. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10637. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10638. var d1 = distSquare(_v0, _v1);
  10639. if (d1 < d) {
  10640. t = _t;
  10641. d = d1;
  10642. }
  10643. }
  10644. d = Infinity;
  10645. // At most 32 iteration
  10646. for (var i = 0; i < 32; i++) {
  10647. if (interval < EPSILON_NUMERIC) {
  10648. break;
  10649. }
  10650. var prev = t - interval;
  10651. var next = t + interval;
  10652. // t - interval
  10653. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10654. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10655. var d1 = distSquare(_v1, _v0);
  10656. if (prev >= 0 && d1 < d) {
  10657. t = prev;
  10658. d = d1;
  10659. }
  10660. else {
  10661. // t + interval
  10662. _v2[0] = quadraticAt(x0, x1, x2, next);
  10663. _v2[1] = quadraticAt(y0, y1, y2, next);
  10664. var d2 = distSquare(_v2, _v0);
  10665. if (next <= 1 && d2 < d) {
  10666. t = next;
  10667. d = d2;
  10668. }
  10669. else {
  10670. interval *= 0.5;
  10671. }
  10672. }
  10673. }
  10674. // t
  10675. if (out) {
  10676. out[0] = quadraticAt(x0, x1, x2, t);
  10677. out[1] = quadraticAt(y0, y1, y2, t);
  10678. }
  10679. // console.log(interval, i);
  10680. return mathSqrt$2(d);
  10681. }
  10682. /**
  10683. * @author Yi Shen(https://github.com/pissang)
  10684. */
  10685. var mathMin$3 = Math.min;
  10686. var mathMax$3 = Math.max;
  10687. var mathSin$2 = Math.sin;
  10688. var mathCos$2 = Math.cos;
  10689. var PI2 = Math.PI * 2;
  10690. var start = create();
  10691. var end = create();
  10692. var extremity = create();
  10693. /**
  10694. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10695. * @module zrender/core/bbox
  10696. * @param {Array<Object>} points 顶点数组
  10697. * @param {number} min
  10698. * @param {number} max
  10699. */
  10700. function fromPoints(points, min$$1, max$$1) {
  10701. if (points.length === 0) {
  10702. return;
  10703. }
  10704. var p = points[0];
  10705. var left = p[0];
  10706. var right = p[0];
  10707. var top = p[1];
  10708. var bottom = p[1];
  10709. var i;
  10710. for (i = 1; i < points.length; i++) {
  10711. p = points[i];
  10712. left = mathMin$3(left, p[0]);
  10713. right = mathMax$3(right, p[0]);
  10714. top = mathMin$3(top, p[1]);
  10715. bottom = mathMax$3(bottom, p[1]);
  10716. }
  10717. min$$1[0] = left;
  10718. min$$1[1] = top;
  10719. max$$1[0] = right;
  10720. max$$1[1] = bottom;
  10721. }
  10722. /**
  10723. * @memberOf module:zrender/core/bbox
  10724. * @param {number} x0
  10725. * @param {number} y0
  10726. * @param {number} x1
  10727. * @param {number} y1
  10728. * @param {Array.<number>} min
  10729. * @param {Array.<number>} max
  10730. */
  10731. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10732. min$$1[0] = mathMin$3(x0, x1);
  10733. min$$1[1] = mathMin$3(y0, y1);
  10734. max$$1[0] = mathMax$3(x0, x1);
  10735. max$$1[1] = mathMax$3(y0, y1);
  10736. }
  10737. var xDim = [];
  10738. var yDim = [];
  10739. /**
  10740. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10741. * @memberOf module:zrender/core/bbox
  10742. * @param {number} x0
  10743. * @param {number} y0
  10744. * @param {number} x1
  10745. * @param {number} y1
  10746. * @param {number} x2
  10747. * @param {number} y2
  10748. * @param {number} x3
  10749. * @param {number} y3
  10750. * @param {Array.<number>} min
  10751. * @param {Array.<number>} max
  10752. */
  10753. function fromCubic(
  10754. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10755. ) {
  10756. var cubicExtrema$$1 = cubicExtrema;
  10757. var cubicAt$$1 = cubicAt;
  10758. var i;
  10759. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10760. min$$1[0] = Infinity;
  10761. min$$1[1] = Infinity;
  10762. max$$1[0] = -Infinity;
  10763. max$$1[1] = -Infinity;
  10764. for (i = 0; i < n; i++) {
  10765. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10766. min$$1[0] = mathMin$3(x, min$$1[0]);
  10767. max$$1[0] = mathMax$3(x, max$$1[0]);
  10768. }
  10769. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10770. for (i = 0; i < n; i++) {
  10771. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10772. min$$1[1] = mathMin$3(y, min$$1[1]);
  10773. max$$1[1] = mathMax$3(y, max$$1[1]);
  10774. }
  10775. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10776. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10777. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10778. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10779. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10780. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10781. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10782. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10783. }
  10784. /**
  10785. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10786. * @memberOf module:zrender/core/bbox
  10787. * @param {number} x0
  10788. * @param {number} y0
  10789. * @param {number} x1
  10790. * @param {number} y1
  10791. * @param {number} x2
  10792. * @param {number} y2
  10793. * @param {Array.<number>} min
  10794. * @param {Array.<number>} max
  10795. */
  10796. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10797. var quadraticExtremum$$1 = quadraticExtremum;
  10798. var quadraticAt$$1 = quadraticAt;
  10799. // Find extremities, where derivative in x dim or y dim is zero
  10800. var tx =
  10801. mathMax$3(
  10802. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10803. );
  10804. var ty =
  10805. mathMax$3(
  10806. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10807. );
  10808. var x = quadraticAt$$1(x0, x1, x2, tx);
  10809. var y = quadraticAt$$1(y0, y1, y2, ty);
  10810. min$$1[0] = mathMin$3(x0, x2, x);
  10811. min$$1[1] = mathMin$3(y0, y2, y);
  10812. max$$1[0] = mathMax$3(x0, x2, x);
  10813. max$$1[1] = mathMax$3(y0, y2, y);
  10814. }
  10815. /**
  10816. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10817. * @method
  10818. * @memberOf module:zrender/core/bbox
  10819. * @param {number} x
  10820. * @param {number} y
  10821. * @param {number} rx
  10822. * @param {number} ry
  10823. * @param {number} startAngle
  10824. * @param {number} endAngle
  10825. * @param {number} anticlockwise
  10826. * @param {Array.<number>} min
  10827. * @param {Array.<number>} max
  10828. */
  10829. function fromArc(
  10830. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10831. ) {
  10832. var vec2Min = min;
  10833. var vec2Max = max;
  10834. var diff = Math.abs(startAngle - endAngle);
  10835. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10836. // Is a circle
  10837. min$$1[0] = x - rx;
  10838. min$$1[1] = y - ry;
  10839. max$$1[0] = x + rx;
  10840. max$$1[1] = y + ry;
  10841. return;
  10842. }
  10843. start[0] = mathCos$2(startAngle) * rx + x;
  10844. start[1] = mathSin$2(startAngle) * ry + y;
  10845. end[0] = mathCos$2(endAngle) * rx + x;
  10846. end[1] = mathSin$2(endAngle) * ry + y;
  10847. vec2Min(min$$1, start, end);
  10848. vec2Max(max$$1, start, end);
  10849. // Thresh to [0, Math.PI * 2]
  10850. startAngle = startAngle % (PI2);
  10851. if (startAngle < 0) {
  10852. startAngle = startAngle + PI2;
  10853. }
  10854. endAngle = endAngle % (PI2);
  10855. if (endAngle < 0) {
  10856. endAngle = endAngle + PI2;
  10857. }
  10858. if (startAngle > endAngle && !anticlockwise) {
  10859. endAngle += PI2;
  10860. }
  10861. else if (startAngle < endAngle && anticlockwise) {
  10862. startAngle += PI2;
  10863. }
  10864. if (anticlockwise) {
  10865. var tmp = endAngle;
  10866. endAngle = startAngle;
  10867. startAngle = tmp;
  10868. }
  10869. // var number = 0;
  10870. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10871. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10872. if (angle > startAngle) {
  10873. extremity[0] = mathCos$2(angle) * rx + x;
  10874. extremity[1] = mathSin$2(angle) * ry + y;
  10875. vec2Min(min$$1, extremity, min$$1);
  10876. vec2Max(max$$1, extremity, max$$1);
  10877. }
  10878. }
  10879. }
  10880. /**
  10881. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10882. * 可以用于 isInsidePath 判断以及获取boundingRect
  10883. *
  10884. * @module zrender/core/PathProxy
  10885. * @author Yi Shen (http://www.github.com/pissang)
  10886. */
  10887. // TODO getTotalLength, getPointAtLength
  10888. var CMD = {
  10889. M: 1,
  10890. L: 2,
  10891. C: 3,
  10892. Q: 4,
  10893. A: 5,
  10894. Z: 6,
  10895. // Rect
  10896. R: 7
  10897. };
  10898. // var CMD_MEM_SIZE = {
  10899. // M: 3,
  10900. // L: 3,
  10901. // C: 7,
  10902. // Q: 5,
  10903. // A: 9,
  10904. // R: 5,
  10905. // Z: 1
  10906. // };
  10907. var min$1 = [];
  10908. var max$1 = [];
  10909. var min2 = [];
  10910. var max2 = [];
  10911. var mathMin$2 = Math.min;
  10912. var mathMax$2 = Math.max;
  10913. var mathCos$1 = Math.cos;
  10914. var mathSin$1 = Math.sin;
  10915. var mathSqrt$1 = Math.sqrt;
  10916. var mathAbs = Math.abs;
  10917. var hasTypedArray = typeof Float32Array != 'undefined';
  10918. /**
  10919. * @alias module:zrender/core/PathProxy
  10920. * @constructor
  10921. */
  10922. var PathProxy = function (notSaveData) {
  10923. this._saveData = !(notSaveData || false);
  10924. if (this._saveData) {
  10925. /**
  10926. * Path data. Stored as flat array
  10927. * @type {Array.<Object>}
  10928. */
  10929. this.data = [];
  10930. }
  10931. this._ctx = null;
  10932. };
  10933. /**
  10934. * 快速计算Path包围盒(并不是最小包围盒)
  10935. * @return {Object}
  10936. */
  10937. PathProxy.prototype = {
  10938. constructor: PathProxy,
  10939. _xi: 0,
  10940. _yi: 0,
  10941. _x0: 0,
  10942. _y0: 0,
  10943. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10944. _ux: 0,
  10945. _uy: 0,
  10946. _len: 0,
  10947. _lineDash: null,
  10948. _dashOffset: 0,
  10949. _dashIdx: 0,
  10950. _dashSum: 0,
  10951. /**
  10952. * @readOnly
  10953. */
  10954. setScale: function (sx, sy) {
  10955. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10956. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10957. },
  10958. getContext: function () {
  10959. return this._ctx;
  10960. },
  10961. /**
  10962. * @param {CanvasRenderingContext2D} ctx
  10963. * @return {module:zrender/core/PathProxy}
  10964. */
  10965. beginPath: function (ctx) {
  10966. this._ctx = ctx;
  10967. ctx && ctx.beginPath();
  10968. ctx && (this.dpr = ctx.dpr);
  10969. // Reset
  10970. if (this._saveData) {
  10971. this._len = 0;
  10972. }
  10973. if (this._lineDash) {
  10974. this._lineDash = null;
  10975. this._dashOffset = 0;
  10976. }
  10977. return this;
  10978. },
  10979. /**
  10980. * @param {number} x
  10981. * @param {number} y
  10982. * @return {module:zrender/core/PathProxy}
  10983. */
  10984. moveTo: function (x, y) {
  10985. this.addData(CMD.M, x, y);
  10986. this._ctx && this._ctx.moveTo(x, y);
  10987. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10988. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10989. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10990. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10991. this._x0 = x;
  10992. this._y0 = y;
  10993. this._xi = x;
  10994. this._yi = y;
  10995. return this;
  10996. },
  10997. /**
  10998. * @param {number} x
  10999. * @param {number} y
  11000. * @return {module:zrender/core/PathProxy}
  11001. */
  11002. lineTo: function (x, y) {
  11003. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11004. || mathAbs(y - this._yi) > this._uy
  11005. // Force draw the first segment
  11006. || this._len < 5;
  11007. this.addData(CMD.L, x, y);
  11008. if (this._ctx && exceedUnit) {
  11009. this._needsDash() ? this._dashedLineTo(x, y)
  11010. : this._ctx.lineTo(x, y);
  11011. }
  11012. if (exceedUnit) {
  11013. this._xi = x;
  11014. this._yi = y;
  11015. }
  11016. return this;
  11017. },
  11018. /**
  11019. * @param {number} x1
  11020. * @param {number} y1
  11021. * @param {number} x2
  11022. * @param {number} y2
  11023. * @param {number} x3
  11024. * @param {number} y3
  11025. * @return {module:zrender/core/PathProxy}
  11026. */
  11027. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11028. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11029. if (this._ctx) {
  11030. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11031. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11032. }
  11033. this._xi = x3;
  11034. this._yi = y3;
  11035. return this;
  11036. },
  11037. /**
  11038. * @param {number} x1
  11039. * @param {number} y1
  11040. * @param {number} x2
  11041. * @param {number} y2
  11042. * @return {module:zrender/core/PathProxy}
  11043. */
  11044. quadraticCurveTo: function (x1, y1, x2, y2) {
  11045. this.addData(CMD.Q, x1, y1, x2, y2);
  11046. if (this._ctx) {
  11047. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11048. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11049. }
  11050. this._xi = x2;
  11051. this._yi = y2;
  11052. return this;
  11053. },
  11054. /**
  11055. * @param {number} cx
  11056. * @param {number} cy
  11057. * @param {number} r
  11058. * @param {number} startAngle
  11059. * @param {number} endAngle
  11060. * @param {boolean} anticlockwise
  11061. * @return {module:zrender/core/PathProxy}
  11062. */
  11063. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11064. this.addData(
  11065. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11066. );
  11067. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11068. this._xi = mathCos$1(endAngle) * r + cx;
  11069. this._yi = mathSin$1(endAngle) * r + cx;
  11070. return this;
  11071. },
  11072. // TODO
  11073. arcTo: function (x1, y1, x2, y2, radius) {
  11074. if (this._ctx) {
  11075. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11076. }
  11077. return this;
  11078. },
  11079. // TODO
  11080. rect: function (x, y, w, h) {
  11081. this._ctx && this._ctx.rect(x, y, w, h);
  11082. this.addData(CMD.R, x, y, w, h);
  11083. return this;
  11084. },
  11085. /**
  11086. * @return {module:zrender/core/PathProxy}
  11087. */
  11088. closePath: function () {
  11089. this.addData(CMD.Z);
  11090. var ctx = this._ctx;
  11091. var x0 = this._x0;
  11092. var y0 = this._y0;
  11093. if (ctx) {
  11094. this._needsDash() && this._dashedLineTo(x0, y0);
  11095. ctx.closePath();
  11096. }
  11097. this._xi = x0;
  11098. this._yi = y0;
  11099. return this;
  11100. },
  11101. /**
  11102. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11103. * stroke 同样
  11104. * @param {CanvasRenderingContext2D} ctx
  11105. * @return {module:zrender/core/PathProxy}
  11106. */
  11107. fill: function (ctx) {
  11108. ctx && ctx.fill();
  11109. this.toStatic();
  11110. },
  11111. /**
  11112. * @param {CanvasRenderingContext2D} ctx
  11113. * @return {module:zrender/core/PathProxy}
  11114. */
  11115. stroke: function (ctx) {
  11116. ctx && ctx.stroke();
  11117. this.toStatic();
  11118. },
  11119. /**
  11120. * 必须在其它绘制命令前调用
  11121. * Must be invoked before all other path drawing methods
  11122. * @return {module:zrender/core/PathProxy}
  11123. */
  11124. setLineDash: function (lineDash) {
  11125. if (lineDash instanceof Array) {
  11126. this._lineDash = lineDash;
  11127. this._dashIdx = 0;
  11128. var lineDashSum = 0;
  11129. for (var i = 0; i < lineDash.length; i++) {
  11130. lineDashSum += lineDash[i];
  11131. }
  11132. this._dashSum = lineDashSum;
  11133. }
  11134. return this;
  11135. },
  11136. /**
  11137. * 必须在其它绘制命令前调用
  11138. * Must be invoked before all other path drawing methods
  11139. * @return {module:zrender/core/PathProxy}
  11140. */
  11141. setLineDashOffset: function (offset) {
  11142. this._dashOffset = offset;
  11143. return this;
  11144. },
  11145. /**
  11146. *
  11147. * @return {boolean}
  11148. */
  11149. len: function () {
  11150. return this._len;
  11151. },
  11152. /**
  11153. * 直接设置 Path 数据
  11154. */
  11155. setData: function (data) {
  11156. var len$$1 = data.length;
  11157. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11158. this.data = new Float32Array(len$$1);
  11159. }
  11160. for (var i = 0; i < len$$1; i++) {
  11161. this.data[i] = data[i];
  11162. }
  11163. this._len = len$$1;
  11164. },
  11165. /**
  11166. * 添加子路径
  11167. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11168. */
  11169. appendPath: function (path) {
  11170. if (!(path instanceof Array)) {
  11171. path = [path];
  11172. }
  11173. var len$$1 = path.length;
  11174. var appendSize = 0;
  11175. var offset = this._len;
  11176. for (var i = 0; i < len$$1; i++) {
  11177. appendSize += path[i].len();
  11178. }
  11179. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11180. this.data = new Float32Array(offset + appendSize);
  11181. }
  11182. for (var i = 0; i < len$$1; i++) {
  11183. var appendPathData = path[i].data;
  11184. for (var k = 0; k < appendPathData.length; k++) {
  11185. this.data[offset++] = appendPathData[k];
  11186. }
  11187. }
  11188. this._len = offset;
  11189. },
  11190. /**
  11191. * 填充 Path 数据。
  11192. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11193. */
  11194. addData: function (cmd) {
  11195. if (!this._saveData) {
  11196. return;
  11197. }
  11198. var data = this.data;
  11199. if (this._len + arguments.length > data.length) {
  11200. // 因为之前的数组已经转换成静态的 Float32Array
  11201. // 所以不够用时需要扩展一个新的动态数组
  11202. this._expandData();
  11203. data = this.data;
  11204. }
  11205. for (var i = 0; i < arguments.length; i++) {
  11206. data[this._len++] = arguments[i];
  11207. }
  11208. this._prevCmd = cmd;
  11209. },
  11210. _expandData: function () {
  11211. // Only if data is Float32Array
  11212. if (!(this.data instanceof Array)) {
  11213. var newData = [];
  11214. for (var i = 0; i < this._len; i++) {
  11215. newData[i] = this.data[i];
  11216. }
  11217. this.data = newData;
  11218. }
  11219. },
  11220. /**
  11221. * If needs js implemented dashed line
  11222. * @return {boolean}
  11223. * @private
  11224. */
  11225. _needsDash: function () {
  11226. return this._lineDash;
  11227. },
  11228. _dashedLineTo: function (x1, y1) {
  11229. var dashSum = this._dashSum;
  11230. var offset = this._dashOffset;
  11231. var lineDash = this._lineDash;
  11232. var ctx = this._ctx;
  11233. var x0 = this._xi;
  11234. var y0 = this._yi;
  11235. var dx = x1 - x0;
  11236. var dy = y1 - y0;
  11237. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11238. var x = x0;
  11239. var y = y0;
  11240. var dash;
  11241. var nDash = lineDash.length;
  11242. var idx;
  11243. dx /= dist$$1;
  11244. dy /= dist$$1;
  11245. if (offset < 0) {
  11246. // Convert to positive offset
  11247. offset = dashSum + offset;
  11248. }
  11249. offset %= dashSum;
  11250. x -= offset * dx;
  11251. y -= offset * dy;
  11252. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11253. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11254. idx = this._dashIdx;
  11255. dash = lineDash[idx];
  11256. x += dx * dash;
  11257. y += dy * dash;
  11258. this._dashIdx = (idx + 1) % nDash;
  11259. // Skip positive offset
  11260. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11261. continue;
  11262. }
  11263. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11264. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11265. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11266. );
  11267. }
  11268. // Offset for next lineTo
  11269. dx = x - x1;
  11270. dy = y - y1;
  11271. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11272. },
  11273. // Not accurate dashed line to
  11274. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11275. var dashSum = this._dashSum;
  11276. var offset = this._dashOffset;
  11277. var lineDash = this._lineDash;
  11278. var ctx = this._ctx;
  11279. var x0 = this._xi;
  11280. var y0 = this._yi;
  11281. var t;
  11282. var dx;
  11283. var dy;
  11284. var cubicAt$$1 = cubicAt;
  11285. var bezierLen = 0;
  11286. var idx = this._dashIdx;
  11287. var nDash = lineDash.length;
  11288. var x;
  11289. var y;
  11290. var tmpLen = 0;
  11291. if (offset < 0) {
  11292. // Convert to positive offset
  11293. offset = dashSum + offset;
  11294. }
  11295. offset %= dashSum;
  11296. // Bezier approx length
  11297. for (t = 0; t < 1; t += 0.1) {
  11298. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11299. - cubicAt$$1(x0, x1, x2, x3, t);
  11300. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11301. - cubicAt$$1(y0, y1, y2, y3, t);
  11302. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11303. }
  11304. // Find idx after add offset
  11305. for (; idx < nDash; idx++) {
  11306. tmpLen += lineDash[idx];
  11307. if (tmpLen > offset) {
  11308. break;
  11309. }
  11310. }
  11311. t = (tmpLen - offset) / bezierLen;
  11312. while (t <= 1) {
  11313. x = cubicAt$$1(x0, x1, x2, x3, t);
  11314. y = cubicAt$$1(y0, y1, y2, y3, t);
  11315. // Use line to approximate dashed bezier
  11316. // Bad result if dash is long
  11317. idx % 2 ? ctx.moveTo(x, y)
  11318. : ctx.lineTo(x, y);
  11319. t += lineDash[idx] / bezierLen;
  11320. idx = (idx + 1) % nDash;
  11321. }
  11322. // Finish the last segment and calculate the new offset
  11323. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11324. dx = x3 - x;
  11325. dy = y3 - y;
  11326. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11327. },
  11328. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11329. // Convert quadratic to cubic using degree elevation
  11330. var x3 = x2;
  11331. var y3 = y2;
  11332. x2 = (x2 + 2 * x1) / 3;
  11333. y2 = (y2 + 2 * y1) / 3;
  11334. x1 = (this._xi + 2 * x1) / 3;
  11335. y1 = (this._yi + 2 * y1) / 3;
  11336. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11337. },
  11338. /**
  11339. * 转成静态的 Float32Array 减少堆内存占用
  11340. * Convert dynamic array to static Float32Array
  11341. */
  11342. toStatic: function () {
  11343. var data = this.data;
  11344. if (data instanceof Array) {
  11345. data.length = this._len;
  11346. if (hasTypedArray) {
  11347. this.data = new Float32Array(data);
  11348. }
  11349. }
  11350. },
  11351. /**
  11352. * @return {module:zrender/core/BoundingRect}
  11353. */
  11354. getBoundingRect: function () {
  11355. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11356. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11357. var data = this.data;
  11358. var xi = 0;
  11359. var yi = 0;
  11360. var x0 = 0;
  11361. var y0 = 0;
  11362. for (var i = 0; i < data.length;) {
  11363. var cmd = data[i++];
  11364. if (i == 1) {
  11365. // 如果第一个命令是 L, C, Q
  11366. // 则 previous point 同绘制命令的第一个 point
  11367. //
  11368. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11369. xi = data[i];
  11370. yi = data[i + 1];
  11371. x0 = xi;
  11372. y0 = yi;
  11373. }
  11374. switch (cmd) {
  11375. case CMD.M:
  11376. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11377. // 在 closePath 的时候使用
  11378. x0 = data[i++];
  11379. y0 = data[i++];
  11380. xi = x0;
  11381. yi = y0;
  11382. min2[0] = x0;
  11383. min2[1] = y0;
  11384. max2[0] = x0;
  11385. max2[1] = y0;
  11386. break;
  11387. case CMD.L:
  11388. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11389. xi = data[i++];
  11390. yi = data[i++];
  11391. break;
  11392. case CMD.C:
  11393. fromCubic(
  11394. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11395. min2, max2
  11396. );
  11397. xi = data[i++];
  11398. yi = data[i++];
  11399. break;
  11400. case CMD.Q:
  11401. fromQuadratic(
  11402. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11403. min2, max2
  11404. );
  11405. xi = data[i++];
  11406. yi = data[i++];
  11407. break;
  11408. case CMD.A:
  11409. // TODO Arc 判断的开销比较大
  11410. var cx = data[i++];
  11411. var cy = data[i++];
  11412. var rx = data[i++];
  11413. var ry = data[i++];
  11414. var startAngle = data[i++];
  11415. var endAngle = data[i++] + startAngle;
  11416. // TODO Arc 旋转
  11417. var psi = data[i++];
  11418. var anticlockwise = 1 - data[i++];
  11419. if (i == 1) {
  11420. // 直接使用 arc 命令
  11421. // 第一个命令起点还未定义
  11422. x0 = mathCos$1(startAngle) * rx + cx;
  11423. y0 = mathSin$1(startAngle) * ry + cy;
  11424. }
  11425. fromArc(
  11426. cx, cy, rx, ry, startAngle, endAngle,
  11427. anticlockwise, min2, max2
  11428. );
  11429. xi = mathCos$1(endAngle) * rx + cx;
  11430. yi = mathSin$1(endAngle) * ry + cy;
  11431. break;
  11432. case CMD.R:
  11433. x0 = xi = data[i++];
  11434. y0 = yi = data[i++];
  11435. var width = data[i++];
  11436. var height = data[i++];
  11437. // Use fromLine
  11438. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11439. break;
  11440. case CMD.Z:
  11441. xi = x0;
  11442. yi = y0;
  11443. break;
  11444. }
  11445. // Union
  11446. min(min$1, min$1, min2);
  11447. max(max$1, max$1, max2);
  11448. }
  11449. // No data
  11450. if (i === 0) {
  11451. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11452. }
  11453. return new BoundingRect(
  11454. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11455. );
  11456. },
  11457. /**
  11458. * Rebuild path from current data
  11459. * Rebuild path will not consider javascript implemented line dash.
  11460. * @param {CanvasRenderingContext2D} ctx
  11461. */
  11462. rebuildPath: function (ctx) {
  11463. var d = this.data;
  11464. var x0, y0;
  11465. var xi, yi;
  11466. var x, y;
  11467. var ux = this._ux;
  11468. var uy = this._uy;
  11469. var len$$1 = this._len;
  11470. for (var i = 0; i < len$$1;) {
  11471. var cmd = d[i++];
  11472. if (i == 1) {
  11473. // 如果第一个命令是 L, C, Q
  11474. // 则 previous point 同绘制命令的第一个 point
  11475. //
  11476. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11477. xi = d[i];
  11478. yi = d[i + 1];
  11479. x0 = xi;
  11480. y0 = yi;
  11481. }
  11482. switch (cmd) {
  11483. case CMD.M:
  11484. x0 = xi = d[i++];
  11485. y0 = yi = d[i++];
  11486. ctx.moveTo(xi, yi);
  11487. break;
  11488. case CMD.L:
  11489. x = d[i++];
  11490. y = d[i++];
  11491. // Not draw too small seg between
  11492. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11493. ctx.lineTo(x, y);
  11494. xi = x;
  11495. yi = y;
  11496. }
  11497. break;
  11498. case CMD.C:
  11499. ctx.bezierCurveTo(
  11500. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11501. );
  11502. xi = d[i - 2];
  11503. yi = d[i - 1];
  11504. break;
  11505. case CMD.Q:
  11506. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11507. xi = d[i - 2];
  11508. yi = d[i - 1];
  11509. break;
  11510. case CMD.A:
  11511. var cx = d[i++];
  11512. var cy = d[i++];
  11513. var rx = d[i++];
  11514. var ry = d[i++];
  11515. var theta = d[i++];
  11516. var dTheta = d[i++];
  11517. var psi = d[i++];
  11518. var fs = d[i++];
  11519. var r = (rx > ry) ? rx : ry;
  11520. var scaleX = (rx > ry) ? 1 : rx / ry;
  11521. var scaleY = (rx > ry) ? ry / rx : 1;
  11522. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11523. var endAngle = theta + dTheta;
  11524. if (isEllipse) {
  11525. ctx.translate(cx, cy);
  11526. ctx.rotate(psi);
  11527. ctx.scale(scaleX, scaleY);
  11528. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11529. ctx.scale(1 / scaleX, 1 / scaleY);
  11530. ctx.rotate(-psi);
  11531. ctx.translate(-cx, -cy);
  11532. }
  11533. else {
  11534. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11535. }
  11536. if (i == 1) {
  11537. // 直接使用 arc 命令
  11538. // 第一个命令起点还未定义
  11539. x0 = mathCos$1(theta) * rx + cx;
  11540. y0 = mathSin$1(theta) * ry + cy;
  11541. }
  11542. xi = mathCos$1(endAngle) * rx + cx;
  11543. yi = mathSin$1(endAngle) * ry + cy;
  11544. break;
  11545. case CMD.R:
  11546. x0 = xi = d[i];
  11547. y0 = yi = d[i + 1];
  11548. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11549. break;
  11550. case CMD.Z:
  11551. ctx.closePath();
  11552. xi = x0;
  11553. yi = y0;
  11554. }
  11555. }
  11556. }
  11557. };
  11558. PathProxy.CMD = CMD;
  11559. /**
  11560. * 线段包含判断
  11561. * @param {number} x0
  11562. * @param {number} y0
  11563. * @param {number} x1
  11564. * @param {number} y1
  11565. * @param {number} lineWidth
  11566. * @param {number} x
  11567. * @param {number} y
  11568. * @return {boolean}
  11569. */
  11570. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11571. if (lineWidth === 0) {
  11572. return false;
  11573. }
  11574. var _l = lineWidth;
  11575. var _a = 0;
  11576. var _b = x0;
  11577. // Quick reject
  11578. if (
  11579. (y > y0 + _l && y > y1 + _l)
  11580. || (y < y0 - _l && y < y1 - _l)
  11581. || (x > x0 + _l && x > x1 + _l)
  11582. || (x < x0 - _l && x < x1 - _l)
  11583. ) {
  11584. return false;
  11585. }
  11586. if (x0 !== x1) {
  11587. _a = (y0 - y1) / (x0 - x1);
  11588. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11589. }
  11590. else {
  11591. return Math.abs(x - x0) <= _l / 2;
  11592. }
  11593. var tmp = _a * x - y + _b;
  11594. var _s = tmp * tmp / (_a * _a + 1);
  11595. return _s <= _l / 2 * _l / 2;
  11596. }
  11597. /**
  11598. * 三次贝塞尔曲线描边包含判断
  11599. * @param {number} x0
  11600. * @param {number} y0
  11601. * @param {number} x1
  11602. * @param {number} y1
  11603. * @param {number} x2
  11604. * @param {number} y2
  11605. * @param {number} x3
  11606. * @param {number} y3
  11607. * @param {number} lineWidth
  11608. * @param {number} x
  11609. * @param {number} y
  11610. * @return {boolean}
  11611. */
  11612. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11613. if (lineWidth === 0) {
  11614. return false;
  11615. }
  11616. var _l = lineWidth;
  11617. // Quick reject
  11618. if (
  11619. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11620. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11621. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11622. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11623. ) {
  11624. return false;
  11625. }
  11626. var d = cubicProjectPoint(
  11627. x0, y0, x1, y1, x2, y2, x3, y3,
  11628. x, y, null
  11629. );
  11630. return d <= _l / 2;
  11631. }
  11632. /**
  11633. * 二次贝塞尔曲线描边包含判断
  11634. * @param {number} x0
  11635. * @param {number} y0
  11636. * @param {number} x1
  11637. * @param {number} y1
  11638. * @param {number} x2
  11639. * @param {number} y2
  11640. * @param {number} lineWidth
  11641. * @param {number} x
  11642. * @param {number} y
  11643. * @return {boolean}
  11644. */
  11645. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11646. if (lineWidth === 0) {
  11647. return false;
  11648. }
  11649. var _l = lineWidth;
  11650. // Quick reject
  11651. if (
  11652. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11653. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11654. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11655. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11656. ) {
  11657. return false;
  11658. }
  11659. var d = quadraticProjectPoint(
  11660. x0, y0, x1, y1, x2, y2,
  11661. x, y, null
  11662. );
  11663. return d <= _l / 2;
  11664. }
  11665. var PI2$3 = Math.PI * 2;
  11666. function normalizeRadian(angle) {
  11667. angle %= PI2$3;
  11668. if (angle < 0) {
  11669. angle += PI2$3;
  11670. }
  11671. return angle;
  11672. }
  11673. var PI2$2 = Math.PI * 2;
  11674. /**
  11675. * 圆弧描边包含判断
  11676. * @param {number} cx
  11677. * @param {number} cy
  11678. * @param {number} r
  11679. * @param {number} startAngle
  11680. * @param {number} endAngle
  11681. * @param {boolean} anticlockwise
  11682. * @param {number} lineWidth
  11683. * @param {number} x
  11684. * @param {number} y
  11685. * @return {Boolean}
  11686. */
  11687. function containStroke$4(
  11688. cx, cy, r, startAngle, endAngle, anticlockwise,
  11689. lineWidth, x, y
  11690. ) {
  11691. if (lineWidth === 0) {
  11692. return false;
  11693. }
  11694. var _l = lineWidth;
  11695. x -= cx;
  11696. y -= cy;
  11697. var d = Math.sqrt(x * x + y * y);
  11698. if ((d - _l > r) || (d + _l < r)) {
  11699. return false;
  11700. }
  11701. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11702. // Is a circle
  11703. return true;
  11704. }
  11705. if (anticlockwise) {
  11706. var tmp = startAngle;
  11707. startAngle = normalizeRadian(endAngle);
  11708. endAngle = normalizeRadian(tmp);
  11709. } else {
  11710. startAngle = normalizeRadian(startAngle);
  11711. endAngle = normalizeRadian(endAngle);
  11712. }
  11713. if (startAngle > endAngle) {
  11714. endAngle += PI2$2;
  11715. }
  11716. var angle = Math.atan2(y, x);
  11717. if (angle < 0) {
  11718. angle += PI2$2;
  11719. }
  11720. return (angle >= startAngle && angle <= endAngle)
  11721. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11722. }
  11723. function windingLine(x0, y0, x1, y1, x, y) {
  11724. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11725. return 0;
  11726. }
  11727. // Ignore horizontal line
  11728. if (y1 === y0) {
  11729. return 0;
  11730. }
  11731. var dir = y1 < y0 ? 1 : -1;
  11732. var t = (y - y0) / (y1 - y0);
  11733. // Avoid winding error when intersection point is the connect point of two line of polygon
  11734. if (t === 1 || t === 0) {
  11735. dir = y1 < y0 ? 0.5 : -0.5;
  11736. }
  11737. var x_ = t * (x1 - x0) + x0;
  11738. return x_ > x ? dir : 0;
  11739. }
  11740. var CMD$1 = PathProxy.CMD;
  11741. var PI2$1 = Math.PI * 2;
  11742. var EPSILON$2 = 1e-4;
  11743. function isAroundEqual(a, b) {
  11744. return Math.abs(a - b) < EPSILON$2;
  11745. }
  11746. // 临时数组
  11747. var roots = [-1, -1, -1];
  11748. var extrema = [-1, -1];
  11749. function swapExtrema() {
  11750. var tmp = extrema[0];
  11751. extrema[0] = extrema[1];
  11752. extrema[1] = tmp;
  11753. }
  11754. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11755. // Quick reject
  11756. if (
  11757. (y > y0 && y > y1 && y > y2 && y > y3)
  11758. || (y < y0 && y < y1 && y < y2 && y < y3)
  11759. ) {
  11760. return 0;
  11761. }
  11762. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11763. if (nRoots === 0) {
  11764. return 0;
  11765. }
  11766. else {
  11767. var w = 0;
  11768. var nExtrema = -1;
  11769. var y0_, y1_;
  11770. for (var i = 0; i < nRoots; i++) {
  11771. var t = roots[i];
  11772. // Avoid winding error when intersection point is the connect point of two line of polygon
  11773. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11774. var x_ = cubicAt(x0, x1, x2, x3, t);
  11775. if (x_ < x) { // Quick reject
  11776. continue;
  11777. }
  11778. if (nExtrema < 0) {
  11779. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11780. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11781. swapExtrema();
  11782. }
  11783. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11784. if (nExtrema > 1) {
  11785. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11786. }
  11787. }
  11788. if (nExtrema == 2) {
  11789. // 分成三段单调函数
  11790. if (t < extrema[0]) {
  11791. w += y0_ < y0 ? unit : -unit;
  11792. }
  11793. else if (t < extrema[1]) {
  11794. w += y1_ < y0_ ? unit : -unit;
  11795. }
  11796. else {
  11797. w += y3 < y1_ ? unit : -unit;
  11798. }
  11799. }
  11800. else {
  11801. // 分成两段单调函数
  11802. if (t < extrema[0]) {
  11803. w += y0_ < y0 ? unit : -unit;
  11804. }
  11805. else {
  11806. w += y3 < y0_ ? unit : -unit;
  11807. }
  11808. }
  11809. }
  11810. return w;
  11811. }
  11812. }
  11813. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11814. // Quick reject
  11815. if (
  11816. (y > y0 && y > y1 && y > y2)
  11817. || (y < y0 && y < y1 && y < y2)
  11818. ) {
  11819. return 0;
  11820. }
  11821. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11822. if (nRoots === 0) {
  11823. return 0;
  11824. }
  11825. else {
  11826. var t = quadraticExtremum(y0, y1, y2);
  11827. if (t >= 0 && t <= 1) {
  11828. var w = 0;
  11829. var y_ = quadraticAt(y0, y1, y2, t);
  11830. for (var i = 0; i < nRoots; i++) {
  11831. // Remove one endpoint.
  11832. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11833. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11834. if (x_ < x) { // Quick reject
  11835. continue;
  11836. }
  11837. if (roots[i] < t) {
  11838. w += y_ < y0 ? unit : -unit;
  11839. }
  11840. else {
  11841. w += y2 < y_ ? unit : -unit;
  11842. }
  11843. }
  11844. return w;
  11845. }
  11846. else {
  11847. // Remove one endpoint.
  11848. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11849. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11850. if (x_ < x) { // Quick reject
  11851. return 0;
  11852. }
  11853. return y2 < y0 ? unit : -unit;
  11854. }
  11855. }
  11856. }
  11857. // TODO
  11858. // Arc 旋转
  11859. function windingArc(
  11860. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11861. ) {
  11862. y -= cy;
  11863. if (y > r || y < -r) {
  11864. return 0;
  11865. }
  11866. var tmp = Math.sqrt(r * r - y * y);
  11867. roots[0] = -tmp;
  11868. roots[1] = tmp;
  11869. var diff = Math.abs(startAngle - endAngle);
  11870. if (diff < 1e-4) {
  11871. return 0;
  11872. }
  11873. if (diff % PI2$1 < 1e-4) {
  11874. // Is a circle
  11875. startAngle = 0;
  11876. endAngle = PI2$1;
  11877. var dir = anticlockwise ? 1 : -1;
  11878. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11879. return dir;
  11880. } else {
  11881. return 0;
  11882. }
  11883. }
  11884. if (anticlockwise) {
  11885. var tmp = startAngle;
  11886. startAngle = normalizeRadian(endAngle);
  11887. endAngle = normalizeRadian(tmp);
  11888. }
  11889. else {
  11890. startAngle = normalizeRadian(startAngle);
  11891. endAngle = normalizeRadian(endAngle);
  11892. }
  11893. if (startAngle > endAngle) {
  11894. endAngle += PI2$1;
  11895. }
  11896. var w = 0;
  11897. for (var i = 0; i < 2; i++) {
  11898. var x_ = roots[i];
  11899. if (x_ + cx > x) {
  11900. var angle = Math.atan2(y, x_);
  11901. var dir = anticlockwise ? 1 : -1;
  11902. if (angle < 0) {
  11903. angle = PI2$1 + angle;
  11904. }
  11905. if (
  11906. (angle >= startAngle && angle <= endAngle)
  11907. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11908. ) {
  11909. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11910. dir = -dir;
  11911. }
  11912. w += dir;
  11913. }
  11914. }
  11915. }
  11916. return w;
  11917. }
  11918. function containPath(data, lineWidth, isStroke, x, y) {
  11919. var w = 0;
  11920. var xi = 0;
  11921. var yi = 0;
  11922. var x0 = 0;
  11923. var y0 = 0;
  11924. for (var i = 0; i < data.length;) {
  11925. var cmd = data[i++];
  11926. // Begin a new subpath
  11927. if (cmd === CMD$1.M && i > 1) {
  11928. // Close previous subpath
  11929. if (!isStroke) {
  11930. w += windingLine(xi, yi, x0, y0, x, y);
  11931. }
  11932. // 如果被任何一个 subpath 包含
  11933. // if (w !== 0) {
  11934. // return true;
  11935. // }
  11936. }
  11937. if (i == 1) {
  11938. // 如果第一个命令是 L, C, Q
  11939. // 则 previous point 同绘制命令的第一个 point
  11940. //
  11941. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11942. xi = data[i];
  11943. yi = data[i + 1];
  11944. x0 = xi;
  11945. y0 = yi;
  11946. }
  11947. switch (cmd) {
  11948. case CMD$1.M:
  11949. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11950. // 在 closePath 的时候使用
  11951. x0 = data[i++];
  11952. y0 = data[i++];
  11953. xi = x0;
  11954. yi = y0;
  11955. break;
  11956. case CMD$1.L:
  11957. if (isStroke) {
  11958. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11959. return true;
  11960. }
  11961. }
  11962. else {
  11963. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11964. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11965. }
  11966. xi = data[i++];
  11967. yi = data[i++];
  11968. break;
  11969. case CMD$1.C:
  11970. if (isStroke) {
  11971. if (containStroke$2(xi, yi,
  11972. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11973. lineWidth, x, y
  11974. )) {
  11975. return true;
  11976. }
  11977. }
  11978. else {
  11979. w += windingCubic(
  11980. xi, yi,
  11981. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11982. x, y
  11983. ) || 0;
  11984. }
  11985. xi = data[i++];
  11986. yi = data[i++];
  11987. break;
  11988. case CMD$1.Q:
  11989. if (isStroke) {
  11990. if (containStroke$3(xi, yi,
  11991. data[i++], data[i++], data[i], data[i + 1],
  11992. lineWidth, x, y
  11993. )) {
  11994. return true;
  11995. }
  11996. }
  11997. else {
  11998. w += windingQuadratic(
  11999. xi, yi,
  12000. data[i++], data[i++], data[i], data[i + 1],
  12001. x, y
  12002. ) || 0;
  12003. }
  12004. xi = data[i++];
  12005. yi = data[i++];
  12006. break;
  12007. case CMD$1.A:
  12008. // TODO Arc 判断的开销比较大
  12009. var cx = data[i++];
  12010. var cy = data[i++];
  12011. var rx = data[i++];
  12012. var ry = data[i++];
  12013. var theta = data[i++];
  12014. var dTheta = data[i++];
  12015. // TODO Arc 旋转
  12016. var psi = data[i++];
  12017. var anticlockwise = 1 - data[i++];
  12018. var x1 = Math.cos(theta) * rx + cx;
  12019. var y1 = Math.sin(theta) * ry + cy;
  12020. // 不是直接使用 arc 命令
  12021. if (i > 1) {
  12022. w += windingLine(xi, yi, x1, y1, x, y);
  12023. }
  12024. else {
  12025. // 第一个命令起点还未定义
  12026. x0 = x1;
  12027. y0 = y1;
  12028. }
  12029. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12030. var _x = (x - cx) * ry / rx + cx;
  12031. if (isStroke) {
  12032. if (containStroke$4(
  12033. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12034. lineWidth, _x, y
  12035. )) {
  12036. return true;
  12037. }
  12038. }
  12039. else {
  12040. w += windingArc(
  12041. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12042. _x, y
  12043. );
  12044. }
  12045. xi = Math.cos(theta + dTheta) * rx + cx;
  12046. yi = Math.sin(theta + dTheta) * ry + cy;
  12047. break;
  12048. case CMD$1.R:
  12049. x0 = xi = data[i++];
  12050. y0 = yi = data[i++];
  12051. var width = data[i++];
  12052. var height = data[i++];
  12053. var x1 = x0 + width;
  12054. var y1 = y0 + height;
  12055. if (isStroke) {
  12056. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12057. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12058. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12059. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12060. ) {
  12061. return true;
  12062. }
  12063. }
  12064. else {
  12065. // FIXME Clockwise ?
  12066. w += windingLine(x1, y0, x1, y1, x, y);
  12067. w += windingLine(x0, y1, x0, y0, x, y);
  12068. }
  12069. break;
  12070. case CMD$1.Z:
  12071. if (isStroke) {
  12072. if (containStroke$1(
  12073. xi, yi, x0, y0, lineWidth, x, y
  12074. )) {
  12075. return true;
  12076. }
  12077. }
  12078. else {
  12079. // Close a subpath
  12080. w += windingLine(xi, yi, x0, y0, x, y);
  12081. // 如果被任何一个 subpath 包含
  12082. // FIXME subpaths may overlap
  12083. // if (w !== 0) {
  12084. // return true;
  12085. // }
  12086. }
  12087. xi = x0;
  12088. yi = y0;
  12089. break;
  12090. }
  12091. }
  12092. if (!isStroke && !isAroundEqual(yi, y0)) {
  12093. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12094. }
  12095. return w !== 0;
  12096. }
  12097. function contain(pathData, x, y) {
  12098. return containPath(pathData, 0, false, x, y);
  12099. }
  12100. function containStroke(pathData, lineWidth, x, y) {
  12101. return containPath(pathData, lineWidth, true, x, y);
  12102. }
  12103. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12104. var abs = Math.abs;
  12105. var pathProxyForDraw = new PathProxy(true);
  12106. /**
  12107. * @alias module:zrender/graphic/Path
  12108. * @extends module:zrender/graphic/Displayable
  12109. * @constructor
  12110. * @param {Object} opts
  12111. */
  12112. function Path(opts) {
  12113. Displayable.call(this, opts);
  12114. /**
  12115. * @type {module:zrender/core/PathProxy}
  12116. * @readOnly
  12117. */
  12118. this.path = null;
  12119. }
  12120. Path.prototype = {
  12121. constructor: Path,
  12122. type: 'path',
  12123. __dirtyPath: true,
  12124. strokeContainThreshold: 5,
  12125. brush: function (ctx, prevEl) {
  12126. var style = this.style;
  12127. var path = this.path || pathProxyForDraw;
  12128. var hasStroke = style.hasStroke();
  12129. var hasFill = style.hasFill();
  12130. var fill = style.fill;
  12131. var stroke = style.stroke;
  12132. var hasFillGradient = hasFill && !!(fill.colorStops);
  12133. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12134. var hasFillPattern = hasFill && !!(fill.image);
  12135. var hasStrokePattern = hasStroke && !!(stroke.image);
  12136. style.bind(ctx, this, prevEl);
  12137. this.setTransform(ctx);
  12138. if (this.__dirty) {
  12139. var rect;
  12140. // Update gradient because bounding rect may changed
  12141. if (hasFillGradient) {
  12142. rect = rect || this.getBoundingRect();
  12143. this._fillGradient = style.getGradient(ctx, fill, rect);
  12144. }
  12145. if (hasStrokeGradient) {
  12146. rect = rect || this.getBoundingRect();
  12147. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12148. }
  12149. }
  12150. // Use the gradient or pattern
  12151. if (hasFillGradient) {
  12152. // PENDING If may have affect the state
  12153. ctx.fillStyle = this._fillGradient;
  12154. }
  12155. else if (hasFillPattern) {
  12156. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12157. }
  12158. if (hasStrokeGradient) {
  12159. ctx.strokeStyle = this._strokeGradient;
  12160. }
  12161. else if (hasStrokePattern) {
  12162. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12163. }
  12164. var lineDash = style.lineDash;
  12165. var lineDashOffset = style.lineDashOffset;
  12166. var ctxLineDash = !!ctx.setLineDash;
  12167. // Update path sx, sy
  12168. var scale = this.getGlobalScale();
  12169. path.setScale(scale[0], scale[1]);
  12170. // Proxy context
  12171. // Rebuild path in following 2 cases
  12172. // 1. Path is dirty
  12173. // 2. Path needs javascript implemented lineDash stroking.
  12174. // In this case, lineDash information will not be saved in PathProxy
  12175. if (this.__dirtyPath
  12176. || (lineDash && !ctxLineDash && hasStroke)
  12177. ) {
  12178. path.beginPath(ctx);
  12179. // Setting line dash before build path
  12180. if (lineDash && !ctxLineDash) {
  12181. path.setLineDash(lineDash);
  12182. path.setLineDashOffset(lineDashOffset);
  12183. }
  12184. this.buildPath(path, this.shape, false);
  12185. // Clear path dirty flag
  12186. if (this.path) {
  12187. this.__dirtyPath = false;
  12188. }
  12189. }
  12190. else {
  12191. // Replay path building
  12192. ctx.beginPath();
  12193. this.path.rebuildPath(ctx);
  12194. }
  12195. hasFill && path.fill(ctx);
  12196. if (lineDash && ctxLineDash) {
  12197. ctx.setLineDash(lineDash);
  12198. ctx.lineDashOffset = lineDashOffset;
  12199. }
  12200. hasStroke && path.stroke(ctx);
  12201. if (lineDash && ctxLineDash) {
  12202. // PENDING
  12203. // Remove lineDash
  12204. ctx.setLineDash([]);
  12205. }
  12206. // Draw rect text
  12207. if (style.text != null) {
  12208. // Only restore transform when needs draw text.
  12209. this.restoreTransform(ctx);
  12210. this.drawRectText(ctx, this.getBoundingRect());
  12211. }
  12212. },
  12213. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12214. // Like in circle
  12215. buildPath: function (ctx, shapeCfg, inBundle) {},
  12216. createPathProxy: function () {
  12217. this.path = new PathProxy();
  12218. },
  12219. getBoundingRect: function () {
  12220. var rect = this._rect;
  12221. var style = this.style;
  12222. var needsUpdateRect = !rect;
  12223. if (needsUpdateRect) {
  12224. var path = this.path;
  12225. if (!path) {
  12226. // Create path on demand.
  12227. path = this.path = new PathProxy();
  12228. }
  12229. if (this.__dirtyPath) {
  12230. path.beginPath();
  12231. this.buildPath(path, this.shape, false);
  12232. }
  12233. rect = path.getBoundingRect();
  12234. }
  12235. this._rect = rect;
  12236. if (style.hasStroke()) {
  12237. // Needs update rect with stroke lineWidth when
  12238. // 1. Element changes scale or lineWidth
  12239. // 2. Shape is changed
  12240. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12241. if (this.__dirty || needsUpdateRect) {
  12242. rectWithStroke.copy(rect);
  12243. // FIXME Must after updateTransform
  12244. var w = style.lineWidth;
  12245. // PENDING, Min line width is needed when line is horizontal or vertical
  12246. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12247. // Only add extra hover lineWidth when there are no fill
  12248. if (!style.hasFill()) {
  12249. w = Math.max(w, this.strokeContainThreshold || 4);
  12250. }
  12251. // Consider line width
  12252. // Line scale can't be 0;
  12253. if (lineScale > 1e-10) {
  12254. rectWithStroke.width += w / lineScale;
  12255. rectWithStroke.height += w / lineScale;
  12256. rectWithStroke.x -= w / lineScale / 2;
  12257. rectWithStroke.y -= w / lineScale / 2;
  12258. }
  12259. }
  12260. // Return rect with stroke
  12261. return rectWithStroke;
  12262. }
  12263. return rect;
  12264. },
  12265. contain: function (x, y) {
  12266. var localPos = this.transformCoordToLocal(x, y);
  12267. var rect = this.getBoundingRect();
  12268. var style = this.style;
  12269. x = localPos[0];
  12270. y = localPos[1];
  12271. if (rect.contain(x, y)) {
  12272. var pathData = this.path.data;
  12273. if (style.hasStroke()) {
  12274. var lineWidth = style.lineWidth;
  12275. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12276. // Line scale can't be 0;
  12277. if (lineScale > 1e-10) {
  12278. // Only add extra hover lineWidth when there are no fill
  12279. if (!style.hasFill()) {
  12280. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12281. }
  12282. if (containStroke(
  12283. pathData, lineWidth / lineScale, x, y
  12284. )) {
  12285. return true;
  12286. }
  12287. }
  12288. }
  12289. if (style.hasFill()) {
  12290. return contain(pathData, x, y);
  12291. }
  12292. }
  12293. return false;
  12294. },
  12295. /**
  12296. * @param {boolean} dirtyPath
  12297. */
  12298. dirty: function (dirtyPath) {
  12299. if (dirtyPath == null) {
  12300. dirtyPath = true;
  12301. }
  12302. // Only mark dirty, not mark clean
  12303. if (dirtyPath) {
  12304. this.__dirtyPath = dirtyPath;
  12305. this._rect = null;
  12306. }
  12307. this.__dirty = true;
  12308. this.__zr && this.__zr.refresh();
  12309. // Used as a clipping path
  12310. if (this.__clipTarget) {
  12311. this.__clipTarget.dirty();
  12312. }
  12313. },
  12314. /**
  12315. * Alias for animate('shape')
  12316. * @param {boolean} loop
  12317. */
  12318. animateShape: function (loop) {
  12319. return this.animate('shape', loop);
  12320. },
  12321. // Overwrite attrKV
  12322. attrKV: function (key, value) {
  12323. // FIXME
  12324. if (key === 'shape') {
  12325. this.setShape(value);
  12326. this.__dirtyPath = true;
  12327. this._rect = null;
  12328. }
  12329. else {
  12330. Displayable.prototype.attrKV.call(this, key, value);
  12331. }
  12332. },
  12333. /**
  12334. * @param {Object|string} key
  12335. * @param {*} value
  12336. */
  12337. setShape: function (key, value) {
  12338. var shape = this.shape;
  12339. // Path from string may not have shape
  12340. if (shape) {
  12341. if (isObject$1(key)) {
  12342. for (var name in key) {
  12343. if (key.hasOwnProperty(name)) {
  12344. shape[name] = key[name];
  12345. }
  12346. }
  12347. }
  12348. else {
  12349. shape[key] = value;
  12350. }
  12351. this.dirty(true);
  12352. }
  12353. return this;
  12354. },
  12355. getLineScale: function () {
  12356. var m = this.transform;
  12357. // Get the line scale.
  12358. // Determinant of `m` means how much the area is enlarged by the
  12359. // transformation. So its square root can be used as a scale factor
  12360. // for width.
  12361. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12362. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12363. : 1;
  12364. }
  12365. };
  12366. /**
  12367. * 扩展一个 Path element, 比如星形,圆等。
  12368. * Extend a path element
  12369. * @param {Object} props
  12370. * @param {string} props.type Path type
  12371. * @param {Function} props.init Initialize
  12372. * @param {Function} props.buildPath Overwrite buildPath method
  12373. * @param {Object} [props.style] Extended default style config
  12374. * @param {Object} [props.shape] Extended default shape config
  12375. */
  12376. Path.extend = function (defaults$$1) {
  12377. var Sub = function (opts) {
  12378. Path.call(this, opts);
  12379. if (defaults$$1.style) {
  12380. // Extend default style
  12381. this.style.extendFrom(defaults$$1.style, false);
  12382. }
  12383. // Extend default shape
  12384. var defaultShape = defaults$$1.shape;
  12385. if (defaultShape) {
  12386. this.shape = this.shape || {};
  12387. var thisShape = this.shape;
  12388. for (var name in defaultShape) {
  12389. if (
  12390. ! thisShape.hasOwnProperty(name)
  12391. && defaultShape.hasOwnProperty(name)
  12392. ) {
  12393. thisShape[name] = defaultShape[name];
  12394. }
  12395. }
  12396. }
  12397. defaults$$1.init && defaults$$1.init.call(this, opts);
  12398. };
  12399. inherits(Sub, Path);
  12400. // FIXME 不能 extend position, rotation 等引用对象
  12401. for (var name in defaults$$1) {
  12402. // Extending prototype values and methods
  12403. if (name !== 'style' && name !== 'shape') {
  12404. Sub.prototype[name] = defaults$$1[name];
  12405. }
  12406. }
  12407. return Sub;
  12408. };
  12409. inherits(Path, Displayable);
  12410. var CMD$2 = PathProxy.CMD;
  12411. var points = [[], [], []];
  12412. var mathSqrt$3 = Math.sqrt;
  12413. var mathAtan2 = Math.atan2;
  12414. var transformPath = function (path, m) {
  12415. var data = path.data;
  12416. var cmd;
  12417. var nPoint;
  12418. var i;
  12419. var j;
  12420. var k;
  12421. var p;
  12422. var M = CMD$2.M;
  12423. var C = CMD$2.C;
  12424. var L = CMD$2.L;
  12425. var R = CMD$2.R;
  12426. var A = CMD$2.A;
  12427. var Q = CMD$2.Q;
  12428. for (i = 0, j = 0; i < data.length;) {
  12429. cmd = data[i++];
  12430. j = i;
  12431. nPoint = 0;
  12432. switch (cmd) {
  12433. case M:
  12434. nPoint = 1;
  12435. break;
  12436. case L:
  12437. nPoint = 1;
  12438. break;
  12439. case C:
  12440. nPoint = 3;
  12441. break;
  12442. case Q:
  12443. nPoint = 2;
  12444. break;
  12445. case A:
  12446. var x = m[4];
  12447. var y = m[5];
  12448. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12449. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12450. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12451. // cx
  12452. data[i] *= sx;
  12453. data[i++] += x;
  12454. // cy
  12455. data[i] *= sy;
  12456. data[i++] += y;
  12457. // Scale rx and ry
  12458. // FIXME Assume psi is 0 here
  12459. data[i++] *= sx;
  12460. data[i++] *= sy;
  12461. // Start angle
  12462. data[i++] += angle;
  12463. // end angle
  12464. data[i++] += angle;
  12465. // FIXME psi
  12466. i += 2;
  12467. j = i;
  12468. break;
  12469. case R:
  12470. // x0, y0
  12471. p[0] = data[i++];
  12472. p[1] = data[i++];
  12473. applyTransform(p, p, m);
  12474. data[j++] = p[0];
  12475. data[j++] = p[1];
  12476. // x1, y1
  12477. p[0] += data[i++];
  12478. p[1] += data[i++];
  12479. applyTransform(p, p, m);
  12480. data[j++] = p[0];
  12481. data[j++] = p[1];
  12482. }
  12483. for (k = 0; k < nPoint; k++) {
  12484. var p = points[k];
  12485. p[0] = data[i++];
  12486. p[1] = data[i++];
  12487. applyTransform(p, p, m);
  12488. // Write back
  12489. data[j++] = p[0];
  12490. data[j++] = p[1];
  12491. }
  12492. }
  12493. };
  12494. // command chars
  12495. var cc = [
  12496. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12497. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12498. ];
  12499. var mathSqrt = Math.sqrt;
  12500. var mathSin = Math.sin;
  12501. var mathCos = Math.cos;
  12502. var PI = Math.PI;
  12503. var vMag = function(v) {
  12504. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12505. };
  12506. var vRatio = function(u, v) {
  12507. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12508. };
  12509. var vAngle = function(u, v) {
  12510. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12511. * Math.acos(vRatio(u, v));
  12512. };
  12513. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12514. var psi = psiDeg * (PI / 180.0);
  12515. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12516. + mathSin(psi) * (y1 - y2) / 2.0;
  12517. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12518. + mathCos(psi) * (y1 - y2) / 2.0;
  12519. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12520. if (lambda > 1) {
  12521. rx *= mathSqrt(lambda);
  12522. ry *= mathSqrt(lambda);
  12523. }
  12524. var f = (fa === fs ? -1 : 1)
  12525. * mathSqrt((((rx * rx) * (ry * ry))
  12526. - ((rx * rx) * (yp * yp))
  12527. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12528. + (ry * ry) * (xp * xp))
  12529. ) || 0;
  12530. var cxp = f * rx * yp / ry;
  12531. var cyp = f * -ry * xp / rx;
  12532. var cx = (x1 + x2) / 2.0
  12533. + mathCos(psi) * cxp
  12534. - mathSin(psi) * cyp;
  12535. var cy = (y1 + y2) / 2.0
  12536. + mathSin(psi) * cxp
  12537. + mathCos(psi) * cyp;
  12538. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12539. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12540. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12541. var dTheta = vAngle(u, v);
  12542. if (vRatio(u, v) <= -1) {
  12543. dTheta = PI;
  12544. }
  12545. if (vRatio(u, v) >= 1) {
  12546. dTheta = 0;
  12547. }
  12548. if (fs === 0 && dTheta > 0) {
  12549. dTheta = dTheta - 2 * PI;
  12550. }
  12551. if (fs === 1 && dTheta < 0) {
  12552. dTheta = dTheta + 2 * PI;
  12553. }
  12554. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12555. }
  12556. function createPathProxyFromString(data) {
  12557. if (!data) {
  12558. return [];
  12559. }
  12560. // command string
  12561. var cs = data.replace(/-/g, ' -')
  12562. .replace(/ /g, ' ')
  12563. .replace(/ /g, ',')
  12564. .replace(/,,/g, ',');
  12565. var n;
  12566. // create pipes so that we can split the data
  12567. for (n = 0; n < cc.length; n++) {
  12568. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12569. }
  12570. // create array
  12571. var arr = cs.split('|');
  12572. // init context point
  12573. var cpx = 0;
  12574. var cpy = 0;
  12575. var path = new PathProxy();
  12576. var CMD = PathProxy.CMD;
  12577. var prevCmd;
  12578. for (n = 1; n < arr.length; n++) {
  12579. var str = arr[n];
  12580. var c = str.charAt(0);
  12581. var off = 0;
  12582. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12583. var cmd;
  12584. if (p.length > 0 && p[0] === '') {
  12585. p.shift();
  12586. }
  12587. for (var i = 0; i < p.length; i++) {
  12588. p[i] = parseFloat(p[i]);
  12589. }
  12590. while (off < p.length && !isNaN(p[off])) {
  12591. if (isNaN(p[0])) {
  12592. break;
  12593. }
  12594. var ctlPtx;
  12595. var ctlPty;
  12596. var rx;
  12597. var ry;
  12598. var psi;
  12599. var fa;
  12600. var fs;
  12601. var x1 = cpx;
  12602. var y1 = cpy;
  12603. // convert l, H, h, V, and v to L
  12604. switch (c) {
  12605. case 'l':
  12606. cpx += p[off++];
  12607. cpy += p[off++];
  12608. cmd = CMD.L;
  12609. path.addData(cmd, cpx, cpy);
  12610. break;
  12611. case 'L':
  12612. cpx = p[off++];
  12613. cpy = p[off++];
  12614. cmd = CMD.L;
  12615. path.addData(cmd, cpx, cpy);
  12616. break;
  12617. case 'm':
  12618. cpx += p[off++];
  12619. cpy += p[off++];
  12620. cmd = CMD.M;
  12621. path.addData(cmd, cpx, cpy);
  12622. c = 'l';
  12623. break;
  12624. case 'M':
  12625. cpx = p[off++];
  12626. cpy = p[off++];
  12627. cmd = CMD.M;
  12628. path.addData(cmd, cpx, cpy);
  12629. c = 'L';
  12630. break;
  12631. case 'h':
  12632. cpx += p[off++];
  12633. cmd = CMD.L;
  12634. path.addData(cmd, cpx, cpy);
  12635. break;
  12636. case 'H':
  12637. cpx = p[off++];
  12638. cmd = CMD.L;
  12639. path.addData(cmd, cpx, cpy);
  12640. break;
  12641. case 'v':
  12642. cpy += p[off++];
  12643. cmd = CMD.L;
  12644. path.addData(cmd, cpx, cpy);
  12645. break;
  12646. case 'V':
  12647. cpy = p[off++];
  12648. cmd = CMD.L;
  12649. path.addData(cmd, cpx, cpy);
  12650. break;
  12651. case 'C':
  12652. cmd = CMD.C;
  12653. path.addData(
  12654. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12655. );
  12656. cpx = p[off - 2];
  12657. cpy = p[off - 1];
  12658. break;
  12659. case 'c':
  12660. cmd = CMD.C;
  12661. path.addData(
  12662. cmd,
  12663. p[off++] + cpx, p[off++] + cpy,
  12664. p[off++] + cpx, p[off++] + cpy,
  12665. p[off++] + cpx, p[off++] + cpy
  12666. );
  12667. cpx += p[off - 2];
  12668. cpy += p[off - 1];
  12669. break;
  12670. case 'S':
  12671. ctlPtx = cpx;
  12672. ctlPty = cpy;
  12673. var len = path.len();
  12674. var pathData = path.data;
  12675. if (prevCmd === CMD.C) {
  12676. ctlPtx += cpx - pathData[len - 4];
  12677. ctlPty += cpy - pathData[len - 3];
  12678. }
  12679. cmd = CMD.C;
  12680. x1 = p[off++];
  12681. y1 = p[off++];
  12682. cpx = p[off++];
  12683. cpy = p[off++];
  12684. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12685. break;
  12686. case 's':
  12687. ctlPtx = cpx;
  12688. ctlPty = cpy;
  12689. var len = path.len();
  12690. var pathData = path.data;
  12691. if (prevCmd === CMD.C) {
  12692. ctlPtx += cpx - pathData[len - 4];
  12693. ctlPty += cpy - pathData[len - 3];
  12694. }
  12695. cmd = CMD.C;
  12696. x1 = cpx + p[off++];
  12697. y1 = cpy + p[off++];
  12698. cpx += p[off++];
  12699. cpy += p[off++];
  12700. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12701. break;
  12702. case 'Q':
  12703. x1 = p[off++];
  12704. y1 = p[off++];
  12705. cpx = p[off++];
  12706. cpy = p[off++];
  12707. cmd = CMD.Q;
  12708. path.addData(cmd, x1, y1, cpx, cpy);
  12709. break;
  12710. case 'q':
  12711. x1 = p[off++] + cpx;
  12712. y1 = p[off++] + cpy;
  12713. cpx += p[off++];
  12714. cpy += p[off++];
  12715. cmd = CMD.Q;
  12716. path.addData(cmd, x1, y1, cpx, cpy);
  12717. break;
  12718. case 'T':
  12719. ctlPtx = cpx;
  12720. ctlPty = cpy;
  12721. var len = path.len();
  12722. var pathData = path.data;
  12723. if (prevCmd === CMD.Q) {
  12724. ctlPtx += cpx - pathData[len - 4];
  12725. ctlPty += cpy - pathData[len - 3];
  12726. }
  12727. cpx = p[off++];
  12728. cpy = p[off++];
  12729. cmd = CMD.Q;
  12730. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12731. break;
  12732. case 't':
  12733. ctlPtx = cpx;
  12734. ctlPty = cpy;
  12735. var len = path.len();
  12736. var pathData = path.data;
  12737. if (prevCmd === CMD.Q) {
  12738. ctlPtx += cpx - pathData[len - 4];
  12739. ctlPty += cpy - pathData[len - 3];
  12740. }
  12741. cpx += p[off++];
  12742. cpy += p[off++];
  12743. cmd = CMD.Q;
  12744. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12745. break;
  12746. case 'A':
  12747. rx = p[off++];
  12748. ry = p[off++];
  12749. psi = p[off++];
  12750. fa = p[off++];
  12751. fs = p[off++];
  12752. x1 = cpx, y1 = cpy;
  12753. cpx = p[off++];
  12754. cpy = p[off++];
  12755. cmd = CMD.A;
  12756. processArc(
  12757. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12758. );
  12759. break;
  12760. case 'a':
  12761. rx = p[off++];
  12762. ry = p[off++];
  12763. psi = p[off++];
  12764. fa = p[off++];
  12765. fs = p[off++];
  12766. x1 = cpx, y1 = cpy;
  12767. cpx += p[off++];
  12768. cpy += p[off++];
  12769. cmd = CMD.A;
  12770. processArc(
  12771. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12772. );
  12773. break;
  12774. }
  12775. }
  12776. if (c === 'z' || c === 'Z') {
  12777. cmd = CMD.Z;
  12778. path.addData(cmd);
  12779. }
  12780. prevCmd = cmd;
  12781. }
  12782. path.toStatic();
  12783. return path;
  12784. }
  12785. // TODO Optimize double memory cost problem
  12786. function createPathOptions(str, opts) {
  12787. var pathProxy = createPathProxyFromString(str);
  12788. opts = opts || {};
  12789. opts.buildPath = function (path) {
  12790. if (path.setData) {
  12791. path.setData(pathProxy.data);
  12792. // Svg and vml renderer don't have context
  12793. var ctx = path.getContext();
  12794. if (ctx) {
  12795. path.rebuildPath(ctx);
  12796. }
  12797. }
  12798. else {
  12799. var ctx = path;
  12800. pathProxy.rebuildPath(ctx);
  12801. }
  12802. };
  12803. opts.applyTransform = function (m) {
  12804. transformPath(pathProxy, m);
  12805. this.dirty(true);
  12806. };
  12807. return opts;
  12808. }
  12809. /**
  12810. * Create a Path object from path string data
  12811. * http://www.w3.org/TR/SVG/paths.html#PathData
  12812. * @param {Object} opts Other options
  12813. */
  12814. function createFromString(str, opts) {
  12815. return new Path(createPathOptions(str, opts));
  12816. }
  12817. /**
  12818. * Create a Path class from path string data
  12819. * @param {string} str
  12820. * @param {Object} opts Other options
  12821. */
  12822. function extendFromString(str, opts) {
  12823. return Path.extend(createPathOptions(str, opts));
  12824. }
  12825. /**
  12826. * Merge multiple paths
  12827. */
  12828. // TODO Apply transform
  12829. // TODO stroke dash
  12830. // TODO Optimize double memory cost problem
  12831. function mergePath$1(pathEls, opts) {
  12832. var pathList = [];
  12833. var len = pathEls.length;
  12834. for (var i = 0; i < len; i++) {
  12835. var pathEl = pathEls[i];
  12836. if (!pathEl.path) {
  12837. pathEl.createPathProxy();
  12838. }
  12839. if (pathEl.__dirtyPath) {
  12840. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12841. }
  12842. pathList.push(pathEl.path);
  12843. }
  12844. var pathBundle = new Path(opts);
  12845. // Need path proxy.
  12846. pathBundle.createPathProxy();
  12847. pathBundle.buildPath = function (path) {
  12848. path.appendPath(pathList);
  12849. // Svg and vml renderer don't have context
  12850. var ctx = path.getContext();
  12851. if (ctx) {
  12852. path.rebuildPath(ctx);
  12853. }
  12854. };
  12855. return pathBundle;
  12856. }
  12857. /**
  12858. * @alias zrender/graphic/Text
  12859. * @extends module:zrender/graphic/Displayable
  12860. * @constructor
  12861. * @param {Object} opts
  12862. */
  12863. var Text = function (opts) { // jshint ignore:line
  12864. Displayable.call(this, opts);
  12865. };
  12866. Text.prototype = {
  12867. constructor: Text,
  12868. type: 'text',
  12869. brush: function (ctx, prevEl) {
  12870. var style = this.style;
  12871. // Optimize, avoid normalize every time.
  12872. this.__dirty && normalizeTextStyle(style, true);
  12873. // Use props with prefix 'text'.
  12874. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12875. style.shadowOffsetX = style.shadowOffsetY = null;
  12876. var text = style.text;
  12877. // Convert to string
  12878. text != null && (text += '');
  12879. // Always bind style
  12880. style.bind(ctx, this, prevEl);
  12881. if (!needDrawText(text, style)) {
  12882. return;
  12883. }
  12884. this.setTransform(ctx);
  12885. renderText(this, ctx, text, style);
  12886. this.restoreTransform(ctx);
  12887. },
  12888. getBoundingRect: function () {
  12889. var style = this.style;
  12890. // Optimize, avoid normalize every time.
  12891. this.__dirty && normalizeTextStyle(style, true);
  12892. if (!this._rect) {
  12893. var text = style.text;
  12894. text != null ? (text += '') : (text = '');
  12895. var rect = getBoundingRect(
  12896. style.text + '',
  12897. style.font,
  12898. style.textAlign,
  12899. style.textVerticalAlign,
  12900. style.textPadding,
  12901. style.rich
  12902. );
  12903. rect.x += style.x || 0;
  12904. rect.y += style.y || 0;
  12905. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12906. var w = style.textStrokeWidth;
  12907. rect.x -= w / 2;
  12908. rect.y -= w / 2;
  12909. rect.width += w;
  12910. rect.height += w;
  12911. }
  12912. this._rect = rect;
  12913. }
  12914. return this._rect;
  12915. }
  12916. };
  12917. inherits(Text, Displayable);
  12918. /**
  12919. * 圆形
  12920. * @module zrender/shape/Circle
  12921. */
  12922. var Circle = Path.extend({
  12923. type: 'circle',
  12924. shape: {
  12925. cx: 0,
  12926. cy: 0,
  12927. r: 0
  12928. },
  12929. buildPath : function (ctx, shape, inBundle) {
  12930. // Better stroking in ShapeBundle
  12931. // Always do it may have performence issue ( fill may be 2x more cost)
  12932. if (inBundle) {
  12933. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12934. }
  12935. // else {
  12936. // if (ctx.allocate && !ctx.data.length) {
  12937. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12938. // }
  12939. // }
  12940. // Better stroking in ShapeBundle
  12941. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12942. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12943. }
  12944. });
  12945. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12946. // where exception "unexpected call to method or property access"
  12947. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12948. // whose area size is zero is drawn and ctx.clip() is called and
  12949. // shadowBlur is set. See #4572, #3112, #5777.
  12950. // (e.g.,
  12951. // ctx.moveTo(10, 10);
  12952. // ctx.lineTo(20, 10);
  12953. // ctx.closePath();
  12954. // ctx.clip();
  12955. // ctx.shadowBlur = 10;
  12956. // ...
  12957. // ctx.fill();
  12958. // )
  12959. var shadowTemp = [
  12960. ['shadowBlur', 0],
  12961. ['shadowColor', '#000'],
  12962. ['shadowOffsetX', 0],
  12963. ['shadowOffsetY', 0]
  12964. ];
  12965. var fixClipWithShadow = function (orignalBrush) {
  12966. // version string can be: '11.0'
  12967. return (env$1.browser.ie && env$1.browser.version >= 11)
  12968. ? function () {
  12969. var clipPaths = this.__clipPaths;
  12970. var style = this.style;
  12971. var modified;
  12972. if (clipPaths) {
  12973. for (var i = 0; i < clipPaths.length; i++) {
  12974. var clipPath = clipPaths[i];
  12975. var shape = clipPath && clipPath.shape;
  12976. var type = clipPath && clipPath.type;
  12977. if (shape && (
  12978. (type === 'sector' && shape.startAngle === shape.endAngle)
  12979. || (type === 'rect' && (!shape.width || !shape.height))
  12980. )) {
  12981. for (var j = 0; j < shadowTemp.length; j++) {
  12982. // It is save to put shadowTemp static, because shadowTemp
  12983. // will be all modified each item brush called.
  12984. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12985. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12986. }
  12987. modified = true;
  12988. break;
  12989. }
  12990. }
  12991. }
  12992. orignalBrush.apply(this, arguments);
  12993. if (modified) {
  12994. for (var j = 0; j < shadowTemp.length; j++) {
  12995. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12996. }
  12997. }
  12998. }
  12999. : orignalBrush;
  13000. };
  13001. /**
  13002. * 扇形
  13003. * @module zrender/graphic/shape/Sector
  13004. */
  13005. var Sector = Path.extend({
  13006. type: 'sector',
  13007. shape: {
  13008. cx: 0,
  13009. cy: 0,
  13010. r0: 0,
  13011. r: 0,
  13012. startAngle: 0,
  13013. endAngle: Math.PI * 2,
  13014. clockwise: true
  13015. },
  13016. brush: fixClipWithShadow(Path.prototype.brush),
  13017. buildPath: function (ctx, shape) {
  13018. var x = shape.cx;
  13019. var y = shape.cy;
  13020. var r0 = Math.max(shape.r0 || 0, 0);
  13021. var r = Math.max(shape.r, 0);
  13022. var startAngle = shape.startAngle;
  13023. var endAngle = shape.endAngle;
  13024. var clockwise = shape.clockwise;
  13025. var unitX = Math.cos(startAngle);
  13026. var unitY = Math.sin(startAngle);
  13027. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13028. ctx.lineTo(unitX * r + x, unitY * r + y);
  13029. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13030. ctx.lineTo(
  13031. Math.cos(endAngle) * r0 + x,
  13032. Math.sin(endAngle) * r0 + y
  13033. );
  13034. if (r0 !== 0) {
  13035. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13036. }
  13037. ctx.closePath();
  13038. }
  13039. });
  13040. /**
  13041. * 圆环
  13042. * @module zrender/graphic/shape/Ring
  13043. */
  13044. var Ring = Path.extend({
  13045. type: 'ring',
  13046. shape: {
  13047. cx: 0,
  13048. cy: 0,
  13049. r: 0,
  13050. r0: 0
  13051. },
  13052. buildPath: function (ctx, shape) {
  13053. var x = shape.cx;
  13054. var y = shape.cy;
  13055. var PI2 = Math.PI * 2;
  13056. ctx.moveTo(x + shape.r, y);
  13057. ctx.arc(x, y, shape.r, 0, PI2, false);
  13058. ctx.moveTo(x + shape.r0, y);
  13059. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13060. }
  13061. });
  13062. /**
  13063. * Catmull-Rom spline 插值折线
  13064. * @module zrender/shape/util/smoothSpline
  13065. * @author pissang (https://www.github.com/pissang)
  13066. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13067. * errorrik (errorrik@gmail.com)
  13068. */
  13069. /**
  13070. * @inner
  13071. */
  13072. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13073. var v0 = (p2 - p0) * 0.5;
  13074. var v1 = (p3 - p1) * 0.5;
  13075. return (2 * (p1 - p2) + v0 + v1) * t3
  13076. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13077. + v0 * t + p1;
  13078. }
  13079. /**
  13080. * @alias module:zrender/shape/util/smoothSpline
  13081. * @param {Array} points 线段顶点数组
  13082. * @param {boolean} isLoop
  13083. * @return {Array}
  13084. */
  13085. var smoothSpline = function (points, isLoop) {
  13086. var len$$1 = points.length;
  13087. var ret = [];
  13088. var distance$$1 = 0;
  13089. for (var i = 1; i < len$$1; i++) {
  13090. distance$$1 += distance(points[i - 1], points[i]);
  13091. }
  13092. var segs = distance$$1 / 2;
  13093. segs = segs < len$$1 ? len$$1 : segs;
  13094. for (var i = 0; i < segs; i++) {
  13095. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13096. var idx = Math.floor(pos);
  13097. var w = pos - idx;
  13098. var p0;
  13099. var p1 = points[idx % len$$1];
  13100. var p2;
  13101. var p3;
  13102. if (!isLoop) {
  13103. p0 = points[idx === 0 ? idx : idx - 1];
  13104. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13105. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13106. }
  13107. else {
  13108. p0 = points[(idx - 1 + len$$1) % len$$1];
  13109. p2 = points[(idx + 1) % len$$1];
  13110. p3 = points[(idx + 2) % len$$1];
  13111. }
  13112. var w2 = w * w;
  13113. var w3 = w * w2;
  13114. ret.push([
  13115. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13116. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13117. ]);
  13118. }
  13119. return ret;
  13120. };
  13121. /**
  13122. * 贝塞尔平滑曲线
  13123. * @module zrender/shape/util/smoothBezier
  13124. * @author pissang (https://www.github.com/pissang)
  13125. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13126. * errorrik (errorrik@gmail.com)
  13127. */
  13128. /**
  13129. * 贝塞尔平滑曲线
  13130. * @alias module:zrender/shape/util/smoothBezier
  13131. * @param {Array} points 线段顶点数组
  13132. * @param {number} smooth 平滑等级, 0-1
  13133. * @param {boolean} isLoop
  13134. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13135. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13136. * 整个折线的包围盒做一个并集用来约束控制点。
  13137. * @param {Array} 计算出来的控制点数组
  13138. */
  13139. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13140. var cps = [];
  13141. var v = [];
  13142. var v1 = [];
  13143. var v2 = [];
  13144. var prevPoint;
  13145. var nextPoint;
  13146. var min$$1, max$$1;
  13147. if (constraint) {
  13148. min$$1 = [Infinity, Infinity];
  13149. max$$1 = [-Infinity, -Infinity];
  13150. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13151. min(min$$1, min$$1, points[i]);
  13152. max(max$$1, max$$1, points[i]);
  13153. }
  13154. // 与指定的包围盒做并集
  13155. min(min$$1, min$$1, constraint[0]);
  13156. max(max$$1, max$$1, constraint[1]);
  13157. }
  13158. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13159. var point = points[i];
  13160. if (isLoop) {
  13161. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13162. nextPoint = points[(i + 1) % len$$1];
  13163. }
  13164. else {
  13165. if (i === 0 || i === len$$1 - 1) {
  13166. cps.push(clone$1(points[i]));
  13167. continue;
  13168. }
  13169. else {
  13170. prevPoint = points[i - 1];
  13171. nextPoint = points[i + 1];
  13172. }
  13173. }
  13174. sub(v, nextPoint, prevPoint);
  13175. // use degree to scale the handle length
  13176. scale(v, v, smooth);
  13177. var d0 = distance(point, prevPoint);
  13178. var d1 = distance(point, nextPoint);
  13179. var sum = d0 + d1;
  13180. if (sum !== 0) {
  13181. d0 /= sum;
  13182. d1 /= sum;
  13183. }
  13184. scale(v1, v, -d0);
  13185. scale(v2, v, d1);
  13186. var cp0 = add([], point, v1);
  13187. var cp1 = add([], point, v2);
  13188. if (constraint) {
  13189. max(cp0, cp0, min$$1);
  13190. min(cp0, cp0, max$$1);
  13191. max(cp1, cp1, min$$1);
  13192. min(cp1, cp1, max$$1);
  13193. }
  13194. cps.push(cp0);
  13195. cps.push(cp1);
  13196. }
  13197. if (isLoop) {
  13198. cps.push(cps.shift());
  13199. }
  13200. return cps;
  13201. };
  13202. function buildPath$1(ctx, shape, closePath) {
  13203. var points = shape.points;
  13204. var smooth = shape.smooth;
  13205. if (points && points.length >= 2) {
  13206. if (smooth && smooth !== 'spline') {
  13207. var controlPoints = smoothBezier(
  13208. points, smooth, closePath, shape.smoothConstraint
  13209. );
  13210. ctx.moveTo(points[0][0], points[0][1]);
  13211. var len = points.length;
  13212. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13213. var cp1 = controlPoints[i * 2];
  13214. var cp2 = controlPoints[i * 2 + 1];
  13215. var p = points[(i + 1) % len];
  13216. ctx.bezierCurveTo(
  13217. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13218. );
  13219. }
  13220. }
  13221. else {
  13222. if (smooth === 'spline') {
  13223. points = smoothSpline(points, closePath);
  13224. }
  13225. ctx.moveTo(points[0][0], points[0][1]);
  13226. for (var i = 1, l = points.length; i < l; i++) {
  13227. ctx.lineTo(points[i][0], points[i][1]);
  13228. }
  13229. }
  13230. closePath && ctx.closePath();
  13231. }
  13232. }
  13233. /**
  13234. * 多边形
  13235. * @module zrender/shape/Polygon
  13236. */
  13237. var Polygon = Path.extend({
  13238. type: 'polygon',
  13239. shape: {
  13240. points: null,
  13241. smooth: false,
  13242. smoothConstraint: null
  13243. },
  13244. buildPath: function (ctx, shape) {
  13245. buildPath$1(ctx, shape, true);
  13246. }
  13247. });
  13248. /**
  13249. * @module zrender/graphic/shape/Polyline
  13250. */
  13251. var Polyline = Path.extend({
  13252. type: 'polyline',
  13253. shape: {
  13254. points: null,
  13255. smooth: false,
  13256. smoothConstraint: null
  13257. },
  13258. style: {
  13259. stroke: '#000',
  13260. fill: null
  13261. },
  13262. buildPath: function (ctx, shape) {
  13263. buildPath$1(ctx, shape, false);
  13264. }
  13265. });
  13266. /**
  13267. * 矩形
  13268. * @module zrender/graphic/shape/Rect
  13269. */
  13270. var Rect = Path.extend({
  13271. type: 'rect',
  13272. shape: {
  13273. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13274. // r缩写为1 相当于 [1, 1, 1, 1]
  13275. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13276. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13277. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13278. r: 0,
  13279. x: 0,
  13280. y: 0,
  13281. width: 0,
  13282. height: 0
  13283. },
  13284. buildPath: function (ctx, shape) {
  13285. var x = shape.x;
  13286. var y = shape.y;
  13287. var width = shape.width;
  13288. var height = shape.height;
  13289. if (!shape.r) {
  13290. ctx.rect(x, y, width, height);
  13291. }
  13292. else {
  13293. buildPath(ctx, shape);
  13294. }
  13295. ctx.closePath();
  13296. return;
  13297. }
  13298. });
  13299. /**
  13300. * 直线
  13301. * @module zrender/graphic/shape/Line
  13302. */
  13303. var Line = Path.extend({
  13304. type: 'line',
  13305. shape: {
  13306. // Start point
  13307. x1: 0,
  13308. y1: 0,
  13309. // End point
  13310. x2: 0,
  13311. y2: 0,
  13312. percent: 1
  13313. },
  13314. style: {
  13315. stroke: '#000',
  13316. fill: null
  13317. },
  13318. buildPath: function (ctx, shape) {
  13319. var x1 = shape.x1;
  13320. var y1 = shape.y1;
  13321. var x2 = shape.x2;
  13322. var y2 = shape.y2;
  13323. var percent = shape.percent;
  13324. if (percent === 0) {
  13325. return;
  13326. }
  13327. ctx.moveTo(x1, y1);
  13328. if (percent < 1) {
  13329. x2 = x1 * (1 - percent) + x2 * percent;
  13330. y2 = y1 * (1 - percent) + y2 * percent;
  13331. }
  13332. ctx.lineTo(x2, y2);
  13333. },
  13334. /**
  13335. * Get point at percent
  13336. * @param {number} percent
  13337. * @return {Array.<number>}
  13338. */
  13339. pointAt: function (p) {
  13340. var shape = this.shape;
  13341. return [
  13342. shape.x1 * (1 - p) + shape.x2 * p,
  13343. shape.y1 * (1 - p) + shape.y2 * p
  13344. ];
  13345. }
  13346. });
  13347. /**
  13348. * 贝塞尔曲线
  13349. * @module zrender/shape/BezierCurve
  13350. */
  13351. var out = [];
  13352. function someVectorAt(shape, t, isTangent) {
  13353. var cpx2 = shape.cpx2;
  13354. var cpy2 = shape.cpy2;
  13355. if (cpx2 === null || cpy2 === null) {
  13356. return [
  13357. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13358. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13359. ];
  13360. }
  13361. else {
  13362. return [
  13363. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13364. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13365. ];
  13366. }
  13367. }
  13368. var BezierCurve = Path.extend({
  13369. type: 'bezier-curve',
  13370. shape: {
  13371. x1: 0,
  13372. y1: 0,
  13373. x2: 0,
  13374. y2: 0,
  13375. cpx1: 0,
  13376. cpy1: 0,
  13377. // cpx2: 0,
  13378. // cpy2: 0
  13379. // Curve show percent, for animating
  13380. percent: 1
  13381. },
  13382. style: {
  13383. stroke: '#000',
  13384. fill: null
  13385. },
  13386. buildPath: function (ctx, shape) {
  13387. var x1 = shape.x1;
  13388. var y1 = shape.y1;
  13389. var x2 = shape.x2;
  13390. var y2 = shape.y2;
  13391. var cpx1 = shape.cpx1;
  13392. var cpy1 = shape.cpy1;
  13393. var cpx2 = shape.cpx2;
  13394. var cpy2 = shape.cpy2;
  13395. var percent = shape.percent;
  13396. if (percent === 0) {
  13397. return;
  13398. }
  13399. ctx.moveTo(x1, y1);
  13400. if (cpx2 == null || cpy2 == null) {
  13401. if (percent < 1) {
  13402. quadraticSubdivide(
  13403. x1, cpx1, x2, percent, out
  13404. );
  13405. cpx1 = out[1];
  13406. x2 = out[2];
  13407. quadraticSubdivide(
  13408. y1, cpy1, y2, percent, out
  13409. );
  13410. cpy1 = out[1];
  13411. y2 = out[2];
  13412. }
  13413. ctx.quadraticCurveTo(
  13414. cpx1, cpy1,
  13415. x2, y2
  13416. );
  13417. }
  13418. else {
  13419. if (percent < 1) {
  13420. cubicSubdivide(
  13421. x1, cpx1, cpx2, x2, percent, out
  13422. );
  13423. cpx1 = out[1];
  13424. cpx2 = out[2];
  13425. x2 = out[3];
  13426. cubicSubdivide(
  13427. y1, cpy1, cpy2, y2, percent, out
  13428. );
  13429. cpy1 = out[1];
  13430. cpy2 = out[2];
  13431. y2 = out[3];
  13432. }
  13433. ctx.bezierCurveTo(
  13434. cpx1, cpy1,
  13435. cpx2, cpy2,
  13436. x2, y2
  13437. );
  13438. }
  13439. },
  13440. /**
  13441. * Get point at percent
  13442. * @param {number} t
  13443. * @return {Array.<number>}
  13444. */
  13445. pointAt: function (t) {
  13446. return someVectorAt(this.shape, t, false);
  13447. },
  13448. /**
  13449. * Get tangent at percent
  13450. * @param {number} t
  13451. * @return {Array.<number>}
  13452. */
  13453. tangentAt: function (t) {
  13454. var p = someVectorAt(this.shape, t, true);
  13455. return normalize(p, p);
  13456. }
  13457. });
  13458. /**
  13459. * 圆弧
  13460. * @module zrender/graphic/shape/Arc
  13461. */
  13462. var Arc = Path.extend({
  13463. type: 'arc',
  13464. shape: {
  13465. cx: 0,
  13466. cy: 0,
  13467. r: 0,
  13468. startAngle: 0,
  13469. endAngle: Math.PI * 2,
  13470. clockwise: true
  13471. },
  13472. style: {
  13473. stroke: '#000',
  13474. fill: null
  13475. },
  13476. buildPath: function (ctx, shape) {
  13477. var x = shape.cx;
  13478. var y = shape.cy;
  13479. var r = Math.max(shape.r, 0);
  13480. var startAngle = shape.startAngle;
  13481. var endAngle = shape.endAngle;
  13482. var clockwise = shape.clockwise;
  13483. var unitX = Math.cos(startAngle);
  13484. var unitY = Math.sin(startAngle);
  13485. ctx.moveTo(unitX * r + x, unitY * r + y);
  13486. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13487. }
  13488. });
  13489. // CompoundPath to improve performance
  13490. var CompoundPath = Path.extend({
  13491. type: 'compound',
  13492. shape: {
  13493. paths: null
  13494. },
  13495. _updatePathDirty: function () {
  13496. var dirtyPath = this.__dirtyPath;
  13497. var paths = this.shape.paths;
  13498. for (var i = 0; i < paths.length; i++) {
  13499. // Mark as dirty if any subpath is dirty
  13500. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13501. }
  13502. this.__dirtyPath = dirtyPath;
  13503. this.__dirty = this.__dirty || dirtyPath;
  13504. },
  13505. beforeBrush: function () {
  13506. this._updatePathDirty();
  13507. var paths = this.shape.paths || [];
  13508. var scale = this.getGlobalScale();
  13509. // Update path scale
  13510. for (var i = 0; i < paths.length; i++) {
  13511. if (!paths[i].path) {
  13512. paths[i].createPathProxy();
  13513. }
  13514. paths[i].path.setScale(scale[0], scale[1]);
  13515. }
  13516. },
  13517. buildPath: function (ctx, shape) {
  13518. var paths = shape.paths || [];
  13519. for (var i = 0; i < paths.length; i++) {
  13520. paths[i].buildPath(ctx, paths[i].shape, true);
  13521. }
  13522. },
  13523. afterBrush: function () {
  13524. var paths = this.shape.paths || [];
  13525. for (var i = 0; i < paths.length; i++) {
  13526. paths[i].__dirtyPath = false;
  13527. }
  13528. },
  13529. getBoundingRect: function () {
  13530. this._updatePathDirty();
  13531. return Path.prototype.getBoundingRect.call(this);
  13532. }
  13533. });
  13534. /**
  13535. * @param {Array.<Object>} colorStops
  13536. */
  13537. var Gradient = function (colorStops) {
  13538. this.colorStops = colorStops || [];
  13539. };
  13540. Gradient.prototype = {
  13541. constructor: Gradient,
  13542. addColorStop: function (offset, color) {
  13543. this.colorStops.push({
  13544. offset: offset,
  13545. color: color
  13546. });
  13547. }
  13548. };
  13549. /**
  13550. * x, y, x2, y2 are all percent from 0 to 1
  13551. * @param {number} [x=0]
  13552. * @param {number} [y=0]
  13553. * @param {number} [x2=1]
  13554. * @param {number} [y2=0]
  13555. * @param {Array.<Object>} colorStops
  13556. * @param {boolean} [globalCoord=false]
  13557. */
  13558. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13559. // Should do nothing more in this constructor. Because gradient can be
  13560. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13561. // this constructor will not be called.
  13562. this.x = x == null ? 0 : x;
  13563. this.y = y == null ? 0 : y;
  13564. this.x2 = x2 == null ? 1 : x2;
  13565. this.y2 = y2 == null ? 0 : y2;
  13566. // Can be cloned
  13567. this.type = 'linear';
  13568. // If use global coord
  13569. this.global = globalCoord || false;
  13570. Gradient.call(this, colorStops);
  13571. };
  13572. LinearGradient.prototype = {
  13573. constructor: LinearGradient
  13574. };
  13575. inherits(LinearGradient, Gradient);
  13576. /**
  13577. * x, y, r are all percent from 0 to 1
  13578. * @param {number} [x=0.5]
  13579. * @param {number} [y=0.5]
  13580. * @param {number} [r=0.5]
  13581. * @param {Array.<Object>} [colorStops]
  13582. * @param {boolean} [globalCoord=false]
  13583. */
  13584. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13585. // Should do nothing more in this constructor. Because gradient can be
  13586. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13587. // this constructor will not be called.
  13588. this.x = x == null ? 0.5 : x;
  13589. this.y = y == null ? 0.5 : y;
  13590. this.r = r == null ? 0.5 : r;
  13591. // Can be cloned
  13592. this.type = 'radial';
  13593. // If use global coord
  13594. this.global = globalCoord || false;
  13595. Gradient.call(this, colorStops);
  13596. };
  13597. RadialGradient.prototype = {
  13598. constructor: RadialGradient
  13599. };
  13600. inherits(RadialGradient, Gradient);
  13601. /**
  13602. * Displayable for incremental rendering. It will be rendered in a separate layer
  13603. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13604. * addDisplayables will render the added displayables incremetally.
  13605. *
  13606. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13607. */
  13608. // TODO Style override ?
  13609. function IncrementalDisplayble(opts) {
  13610. Displayable.call(this, opts);
  13611. this._displayables = [];
  13612. this._temporaryDisplayables = [];
  13613. this._cursor = 0;
  13614. this.notClear = true;
  13615. }
  13616. IncrementalDisplayble.prototype.incremental = true;
  13617. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13618. this._displayables = [];
  13619. this._temporaryDisplayables = [];
  13620. this._cursor = 0;
  13621. this.dirty();
  13622. this.notClear = false;
  13623. };
  13624. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13625. if (notPersistent) {
  13626. this._temporaryDisplayables.push(displayable);
  13627. }
  13628. else {
  13629. this._displayables.push(displayable);
  13630. }
  13631. this.dirty();
  13632. };
  13633. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13634. notPersistent = notPersistent || false;
  13635. for (var i = 0; i < displayables.length; i++) {
  13636. this.addDisplayable(displayables[i], notPersistent);
  13637. }
  13638. };
  13639. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13640. for (var i = this._cursor; i < this._displayables.length; i++) {
  13641. cb && cb(this._displayables[i]);
  13642. }
  13643. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13644. cb && cb(this._temporaryDisplayables[i]);
  13645. }
  13646. };
  13647. IncrementalDisplayble.prototype.update = function () {
  13648. this.updateTransform();
  13649. for (var i = this._cursor; i < this._displayables.length; i++) {
  13650. var displayable = this._displayables[i];
  13651. // PENDING
  13652. displayable.parent = this;
  13653. displayable.update();
  13654. displayable.parent = null;
  13655. }
  13656. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13657. var displayable = this._temporaryDisplayables[i];
  13658. // PENDING
  13659. displayable.parent = this;
  13660. displayable.update();
  13661. displayable.parent = null;
  13662. }
  13663. };
  13664. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13665. // Render persistant displayables.
  13666. for (var i = this._cursor; i < this._displayables.length; i++) {
  13667. var displayable = this._temporaryDisplayables[i];
  13668. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13669. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13670. displayable.afterBrush && displayable.afterBrush(ctx);
  13671. }
  13672. this._cursor = i;
  13673. // Render temporary displayables.
  13674. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13675. var displayable = this._temporaryDisplayables[i];
  13676. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13677. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13678. displayable.afterBrush && displayable.afterBrush(ctx);
  13679. }
  13680. this._temporaryDisplayables = [];
  13681. this.notClear = true;
  13682. };
  13683. var m = [];
  13684. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13685. if (!this._rect) {
  13686. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13687. for (var i = 0; i < this._displayables.length; i++) {
  13688. var displayable = this._displayables[i];
  13689. var childRect = displayable.getBoundingRect().clone();
  13690. if (displayable.needLocalTransform()) {
  13691. childRect.applyTransform(displayable.getLocalTransform(m));
  13692. }
  13693. rect.union(childRect);
  13694. }
  13695. this._rect = rect;
  13696. }
  13697. return this._rect;
  13698. };
  13699. IncrementalDisplayble.prototype.contain = function (x, y) {
  13700. var localPos = this.transformCoordToLocal(x, y);
  13701. var rect = this.getBoundingRect();
  13702. if (rect.contain(localPos[0], localPos[1])) {
  13703. for (var i = 0; i < this._displayables.length; i++) {
  13704. var displayable = this._displayables[i];
  13705. if (displayable.contain(x, y)) {
  13706. return true;
  13707. }
  13708. }
  13709. }
  13710. return false;
  13711. };
  13712. inherits(IncrementalDisplayble, Displayable);
  13713. var round = Math.round;
  13714. var mathMax$1 = Math.max;
  13715. var mathMin$1 = Math.min;
  13716. var EMPTY_OBJ = {};
  13717. /**
  13718. * Extend shape with parameters
  13719. */
  13720. function extendShape(opts) {
  13721. return Path.extend(opts);
  13722. }
  13723. /**
  13724. * Extend path
  13725. */
  13726. function extendPath(pathData, opts) {
  13727. return extendFromString(pathData, opts);
  13728. }
  13729. /**
  13730. * Create a path element from path data string
  13731. * @param {string} pathData
  13732. * @param {Object} opts
  13733. * @param {module:zrender/core/BoundingRect} rect
  13734. * @param {string} [layout=cover] 'center' or 'cover'
  13735. */
  13736. function makePath(pathData, opts, rect, layout) {
  13737. var path = createFromString(pathData, opts);
  13738. var boundingRect = path.getBoundingRect();
  13739. if (rect) {
  13740. if (layout === 'center') {
  13741. rect = centerGraphic(rect, boundingRect);
  13742. }
  13743. resizePath(path, rect);
  13744. }
  13745. return path;
  13746. }
  13747. /**
  13748. * Create a image element from image url
  13749. * @param {string} imageUrl image url
  13750. * @param {Object} opts options
  13751. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13752. * @param {string} [layout=cover] 'center' or 'cover'
  13753. */
  13754. function makeImage(imageUrl, rect, layout) {
  13755. var path = new ZImage({
  13756. style: {
  13757. image: imageUrl,
  13758. x: rect.x,
  13759. y: rect.y,
  13760. width: rect.width,
  13761. height: rect.height
  13762. },
  13763. onload: function (img) {
  13764. if (layout === 'center') {
  13765. var boundingRect = {
  13766. width: img.width,
  13767. height: img.height
  13768. };
  13769. path.setStyle(centerGraphic(rect, boundingRect));
  13770. }
  13771. }
  13772. });
  13773. return path;
  13774. }
  13775. /**
  13776. * Get position of centered element in bounding box.
  13777. *
  13778. * @param {Object} rect element local bounding box
  13779. * @param {Object} boundingRect constraint bounding box
  13780. * @return {Object} element position containing x, y, width, and height
  13781. */
  13782. function centerGraphic(rect, boundingRect) {
  13783. // Set rect to center, keep width / height ratio.
  13784. var aspect = boundingRect.width / boundingRect.height;
  13785. var width = rect.height * aspect;
  13786. var height;
  13787. if (width <= rect.width) {
  13788. height = rect.height;
  13789. }
  13790. else {
  13791. width = rect.width;
  13792. height = width / aspect;
  13793. }
  13794. var cx = rect.x + rect.width / 2;
  13795. var cy = rect.y + rect.height / 2;
  13796. return {
  13797. x: cx - width / 2,
  13798. y: cy - height / 2,
  13799. width: width,
  13800. height: height
  13801. };
  13802. }
  13803. var mergePath = mergePath$1;
  13804. /**
  13805. * Resize a path to fit the rect
  13806. * @param {module:zrender/graphic/Path} path
  13807. * @param {Object} rect
  13808. */
  13809. function resizePath(path, rect) {
  13810. if (!path.applyTransform) {
  13811. return;
  13812. }
  13813. var pathRect = path.getBoundingRect();
  13814. var m = pathRect.calculateTransform(rect);
  13815. path.applyTransform(m);
  13816. }
  13817. /**
  13818. * Sub pixel optimize line for canvas
  13819. *
  13820. * @param {Object} param
  13821. * @param {Object} [param.shape]
  13822. * @param {number} [param.shape.x1]
  13823. * @param {number} [param.shape.y1]
  13824. * @param {number} [param.shape.x2]
  13825. * @param {number} [param.shape.y2]
  13826. * @param {Object} [param.style]
  13827. * @param {number} [param.style.lineWidth]
  13828. * @return {Object} Modified param
  13829. */
  13830. function subPixelOptimizeLine(param) {
  13831. var shape = param.shape;
  13832. var lineWidth = param.style.lineWidth;
  13833. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13834. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13835. }
  13836. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13837. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13838. }
  13839. return param;
  13840. }
  13841. /**
  13842. * Sub pixel optimize rect for canvas
  13843. *
  13844. * @param {Object} param
  13845. * @param {Object} [param.shape]
  13846. * @param {number} [param.shape.x]
  13847. * @param {number} [param.shape.y]
  13848. * @param {number} [param.shape.width]
  13849. * @param {number} [param.shape.height]
  13850. * @param {Object} [param.style]
  13851. * @param {number} [param.style.lineWidth]
  13852. * @return {Object} Modified param
  13853. */
  13854. function subPixelOptimizeRect(param) {
  13855. var shape = param.shape;
  13856. var lineWidth = param.style.lineWidth;
  13857. var originX = shape.x;
  13858. var originY = shape.y;
  13859. var originWidth = shape.width;
  13860. var originHeight = shape.height;
  13861. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13862. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13863. shape.width = Math.max(
  13864. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13865. originWidth === 0 ? 0 : 1
  13866. );
  13867. shape.height = Math.max(
  13868. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13869. originHeight === 0 ? 0 : 1
  13870. );
  13871. return param;
  13872. }
  13873. /**
  13874. * Sub pixel optimize for canvas
  13875. *
  13876. * @param {number} position Coordinate, such as x, y
  13877. * @param {number} lineWidth Should be nonnegative integer.
  13878. * @param {boolean=} positiveOrNegative Default false (negative).
  13879. * @return {number} Optimized position.
  13880. */
  13881. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13882. // Assure that (position + lineWidth / 2) is near integer edge,
  13883. // otherwise line will be fuzzy in canvas.
  13884. var doubledPosition = round(position * 2);
  13885. return (doubledPosition + round(lineWidth)) % 2 === 0
  13886. ? doubledPosition / 2
  13887. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13888. }
  13889. function hasFillOrStroke(fillOrStroke) {
  13890. return fillOrStroke != null && fillOrStroke != 'none';
  13891. }
  13892. function liftColor(color) {
  13893. return typeof color === 'string' ? lift(color, -0.1) : color;
  13894. }
  13895. /**
  13896. * @private
  13897. */
  13898. function cacheElementStl(el) {
  13899. if (el.__hoverStlDirty) {
  13900. var stroke = el.style.stroke;
  13901. var fill = el.style.fill;
  13902. // Create hoverStyle on mouseover
  13903. var hoverStyle = el.__hoverStl;
  13904. hoverStyle.fill = hoverStyle.fill
  13905. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13906. hoverStyle.stroke = hoverStyle.stroke
  13907. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13908. var normalStyle = {};
  13909. for (var name in hoverStyle) {
  13910. // See comment in `doSingleEnterHover`.
  13911. if (hoverStyle[name] != null) {
  13912. normalStyle[name] = el.style[name];
  13913. }
  13914. }
  13915. el.__normalStl = normalStyle;
  13916. el.__hoverStlDirty = false;
  13917. }
  13918. }
  13919. /**
  13920. * @private
  13921. */
  13922. function doSingleEnterHover(el) {
  13923. if (el.__isHover) {
  13924. return;
  13925. }
  13926. cacheElementStl(el);
  13927. if (el.useHoverLayer) {
  13928. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13929. }
  13930. else {
  13931. var style = el.style;
  13932. var insideRollbackOpt = style.insideRollbackOpt;
  13933. // Consider case: only `position: 'top'` is set on emphasis, then text
  13934. // color should be returned to `autoColor`, rather than remain '#fff'.
  13935. // So we should rollback then apply again after style merging.
  13936. insideRollbackOpt && rollbackInsideStyle(style);
  13937. // styles can be:
  13938. // {
  13939. // label: {
  13940. // show: false,
  13941. // position: 'outside',
  13942. // fontSize: 18
  13943. // },
  13944. // emphasis: {
  13945. // label: {
  13946. // show: true
  13947. // }
  13948. // }
  13949. // },
  13950. // where properties of `emphasis` may not appear in `normal`. We previously use
  13951. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13952. // But consider rich text and setOption in merge mode, it is impossible to cover
  13953. // all properties in merge. So we use merge mode when setting style here, where
  13954. // only properties that is not `null/undefined` can be set. The disadventage:
  13955. // null/undefined can not be used to remove style any more in `emphasis`.
  13956. style.extendFrom(el.__hoverStl);
  13957. // Do not save `insideRollback`.
  13958. if (insideRollbackOpt) {
  13959. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13960. // textFill may be rollbacked to null.
  13961. if (style.textFill == null) {
  13962. style.textFill = insideRollbackOpt.autoColor;
  13963. }
  13964. }
  13965. el.dirty(false);
  13966. el.z2 += 1;
  13967. }
  13968. el.__isHover = true;
  13969. }
  13970. /**
  13971. * @inner
  13972. */
  13973. function doSingleLeaveHover(el) {
  13974. if (!el.__isHover) {
  13975. return;
  13976. }
  13977. var normalStl = el.__normalStl;
  13978. if (el.useHoverLayer) {
  13979. el.__zr && el.__zr.removeHover(el);
  13980. }
  13981. else {
  13982. // Consider null/undefined value, should use
  13983. // `setStyle` but not `extendFrom(stl, true)`.
  13984. normalStl && el.setStyle(normalStl);
  13985. el.z2 -= 1;
  13986. }
  13987. el.__isHover = false;
  13988. }
  13989. /**
  13990. * @inner
  13991. */
  13992. function doEnterHover(el) {
  13993. el.type === 'group'
  13994. ? el.traverse(function (child) {
  13995. if (child.type !== 'group') {
  13996. doSingleEnterHover(child);
  13997. }
  13998. })
  13999. : doSingleEnterHover(el);
  14000. }
  14001. function doLeaveHover(el) {
  14002. el.type === 'group'
  14003. ? el.traverse(function (child) {
  14004. if (child.type !== 'group') {
  14005. doSingleLeaveHover(child);
  14006. }
  14007. })
  14008. : doSingleLeaveHover(el);
  14009. }
  14010. /**
  14011. * @inner
  14012. */
  14013. function setElementHoverStl(el, hoverStl) {
  14014. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14015. // Often used when item group has a label element and it's hoverStyle is different
  14016. el.__hoverStl = el.hoverStyle || hoverStl || {};
  14017. el.__hoverStlDirty = true;
  14018. if (el.__isHover) {
  14019. cacheElementStl(el);
  14020. }
  14021. }
  14022. /**
  14023. * @inner
  14024. */
  14025. function onElementMouseOver(e) {
  14026. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14027. return;
  14028. }
  14029. // Only if element is not in emphasis status
  14030. !this.__isEmphasis && doEnterHover(this);
  14031. }
  14032. /**
  14033. * @inner
  14034. */
  14035. function onElementMouseOut(e) {
  14036. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14037. return;
  14038. }
  14039. // Only if element is not in emphasis status
  14040. !this.__isEmphasis && doLeaveHover(this);
  14041. }
  14042. /**
  14043. * @inner
  14044. */
  14045. function enterEmphasis() {
  14046. this.__isEmphasis = true;
  14047. doEnterHover(this);
  14048. }
  14049. /**
  14050. * @inner
  14051. */
  14052. function leaveEmphasis() {
  14053. this.__isEmphasis = false;
  14054. doLeaveHover(this);
  14055. }
  14056. /**
  14057. * Set hover style of element.
  14058. * This method can be called repeatly without side-effects.
  14059. * @param {module:zrender/Element} el
  14060. * @param {Object} [hoverStyle]
  14061. * @param {Object} [opt]
  14062. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14063. * In touch device, mouseover event will be trigger on touchstart event
  14064. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14065. * conviniently use hoverStyle when tap on touch screen without additional
  14066. * code for compatibility.
  14067. * But if the chart/component has select feature, which usually also use
  14068. * hoverStyle, there might be conflict between 'select-highlight' and
  14069. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14070. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14071. * on touch device.
  14072. */
  14073. function setHoverStyle(el, hoverStyle, opt) {
  14074. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14075. el.type === 'group'
  14076. ? el.traverse(function (child) {
  14077. if (child.type !== 'group') {
  14078. setElementHoverStl(child, hoverStyle);
  14079. }
  14080. })
  14081. : setElementHoverStl(el, hoverStyle);
  14082. // Duplicated function will be auto-ignored, see Eventful.js.
  14083. el.on('mouseover', onElementMouseOver)
  14084. .on('mouseout', onElementMouseOut);
  14085. // Emphasis, normal can be triggered manually
  14086. el.on('emphasis', enterEmphasis)
  14087. .on('normal', leaveEmphasis);
  14088. }
  14089. /**
  14090. * @param {Object|module:zrender/graphic/Style} normalStyle
  14091. * @param {Object} emphasisStyle
  14092. * @param {module:echarts/model/Model} normalModel
  14093. * @param {module:echarts/model/Model} emphasisModel
  14094. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14095. * @param {string|Function} [opt.defaultText]
  14096. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14097. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14098. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14099. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14100. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14101. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14102. * @param {Object} [normalSpecified]
  14103. * @param {Object} [emphasisSpecified]
  14104. */
  14105. function setLabelStyle(
  14106. normalStyle, emphasisStyle,
  14107. normalModel, emphasisModel,
  14108. opt,
  14109. normalSpecified, emphasisSpecified
  14110. ) {
  14111. opt = opt || EMPTY_OBJ;
  14112. var labelFetcher = opt.labelFetcher;
  14113. var labelDataIndex = opt.labelDataIndex;
  14114. var labelDimIndex = opt.labelDimIndex;
  14115. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14116. // is not supported util someone requests.
  14117. var showNormal = normalModel.getShallow('show');
  14118. var showEmphasis = emphasisModel.getShallow('show');
  14119. // Consider performance, only fetch label when necessary.
  14120. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14121. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14122. var baseText;
  14123. if (showNormal || showEmphasis) {
  14124. if (labelFetcher) {
  14125. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14126. }
  14127. if (baseText == null) {
  14128. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14129. }
  14130. }
  14131. var normalStyleText = showNormal ? baseText : null;
  14132. var emphasisStyleText = showEmphasis
  14133. ? retrieve2(
  14134. labelFetcher
  14135. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14136. : null,
  14137. baseText
  14138. )
  14139. : null;
  14140. // Optimize: If style.text is null, text will not be drawn.
  14141. if (normalStyleText != null || emphasisStyleText != null) {
  14142. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14143. // values have to be set on `normalStyle`.
  14144. // If we set default values on `emphasisStyle`, consider case:
  14145. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14146. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14147. // Then the 'red' will not work on emphasis.
  14148. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14149. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14150. }
  14151. normalStyle.text = normalStyleText;
  14152. emphasisStyle.text = emphasisStyleText;
  14153. }
  14154. /**
  14155. * Set basic textStyle properties.
  14156. * @param {Object|module:zrender/graphic/Style} textStyle
  14157. * @param {module:echarts/model/Model} model
  14158. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14159. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14160. * @param {boolean} [isEmphasis]
  14161. */
  14162. function setTextStyle(
  14163. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14164. ) {
  14165. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14166. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14167. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14168. return textStyle;
  14169. }
  14170. /**
  14171. * Set text option in the style.
  14172. * @deprecated
  14173. * @param {Object} textStyle
  14174. * @param {module:echarts/model/Model} labelModel
  14175. * @param {string|boolean} defaultColor Default text color.
  14176. * If set as false, it will be processed as a emphasis style.
  14177. */
  14178. function setText(textStyle, labelModel, defaultColor) {
  14179. var opt = {isRectText: true};
  14180. var isEmphasis;
  14181. if (defaultColor === false) {
  14182. isEmphasis = true;
  14183. }
  14184. else {
  14185. // Support setting color as 'auto' to get visual color.
  14186. opt.autoColor = defaultColor;
  14187. }
  14188. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14189. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14190. }
  14191. /**
  14192. * {
  14193. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14194. * isRectText: boolean,
  14195. * autoColor: string, specify a color when color is 'auto',
  14196. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14197. * If autoColor specified, it is used as default textFill.
  14198. * useInsideStyle:
  14199. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14200. * if `textFill` is not specified.
  14201. * `false`: Do not use inside style.
  14202. * `null/undefined`: use inside style if `isRectText` is true and
  14203. * `textFill` is not specified and textPosition contains `'inside'`.
  14204. * forceRich: boolean
  14205. * }
  14206. */
  14207. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14208. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14209. opt = opt || EMPTY_OBJ;
  14210. if (opt.isRectText) {
  14211. var textPosition = textStyleModel.getShallow('position')
  14212. || (isEmphasis ? null : 'inside');
  14213. // 'outside' is not a valid zr textPostion value, but used
  14214. // in bar series, and magric type should be considered.
  14215. textPosition === 'outside' && (textPosition = 'top');
  14216. textStyle.textPosition = textPosition;
  14217. textStyle.textOffset = textStyleModel.getShallow('offset');
  14218. var labelRotate = textStyleModel.getShallow('rotate');
  14219. labelRotate != null && (labelRotate *= Math.PI / 180);
  14220. textStyle.textRotation = labelRotate;
  14221. textStyle.textDistance = retrieve2(
  14222. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14223. );
  14224. }
  14225. var ecModel = textStyleModel.ecModel;
  14226. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14227. // Consider case:
  14228. // {
  14229. // data: [{
  14230. // value: 12,
  14231. // label: {
  14232. // rich: {
  14233. // // no 'a' here but using parent 'a'.
  14234. // }
  14235. // }
  14236. // }],
  14237. // rich: {
  14238. // a: { ... }
  14239. // }
  14240. // }
  14241. var richItemNames = getRichItemNames(textStyleModel);
  14242. var richResult;
  14243. if (richItemNames) {
  14244. richResult = {};
  14245. for (var name in richItemNames) {
  14246. if (richItemNames.hasOwnProperty(name)) {
  14247. // Cascade is supported in rich.
  14248. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14249. // In rich, never `disableBox`.
  14250. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14251. }
  14252. }
  14253. }
  14254. textStyle.rich = richResult;
  14255. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14256. if (opt.forceRich && !opt.textStyle) {
  14257. opt.textStyle = {};
  14258. }
  14259. return textStyle;
  14260. }
  14261. // Consider case:
  14262. // {
  14263. // data: [{
  14264. // value: 12,
  14265. // label: {
  14266. // rich: {
  14267. // // no 'a' here but using parent 'a'.
  14268. // }
  14269. // }
  14270. // }],
  14271. // rich: {
  14272. // a: { ... }
  14273. // }
  14274. // }
  14275. function getRichItemNames(textStyleModel) {
  14276. // Use object to remove duplicated names.
  14277. var richItemNameMap;
  14278. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14279. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14280. if (rich) {
  14281. richItemNameMap = richItemNameMap || {};
  14282. for (var name in rich) {
  14283. if (rich.hasOwnProperty(name)) {
  14284. richItemNameMap[name] = 1;
  14285. }
  14286. }
  14287. }
  14288. textStyleModel = textStyleModel.parentModel;
  14289. }
  14290. return richItemNameMap;
  14291. }
  14292. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14293. // In merge mode, default value should not be given.
  14294. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14295. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14296. || globalTextStyle.color;
  14297. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14298. || globalTextStyle.textBorderColor;
  14299. textStyle.textStrokeWidth = retrieve2(
  14300. textStyleModel.getShallow('textBorderWidth'),
  14301. globalTextStyle.textBorderWidth
  14302. );
  14303. if (!isEmphasis) {
  14304. if (isBlock) {
  14305. // Always set `insideRollback`, for clearing previous.
  14306. var originalTextPosition = textStyle.textPosition;
  14307. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14308. // Save original textPosition, because style.textPosition will be repalced by
  14309. // real location (like [10, 30]) in zrender.
  14310. textStyle.insideOriginalTextPosition = originalTextPosition;
  14311. textStyle.insideRollbackOpt = opt;
  14312. }
  14313. // Set default finally.
  14314. if (textStyle.textFill == null) {
  14315. textStyle.textFill = opt.autoColor;
  14316. }
  14317. }
  14318. // Do not use `getFont` here, because merge should be supported, where
  14319. // part of these properties may be changed in emphasis style, and the
  14320. // others should remain their original value got from normal style.
  14321. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14322. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14323. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14324. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14325. textStyle.textAlign = textStyleModel.getShallow('align');
  14326. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14327. || textStyleModel.getShallow('baseline');
  14328. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14329. textStyle.textWidth = textStyleModel.getShallow('width');
  14330. textStyle.textHeight = textStyleModel.getShallow('height');
  14331. textStyle.textTag = textStyleModel.getShallow('tag');
  14332. if (!isBlock || !opt.disableBox) {
  14333. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14334. textStyle.textPadding = textStyleModel.getShallow('padding');
  14335. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14336. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14337. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14338. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14339. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14340. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14341. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14342. }
  14343. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14344. || globalTextStyle.textShadowColor;
  14345. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14346. || globalTextStyle.textShadowBlur;
  14347. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14348. || globalTextStyle.textShadowOffsetX;
  14349. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14350. || globalTextStyle.textShadowOffsetY;
  14351. }
  14352. function getAutoColor(color, opt) {
  14353. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14354. }
  14355. function applyInsideStyle(textStyle, textPosition, opt) {
  14356. var useInsideStyle = opt.useInsideStyle;
  14357. var insideRollback;
  14358. if (textStyle.textFill == null
  14359. && useInsideStyle !== false
  14360. && (useInsideStyle === true
  14361. || (opt.isRectText
  14362. && textPosition
  14363. // textPosition can be [10, 30]
  14364. && typeof textPosition === 'string'
  14365. && textPosition.indexOf('inside') >= 0
  14366. )
  14367. )
  14368. ) {
  14369. insideRollback = {
  14370. textFill: null,
  14371. textStroke: textStyle.textStroke,
  14372. textStrokeWidth: textStyle.textStrokeWidth
  14373. };
  14374. textStyle.textFill = '#fff';
  14375. // Consider text with #fff overflow its container.
  14376. if (textStyle.textStroke == null) {
  14377. textStyle.textStroke = opt.autoColor;
  14378. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14379. }
  14380. }
  14381. return insideRollback;
  14382. }
  14383. function rollbackInsideStyle(style) {
  14384. var insideRollback = style.insideRollback;
  14385. if (insideRollback) {
  14386. style.textFill = insideRollback.textFill;
  14387. style.textStroke = insideRollback.textStroke;
  14388. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14389. }
  14390. }
  14391. function getFont(opt, ecModel) {
  14392. // ecModel or default text style model.
  14393. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14394. return trim([
  14395. // FIXME in node-canvas fontWeight is before fontStyle
  14396. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14397. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14398. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14399. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14400. ].join(' '));
  14401. }
  14402. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14403. if (typeof dataIndex === 'function') {
  14404. cb = dataIndex;
  14405. dataIndex = null;
  14406. }
  14407. // Do not check 'animation' property directly here. Consider this case:
  14408. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14409. // but its parent model (`seriesModel`) does.
  14410. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14411. if (animationEnabled) {
  14412. var postfix = isUpdate ? 'Update' : '';
  14413. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14414. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14415. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14416. if (typeof animationDelay === 'function') {
  14417. animationDelay = animationDelay(
  14418. dataIndex,
  14419. animatableModel.getAnimationDelayParams
  14420. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14421. : null
  14422. );
  14423. }
  14424. if (typeof duration === 'function') {
  14425. duration = duration(dataIndex);
  14426. }
  14427. duration > 0
  14428. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14429. : (el.stopAnimation(), el.attr(props), cb && cb());
  14430. }
  14431. else {
  14432. el.stopAnimation();
  14433. el.attr(props);
  14434. cb && cb();
  14435. }
  14436. }
  14437. /**
  14438. * Update graphic element properties with or without animation according to the
  14439. * configuration in series.
  14440. *
  14441. * Caution: this method will stop previous animation.
  14442. * So if do not use this method to one element twice before
  14443. * animation starts, unless you know what you are doing.
  14444. *
  14445. * @param {module:zrender/Element} el
  14446. * @param {Object} props
  14447. * @param {module:echarts/model/Model} [animatableModel]
  14448. * @param {number} [dataIndex]
  14449. * @param {Function} [cb]
  14450. * @example
  14451. * graphic.updateProps(el, {
  14452. * position: [100, 100]
  14453. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14454. * // Or
  14455. * graphic.updateProps(el, {
  14456. * position: [100, 100]
  14457. * }, seriesModel, function () { console.log('Animation done!'); });
  14458. */
  14459. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14460. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14461. }
  14462. /**
  14463. * Init graphic element properties with or without animation according to the
  14464. * configuration in series.
  14465. *
  14466. * Caution: this method will stop previous animation.
  14467. * So if do not use this method to one element twice before
  14468. * animation starts, unless you know what you are doing.
  14469. *
  14470. * @param {module:zrender/Element} el
  14471. * @param {Object} props
  14472. * @param {module:echarts/model/Model} [animatableModel]
  14473. * @param {number} [dataIndex]
  14474. * @param {Function} cb
  14475. */
  14476. function initProps(el, props, animatableModel, dataIndex, cb) {
  14477. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14478. }
  14479. /**
  14480. * Get transform matrix of target (param target),
  14481. * in coordinate of its ancestor (param ancestor)
  14482. *
  14483. * @param {module:zrender/mixin/Transformable} target
  14484. * @param {module:zrender/mixin/Transformable} [ancestor]
  14485. */
  14486. function getTransform(target, ancestor) {
  14487. var mat = identity([]);
  14488. while (target && target !== ancestor) {
  14489. mul$1(mat, target.getLocalTransform(), mat);
  14490. target = target.parent;
  14491. }
  14492. return mat;
  14493. }
  14494. /**
  14495. * Apply transform to an vertex.
  14496. * @param {Array.<number>} target [x, y]
  14497. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14498. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14499. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14500. * @param {boolean=} invert Whether use invert matrix.
  14501. * @return {Array.<number>} [x, y]
  14502. */
  14503. function applyTransform$1(target, transform, invert$$1) {
  14504. if (transform && !isArrayLike(transform)) {
  14505. transform = Transformable.getLocalTransform(transform);
  14506. }
  14507. if (invert$$1) {
  14508. transform = invert([], transform);
  14509. }
  14510. return applyTransform([], target, transform);
  14511. }
  14512. /**
  14513. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14514. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14515. * @param {boolean=} invert Whether use invert matrix.
  14516. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14517. */
  14518. function transformDirection(direction, transform, invert$$1) {
  14519. // Pick a base, ensure that transform result will not be (0, 0).
  14520. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14521. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14522. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14523. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14524. var vertex = [
  14525. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14526. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14527. ];
  14528. vertex = applyTransform$1(vertex, transform, invert$$1);
  14529. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14530. ? (vertex[0] > 0 ? 'right' : 'left')
  14531. : (vertex[1] > 0 ? 'bottom' : 'top');
  14532. }
  14533. /**
  14534. * Apply group transition animation from g1 to g2.
  14535. * If no animatableModel, no animation.
  14536. */
  14537. function groupTransition(g1, g2, animatableModel, cb) {
  14538. if (!g1 || !g2) {
  14539. return;
  14540. }
  14541. function getElMap(g) {
  14542. var elMap = {};
  14543. g.traverse(function (el) {
  14544. if (!el.isGroup && el.anid) {
  14545. elMap[el.anid] = el;
  14546. }
  14547. });
  14548. return elMap;
  14549. }
  14550. function getAnimatableProps(el) {
  14551. var obj = {
  14552. position: clone$1(el.position),
  14553. rotation: el.rotation
  14554. };
  14555. if (el.shape) {
  14556. obj.shape = extend({}, el.shape);
  14557. }
  14558. return obj;
  14559. }
  14560. var elMap1 = getElMap(g1);
  14561. g2.traverse(function (el) {
  14562. if (!el.isGroup && el.anid) {
  14563. var oldEl = elMap1[el.anid];
  14564. if (oldEl) {
  14565. var newProp = getAnimatableProps(el);
  14566. el.attr(getAnimatableProps(oldEl));
  14567. updateProps(el, newProp, animatableModel, el.dataIndex);
  14568. }
  14569. // else {
  14570. // if (el.previousProps) {
  14571. // graphic.updateProps
  14572. // }
  14573. // }
  14574. }
  14575. });
  14576. }
  14577. /**
  14578. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14579. * @param {Object} rect {x, y, width, height}
  14580. * @return {Array.<Array.<number>>} A new clipped points.
  14581. */
  14582. function clipPointsByRect(points, rect) {
  14583. return map(points, function (point) {
  14584. var x = point[0];
  14585. x = mathMax$1(x, rect.x);
  14586. x = mathMin$1(x, rect.x + rect.width);
  14587. var y = point[1];
  14588. y = mathMax$1(y, rect.y);
  14589. y = mathMin$1(y, rect.y + rect.height);
  14590. return [x, y];
  14591. });
  14592. }
  14593. /**
  14594. * @param {Object} targetRect {x, y, width, height}
  14595. * @param {Object} rect {x, y, width, height}
  14596. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14597. */
  14598. function clipRectByRect(targetRect, rect) {
  14599. var x = mathMax$1(targetRect.x, rect.x);
  14600. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14601. var y = mathMax$1(targetRect.y, rect.y);
  14602. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14603. if (x2 >= x && y2 >= y) {
  14604. return {
  14605. x: x,
  14606. y: y,
  14607. width: x2 - x,
  14608. height: y2 - y
  14609. };
  14610. }
  14611. }
  14612. /**
  14613. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14614. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14615. * @param {Object} [rect] {x, y, width, height}
  14616. * @return {module:zrender/Element} Icon path or image element.
  14617. */
  14618. function createIcon(iconStr, opt, rect) {
  14619. opt = extend({rectHover: true}, opt);
  14620. var style = opt.style = {strokeNoScale: true};
  14621. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14622. if (iconStr) {
  14623. return iconStr.indexOf('image://') === 0
  14624. ? (
  14625. style.image = iconStr.slice(8),
  14626. defaults(style, rect),
  14627. new ZImage(opt)
  14628. )
  14629. : (
  14630. makePath(
  14631. iconStr.replace('path://', ''),
  14632. opt,
  14633. rect,
  14634. 'center'
  14635. )
  14636. );
  14637. }
  14638. }
  14639. var graphic = (Object.freeze || Object)({
  14640. extendShape: extendShape,
  14641. extendPath: extendPath,
  14642. makePath: makePath,
  14643. makeImage: makeImage,
  14644. mergePath: mergePath,
  14645. resizePath: resizePath,
  14646. subPixelOptimizeLine: subPixelOptimizeLine,
  14647. subPixelOptimizeRect: subPixelOptimizeRect,
  14648. subPixelOptimize: subPixelOptimize,
  14649. setHoverStyle: setHoverStyle,
  14650. setLabelStyle: setLabelStyle,
  14651. setTextStyle: setTextStyle,
  14652. setText: setText,
  14653. getFont: getFont,
  14654. updateProps: updateProps,
  14655. initProps: initProps,
  14656. getTransform: getTransform,
  14657. applyTransform: applyTransform$1,
  14658. transformDirection: transformDirection,
  14659. groupTransition: groupTransition,
  14660. clipPointsByRect: clipPointsByRect,
  14661. clipRectByRect: clipRectByRect,
  14662. createIcon: createIcon,
  14663. Group: Group,
  14664. Image: ZImage,
  14665. Text: Text,
  14666. Circle: Circle,
  14667. Sector: Sector,
  14668. Ring: Ring,
  14669. Polygon: Polygon,
  14670. Polyline: Polyline,
  14671. Rect: Rect,
  14672. Line: Line,
  14673. BezierCurve: BezierCurve,
  14674. Arc: Arc,
  14675. IncrementalDisplayable: IncrementalDisplayble,
  14676. CompoundPath: CompoundPath,
  14677. LinearGradient: LinearGradient,
  14678. RadialGradient: RadialGradient,
  14679. BoundingRect: BoundingRect
  14680. });
  14681. var PATH_COLOR = ['textStyle', 'color'];
  14682. var textStyleMixin = {
  14683. /**
  14684. * Get color property or get color from option.textStyle.color
  14685. * @param {boolean} [isEmphasis]
  14686. * @return {string}
  14687. */
  14688. getTextColor: function (isEmphasis) {
  14689. var ecModel = this.ecModel;
  14690. return this.getShallow('color')
  14691. || (
  14692. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14693. );
  14694. },
  14695. /**
  14696. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14697. * @return {string}
  14698. */
  14699. getFont: function () {
  14700. return getFont({
  14701. fontStyle: this.getShallow('fontStyle'),
  14702. fontWeight: this.getShallow('fontWeight'),
  14703. fontSize: this.getShallow('fontSize'),
  14704. fontFamily: this.getShallow('fontFamily')
  14705. }, this.ecModel);
  14706. },
  14707. getTextRect: function (text) {
  14708. return getBoundingRect(
  14709. text,
  14710. this.getFont(),
  14711. this.getShallow('align'),
  14712. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14713. this.getShallow('padding'),
  14714. this.getShallow('rich'),
  14715. this.getShallow('truncateText')
  14716. );
  14717. }
  14718. };
  14719. var getItemStyle = makeStyleMapper(
  14720. [
  14721. ['fill', 'color'],
  14722. ['stroke', 'borderColor'],
  14723. ['lineWidth', 'borderWidth'],
  14724. ['opacity'],
  14725. ['shadowBlur'],
  14726. ['shadowOffsetX'],
  14727. ['shadowOffsetY'],
  14728. ['shadowColor'],
  14729. ['textPosition'],
  14730. ['textAlign']
  14731. ]
  14732. );
  14733. var itemStyleMixin = {
  14734. getItemStyle: function (excludes, includes) {
  14735. var style = getItemStyle(this, excludes, includes);
  14736. var lineDash = this.getBorderLineDash();
  14737. lineDash && (style.lineDash = lineDash);
  14738. return style;
  14739. },
  14740. getBorderLineDash: function () {
  14741. var lineType = this.get('borderType');
  14742. return (lineType === 'solid' || lineType == null) ? null
  14743. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14744. }
  14745. };
  14746. /**
  14747. * @module echarts/model/Model
  14748. */
  14749. var mixin$1 = mixin;
  14750. var inner = makeInner();
  14751. /**
  14752. * @alias module:echarts/model/Model
  14753. * @constructor
  14754. * @param {Object} option
  14755. * @param {module:echarts/model/Model} [parentModel]
  14756. * @param {module:echarts/model/Global} [ecModel]
  14757. */
  14758. function Model(option, parentModel, ecModel) {
  14759. /**
  14760. * @type {module:echarts/model/Model}
  14761. * @readOnly
  14762. */
  14763. this.parentModel = parentModel;
  14764. /**
  14765. * @type {module:echarts/model/Global}
  14766. * @readOnly
  14767. */
  14768. this.ecModel = ecModel;
  14769. /**
  14770. * @type {Object}
  14771. * @protected
  14772. */
  14773. this.option = option;
  14774. // Simple optimization
  14775. // if (this.init) {
  14776. // if (arguments.length <= 4) {
  14777. // this.init(option, parentModel, ecModel, extraOpt);
  14778. // }
  14779. // else {
  14780. // this.init.apply(this, arguments);
  14781. // }
  14782. // }
  14783. }
  14784. Model.prototype = {
  14785. constructor: Model,
  14786. /**
  14787. * Model 的初始化函数
  14788. * @param {Object} option
  14789. */
  14790. init: null,
  14791. /**
  14792. * 从新的 Option merge
  14793. */
  14794. mergeOption: function (option) {
  14795. merge(this.option, option, true);
  14796. },
  14797. /**
  14798. * @param {string|Array.<string>} path
  14799. * @param {boolean} [ignoreParent=false]
  14800. * @return {*}
  14801. */
  14802. get: function (path, ignoreParent) {
  14803. if (path == null) {
  14804. return this.option;
  14805. }
  14806. return doGet(
  14807. this.option,
  14808. this.parsePath(path),
  14809. !ignoreParent && getParent(this, path)
  14810. );
  14811. },
  14812. /**
  14813. * @param {string} key
  14814. * @param {boolean} [ignoreParent=false]
  14815. * @return {*}
  14816. */
  14817. getShallow: function (key, ignoreParent) {
  14818. var option = this.option;
  14819. var val = option == null ? option : option[key];
  14820. var parentModel = !ignoreParent && getParent(this, key);
  14821. if (val == null && parentModel) {
  14822. val = parentModel.getShallow(key);
  14823. }
  14824. return val;
  14825. },
  14826. /**
  14827. * @param {string|Array.<string>} [path]
  14828. * @param {module:echarts/model/Model} [parentModel]
  14829. * @return {module:echarts/model/Model}
  14830. */
  14831. getModel: function (path, parentModel) {
  14832. var obj = path == null
  14833. ? this.option
  14834. : doGet(this.option, path = this.parsePath(path));
  14835. var thisParentModel;
  14836. parentModel = parentModel || (
  14837. (thisParentModel = getParent(this, path))
  14838. && thisParentModel.getModel(path)
  14839. );
  14840. return new Model(obj, parentModel, this.ecModel);
  14841. },
  14842. /**
  14843. * If model has option
  14844. */
  14845. isEmpty: function () {
  14846. return this.option == null;
  14847. },
  14848. restoreData: function () {},
  14849. // Pending
  14850. clone: function () {
  14851. var Ctor = this.constructor;
  14852. return new Ctor(clone(this.option));
  14853. },
  14854. setReadOnly: function (properties) {
  14855. // clazzUtil.setReadOnly(this, properties);
  14856. },
  14857. // If path is null/undefined, return null/undefined.
  14858. parsePath: function(path) {
  14859. if (typeof path === 'string') {
  14860. path = path.split('.');
  14861. }
  14862. return path;
  14863. },
  14864. /**
  14865. * @param {Function} getParentMethod
  14866. * param {Array.<string>|string} path
  14867. * return {module:echarts/model/Model}
  14868. */
  14869. customizeGetParent: function (getParentMethod) {
  14870. inner(this).getParent = getParentMethod;
  14871. },
  14872. isAnimationEnabled: function () {
  14873. if (!env$1.node) {
  14874. if (this.option.animation != null) {
  14875. return !!this.option.animation;
  14876. }
  14877. else if (this.parentModel) {
  14878. return this.parentModel.isAnimationEnabled();
  14879. }
  14880. }
  14881. }
  14882. };
  14883. function doGet(obj, pathArr, parentModel) {
  14884. for (var i = 0; i < pathArr.length; i++) {
  14885. // Ignore empty
  14886. if (!pathArr[i]) {
  14887. continue;
  14888. }
  14889. // obj could be number/string/... (like 0)
  14890. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14891. if (obj == null) {
  14892. break;
  14893. }
  14894. }
  14895. if (obj == null && parentModel) {
  14896. obj = parentModel.get(pathArr);
  14897. }
  14898. return obj;
  14899. }
  14900. // `path` can be null/undefined
  14901. function getParent(model, path) {
  14902. var getParentMethod = inner(model).getParent;
  14903. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14904. }
  14905. // Enable Model.extend.
  14906. enableClassExtend(Model);
  14907. enableClassCheck(Model);
  14908. mixin$1(Model, lineStyleMixin);
  14909. mixin$1(Model, areaStyleMixin);
  14910. mixin$1(Model, textStyleMixin);
  14911. mixin$1(Model, itemStyleMixin);
  14912. var base = 0;
  14913. /**
  14914. * @public
  14915. * @param {string} type
  14916. * @return {string}
  14917. */
  14918. function getUID(type) {
  14919. // Considering the case of crossing js context,
  14920. // use Math.random to make id as unique as possible.
  14921. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14922. }
  14923. /**
  14924. * @inner
  14925. */
  14926. function enableSubTypeDefaulter(entity) {
  14927. var subTypeDefaulters = {};
  14928. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14929. componentType = parseClassType$1(componentType);
  14930. subTypeDefaulters[componentType.main] = defaulter;
  14931. };
  14932. entity.determineSubType = function (componentType, option) {
  14933. var type = option.type;
  14934. if (!type) {
  14935. var componentTypeMain = parseClassType$1(componentType).main;
  14936. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14937. type = subTypeDefaulters[componentTypeMain](option);
  14938. }
  14939. }
  14940. return type;
  14941. };
  14942. return entity;
  14943. }
  14944. /**
  14945. * Topological travel on Activity Network (Activity On Vertices).
  14946. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14947. *
  14948. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14949. *
  14950. * If there is circle dependencey, Error will be thrown.
  14951. *
  14952. */
  14953. function enableTopologicalTravel(entity, dependencyGetter) {
  14954. /**
  14955. * @public
  14956. * @param {Array.<string>} targetNameList Target Component type list.
  14957. * Can be ['aa', 'bb', 'aa.xx']
  14958. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14959. * @param {Function} callback Params: componentType, dependencies.
  14960. * @param {Object} context Scope of callback.
  14961. */
  14962. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14963. if (!targetNameList.length) {
  14964. return;
  14965. }
  14966. var result = makeDepndencyGraph(fullNameList);
  14967. var graph = result.graph;
  14968. var stack = result.noEntryList;
  14969. var targetNameSet = {};
  14970. each$1(targetNameList, function (name) {
  14971. targetNameSet[name] = true;
  14972. });
  14973. while (stack.length) {
  14974. var currComponentType = stack.pop();
  14975. var currVertex = graph[currComponentType];
  14976. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14977. if (isInTargetNameSet) {
  14978. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14979. delete targetNameSet[currComponentType];
  14980. }
  14981. each$1(
  14982. currVertex.successor,
  14983. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14984. );
  14985. }
  14986. each$1(targetNameSet, function () {
  14987. throw new Error('Circle dependency may exists');
  14988. });
  14989. function removeEdge(succComponentType) {
  14990. graph[succComponentType].entryCount--;
  14991. if (graph[succComponentType].entryCount === 0) {
  14992. stack.push(succComponentType);
  14993. }
  14994. }
  14995. // Consider this case: legend depends on series, and we call
  14996. // chart.setOption({series: [...]}), where only series is in option.
  14997. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14998. // not be called, but only sereis.mergeOption is called. Thus legend
  14999. // have no chance to update its local record about series (like which
  15000. // name of series is available in legend).
  15001. function removeEdgeAndAdd(succComponentType) {
  15002. targetNameSet[succComponentType] = true;
  15003. removeEdge(succComponentType);
  15004. }
  15005. };
  15006. /**
  15007. * DepndencyGraph: {Object}
  15008. * key: conponentType,
  15009. * value: {
  15010. * successor: [conponentTypes...],
  15011. * originalDeps: [conponentTypes...],
  15012. * entryCount: {number}
  15013. * }
  15014. */
  15015. function makeDepndencyGraph(fullNameList) {
  15016. var graph = {};
  15017. var noEntryList = [];
  15018. each$1(fullNameList, function (name) {
  15019. var thisItem = createDependencyGraphItem(graph, name);
  15020. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15021. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15022. thisItem.entryCount = availableDeps.length;
  15023. if (thisItem.entryCount === 0) {
  15024. noEntryList.push(name);
  15025. }
  15026. each$1(availableDeps, function (dependentName) {
  15027. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15028. thisItem.predecessor.push(dependentName);
  15029. }
  15030. var thatItem = createDependencyGraphItem(graph, dependentName);
  15031. if (indexOf(thatItem.successor, dependentName) < 0) {
  15032. thatItem.successor.push(name);
  15033. }
  15034. });
  15035. });
  15036. return {graph: graph, noEntryList: noEntryList};
  15037. }
  15038. function createDependencyGraphItem(graph, name) {
  15039. if (!graph[name]) {
  15040. graph[name] = {predecessor: [], successor: []};
  15041. }
  15042. return graph[name];
  15043. }
  15044. function getAvailableDependencies(originalDeps, fullNameList) {
  15045. var availableDeps = [];
  15046. each$1(originalDeps, function (dep) {
  15047. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15048. });
  15049. return availableDeps;
  15050. }
  15051. }
  15052. var RADIAN_EPSILON = 1e-4;
  15053. function _trim(str) {
  15054. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15055. }
  15056. /**
  15057. * Linear mapping a value from domain to range
  15058. * @memberOf module:echarts/util/number
  15059. * @param {(number|Array.<number>)} val
  15060. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15061. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15062. * @param {boolean} clamp
  15063. * @return {(number|Array.<number>}
  15064. */
  15065. function linearMap(val, domain, range, clamp) {
  15066. var subDomain = domain[1] - domain[0];
  15067. var subRange = range[1] - range[0];
  15068. if (subDomain === 0) {
  15069. return subRange === 0
  15070. ? range[0]
  15071. : (range[0] + range[1]) / 2;
  15072. }
  15073. // Avoid accuracy problem in edge, such as
  15074. // 146.39 - 62.83 === 83.55999999999999.
  15075. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15076. // It is a little verbose for efficiency considering this method
  15077. // is a hotspot.
  15078. if (clamp) {
  15079. if (subDomain > 0) {
  15080. if (val <= domain[0]) {
  15081. return range[0];
  15082. }
  15083. else if (val >= domain[1]) {
  15084. return range[1];
  15085. }
  15086. }
  15087. else {
  15088. if (val >= domain[0]) {
  15089. return range[0];
  15090. }
  15091. else if (val <= domain[1]) {
  15092. return range[1];
  15093. }
  15094. }
  15095. }
  15096. else {
  15097. if (val === domain[0]) {
  15098. return range[0];
  15099. }
  15100. if (val === domain[1]) {
  15101. return range[1];
  15102. }
  15103. }
  15104. return (val - domain[0]) / subDomain * subRange + range[0];
  15105. }
  15106. /**
  15107. * Convert a percent string to absolute number.
  15108. * Returns NaN if percent is not a valid string or number
  15109. * @memberOf module:echarts/util/number
  15110. * @param {string|number} percent
  15111. * @param {number} all
  15112. * @return {number}
  15113. */
  15114. function parsePercent$1(percent, all) {
  15115. switch (percent) {
  15116. case 'center':
  15117. case 'middle':
  15118. percent = '50%';
  15119. break;
  15120. case 'left':
  15121. case 'top':
  15122. percent = '0%';
  15123. break;
  15124. case 'right':
  15125. case 'bottom':
  15126. percent = '100%';
  15127. break;
  15128. }
  15129. if (typeof percent === 'string') {
  15130. if (_trim(percent).match(/%$/)) {
  15131. return parseFloat(percent) / 100 * all;
  15132. }
  15133. return parseFloat(percent);
  15134. }
  15135. return percent == null ? NaN : +percent;
  15136. }
  15137. /**
  15138. * (1) Fix rounding error of float numbers.
  15139. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15140. *
  15141. * @param {number} x
  15142. * @param {number} [precision]
  15143. * @param {boolean} [returnStr]
  15144. * @return {number|string}
  15145. */
  15146. function round$1(x, precision, returnStr) {
  15147. if (precision == null) {
  15148. precision = 10;
  15149. }
  15150. // Avoid range error
  15151. precision = Math.min(Math.max(0, precision), 20);
  15152. x = (+x).toFixed(precision);
  15153. return returnStr ? x : +x;
  15154. }
  15155. function asc(arr) {
  15156. arr.sort(function (a, b) {
  15157. return a - b;
  15158. });
  15159. return arr;
  15160. }
  15161. /**
  15162. * Get precision
  15163. * @param {number} val
  15164. */
  15165. function getPrecision(val) {
  15166. val = +val;
  15167. if (isNaN(val)) {
  15168. return 0;
  15169. }
  15170. // It is much faster than methods converting number to string as follows
  15171. // var tmp = val.toString();
  15172. // return tmp.length - 1 - tmp.indexOf('.');
  15173. // especially when precision is low
  15174. var e = 1;
  15175. var count = 0;
  15176. while (Math.round(val * e) / e !== val) {
  15177. e *= 10;
  15178. count++;
  15179. }
  15180. return count;
  15181. }
  15182. /**
  15183. * @param {string|number} val
  15184. * @return {number}
  15185. */
  15186. function getPrecisionSafe(val) {
  15187. var str = val.toString();
  15188. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15189. var eIndex = str.indexOf('e');
  15190. if (eIndex > 0) {
  15191. var precision = +str.slice(eIndex + 1);
  15192. return precision < 0 ? -precision : 0;
  15193. }
  15194. else {
  15195. var dotIndex = str.indexOf('.');
  15196. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15197. }
  15198. }
  15199. /**
  15200. * Minimal dicernible data precisioin according to a single pixel.
  15201. *
  15202. * @param {Array.<number>} dataExtent
  15203. * @param {Array.<number>} pixelExtent
  15204. * @return {number} precision
  15205. */
  15206. function getPixelPrecision(dataExtent, pixelExtent) {
  15207. var log = Math.log;
  15208. var LN10 = Math.LN10;
  15209. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15210. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15211. // toFixed() digits argument must be between 0 and 20.
  15212. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15213. return !isFinite(precision) ? 20 : precision;
  15214. }
  15215. /**
  15216. * Get a data of given precision, assuring the sum of percentages
  15217. * in valueList is 1.
  15218. * The largest remainer method is used.
  15219. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15220. *
  15221. * @param {Array.<number>} valueList a list of all data
  15222. * @param {number} idx index of the data to be processed in valueList
  15223. * @param {number} precision integer number showing digits of precision
  15224. * @return {number} percent ranging from 0 to 100
  15225. */
  15226. function getPercentWithPrecision(valueList, idx, precision) {
  15227. if (!valueList[idx]) {
  15228. return 0;
  15229. }
  15230. var sum = reduce(valueList, function (acc, val) {
  15231. return acc + (isNaN(val) ? 0 : val);
  15232. }, 0);
  15233. if (sum === 0) {
  15234. return 0;
  15235. }
  15236. var digits = Math.pow(10, precision);
  15237. var votesPerQuota = map(valueList, function (val) {
  15238. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15239. });
  15240. var targetSeats = digits * 100;
  15241. var seats = map(votesPerQuota, function (votes) {
  15242. // Assign automatic seats.
  15243. return Math.floor(votes);
  15244. });
  15245. var currentSum = reduce(seats, function (acc, val) {
  15246. return acc + val;
  15247. }, 0);
  15248. var remainder = map(votesPerQuota, function (votes, idx) {
  15249. return votes - seats[idx];
  15250. });
  15251. // Has remainding votes.
  15252. while (currentSum < targetSeats) {
  15253. // Find next largest remainder.
  15254. var max = Number.NEGATIVE_INFINITY;
  15255. var maxId = null;
  15256. for (var i = 0, len = remainder.length; i < len; ++i) {
  15257. if (remainder[i] > max) {
  15258. max = remainder[i];
  15259. maxId = i;
  15260. }
  15261. }
  15262. // Add a vote to max remainder.
  15263. ++seats[maxId];
  15264. remainder[maxId] = 0;
  15265. ++currentSum;
  15266. }
  15267. return seats[idx] / digits;
  15268. }
  15269. // Number.MAX_SAFE_INTEGER, ie do not support.
  15270. var MAX_SAFE_INTEGER = 9007199254740991;
  15271. /**
  15272. * To 0 - 2 * PI, considering negative radian.
  15273. * @param {number} radian
  15274. * @return {number}
  15275. */
  15276. function remRadian(radian) {
  15277. var pi2 = Math.PI * 2;
  15278. return (radian % pi2 + pi2) % pi2;
  15279. }
  15280. /**
  15281. * @param {type} radian
  15282. * @return {boolean}
  15283. */
  15284. function isRadianAroundZero(val) {
  15285. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15286. }
  15287. 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
  15288. /**
  15289. * @param {string|Date|number} value These values can be accepted:
  15290. * + An instance of Date, represent a time in its own time zone.
  15291. * + Or string in a subset of ISO 8601, only including:
  15292. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15293. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15294. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15295. * all of which will be treated as local time if time zone is not specified
  15296. * (see <https://momentjs.com/>).
  15297. * + Or other string format, including (all of which will be treated as loacal time):
  15298. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15299. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15300. * + a timestamp, which represent a time in UTC.
  15301. * @return {Date} date
  15302. */
  15303. function parseDate(value) {
  15304. if (value instanceof Date) {
  15305. return value;
  15306. }
  15307. else if (typeof value === 'string') {
  15308. // Different browsers parse date in different way, so we parse it manually.
  15309. // Some other issues:
  15310. // new Date('1970-01-01') is UTC,
  15311. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15312. // See issue #3623
  15313. var match = TIME_REG.exec(value);
  15314. if (!match) {
  15315. // return Invalid Date.
  15316. return new Date(NaN);
  15317. }
  15318. // Use local time when no timezone offset specifed.
  15319. if (!match[8]) {
  15320. // match[n] can only be string or undefined.
  15321. // But take care of '12' + 1 => '121'.
  15322. return new Date(
  15323. +match[1],
  15324. +(match[2] || 1) - 1,
  15325. +match[3] || 1,
  15326. +match[4] || 0,
  15327. +(match[5] || 0),
  15328. +match[6] || 0,
  15329. +match[7] || 0
  15330. );
  15331. }
  15332. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15333. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15334. // For example, system timezone is set as "Time Zone: America/Toronto",
  15335. // then these code will get different result:
  15336. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15337. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15338. // So we should not use `new Date`, but use `Date.UTC`.
  15339. else {
  15340. var hour = +match[4] || 0;
  15341. if (match[8].toUpperCase() !== 'Z') {
  15342. hour -= match[8].slice(0, 3);
  15343. }
  15344. return new Date(Date.UTC(
  15345. +match[1],
  15346. +(match[2] || 1) - 1,
  15347. +match[3] || 1,
  15348. hour,
  15349. +(match[5] || 0),
  15350. +match[6] || 0,
  15351. +match[7] || 0
  15352. ));
  15353. }
  15354. }
  15355. else if (value == null) {
  15356. return new Date(NaN);
  15357. }
  15358. return new Date(Math.round(value));
  15359. }
  15360. /**
  15361. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15362. *
  15363. * @param {number} val
  15364. * @return {number}
  15365. */
  15366. function quantity(val) {
  15367. return Math.pow(10, quantityExponent(val));
  15368. }
  15369. function quantityExponent(val) {
  15370. return Math.floor(Math.log(val) / Math.LN10);
  15371. }
  15372. /**
  15373. * find a “nice” number approximately equal to x. Round the number if round = true,
  15374. * take ceiling if round = false. The primary observation is that the “nicest”
  15375. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15376. *
  15377. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15378. *
  15379. * @param {number} val Non-negative value.
  15380. * @param {boolean} round
  15381. * @return {number}
  15382. */
  15383. function nice(val, round) {
  15384. var exponent = quantityExponent(val);
  15385. var exp10 = Math.pow(10, exponent);
  15386. var f = val / exp10; // 1 <= f < 10
  15387. var nf;
  15388. if (round) {
  15389. if (f < 1.5) { nf = 1; }
  15390. else if (f < 2.5) { nf = 2; }
  15391. else if (f < 4) { nf = 3; }
  15392. else if (f < 7) { nf = 5; }
  15393. else { nf = 10; }
  15394. }
  15395. else {
  15396. if (f < 1) { nf = 1; }
  15397. else if (f < 2) { nf = 2; }
  15398. else if (f < 3) { nf = 3; }
  15399. else if (f < 5) { nf = 5; }
  15400. else { nf = 10; }
  15401. }
  15402. val = nf * exp10;
  15403. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15404. // 20 is the uppper bound of toFixed.
  15405. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15406. }
  15407. /**
  15408. * Order intervals asc, and split them when overlap.
  15409. * expect(numberUtil.reformIntervals([
  15410. * {interval: [18, 62], close: [1, 1]},
  15411. * {interval: [-Infinity, -70], close: [0, 0]},
  15412. * {interval: [-70, -26], close: [1, 1]},
  15413. * {interval: [-26, 18], close: [1, 1]},
  15414. * {interval: [62, 150], close: [1, 1]},
  15415. * {interval: [106, 150], close: [1, 1]},
  15416. * {interval: [150, Infinity], close: [0, 0]}
  15417. * ])).toEqual([
  15418. * {interval: [-Infinity, -70], close: [0, 0]},
  15419. * {interval: [-70, -26], close: [1, 1]},
  15420. * {interval: [-26, 18], close: [0, 1]},
  15421. * {interval: [18, 62], close: [0, 1]},
  15422. * {interval: [62, 150], close: [0, 1]},
  15423. * {interval: [150, Infinity], close: [0, 0]}
  15424. * ]);
  15425. * @param {Array.<Object>} list, where `close` mean open or close
  15426. * of the interval, and Infinity can be used.
  15427. * @return {Array.<Object>} The origin list, which has been reformed.
  15428. */
  15429. function reformIntervals(list) {
  15430. list.sort(function (a, b) {
  15431. return littleThan(a, b, 0) ? -1 : 1;
  15432. });
  15433. var curr = -Infinity;
  15434. var currClose = 1;
  15435. for (var i = 0; i < list.length;) {
  15436. var interval = list[i].interval;
  15437. var close = list[i].close;
  15438. for (var lg = 0; lg < 2; lg++) {
  15439. if (interval[lg] <= curr) {
  15440. interval[lg] = curr;
  15441. close[lg] = !lg ? 1 - currClose : 1;
  15442. }
  15443. curr = interval[lg];
  15444. currClose = close[lg];
  15445. }
  15446. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15447. list.splice(i, 1);
  15448. }
  15449. else {
  15450. i++;
  15451. }
  15452. }
  15453. return list;
  15454. function littleThan(a, b, lg) {
  15455. return a.interval[lg] < b.interval[lg]
  15456. || (
  15457. a.interval[lg] === b.interval[lg]
  15458. && (
  15459. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15460. || (!lg && littleThan(a, b, 1))
  15461. )
  15462. );
  15463. }
  15464. }
  15465. /**
  15466. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15467. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15468. * subtraction forces infinities to NaN
  15469. *
  15470. * @param {*} v
  15471. * @return {boolean}
  15472. */
  15473. function isNumeric(v) {
  15474. return v - parseFloat(v) >= 0;
  15475. }
  15476. var number = (Object.freeze || Object)({
  15477. linearMap: linearMap,
  15478. parsePercent: parsePercent$1,
  15479. round: round$1,
  15480. asc: asc,
  15481. getPrecision: getPrecision,
  15482. getPrecisionSafe: getPrecisionSafe,
  15483. getPixelPrecision: getPixelPrecision,
  15484. getPercentWithPrecision: getPercentWithPrecision,
  15485. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15486. remRadian: remRadian,
  15487. isRadianAroundZero: isRadianAroundZero,
  15488. parseDate: parseDate,
  15489. quantity: quantity,
  15490. nice: nice,
  15491. reformIntervals: reformIntervals,
  15492. isNumeric: isNumeric
  15493. });
  15494. /**
  15495. * 每三位默认加,格式化
  15496. * @param {string|number} x
  15497. * @return {string}
  15498. */
  15499. function addCommas(x) {
  15500. if (isNaN(x)) {
  15501. return '-';
  15502. }
  15503. x = (x + '').split('.');
  15504. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15505. + (x.length > 1 ? ('.' + x[1]) : '');
  15506. }
  15507. /**
  15508. * @param {string} str
  15509. * @param {boolean} [upperCaseFirst=false]
  15510. * @return {string} str
  15511. */
  15512. function toCamelCase(str, upperCaseFirst) {
  15513. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15514. return group1.toUpperCase();
  15515. });
  15516. if (upperCaseFirst && str) {
  15517. str = str.charAt(0).toUpperCase() + str.slice(1);
  15518. }
  15519. return str;
  15520. }
  15521. var normalizeCssArray$1 = normalizeCssArray;
  15522. function encodeHTML(source) {
  15523. return String(source)
  15524. .replace(/&/g, '&amp;')
  15525. .replace(/</g, '&lt;')
  15526. .replace(/>/g, '&gt;')
  15527. .replace(/"/g, '&quot;')
  15528. .replace(/'/g, '&#39;');
  15529. }
  15530. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15531. var wrapVar = function (varName, seriesIdx) {
  15532. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15533. };
  15534. /**
  15535. * Template formatter
  15536. * @param {string} tpl
  15537. * @param {Array.<Object>|Object} paramsList
  15538. * @param {boolean} [encode=false]
  15539. * @return {string}
  15540. */
  15541. function formatTpl(tpl, paramsList, encode) {
  15542. if (!isArray(paramsList)) {
  15543. paramsList = [paramsList];
  15544. }
  15545. var seriesLen = paramsList.length;
  15546. if (!seriesLen) {
  15547. return '';
  15548. }
  15549. var $vars = paramsList[0].$vars || [];
  15550. for (var i = 0; i < $vars.length; i++) {
  15551. var alias = TPL_VAR_ALIAS[i];
  15552. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15553. }
  15554. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15555. for (var k = 0; k < $vars.length; k++) {
  15556. var val = paramsList[seriesIdx][$vars[k]];
  15557. tpl = tpl.replace(
  15558. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15559. encode ? encodeHTML(val) : val
  15560. );
  15561. }
  15562. }
  15563. return tpl;
  15564. }
  15565. /**
  15566. * simple Template formatter
  15567. *
  15568. * @param {string} tpl
  15569. * @param {Object} param
  15570. * @param {boolean} [encode=false]
  15571. * @return {string}
  15572. */
  15573. function formatTplSimple(tpl, param, encode) {
  15574. each$1(param, function (value, key) {
  15575. tpl = tpl.replace(
  15576. '{' + key + '}',
  15577. encode ? encodeHTML(value) : value
  15578. );
  15579. });
  15580. return tpl;
  15581. }
  15582. /**
  15583. * @param {Object|string} [opt] If string, means color.
  15584. * @param {string} [opt.color]
  15585. * @param {string} [opt.extraCssText]
  15586. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15587. * @return {string}
  15588. */
  15589. function getTooltipMarker(opt, extraCssText) {
  15590. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15591. var color = opt.color;
  15592. var type = opt.type;
  15593. var extraCssText = opt.extraCssText;
  15594. if (!color) {
  15595. return '';
  15596. }
  15597. return type === 'subItem'
  15598. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15599. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15600. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15601. : '<span style="display:inline-block;margin-right:5px;'
  15602. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15603. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15604. }
  15605. function pad(str, len) {
  15606. str += '';
  15607. return '0000'.substr(0, len - str.length) + str;
  15608. }
  15609. /**
  15610. * ISO Date format
  15611. * @param {string} tpl
  15612. * @param {number} value
  15613. * @param {boolean} [isUTC=false] Default in local time.
  15614. * see `module:echarts/scale/Time`
  15615. * and `module:echarts/util/number#parseDate`.
  15616. * @inner
  15617. */
  15618. function formatTime(tpl, value, isUTC) {
  15619. if (tpl === 'week'
  15620. || tpl === 'month'
  15621. || tpl === 'quarter'
  15622. || tpl === 'half-year'
  15623. || tpl === 'year'
  15624. ) {
  15625. tpl = 'MM-dd\nyyyy';
  15626. }
  15627. var date = parseDate(value);
  15628. var utc = isUTC ? 'UTC' : '';
  15629. var y = date['get' + utc + 'FullYear']();
  15630. var M = date['get' + utc + 'Month']() + 1;
  15631. var d = date['get' + utc + 'Date']();
  15632. var h = date['get' + utc + 'Hours']();
  15633. var m = date['get' + utc + 'Minutes']();
  15634. var s = date['get' + utc + 'Seconds']();
  15635. var S = date['get' + utc + 'Milliseconds']();
  15636. tpl = tpl.replace('MM', pad(M, 2))
  15637. .replace('M', M)
  15638. .replace('yyyy', y)
  15639. .replace('yy', y % 100)
  15640. .replace('dd', pad(d, 2))
  15641. .replace('d', d)
  15642. .replace('hh', pad(h, 2))
  15643. .replace('h', h)
  15644. .replace('mm', pad(m, 2))
  15645. .replace('m', m)
  15646. .replace('ss', pad(s, 2))
  15647. .replace('s', s)
  15648. .replace('SSS', pad(S, 3));
  15649. return tpl;
  15650. }
  15651. /**
  15652. * Capital first
  15653. * @param {string} str
  15654. * @return {string}
  15655. */
  15656. function capitalFirst(str) {
  15657. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15658. }
  15659. var truncateText$1 = truncateText;
  15660. var getTextRect = getBoundingRect;
  15661. var format = (Object.freeze || Object)({
  15662. addCommas: addCommas,
  15663. toCamelCase: toCamelCase,
  15664. normalizeCssArray: normalizeCssArray$1,
  15665. encodeHTML: encodeHTML,
  15666. formatTpl: formatTpl,
  15667. formatTplSimple: formatTplSimple,
  15668. getTooltipMarker: getTooltipMarker,
  15669. formatTime: formatTime,
  15670. capitalFirst: capitalFirst,
  15671. truncateText: truncateText$1,
  15672. getTextRect: getTextRect
  15673. });
  15674. // Layout helpers for each component positioning
  15675. var each$3 = each$1;
  15676. /**
  15677. * @public
  15678. */
  15679. var LOCATION_PARAMS = [
  15680. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15681. ];
  15682. /**
  15683. * @public
  15684. */
  15685. var HV_NAMES = [
  15686. ['width', 'left', 'right'],
  15687. ['height', 'top', 'bottom']
  15688. ];
  15689. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15690. var x = 0;
  15691. var y = 0;
  15692. if (maxWidth == null) {
  15693. maxWidth = Infinity;
  15694. }
  15695. if (maxHeight == null) {
  15696. maxHeight = Infinity;
  15697. }
  15698. var currentLineMaxSize = 0;
  15699. group.eachChild(function (child, idx) {
  15700. var position = child.position;
  15701. var rect = child.getBoundingRect();
  15702. var nextChild = group.childAt(idx + 1);
  15703. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15704. var nextX;
  15705. var nextY;
  15706. if (orient === 'horizontal') {
  15707. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15708. nextX = x + moveX;
  15709. // Wrap when width exceeds maxWidth or meet a `newline` group
  15710. // FIXME compare before adding gap?
  15711. if (nextX > maxWidth || child.newline) {
  15712. x = 0;
  15713. nextX = moveX;
  15714. y += currentLineMaxSize + gap;
  15715. currentLineMaxSize = rect.height;
  15716. }
  15717. else {
  15718. // FIXME: consider rect.y is not `0`?
  15719. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15720. }
  15721. }
  15722. else {
  15723. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15724. nextY = y + moveY;
  15725. // Wrap when width exceeds maxHeight or meet a `newline` group
  15726. if (nextY > maxHeight || child.newline) {
  15727. x += currentLineMaxSize + gap;
  15728. y = 0;
  15729. nextY = moveY;
  15730. currentLineMaxSize = rect.width;
  15731. }
  15732. else {
  15733. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15734. }
  15735. }
  15736. if (child.newline) {
  15737. return;
  15738. }
  15739. position[0] = x;
  15740. position[1] = y;
  15741. orient === 'horizontal'
  15742. ? (x = nextX + gap)
  15743. : (y = nextY + gap);
  15744. });
  15745. }
  15746. /**
  15747. * VBox or HBox layouting
  15748. * @param {string} orient
  15749. * @param {module:zrender/container/Group} group
  15750. * @param {number} gap
  15751. * @param {number} [width=Infinity]
  15752. * @param {number} [height=Infinity]
  15753. */
  15754. var box = boxLayout;
  15755. /**
  15756. * VBox layouting
  15757. * @param {module:zrender/container/Group} group
  15758. * @param {number} gap
  15759. * @param {number} [width=Infinity]
  15760. * @param {number} [height=Infinity]
  15761. */
  15762. var vbox = curry(boxLayout, 'vertical');
  15763. /**
  15764. * HBox layouting
  15765. * @param {module:zrender/container/Group} group
  15766. * @param {number} gap
  15767. * @param {number} [width=Infinity]
  15768. * @param {number} [height=Infinity]
  15769. */
  15770. var hbox = curry(boxLayout, 'horizontal');
  15771. /**
  15772. * If x or x2 is not specified or 'center' 'left' 'right',
  15773. * the width would be as long as possible.
  15774. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15775. * the height would be as long as possible.
  15776. *
  15777. * @param {Object} positionInfo
  15778. * @param {number|string} [positionInfo.x]
  15779. * @param {number|string} [positionInfo.y]
  15780. * @param {number|string} [positionInfo.x2]
  15781. * @param {number|string} [positionInfo.y2]
  15782. * @param {Object} containerRect {width, height}
  15783. * @param {string|number} margin
  15784. * @return {Object} {width, height}
  15785. */
  15786. function getAvailableSize(positionInfo, containerRect, margin) {
  15787. var containerWidth = containerRect.width;
  15788. var containerHeight = containerRect.height;
  15789. var x = parsePercent$1(positionInfo.x, containerWidth);
  15790. var y = parsePercent$1(positionInfo.y, containerHeight);
  15791. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  15792. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  15793. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  15794. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  15795. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  15796. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  15797. margin = normalizeCssArray$1(margin || 0);
  15798. return {
  15799. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15800. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15801. };
  15802. }
  15803. /**
  15804. * Parse position info.
  15805. *
  15806. * @param {Object} positionInfo
  15807. * @param {number|string} [positionInfo.left]
  15808. * @param {number|string} [positionInfo.top]
  15809. * @param {number|string} [positionInfo.right]
  15810. * @param {number|string} [positionInfo.bottom]
  15811. * @param {number|string} [positionInfo.width]
  15812. * @param {number|string} [positionInfo.height]
  15813. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15814. * @param {Object} containerRect
  15815. * @param {string|number} [margin]
  15816. *
  15817. * @return {module:zrender/core/BoundingRect}
  15818. */
  15819. function getLayoutRect(
  15820. positionInfo, containerRect, margin
  15821. ) {
  15822. margin = normalizeCssArray$1(margin || 0);
  15823. var containerWidth = containerRect.width;
  15824. var containerHeight = containerRect.height;
  15825. var left = parsePercent$1(positionInfo.left, containerWidth);
  15826. var top = parsePercent$1(positionInfo.top, containerHeight);
  15827. var right = parsePercent$1(positionInfo.right, containerWidth);
  15828. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15829. var width = parsePercent$1(positionInfo.width, containerWidth);
  15830. var height = parsePercent$1(positionInfo.height, containerHeight);
  15831. var verticalMargin = margin[2] + margin[0];
  15832. var horizontalMargin = margin[1] + margin[3];
  15833. var aspect = positionInfo.aspect;
  15834. // If width is not specified, calculate width from left and right
  15835. if (isNaN(width)) {
  15836. width = containerWidth - right - horizontalMargin - left;
  15837. }
  15838. if (isNaN(height)) {
  15839. height = containerHeight - bottom - verticalMargin - top;
  15840. }
  15841. if (aspect != null) {
  15842. // If width and height are not given
  15843. // 1. Graph should not exceeds the container
  15844. // 2. Aspect must be keeped
  15845. // 3. Graph should take the space as more as possible
  15846. // FIXME
  15847. // Margin is not considered, because there is no case that both
  15848. // using margin and aspect so far.
  15849. if (isNaN(width) && isNaN(height)) {
  15850. if (aspect > containerWidth / containerHeight) {
  15851. width = containerWidth * 0.8;
  15852. }
  15853. else {
  15854. height = containerHeight * 0.8;
  15855. }
  15856. }
  15857. // Calculate width or height with given aspect
  15858. if (isNaN(width)) {
  15859. width = aspect * height;
  15860. }
  15861. if (isNaN(height)) {
  15862. height = width / aspect;
  15863. }
  15864. }
  15865. // If left is not specified, calculate left from right and width
  15866. if (isNaN(left)) {
  15867. left = containerWidth - right - width - horizontalMargin;
  15868. }
  15869. if (isNaN(top)) {
  15870. top = containerHeight - bottom - height - verticalMargin;
  15871. }
  15872. // Align left and top
  15873. switch (positionInfo.left || positionInfo.right) {
  15874. case 'center':
  15875. left = containerWidth / 2 - width / 2 - margin[3];
  15876. break;
  15877. case 'right':
  15878. left = containerWidth - width - horizontalMargin;
  15879. break;
  15880. }
  15881. switch (positionInfo.top || positionInfo.bottom) {
  15882. case 'middle':
  15883. case 'center':
  15884. top = containerHeight / 2 - height / 2 - margin[0];
  15885. break;
  15886. case 'bottom':
  15887. top = containerHeight - height - verticalMargin;
  15888. break;
  15889. }
  15890. // If something is wrong and left, top, width, height are calculated as NaN
  15891. left = left || 0;
  15892. top = top || 0;
  15893. if (isNaN(width)) {
  15894. // Width may be NaN if only one value is given except width
  15895. width = containerWidth - horizontalMargin - left - (right || 0);
  15896. }
  15897. if (isNaN(height)) {
  15898. // Height may be NaN if only one value is given except height
  15899. height = containerHeight - verticalMargin - top - (bottom || 0);
  15900. }
  15901. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15902. rect.margin = margin;
  15903. return rect;
  15904. }
  15905. /**
  15906. * Position a zr element in viewport
  15907. * Group position is specified by either
  15908. * {left, top}, {right, bottom}
  15909. * If all properties exists, right and bottom will be igonred.
  15910. *
  15911. * Logic:
  15912. * 1. Scale (against origin point in parent coord)
  15913. * 2. Rotate (against origin point in parent coord)
  15914. * 3. Traslate (with el.position by this method)
  15915. * So this method only fixes the last step 'Traslate', which does not affect
  15916. * scaling and rotating.
  15917. *
  15918. * If be called repeatly with the same input el, the same result will be gotten.
  15919. *
  15920. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15921. * @param {Object} positionInfo
  15922. * @param {number|string} [positionInfo.left]
  15923. * @param {number|string} [positionInfo.top]
  15924. * @param {number|string} [positionInfo.right]
  15925. * @param {number|string} [positionInfo.bottom]
  15926. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15927. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15928. * @param {Object} containerRect
  15929. * @param {string|number} margin
  15930. * @param {Object} [opt]
  15931. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15932. * @param {Array.<number>} [opt.boundingMode='all']
  15933. * Specify how to calculate boundingRect when locating.
  15934. * 'all': Position the boundingRect that is transformed and uioned
  15935. * both itself and its descendants.
  15936. * This mode simplies confine the elements in the bounding
  15937. * of their container (e.g., using 'right: 0').
  15938. * 'raw': Position the boundingRect that is not transformed and only itself.
  15939. * This mode is useful when you want a element can overflow its
  15940. * container. (Consider a rotated circle needs to be located in a corner.)
  15941. * In this mode positionInfo.width/height can only be number.
  15942. */
  15943. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15944. var h = !opt || !opt.hv || opt.hv[0];
  15945. var v = !opt || !opt.hv || opt.hv[1];
  15946. var boundingMode = opt && opt.boundingMode || 'all';
  15947. if (!h && !v) {
  15948. return;
  15949. }
  15950. var rect;
  15951. if (boundingMode === 'raw') {
  15952. rect = el.type === 'group'
  15953. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15954. : el.getBoundingRect();
  15955. }
  15956. else {
  15957. rect = el.getBoundingRect();
  15958. if (el.needLocalTransform()) {
  15959. var transform = el.getLocalTransform();
  15960. // Notice: raw rect may be inner object of el,
  15961. // which should not be modified.
  15962. rect = rect.clone();
  15963. rect.applyTransform(transform);
  15964. }
  15965. }
  15966. // The real width and height can not be specified but calculated by the given el.
  15967. positionInfo = getLayoutRect(
  15968. defaults(
  15969. {width: rect.width, height: rect.height},
  15970. positionInfo
  15971. ),
  15972. containerRect,
  15973. margin
  15974. );
  15975. // Because 'tranlate' is the last step in transform
  15976. // (see zrender/core/Transformable#getLocalTransform),
  15977. // we can just only modify el.position to get final result.
  15978. var elPos = el.position;
  15979. var dx = h ? positionInfo.x - rect.x : 0;
  15980. var dy = v ? positionInfo.y - rect.y : 0;
  15981. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15982. }
  15983. /**
  15984. * @param {Object} option Contains some of the properties in HV_NAMES.
  15985. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15986. */
  15987. function sizeCalculable(option, hvIdx) {
  15988. return option[HV_NAMES[hvIdx][0]] != null
  15989. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  15990. }
  15991. /**
  15992. * Consider Case:
  15993. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15994. * through setOption or media query, using normal zrUtil.merge will cause
  15995. * {right: 0} does not take effect.
  15996. *
  15997. * @example
  15998. * ComponentModel.extend({
  15999. * init: function () {
  16000. * ...
  16001. * var inputPositionParams = layout.getLayoutParams(option);
  16002. * this.mergeOption(inputPositionParams);
  16003. * },
  16004. * mergeOption: function (newOption) {
  16005. * newOption && zrUtil.merge(thisOption, newOption, true);
  16006. * layout.mergeLayoutParam(thisOption, newOption);
  16007. * }
  16008. * });
  16009. *
  16010. * @param {Object} targetOption
  16011. * @param {Object} newOption
  16012. * @param {Object|string} [opt]
  16013. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16014. * that width (or height) should not be calculated by left and right (or top and bottom).
  16015. */
  16016. function mergeLayoutParam(targetOption, newOption, opt) {
  16017. !isObject$1(opt) && (opt = {});
  16018. var ignoreSize = opt.ignoreSize;
  16019. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16020. var hResult = merge$$1(HV_NAMES[0], 0);
  16021. var vResult = merge$$1(HV_NAMES[1], 1);
  16022. copy(HV_NAMES[0], targetOption, hResult);
  16023. copy(HV_NAMES[1], targetOption, vResult);
  16024. function merge$$1(names, hvIdx) {
  16025. var newParams = {};
  16026. var newValueCount = 0;
  16027. var merged = {};
  16028. var mergedValueCount = 0;
  16029. var enoughParamNumber = 2;
  16030. each$3(names, function (name) {
  16031. merged[name] = targetOption[name];
  16032. });
  16033. each$3(names, function (name) {
  16034. // Consider case: newOption.width is null, which is
  16035. // set by user for removing width setting.
  16036. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16037. hasValue(newParams, name) && newValueCount++;
  16038. hasValue(merged, name) && mergedValueCount++;
  16039. });
  16040. if (ignoreSize[hvIdx]) {
  16041. // Only one of left/right is premitted to exist.
  16042. if (hasValue(newOption, names[1])) {
  16043. merged[names[2]] = null;
  16044. }
  16045. else if (hasValue(newOption, names[2])) {
  16046. merged[names[1]] = null;
  16047. }
  16048. return merged;
  16049. }
  16050. // Case: newOption: {width: ..., right: ...},
  16051. // or targetOption: {right: ...} and newOption: {width: ...},
  16052. // There is no conflict when merged only has params count
  16053. // little than enoughParamNumber.
  16054. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16055. return merged;
  16056. }
  16057. // Case: newOption: {width: ..., right: ...},
  16058. // Than we can make sure user only want those two, and ignore
  16059. // all origin params in targetOption.
  16060. else if (newValueCount >= enoughParamNumber) {
  16061. return newParams;
  16062. }
  16063. else {
  16064. // Chose another param from targetOption by priority.
  16065. for (var i = 0; i < names.length; i++) {
  16066. var name = names[i];
  16067. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16068. newParams[name] = targetOption[name];
  16069. break;
  16070. }
  16071. }
  16072. return newParams;
  16073. }
  16074. }
  16075. function hasProp(obj, name) {
  16076. return obj.hasOwnProperty(name);
  16077. }
  16078. function hasValue(obj, name) {
  16079. return obj[name] != null && obj[name] !== 'auto';
  16080. }
  16081. function copy(names, target, source) {
  16082. each$3(names, function (name) {
  16083. target[name] = source[name];
  16084. });
  16085. }
  16086. }
  16087. /**
  16088. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16089. * @param {Object} source
  16090. * @return {Object} Result contains those props.
  16091. */
  16092. function getLayoutParams(source) {
  16093. return copyLayoutParams({}, source);
  16094. }
  16095. /**
  16096. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16097. * @param {Object} source
  16098. * @return {Object} Result contains those props.
  16099. */
  16100. function copyLayoutParams(target, source) {
  16101. source && target && each$3(LOCATION_PARAMS, function (name) {
  16102. source.hasOwnProperty(name) && (target[name] = source[name]);
  16103. });
  16104. return target;
  16105. }
  16106. var boxLayoutMixin = {
  16107. getBoxLayoutParams: function () {
  16108. return {
  16109. left: this.get('left'),
  16110. top: this.get('top'),
  16111. right: this.get('right'),
  16112. bottom: this.get('bottom'),
  16113. width: this.get('width'),
  16114. height: this.get('height')
  16115. };
  16116. }
  16117. };
  16118. /**
  16119. * Component model
  16120. *
  16121. * @module echarts/model/Component
  16122. */
  16123. var inner$1 = makeInner();
  16124. /**
  16125. * @alias module:echarts/model/Component
  16126. * @constructor
  16127. * @param {Object} option
  16128. * @param {module:echarts/model/Model} parentModel
  16129. * @param {module:echarts/model/Model} ecModel
  16130. */
  16131. var ComponentModel = Model.extend({
  16132. type: 'component',
  16133. /**
  16134. * @readOnly
  16135. * @type {string}
  16136. */
  16137. id: '',
  16138. /**
  16139. * Because simplified concept is probably better, series.name (or component.name)
  16140. * has been having too many resposibilities:
  16141. * (1) Generating id (which requires name in option should not be modified).
  16142. * (2) As an index to mapping series when merging option or calling API (a name
  16143. * can refer to more then one components, which is convinient is some case).
  16144. * (3) Display.
  16145. * @readOnly
  16146. */
  16147. name: '',
  16148. /**
  16149. * @readOnly
  16150. * @type {string}
  16151. */
  16152. mainType: '',
  16153. /**
  16154. * @readOnly
  16155. * @type {string}
  16156. */
  16157. subType: '',
  16158. /**
  16159. * @readOnly
  16160. * @type {number}
  16161. */
  16162. componentIndex: 0,
  16163. /**
  16164. * @type {Object}
  16165. * @protected
  16166. */
  16167. defaultOption: null,
  16168. /**
  16169. * @type {module:echarts/model/Global}
  16170. * @readOnly
  16171. */
  16172. ecModel: null,
  16173. /**
  16174. * key: componentType
  16175. * value: Component model list, can not be null.
  16176. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16177. * @readOnly
  16178. */
  16179. dependentModels: [],
  16180. /**
  16181. * @type {string}
  16182. * @readOnly
  16183. */
  16184. uid: null,
  16185. /**
  16186. * Support merge layout params.
  16187. * Only support 'box' now (left/right/top/bottom/width/height).
  16188. * @type {string|Object} Object can be {ignoreSize: true}
  16189. * @readOnly
  16190. */
  16191. layoutMode: null,
  16192. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16193. Model.call(this, option, parentModel, ecModel, extraOpt);
  16194. this.uid = getUID('ec_cpt_model');
  16195. },
  16196. init: function (option, parentModel, ecModel, extraOpt) {
  16197. this.mergeDefaultAndTheme(option, ecModel);
  16198. },
  16199. mergeDefaultAndTheme: function (option, ecModel) {
  16200. var layoutMode = this.layoutMode;
  16201. var inputPositionParams = layoutMode
  16202. ? getLayoutParams(option) : {};
  16203. var themeModel = ecModel.getTheme();
  16204. merge(option, themeModel.get(this.mainType));
  16205. merge(option, this.getDefaultOption());
  16206. if (layoutMode) {
  16207. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16208. }
  16209. },
  16210. mergeOption: function (option, extraOpt) {
  16211. merge(this.option, option, true);
  16212. var layoutMode = this.layoutMode;
  16213. if (layoutMode) {
  16214. mergeLayoutParam(this.option, option, layoutMode);
  16215. }
  16216. },
  16217. // Hooker after init or mergeOption
  16218. optionUpdated: function (newCptOption, isInit) {},
  16219. getDefaultOption: function () {
  16220. var fields = inner$1(this);
  16221. if (!fields.defaultOption) {
  16222. var optList = [];
  16223. var Class = this.constructor;
  16224. while (Class) {
  16225. var opt = Class.prototype.defaultOption;
  16226. opt && optList.push(opt);
  16227. Class = Class.superClass;
  16228. }
  16229. var defaultOption = {};
  16230. for (var i = optList.length - 1; i >= 0; i--) {
  16231. defaultOption = merge(defaultOption, optList[i], true);
  16232. }
  16233. fields.defaultOption = defaultOption;
  16234. }
  16235. return fields.defaultOption;
  16236. },
  16237. getReferringComponents: function (mainType) {
  16238. return this.ecModel.queryComponents({
  16239. mainType: mainType,
  16240. index: this.get(mainType + 'Index', true),
  16241. id: this.get(mainType + 'Id', true)
  16242. });
  16243. }
  16244. });
  16245. // Reset ComponentModel.extend, add preConstruct.
  16246. // clazzUtil.enableClassExtend(
  16247. // ComponentModel,
  16248. // function (option, parentModel, ecModel, extraOpt) {
  16249. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16250. // zrUtil.extend(this, extraOpt);
  16251. // this.uid = componentUtil.getUID('componentModel');
  16252. // // this.setReadOnly([
  16253. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16254. // // 'dependentModels', 'componentIndex'
  16255. // // ]);
  16256. // }
  16257. // );
  16258. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16259. enableClassManagement(
  16260. ComponentModel, {registerWhenExtend: true}
  16261. );
  16262. enableSubTypeDefaulter(ComponentModel);
  16263. // Add capability of ComponentModel.topologicalTravel.
  16264. enableTopologicalTravel(ComponentModel, getDependencies);
  16265. function getDependencies(componentType) {
  16266. var deps = [];
  16267. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16268. deps = deps.concat(Clazz.prototype.dependencies || []);
  16269. });
  16270. // Ensure main type.
  16271. deps = map(deps, function (type) {
  16272. return parseClassType$1(type).main;
  16273. });
  16274. // Hack dataset for convenience.
  16275. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16276. deps.unshift('dataset');
  16277. }
  16278. return deps;
  16279. }
  16280. mixin(ComponentModel, boxLayoutMixin);
  16281. var platform = '';
  16282. // Navigator not exists in node
  16283. if (typeof navigator !== 'undefined') {
  16284. platform = navigator.platform || '';
  16285. }
  16286. var globalDefault = {
  16287. // backgroundColor: 'rgba(0,0,0,0)',
  16288. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16289. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16290. // Light colors:
  16291. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16292. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16293. // Dark colors:
  16294. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16295. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16296. // If xAxis and yAxis declared, grid is created by default.
  16297. // grid: {},
  16298. textStyle: {
  16299. // color: '#000',
  16300. // decoration: 'none',
  16301. // PENDING
  16302. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16303. // fontFamily: 'Arial, Verdana, sans-serif',
  16304. fontSize: 12,
  16305. fontStyle: 'normal',
  16306. fontWeight: 'normal'
  16307. },
  16308. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16309. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16310. // Default is source-over
  16311. blendMode: null,
  16312. animation: 'auto',
  16313. animationDuration: 1000,
  16314. animationDurationUpdate: 300,
  16315. animationEasing: 'exponentialOut',
  16316. animationEasingUpdate: 'cubicOut',
  16317. animationThreshold: 2000,
  16318. // Configuration for progressive/incremental rendering
  16319. progressiveThreshold: 3000,
  16320. progressive: 400,
  16321. // Threshold of if use single hover layer to optimize.
  16322. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16323. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16324. // which is unexpected.
  16325. // see example <echarts/test/heatmap-large.html>.
  16326. hoverLayerThreshold: 3000,
  16327. // See: module:echarts/scale/Time
  16328. useUTC: false
  16329. };
  16330. var inner$2 = makeInner();
  16331. function getNearestColorPalette(colors, requestColorNum) {
  16332. var paletteNum = colors.length;
  16333. // TODO colors must be in order
  16334. for (var i = 0; i < paletteNum; i++) {
  16335. if (colors[i].length > requestColorNum) {
  16336. return colors[i];
  16337. }
  16338. }
  16339. return colors[paletteNum - 1];
  16340. }
  16341. var colorPaletteMixin = {
  16342. clearColorPalette: function () {
  16343. inner$2(this).colorIdx = 0;
  16344. inner$2(this).colorNameMap = {};
  16345. },
  16346. /**
  16347. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16348. * twise with the same parameters will get different result.
  16349. * @param {Object} [scope=this]
  16350. * @param {Object} [requestColorNum]
  16351. * @return {string} color string.
  16352. */
  16353. getColorFromPalette: function (name, scope, requestColorNum) {
  16354. scope = scope || this;
  16355. var scopeFields = inner$2(scope);
  16356. var colorIdx = scopeFields.colorIdx || 0;
  16357. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16358. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16359. if (colorNameMap.hasOwnProperty(name)) {
  16360. return colorNameMap[name];
  16361. }
  16362. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16363. var layeredColorPalette = this.get('colorLayer', true);
  16364. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16365. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16366. // In case can't find in layered color palette.
  16367. colorPalette = colorPalette || defaultColorPalette;
  16368. if (!colorPalette || !colorPalette.length) {
  16369. return;
  16370. }
  16371. var color = colorPalette[colorIdx];
  16372. if (name) {
  16373. colorNameMap[name] = color;
  16374. }
  16375. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16376. return color;
  16377. }
  16378. };
  16379. /**
  16380. * Helper for model references.
  16381. * There are many manners to refer axis/coordSys.
  16382. */
  16383. // TODO
  16384. // merge relevant logic to this file?
  16385. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16386. /**
  16387. * @return {Object} For example:
  16388. * {
  16389. * coordSysName: 'cartesian2d',
  16390. * coordSysDims: ['x', 'y', ...],
  16391. * axisMap: HashMap({
  16392. * x: xAxisModel,
  16393. * y: yAxisModel
  16394. * }),
  16395. * categoryAxisMap: HashMap({
  16396. * x: xAxisModel,
  16397. * y: undefined
  16398. * }),
  16399. * // It also indicate that whether there is category axis.
  16400. * firstCategoryDimIndex: 1,
  16401. * // To replace user specified encode.
  16402. * }
  16403. */
  16404. function getCoordSysDefineBySeries(seriesModel) {
  16405. var coordSysName = seriesModel.get('coordinateSystem');
  16406. var result = {
  16407. coordSysName: coordSysName,
  16408. coordSysDims: [],
  16409. axisMap: createHashMap(),
  16410. categoryAxisMap: createHashMap()
  16411. };
  16412. var fetch = fetchers[coordSysName];
  16413. if (fetch) {
  16414. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16415. return result;
  16416. }
  16417. }
  16418. var fetchers = {
  16419. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16420. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16421. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16422. if (__DEV__) {
  16423. if (!xAxisModel) {
  16424. throw new Error('xAxis "' + retrieve(
  16425. seriesModel.get('xAxisIndex'),
  16426. seriesModel.get('xAxisId'),
  16427. 0
  16428. ) + '" not found');
  16429. }
  16430. if (!yAxisModel) {
  16431. throw new Error('yAxis "' + retrieve(
  16432. seriesModel.get('xAxisIndex'),
  16433. seriesModel.get('yAxisId'),
  16434. 0
  16435. ) + '" not found');
  16436. }
  16437. }
  16438. result.coordSysDims = ['x', 'y'];
  16439. axisMap.set('x', xAxisModel);
  16440. axisMap.set('y', yAxisModel);
  16441. if (isCategory(xAxisModel)) {
  16442. categoryAxisMap.set('x', xAxisModel);
  16443. result.firstCategoryDimIndex = 0;
  16444. }
  16445. if (isCategory(yAxisModel)) {
  16446. categoryAxisMap.set('y', yAxisModel);
  16447. result.firstCategoryDimIndex = 1;
  16448. }
  16449. },
  16450. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16451. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16452. if (__DEV__) {
  16453. if (!singleAxisModel) {
  16454. throw new Error('singleAxis should be specified.');
  16455. }
  16456. }
  16457. result.coordSysDims = ['single'];
  16458. axisMap.set('single', singleAxisModel);
  16459. if (isCategory(singleAxisModel)) {
  16460. categoryAxisMap.set('single', singleAxisModel);
  16461. result.firstCategoryDimIndex = 0;
  16462. }
  16463. },
  16464. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16465. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16466. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16467. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16468. if (__DEV__) {
  16469. if (!angleAxisModel) {
  16470. throw new Error('angleAxis option not found');
  16471. }
  16472. if (!radiusAxisModel) {
  16473. throw new Error('radiusAxis option not found');
  16474. }
  16475. }
  16476. result.coordSysDims = ['radius', 'angle'];
  16477. axisMap.set('radius', radiusAxisModel);
  16478. axisMap.set('angle', angleAxisModel);
  16479. if (isCategory(radiusAxisModel)) {
  16480. categoryAxisMap.set('radius', radiusAxisModel);
  16481. result.firstCategoryDimIndex = 0;
  16482. }
  16483. if (isCategory(angleAxisModel)) {
  16484. categoryAxisMap.set('angle', angleAxisModel);
  16485. result.firstCategoryDimIndex = 1;
  16486. }
  16487. },
  16488. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16489. result.coordSysDims = ['lng', 'lat'];
  16490. },
  16491. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16492. var ecModel = seriesModel.ecModel;
  16493. var parallelModel = ecModel.getComponent(
  16494. 'parallel', seriesModel.get('parallelIndex')
  16495. );
  16496. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16497. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16498. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16499. var axisDim = coordSysDims[index];
  16500. axisMap.set(axisDim, axisModel);
  16501. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16502. categoryAxisMap.set(axisDim, axisModel);
  16503. result.firstCategoryDimIndex = index;
  16504. }
  16505. });
  16506. }
  16507. };
  16508. function isCategory(axisModel) {
  16509. return axisModel.get('type') === 'category';
  16510. }
  16511. // Avoid typo.
  16512. var SOURCE_FORMAT_ORIGINAL = 'original';
  16513. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16514. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16515. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16516. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16517. // ??? CHANGE A NAME
  16518. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16519. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16520. var SERIES_LAYOUT_BY_ROW = 'row';
  16521. /**
  16522. * [sourceFormat]
  16523. *
  16524. * + "original":
  16525. * This format is only used in series.data, where
  16526. * itemStyle can be specified in data item.
  16527. *
  16528. * + "arrayRows":
  16529. * [
  16530. * ['product', 'score', 'amount'],
  16531. * ['Matcha Latte', 89.3, 95.8],
  16532. * ['Milk Tea', 92.1, 89.4],
  16533. * ['Cheese Cocoa', 94.4, 91.2],
  16534. * ['Walnut Brownie', 85.4, 76.9]
  16535. * ]
  16536. *
  16537. * + "objectRows":
  16538. * [
  16539. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16540. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16541. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16542. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16543. * ]
  16544. *
  16545. * + "keyedColumns":
  16546. * {
  16547. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16548. * 'count': [823, 235, 1042, 988],
  16549. * 'score': [95.8, 81.4, 91.2, 76.9]
  16550. * }
  16551. *
  16552. * + "typedArray"
  16553. *
  16554. * + "unknown"
  16555. */
  16556. /**
  16557. * @constructor
  16558. * @param {Object} fields
  16559. * @param {string} fields.sourceFormat
  16560. * @param {Array|Object} fields.fromDataset
  16561. * @param {Array|Object} [fields.data]
  16562. * @param {string} [seriesLayoutBy='column']
  16563. * @param {Array.<Object|string>} [dimensionsDefine]
  16564. * @param {Objet|HashMap} [encodeDefine]
  16565. * @param {number} [startIndex=0]
  16566. * @param {number} [dimensionsDetectCount]
  16567. */
  16568. function Source(fields) {
  16569. /**
  16570. * @type {boolean}
  16571. */
  16572. this.fromDataset = fields.fromDataset;
  16573. /**
  16574. * Not null/undefined.
  16575. * @type {Array|Object}
  16576. */
  16577. this.data = fields.data || (
  16578. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16579. );
  16580. /**
  16581. * See also "detectSourceFormat".
  16582. * Not null/undefined.
  16583. * @type {string}
  16584. */
  16585. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16586. /**
  16587. * 'row' or 'column'
  16588. * Not null/undefined.
  16589. * @type {string} seriesLayoutBy
  16590. */
  16591. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16592. /**
  16593. * dimensions definition in option.
  16594. * can be null/undefined.
  16595. * @type {Array.<Object|string>}
  16596. */
  16597. this.dimensionsDefine = fields.dimensionsDefine;
  16598. /**
  16599. * encode definition in option.
  16600. * can be null/undefined.
  16601. * @type {Objet|HashMap}
  16602. */
  16603. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16604. /**
  16605. * Not null/undefined, uint.
  16606. * @type {number}
  16607. */
  16608. this.startIndex = fields.startIndex || 0;
  16609. /**
  16610. * Can be null/undefined (when unknown), uint.
  16611. * @type {number}
  16612. */
  16613. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16614. }
  16615. /**
  16616. * Wrap original series data for some compatibility cases.
  16617. */
  16618. Source.seriesDataToSource = function (data) {
  16619. return new Source({
  16620. data: data,
  16621. sourceFormat: isTypedArray(data)
  16622. ? SOURCE_FORMAT_TYPED_ARRAY
  16623. : SOURCE_FORMAT_ORIGINAL,
  16624. fromDataset: false
  16625. });
  16626. };
  16627. enableClassCheck(Source);
  16628. var inner$3 = makeInner();
  16629. /**
  16630. * @see {module:echarts/data/Source}
  16631. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  16632. * @return {string} sourceFormat
  16633. */
  16634. function detectSourceFormat(datasetModel) {
  16635. var data = datasetModel.option.source;
  16636. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  16637. if (isTypedArray(data)) {
  16638. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  16639. }
  16640. else if (isArray(data)) {
  16641. // FIXME Whether tolerate null in top level array?
  16642. for (var i = 0, len = data.length; i < len; i++) {
  16643. var item = data[i];
  16644. if (item == null) {
  16645. continue;
  16646. }
  16647. else if (isArray(item)) {
  16648. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  16649. break;
  16650. }
  16651. else if (isObject$1(item)) {
  16652. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  16653. break;
  16654. }
  16655. }
  16656. }
  16657. else if (isObject$1(data)) {
  16658. for (var key in data) {
  16659. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  16660. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  16661. break;
  16662. }
  16663. }
  16664. }
  16665. else if (data != null) {
  16666. throw new Error('Invalid data');
  16667. }
  16668. inner$3(datasetModel).sourceFormat = sourceFormat;
  16669. }
  16670. /**
  16671. * [Scenarios]:
  16672. * (1) Provide source data directly:
  16673. * series: {
  16674. * encode: {...},
  16675. * dimensions: [...]
  16676. * seriesLayoutBy: 'row',
  16677. * data: [[...]]
  16678. * }
  16679. * (2) Refer to datasetModel.
  16680. * series: [{
  16681. * encode: {...}
  16682. * // Ignore datasetIndex means `datasetIndex: 0`
  16683. * // and the dimensions defination in dataset is used
  16684. * }, {
  16685. * encode: {...},
  16686. * seriesLayoutBy: 'column',
  16687. * datasetIndex: 1
  16688. * }]
  16689. *
  16690. * Get data from series itself or datset.
  16691. * @return {module:echarts/data/Source} source
  16692. */
  16693. function getSource(seriesModel) {
  16694. return inner$3(seriesModel).source;
  16695. }
  16696. /**
  16697. * MUST be called before mergeOption of all series.
  16698. * @param {module:echarts/model/Global} ecModel
  16699. */
  16700. function resetSourceDefaulter(ecModel) {
  16701. // `datasetMap` is used to make default encode.
  16702. inner$3(ecModel).datasetMap = createHashMap();
  16703. }
  16704. /**
  16705. * [Caution]:
  16706. * MUST be called after series option merged and
  16707. * before "series.getInitailData()" called.
  16708. *
  16709. * [The rule of making default encode]:
  16710. * Category axis (if exists) alway map to the first dimension.
  16711. * Each other axis occupies a subsequent dimension.
  16712. *
  16713. * [Why make default encode]:
  16714. * Simplify the typing of encode in option, avoiding the case like that:
  16715. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16716. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16717. *
  16718. * @param {module:echarts/model/Series} seriesModel
  16719. */
  16720. function prepareSource(seriesModel) {
  16721. var seriesOption = seriesModel.option;
  16722. var data = seriesOption.data;
  16723. var sourceFormat = isTypedArray(data)
  16724. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16725. var fromDataset = false;
  16726. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16727. var sourceHeader = seriesOption.sourceHeader;
  16728. var dimensionsDefine = seriesOption.dimensions;
  16729. var datasetModel = getDatasetModel(seriesModel);
  16730. if (datasetModel) {
  16731. var datasetOption = datasetModel.option;
  16732. data = datasetOption.source;
  16733. sourceFormat = inner$3(datasetModel).sourceFormat;
  16734. fromDataset = true;
  16735. // These settings from series has higher priority.
  16736. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16737. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16738. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16739. }
  16740. var completeResult = completeBySourceData(
  16741. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16742. );
  16743. // Note: dataset option does not have `encode`.
  16744. var encodeDefine = seriesOption.encode;
  16745. if (!encodeDefine && datasetModel) {
  16746. encodeDefine = makeDefaultEncode(
  16747. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16748. );
  16749. }
  16750. inner$3(seriesModel).source = new Source({
  16751. data: data,
  16752. fromDataset: fromDataset,
  16753. seriesLayoutBy: seriesLayoutBy,
  16754. sourceFormat: sourceFormat,
  16755. dimensionsDefine: completeResult.dimensionsDefine,
  16756. startIndex: completeResult.startIndex,
  16757. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16758. encodeDefine: encodeDefine
  16759. });
  16760. }
  16761. // return {startIndex, dimensionsDefine, dimensionsCount}
  16762. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16763. if (!data) {
  16764. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16765. }
  16766. var dimensionsDetectCount;
  16767. var startIndex;
  16768. var findPotentialName;
  16769. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16770. // Rule: Most of the first line are string: it is header.
  16771. // Caution: consider a line with 5 string and 1 number,
  16772. // it still can not be sure it is a head, because the
  16773. // 5 string may be 5 values of category columns.
  16774. if (sourceHeader === 'auto' || sourceHeader == null) {
  16775. arrayRowsTravelFirst(function (val) {
  16776. // '-' is regarded as null/undefined.
  16777. if (val != null && val !== '-') {
  16778. if (isString(val)) {
  16779. startIndex == null && (startIndex = 1);
  16780. }
  16781. else {
  16782. startIndex = 0;
  16783. }
  16784. }
  16785. // 10 is an experience number, avoid long loop.
  16786. }, seriesLayoutBy, data, 10);
  16787. }
  16788. else {
  16789. startIndex = sourceHeader ? 1 : 0;
  16790. }
  16791. if (!dimensionsDefine && startIndex === 1) {
  16792. dimensionsDefine = [];
  16793. arrayRowsTravelFirst(function (val, index) {
  16794. dimensionsDefine[index] = val != null ? val : '';
  16795. }, seriesLayoutBy, data);
  16796. }
  16797. dimensionsDetectCount = dimensionsDefine
  16798. ? dimensionsDefine.length
  16799. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16800. ? data.length
  16801. : data[0]
  16802. ? data[0].length
  16803. : null;
  16804. }
  16805. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16806. if (!dimensionsDefine) {
  16807. dimensionsDefine = objectRowsCollectDimensions(data);
  16808. findPotentialName = true;
  16809. }
  16810. }
  16811. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16812. if (!dimensionsDefine) {
  16813. dimensionsDefine = [];
  16814. findPotentialName = true;
  16815. each$1(data, function (colArr, key) {
  16816. dimensionsDefine.push(key);
  16817. });
  16818. }
  16819. }
  16820. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16821. var value0 = getDataItemValue(data[0]);
  16822. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16823. }
  16824. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16825. if (__DEV__) {
  16826. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16827. }
  16828. }
  16829. var potentialNameDimIndex;
  16830. if (findPotentialName) {
  16831. each$1(dimensionsDefine, function (dim, idx) {
  16832. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16833. potentialNameDimIndex = idx;
  16834. }
  16835. });
  16836. }
  16837. return {
  16838. startIndex: startIndex,
  16839. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16840. dimensionsDetectCount: dimensionsDetectCount,
  16841. potentialNameDimIndex: potentialNameDimIndex
  16842. // TODO: potentialIdDimIdx
  16843. };
  16844. }
  16845. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16846. // which is reasonable. But dimension name is duplicated.
  16847. // Returns undefined or an array contains only object without null/undefiend or string.
  16848. function normalizeDimensionsDefine(dimensionsDefine) {
  16849. if (!dimensionsDefine) {
  16850. // The meaning of null/undefined is different from empty array.
  16851. return;
  16852. }
  16853. var nameMap = createHashMap();
  16854. return map(dimensionsDefine, function (item, index) {
  16855. item = extend({}, isObject$1(item) ? item : {name: item});
  16856. // User can set null in dimensions.
  16857. // We dont auto specify name, othewise a given name may
  16858. // cause it be refered unexpectedly.
  16859. if (item.name == null) {
  16860. return item;
  16861. }
  16862. // Also consider number form like 2012.
  16863. item.name += '';
  16864. // User may also specify displayName.
  16865. // displayName will always exists except user not
  16866. // specified or dim name is not specified or detected.
  16867. // (A auto generated dim name will not be used as
  16868. // displayName).
  16869. if (item.displayName == null) {
  16870. item.displayName = item.name;
  16871. }
  16872. var exist = nameMap.get(item.name);
  16873. if (!exist) {
  16874. nameMap.set(item.name, {count: 1});
  16875. }
  16876. else {
  16877. item.name += '-' + exist.count++;
  16878. }
  16879. return item;
  16880. });
  16881. }
  16882. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16883. maxLoop == null && (maxLoop = Infinity);
  16884. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16885. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16886. cb(data[i] ? data[i][0] : null, i);
  16887. }
  16888. }
  16889. else {
  16890. var value0 = data[0] || [];
  16891. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16892. cb(value0[i], i);
  16893. }
  16894. }
  16895. }
  16896. function objectRowsCollectDimensions(data) {
  16897. var firstIndex = 0;
  16898. var obj;
  16899. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16900. if (obj) {
  16901. var dimensions = [];
  16902. each$1(obj, function (value, key) {
  16903. dimensions.push(key);
  16904. });
  16905. return dimensions;
  16906. }
  16907. }
  16908. // ??? TODO merge to completedimensions, where also has
  16909. // default encode making logic. And the default rule
  16910. // should depends on series? consider 'map'.
  16911. function makeDefaultEncode(
  16912. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16913. ) {
  16914. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16915. var encode = {};
  16916. // var encodeTooltip = [];
  16917. // var encodeLabel = [];
  16918. var encodeItemName = [];
  16919. var encodeSeriesName = [];
  16920. var seriesType = seriesModel.subType;
  16921. // ??? TODO refactor: provide by series itself.
  16922. // Consider the case: 'map' series is based on geo coordSys,
  16923. // 'graph', 'heatmap' can be based on cartesian. But can not
  16924. // give default rule simply here.
  16925. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16926. var cSeriesMap = createHashMap([
  16927. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16928. ]);
  16929. // Usually in this case series will use the first data
  16930. // dimension as the "value" dimension, or other default
  16931. // processes respectively.
  16932. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16933. var ecModel = seriesModel.ecModel;
  16934. var datasetMap = inner$3(ecModel).datasetMap;
  16935. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16936. var datasetRecord = datasetMap.get(key)
  16937. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16938. // TODO
  16939. // Auto detect first time axis and do arrangement.
  16940. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16941. // In value way.
  16942. if (coordSysDefine.firstCategoryDimIndex == null) {
  16943. var dataDim = datasetRecord.valueWayDim++;
  16944. encode[coordDim] = dataDim;
  16945. // ??? TODO give a better default series name rule?
  16946. // especially when encode x y specified.
  16947. // consider: when mutiple series share one dimension
  16948. // category axis, series name should better use
  16949. // the other dimsion name. On the other hand, use
  16950. // both dimensions name.
  16951. encodeSeriesName.push(dataDim);
  16952. // encodeTooltip.push(dataDim);
  16953. // encodeLabel.push(dataDim);
  16954. }
  16955. // In category way, category axis.
  16956. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16957. encode[coordDim] = 0;
  16958. encodeItemName.push(0);
  16959. }
  16960. // In category way, non-category axis.
  16961. else {
  16962. var dataDim = datasetRecord.categoryWayDim++;
  16963. encode[coordDim] = dataDim;
  16964. // encodeTooltip.push(dataDim);
  16965. // encodeLabel.push(dataDim);
  16966. encodeSeriesName.push(dataDim);
  16967. }
  16968. });
  16969. }
  16970. // Do not make a complex rule! Hard to code maintain and not necessary.
  16971. // ??? TODO refactor: provide by series itself.
  16972. // [{name: ..., value: ...}, ...] like:
  16973. else if (nSeriesMap.get(seriesType) != null) {
  16974. // Find the first not ordinal. (5 is an experience value)
  16975. var firstNotOrdinal;
  16976. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16977. if (!doGuessOrdinal(
  16978. data, sourceFormat, seriesLayoutBy,
  16979. completeResult.dimensionsDefine, completeResult.startIndex, i
  16980. )) {
  16981. firstNotOrdinal = i;
  16982. }
  16983. }
  16984. if (firstNotOrdinal != null) {
  16985. encode.value = firstNotOrdinal;
  16986. var nameDimIndex = completeResult.potentialNameDimIndex
  16987. || Math.max(firstNotOrdinal - 1, 0);
  16988. // By default, label use itemName in charts.
  16989. // So we dont set encodeLabel here.
  16990. encodeSeriesName.push(nameDimIndex);
  16991. encodeItemName.push(nameDimIndex);
  16992. // encodeTooltip.push(firstNotOrdinal);
  16993. }
  16994. }
  16995. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16996. // encodeLabel.length && (encode.label = encodeLabel);
  16997. encodeItemName.length && (encode.itemName = encodeItemName);
  16998. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16999. return encode;
  17000. }
  17001. /**
  17002. * If return null/undefined, indicate that should not use datasetModel.
  17003. */
  17004. function getDatasetModel(seriesModel) {
  17005. var option = seriesModel.option;
  17006. // Caution: consider the scenario:
  17007. // A dataset is declared and a series is not expected to use the dataset,
  17008. // and at the beginning `setOption({series: { noData })` (just prepare other
  17009. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17010. // the user should set an empty array to avoid that dataset is used by default.
  17011. var thisData = option.data;
  17012. if (!thisData) {
  17013. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17014. }
  17015. }
  17016. /**
  17017. * The rule should not be complex, otherwise user might not
  17018. * be able to known where the data is wrong.
  17019. * The code is ugly, but how to make it neat?
  17020. *
  17021. * @param {module:echars/data/Source} source
  17022. * @param {number} dimIndex
  17023. * @return {boolean} Whether ordinal.
  17024. */
  17025. function guessOrdinal(source, dimIndex) {
  17026. return doGuessOrdinal(
  17027. source.data,
  17028. source.sourceFormat,
  17029. source.seriesLayoutBy,
  17030. source.dimensionsDefine,
  17031. source.startIndex,
  17032. dimIndex
  17033. );
  17034. }
  17035. // dimIndex may be overflow source data.
  17036. function doGuessOrdinal(
  17037. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17038. ) {
  17039. var result;
  17040. // Experience value.
  17041. var maxLoop = 5;
  17042. if (isTypedArray(data)) {
  17043. return false;
  17044. }
  17045. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17046. // always exists in source.
  17047. var dimName;
  17048. if (dimensionsDefine) {
  17049. dimName = dimensionsDefine[dimIndex];
  17050. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17051. }
  17052. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17053. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17054. var sample = data[dimIndex];
  17055. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17056. if ((result = detectValue(sample[startIndex + i])) != null) {
  17057. return result;
  17058. }
  17059. }
  17060. }
  17061. else {
  17062. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17063. var row = data[startIndex + i];
  17064. if (row && (result = detectValue(row[dimIndex])) != null) {
  17065. return result;
  17066. }
  17067. }
  17068. }
  17069. }
  17070. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17071. if (!dimName) {
  17072. return;
  17073. }
  17074. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17075. var item = data[i];
  17076. if (item && (result = detectValue(item[dimName])) != null) {
  17077. return result;
  17078. }
  17079. }
  17080. }
  17081. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17082. if (!dimName) {
  17083. return;
  17084. }
  17085. var sample = data[dimName];
  17086. if (!sample || isTypedArray(sample)) {
  17087. return false;
  17088. }
  17089. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17090. if ((result = detectValue(sample[i])) != null) {
  17091. return result;
  17092. }
  17093. }
  17094. }
  17095. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17096. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17097. var item = data[i];
  17098. var val = getDataItemValue(item);
  17099. if (!isArray(val)) {
  17100. return false;
  17101. }
  17102. if ((result = detectValue(val[dimIndex])) != null) {
  17103. return result;
  17104. }
  17105. }
  17106. }
  17107. function detectValue(val) {
  17108. // Consider usage convenience, '1', '2' will be treated as "number".
  17109. // `isFinit('')` get `true`.
  17110. if (val != null && isFinite(val) && val !== '') {
  17111. return false;
  17112. }
  17113. else if (isString(val) && val !== '-') {
  17114. return true;
  17115. }
  17116. }
  17117. return false;
  17118. }
  17119. /**
  17120. * ECharts global model
  17121. *
  17122. * @module {echarts/model/Global}
  17123. */
  17124. /**
  17125. * Caution: If the mechanism should be changed some day, these cases
  17126. * should be considered:
  17127. *
  17128. * (1) In `merge option` mode, if using the same option to call `setOption`
  17129. * many times, the result should be the same (try our best to ensure that).
  17130. * (2) In `merge option` mode, if a component has no id/name specified, it
  17131. * will be merged by index, and the result sequence of the components is
  17132. * consistent to the original sequence.
  17133. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17134. * `mergeOption` in module:echarts/model/OptionManager.
  17135. */
  17136. var OPTION_INNER_KEY = '\0_ec_inner';
  17137. /**
  17138. * @alias module:echarts/model/Global
  17139. *
  17140. * @param {Object} option
  17141. * @param {module:echarts/model/Model} parentModel
  17142. * @param {Object} theme
  17143. */
  17144. var GlobalModel = Model.extend({
  17145. constructor: GlobalModel,
  17146. init: function (option, parentModel, theme, optionManager) {
  17147. theme = theme || {};
  17148. this.option = null; // Mark as not initialized.
  17149. /**
  17150. * @type {module:echarts/model/Model}
  17151. * @private
  17152. */
  17153. this._theme = new Model(theme);
  17154. /**
  17155. * @type {module:echarts/model/OptionManager}
  17156. */
  17157. this._optionManager = optionManager;
  17158. },
  17159. setOption: function (option, optionPreprocessorFuncs) {
  17160. assert$1(
  17161. !(OPTION_INNER_KEY in option),
  17162. 'please use chart.getOption()'
  17163. );
  17164. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17165. this.resetOption(null);
  17166. },
  17167. /**
  17168. * @param {string} type null/undefined: reset all.
  17169. * 'recreate': force recreate all.
  17170. * 'timeline': only reset timeline option
  17171. * 'media': only reset media query option
  17172. * @return {boolean} Whether option changed.
  17173. */
  17174. resetOption: function (type) {
  17175. var optionChanged = false;
  17176. var optionManager = this._optionManager;
  17177. if (!type || type === 'recreate') {
  17178. var baseOption = optionManager.mountOption(type === 'recreate');
  17179. if (!this.option || type === 'recreate') {
  17180. initBase.call(this, baseOption);
  17181. }
  17182. else {
  17183. this.restoreData();
  17184. this.mergeOption(baseOption);
  17185. }
  17186. optionChanged = true;
  17187. }
  17188. if (type === 'timeline' || type === 'media') {
  17189. this.restoreData();
  17190. }
  17191. if (!type || type === 'recreate' || type === 'timeline') {
  17192. var timelineOption = optionManager.getTimelineOption(this);
  17193. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17194. }
  17195. if (!type || type === 'recreate' || type === 'media') {
  17196. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17197. if (mediaOptions.length) {
  17198. each$1(mediaOptions, function (mediaOption) {
  17199. this.mergeOption(mediaOption, optionChanged = true);
  17200. }, this);
  17201. }
  17202. }
  17203. return optionChanged;
  17204. },
  17205. /**
  17206. * @protected
  17207. */
  17208. mergeOption: function (newOption) {
  17209. var option = this.option;
  17210. var componentsMap = this._componentsMap;
  17211. var newCptTypes = [];
  17212. resetSourceDefaulter(this);
  17213. // If no component class, merge directly.
  17214. // For example: color, animaiton options, etc.
  17215. each$1(newOption, function (componentOption, mainType) {
  17216. if (componentOption == null) {
  17217. return;
  17218. }
  17219. if (!ComponentModel.hasClass(mainType)) {
  17220. // globalSettingTask.dirty();
  17221. option[mainType] = option[mainType] == null
  17222. ? clone(componentOption)
  17223. : merge(option[mainType], componentOption, true);
  17224. }
  17225. else if (mainType) {
  17226. newCptTypes.push(mainType);
  17227. }
  17228. });
  17229. ComponentModel.topologicalTravel(
  17230. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17231. );
  17232. function visitComponent(mainType, dependencies) {
  17233. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17234. var mapResult = mappingToExists(
  17235. componentsMap.get(mainType), newCptOptionList
  17236. );
  17237. makeIdAndName(mapResult);
  17238. // Set mainType and complete subType.
  17239. each$1(mapResult, function (item, index) {
  17240. var opt = item.option;
  17241. if (isObject$1(opt)) {
  17242. item.keyInfo.mainType = mainType;
  17243. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17244. }
  17245. });
  17246. var dependentModels = getComponentsByTypes(
  17247. componentsMap, dependencies
  17248. );
  17249. option[mainType] = [];
  17250. componentsMap.set(mainType, []);
  17251. each$1(mapResult, function (resultItem, index) {
  17252. var componentModel = resultItem.exist;
  17253. var newCptOption = resultItem.option;
  17254. assert$1(
  17255. isObject$1(newCptOption) || componentModel,
  17256. 'Empty component definition'
  17257. );
  17258. // Consider where is no new option and should be merged using {},
  17259. // see removeEdgeAndAdd in topologicalTravel and
  17260. // ComponentModel.getAllClassMainTypes.
  17261. if (!newCptOption) {
  17262. componentModel.mergeOption({}, this);
  17263. componentModel.optionUpdated({}, false);
  17264. }
  17265. else {
  17266. var ComponentModelClass = ComponentModel.getClass(
  17267. mainType, resultItem.keyInfo.subType, true
  17268. );
  17269. if (componentModel && componentModel instanceof ComponentModelClass) {
  17270. componentModel.name = resultItem.keyInfo.name;
  17271. // componentModel.settingTask && componentModel.settingTask.dirty();
  17272. componentModel.mergeOption(newCptOption, this);
  17273. componentModel.optionUpdated(newCptOption, false);
  17274. }
  17275. else {
  17276. // PENDING Global as parent ?
  17277. var extraOpt = extend(
  17278. {
  17279. dependentModels: dependentModels,
  17280. componentIndex: index
  17281. },
  17282. resultItem.keyInfo
  17283. );
  17284. componentModel = new ComponentModelClass(
  17285. newCptOption, this, this, extraOpt
  17286. );
  17287. extend(componentModel, extraOpt);
  17288. componentModel.init(newCptOption, this, this, extraOpt);
  17289. // Call optionUpdated after init.
  17290. // newCptOption has been used as componentModel.option
  17291. // and may be merged with theme and default, so pass null
  17292. // to avoid confusion.
  17293. componentModel.optionUpdated(null, true);
  17294. }
  17295. }
  17296. componentsMap.get(mainType)[index] = componentModel;
  17297. option[mainType][index] = componentModel.option;
  17298. }, this);
  17299. // Backup series for filtering.
  17300. if (mainType === 'series') {
  17301. createSeriesIndices(this, componentsMap.get('series'));
  17302. }
  17303. }
  17304. this._seriesIndicesMap = createHashMap(
  17305. this._seriesIndices = this._seriesIndices || []
  17306. );
  17307. },
  17308. /**
  17309. * Get option for output (cloned option and inner info removed)
  17310. * @public
  17311. * @return {Object}
  17312. */
  17313. getOption: function () {
  17314. var option = clone(this.option);
  17315. each$1(option, function (opts, mainType) {
  17316. if (ComponentModel.hasClass(mainType)) {
  17317. var opts = normalizeToArray(opts);
  17318. for (var i = opts.length - 1; i >= 0; i--) {
  17319. // Remove options with inner id.
  17320. if (isIdInner(opts[i])) {
  17321. opts.splice(i, 1);
  17322. }
  17323. }
  17324. option[mainType] = opts;
  17325. }
  17326. });
  17327. delete option[OPTION_INNER_KEY];
  17328. return option;
  17329. },
  17330. /**
  17331. * @return {module:echarts/model/Model}
  17332. */
  17333. getTheme: function () {
  17334. return this._theme;
  17335. },
  17336. /**
  17337. * @param {string} mainType
  17338. * @param {number} [idx=0]
  17339. * @return {module:echarts/model/Component}
  17340. */
  17341. getComponent: function (mainType, idx) {
  17342. var list = this._componentsMap.get(mainType);
  17343. if (list) {
  17344. return list[idx || 0];
  17345. }
  17346. },
  17347. /**
  17348. * If none of index and id and name used, return all components with mainType.
  17349. * @param {Object} condition
  17350. * @param {string} condition.mainType
  17351. * @param {string} [condition.subType] If ignore, only query by mainType
  17352. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17353. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17354. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17355. * @return {Array.<module:echarts/model/Component>}
  17356. */
  17357. queryComponents: function (condition) {
  17358. var mainType = condition.mainType;
  17359. if (!mainType) {
  17360. return [];
  17361. }
  17362. var index = condition.index;
  17363. var id = condition.id;
  17364. var name = condition.name;
  17365. var cpts = this._componentsMap.get(mainType);
  17366. if (!cpts || !cpts.length) {
  17367. return [];
  17368. }
  17369. var result;
  17370. if (index != null) {
  17371. if (!isArray(index)) {
  17372. index = [index];
  17373. }
  17374. result = filter(map(index, function (idx) {
  17375. return cpts[idx];
  17376. }), function (val) {
  17377. return !!val;
  17378. });
  17379. }
  17380. else if (id != null) {
  17381. var isIdArray = isArray(id);
  17382. result = filter(cpts, function (cpt) {
  17383. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17384. || (!isIdArray && cpt.id === id);
  17385. });
  17386. }
  17387. else if (name != null) {
  17388. var isNameArray = isArray(name);
  17389. result = filter(cpts, function (cpt) {
  17390. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17391. || (!isNameArray && cpt.name === name);
  17392. });
  17393. }
  17394. else {
  17395. // Return all components with mainType
  17396. result = cpts.slice();
  17397. }
  17398. return filterBySubType(result, condition);
  17399. },
  17400. /**
  17401. * The interface is different from queryComponents,
  17402. * which is convenient for inner usage.
  17403. *
  17404. * @usage
  17405. * var result = findComponents(
  17406. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17407. * );
  17408. * var result = findComponents(
  17409. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17410. * );
  17411. * var result = findComponents(
  17412. * {mainType: 'series'},
  17413. * function (model, index) {...}
  17414. * );
  17415. * // result like [component0, componnet1, ...]
  17416. *
  17417. * @param {Object} condition
  17418. * @param {string} condition.mainType Mandatory.
  17419. * @param {string} [condition.subType] Optional.
  17420. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17421. * where xxx is mainType.
  17422. * If query attribute is null/undefined or has no index/id/name,
  17423. * do not filtering by query conditions, which is convenient for
  17424. * no-payload situations or when target of action is global.
  17425. * @param {Function} [condition.filter] parameter: component, return boolean.
  17426. * @return {Array.<module:echarts/model/Component>}
  17427. */
  17428. findComponents: function (condition) {
  17429. var query = condition.query;
  17430. var mainType = condition.mainType;
  17431. var queryCond = getQueryCond(query);
  17432. var result = queryCond
  17433. ? this.queryComponents(queryCond)
  17434. : this._componentsMap.get(mainType);
  17435. return doFilter(filterBySubType(result, condition));
  17436. function getQueryCond(q) {
  17437. var indexAttr = mainType + 'Index';
  17438. var idAttr = mainType + 'Id';
  17439. var nameAttr = mainType + 'Name';
  17440. return q && (
  17441. q[indexAttr] != null
  17442. || q[idAttr] != null
  17443. || q[nameAttr] != null
  17444. )
  17445. ? {
  17446. mainType: mainType,
  17447. // subType will be filtered finally.
  17448. index: q[indexAttr],
  17449. id: q[idAttr],
  17450. name: q[nameAttr]
  17451. }
  17452. : null;
  17453. }
  17454. function doFilter(res) {
  17455. return condition.filter
  17456. ? filter(res, condition.filter)
  17457. : res;
  17458. }
  17459. },
  17460. /**
  17461. * @usage
  17462. * eachComponent('legend', function (legendModel, index) {
  17463. * ...
  17464. * });
  17465. * eachComponent(function (componentType, model, index) {
  17466. * // componentType does not include subType
  17467. * // (componentType is 'xxx' but not 'xxx.aa')
  17468. * });
  17469. * eachComponent(
  17470. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17471. * function (model, index) {...}
  17472. * );
  17473. * eachComponent(
  17474. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17475. * function (model, index) {...}
  17476. * );
  17477. *
  17478. * @param {string|Object=} mainType When mainType is object, the definition
  17479. * is the same as the method 'findComponents'.
  17480. * @param {Function} cb
  17481. * @param {*} context
  17482. */
  17483. eachComponent: function (mainType, cb, context) {
  17484. var componentsMap = this._componentsMap;
  17485. if (typeof mainType === 'function') {
  17486. context = cb;
  17487. cb = mainType;
  17488. componentsMap.each(function (components, componentType) {
  17489. each$1(components, function (component, index) {
  17490. cb.call(context, componentType, component, index);
  17491. });
  17492. });
  17493. }
  17494. else if (isString(mainType)) {
  17495. each$1(componentsMap.get(mainType), cb, context);
  17496. }
  17497. else if (isObject$1(mainType)) {
  17498. var queryResult = this.findComponents(mainType);
  17499. each$1(queryResult, cb, context);
  17500. }
  17501. },
  17502. /**
  17503. * @param {string} name
  17504. * @return {Array.<module:echarts/model/Series>}
  17505. */
  17506. getSeriesByName: function (name) {
  17507. var series = this._componentsMap.get('series');
  17508. return filter(series, function (oneSeries) {
  17509. return oneSeries.name === name;
  17510. });
  17511. },
  17512. /**
  17513. * @param {number} seriesIndex
  17514. * @return {module:echarts/model/Series}
  17515. */
  17516. getSeriesByIndex: function (seriesIndex) {
  17517. return this._componentsMap.get('series')[seriesIndex];
  17518. },
  17519. /**
  17520. * Get series list before filtered by type.
  17521. * FIXME: rename to getRawSeriesByType?
  17522. *
  17523. * @param {string} subType
  17524. * @return {Array.<module:echarts/model/Series>}
  17525. */
  17526. getSeriesByType: function (subType) {
  17527. var series = this._componentsMap.get('series');
  17528. return filter(series, function (oneSeries) {
  17529. return oneSeries.subType === subType;
  17530. });
  17531. },
  17532. /**
  17533. * @return {Array.<module:echarts/model/Series>}
  17534. */
  17535. getSeries: function () {
  17536. return this._componentsMap.get('series').slice();
  17537. },
  17538. /**
  17539. * @return {number}
  17540. */
  17541. getSeriesCount: function () {
  17542. return this._componentsMap.get('series').length;
  17543. },
  17544. /**
  17545. * After filtering, series may be different
  17546. * frome raw series.
  17547. *
  17548. * @param {Function} cb
  17549. * @param {*} context
  17550. */
  17551. eachSeries: function (cb, context) {
  17552. assertSeriesInitialized(this);
  17553. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17554. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17555. cb.call(context, series, rawSeriesIndex);
  17556. }, this);
  17557. },
  17558. /**
  17559. * Iterate raw series before filtered.
  17560. *
  17561. * @param {Function} cb
  17562. * @param {*} context
  17563. */
  17564. eachRawSeries: function (cb, context) {
  17565. each$1(this._componentsMap.get('series'), cb, context);
  17566. },
  17567. /**
  17568. * After filtering, series may be different.
  17569. * frome raw series.
  17570. *
  17571. * @parma {string} subType
  17572. * @param {Function} cb
  17573. * @param {*} context
  17574. */
  17575. eachSeriesByType: function (subType, cb, context) {
  17576. assertSeriesInitialized(this);
  17577. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17578. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17579. if (series.subType === subType) {
  17580. cb.call(context, series, rawSeriesIndex);
  17581. }
  17582. }, this);
  17583. },
  17584. /**
  17585. * Iterate raw series before filtered of given type.
  17586. *
  17587. * @parma {string} subType
  17588. * @param {Function} cb
  17589. * @param {*} context
  17590. */
  17591. eachRawSeriesByType: function (subType, cb, context) {
  17592. return each$1(this.getSeriesByType(subType), cb, context);
  17593. },
  17594. /**
  17595. * @param {module:echarts/model/Series} seriesModel
  17596. */
  17597. isSeriesFiltered: function (seriesModel) {
  17598. assertSeriesInitialized(this);
  17599. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17600. },
  17601. /**
  17602. * @return {Array.<number>}
  17603. */
  17604. getCurrentSeriesIndices: function () {
  17605. return (this._seriesIndices || []).slice();
  17606. },
  17607. /**
  17608. * @param {Function} cb
  17609. * @param {*} context
  17610. */
  17611. filterSeries: function (cb, context) {
  17612. assertSeriesInitialized(this);
  17613. var filteredSeries = filter(
  17614. this._componentsMap.get('series'), cb, context
  17615. );
  17616. createSeriesIndices(this, filteredSeries);
  17617. },
  17618. restoreData: function (payload) {
  17619. var componentsMap = this._componentsMap;
  17620. createSeriesIndices(this, componentsMap.get('series'));
  17621. var componentTypes = [];
  17622. componentsMap.each(function (components, componentType) {
  17623. componentTypes.push(componentType);
  17624. });
  17625. ComponentModel.topologicalTravel(
  17626. componentTypes,
  17627. ComponentModel.getAllClassMainTypes(),
  17628. function (componentType, dependencies) {
  17629. each$1(componentsMap.get(componentType), function (component) {
  17630. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  17631. && component.restoreData();
  17632. });
  17633. }
  17634. );
  17635. }
  17636. });
  17637. function isNotTargetSeries(seriesModel, payload) {
  17638. if (payload) {
  17639. var index = payload.seiresIndex;
  17640. var id = payload.seriesId;
  17641. var name = payload.seriesName;
  17642. return (index != null && seriesModel.componentIndex !== index)
  17643. || (id != null && seriesModel.id !== id)
  17644. || (name != null && seriesModel.name !== name);
  17645. }
  17646. }
  17647. /**
  17648. * @inner
  17649. */
  17650. function mergeTheme(option, theme) {
  17651. // PENDING
  17652. // NOT use `colorLayer` in theme if option has `color`
  17653. var notMergeColorLayer = option.color && !option.colorLayer;
  17654. each$1(theme, function (themeItem, name) {
  17655. if (name === 'colorLayer' && notMergeColorLayer) {
  17656. return;
  17657. }
  17658. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  17659. if (!ComponentModel.hasClass(name)) {
  17660. if (typeof themeItem === 'object') {
  17661. option[name] = !option[name]
  17662. ? clone(themeItem)
  17663. : merge(option[name], themeItem, false);
  17664. }
  17665. else {
  17666. if (option[name] == null) {
  17667. option[name] = themeItem;
  17668. }
  17669. }
  17670. }
  17671. });
  17672. }
  17673. function initBase(baseOption) {
  17674. baseOption = baseOption;
  17675. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17676. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17677. this.option = {};
  17678. this.option[OPTION_INNER_KEY] = 1;
  17679. /**
  17680. * Init with series: [], in case of calling findSeries method
  17681. * before series initialized.
  17682. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17683. * @private
  17684. */
  17685. this._componentsMap = createHashMap({series: []});
  17686. /**
  17687. * Mapping between filtered series list and raw series list.
  17688. * key: filtered series indices, value: raw series indices.
  17689. * @type {Array.<nubmer>}
  17690. * @private
  17691. */
  17692. this._seriesIndices;
  17693. this._seriesIndicesMap;
  17694. mergeTheme(baseOption, this._theme.option);
  17695. // TODO Needs clone when merging to the unexisted property
  17696. merge(baseOption, globalDefault, false);
  17697. this.mergeOption(baseOption);
  17698. }
  17699. /**
  17700. * @inner
  17701. * @param {Array.<string>|string} types model types
  17702. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17703. */
  17704. function getComponentsByTypes(componentsMap, types) {
  17705. if (!isArray(types)) {
  17706. types = types ? [types] : [];
  17707. }
  17708. var ret = {};
  17709. each$1(types, function (type) {
  17710. ret[type] = (componentsMap.get(type) || []).slice();
  17711. });
  17712. return ret;
  17713. }
  17714. /**
  17715. * @inner
  17716. */
  17717. function determineSubType(mainType, newCptOption, existComponent) {
  17718. var subType = newCptOption.type
  17719. ? newCptOption.type
  17720. : existComponent
  17721. ? existComponent.subType
  17722. // Use determineSubType only when there is no existComponent.
  17723. : ComponentModel.determineSubType(mainType, newCptOption);
  17724. // tooltip, markline, markpoint may always has no subType
  17725. return subType;
  17726. }
  17727. /**
  17728. * @inner
  17729. */
  17730. function createSeriesIndices(ecModel, seriesModels) {
  17731. ecModel._seriesIndicesMap = createHashMap(
  17732. ecModel._seriesIndices = map(seriesModels, function (series) {
  17733. return series.componentIndex;
  17734. }) || []
  17735. );
  17736. }
  17737. /**
  17738. * @inner
  17739. */
  17740. function filterBySubType(components, condition) {
  17741. // Using hasOwnProperty for restrict. Consider
  17742. // subType is undefined in user payload.
  17743. return condition.hasOwnProperty('subType')
  17744. ? filter(components, function (cpt) {
  17745. return cpt.subType === condition.subType;
  17746. })
  17747. : components;
  17748. }
  17749. /**
  17750. * @inner
  17751. */
  17752. function assertSeriesInitialized(ecModel) {
  17753. // Components that use _seriesIndices should depends on series component,
  17754. // which make sure that their initialization is after series.
  17755. if (__DEV__) {
  17756. if (!ecModel._seriesIndices) {
  17757. throw new Error('Option should contains series.');
  17758. }
  17759. }
  17760. }
  17761. mixin(GlobalModel, colorPaletteMixin);
  17762. var echartsAPIList = [
  17763. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17764. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17765. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17766. ];
  17767. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17768. function ExtensionAPI(chartInstance) {
  17769. each$1(echartsAPIList, function (name) {
  17770. this[name] = bind(chartInstance[name], chartInstance);
  17771. }, this);
  17772. }
  17773. var coordinateSystemCreators = {};
  17774. function CoordinateSystemManager() {
  17775. this._coordinateSystems = [];
  17776. }
  17777. CoordinateSystemManager.prototype = {
  17778. constructor: CoordinateSystemManager,
  17779. create: function (ecModel, api) {
  17780. var coordinateSystems = [];
  17781. each$1(coordinateSystemCreators, function (creater, type) {
  17782. var list = creater.create(ecModel, api);
  17783. coordinateSystems = coordinateSystems.concat(list || []);
  17784. });
  17785. this._coordinateSystems = coordinateSystems;
  17786. },
  17787. update: function (ecModel, api) {
  17788. each$1(this._coordinateSystems, function (coordSys) {
  17789. coordSys.update && coordSys.update(ecModel, api);
  17790. });
  17791. },
  17792. getCoordinateSystems: function () {
  17793. return this._coordinateSystems.slice();
  17794. }
  17795. };
  17796. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17797. coordinateSystemCreators[type] = coordinateSystemCreator;
  17798. };
  17799. CoordinateSystemManager.get = function (type) {
  17800. return coordinateSystemCreators[type];
  17801. };
  17802. /**
  17803. * ECharts option manager
  17804. *
  17805. * @module {echarts/model/OptionManager}
  17806. */
  17807. var each$4 = each$1;
  17808. var clone$3 = clone;
  17809. var map$1 = map;
  17810. var merge$1 = merge;
  17811. var QUERY_REG = /^(min|max)?(.+)$/;
  17812. /**
  17813. * TERM EXPLANATIONS:
  17814. *
  17815. * [option]:
  17816. *
  17817. * An object that contains definitions of components. For example:
  17818. * var option = {
  17819. * title: {...},
  17820. * legend: {...},
  17821. * visualMap: {...},
  17822. * series: [
  17823. * {data: [...]},
  17824. * {data: [...]},
  17825. * ...
  17826. * ]
  17827. * };
  17828. *
  17829. * [rawOption]:
  17830. *
  17831. * An object input to echarts.setOption. 'rawOption' may be an
  17832. * 'option', or may be an object contains multi-options. For example:
  17833. * var option = {
  17834. * baseOption: {
  17835. * title: {...},
  17836. * legend: {...},
  17837. * series: [
  17838. * {data: [...]},
  17839. * {data: [...]},
  17840. * ...
  17841. * ]
  17842. * },
  17843. * timeline: {...},
  17844. * options: [
  17845. * {title: {...}, series: {data: [...]}},
  17846. * {title: {...}, series: {data: [...]}},
  17847. * ...
  17848. * ],
  17849. * media: [
  17850. * {
  17851. * query: {maxWidth: 320},
  17852. * option: {series: {x: 20}, visualMap: {show: false}}
  17853. * },
  17854. * {
  17855. * query: {minWidth: 320, maxWidth: 720},
  17856. * option: {series: {x: 500}, visualMap: {show: true}}
  17857. * },
  17858. * {
  17859. * option: {series: {x: 1200}, visualMap: {show: true}}
  17860. * }
  17861. * ]
  17862. * };
  17863. *
  17864. * @alias module:echarts/model/OptionManager
  17865. * @param {module:echarts/ExtensionAPI} api
  17866. */
  17867. function OptionManager(api) {
  17868. /**
  17869. * @private
  17870. * @type {module:echarts/ExtensionAPI}
  17871. */
  17872. this._api = api;
  17873. /**
  17874. * @private
  17875. * @type {Array.<number>}
  17876. */
  17877. this._timelineOptions = [];
  17878. /**
  17879. * @private
  17880. * @type {Array.<Object>}
  17881. */
  17882. this._mediaList = [];
  17883. /**
  17884. * @private
  17885. * @type {Object}
  17886. */
  17887. this._mediaDefault;
  17888. /**
  17889. * -1, means default.
  17890. * empty means no media.
  17891. * @private
  17892. * @type {Array.<number>}
  17893. */
  17894. this._currentMediaIndices = [];
  17895. /**
  17896. * @private
  17897. * @type {Object}
  17898. */
  17899. this._optionBackup;
  17900. /**
  17901. * @private
  17902. * @type {Object}
  17903. */
  17904. this._newBaseOption;
  17905. }
  17906. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17907. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17908. // rawOption cloned and backuped when timeline changed, which does no
  17909. // good to performance. What's more, that both timeline and setOption
  17910. // method supply 'notMerge' brings complex and some problems.
  17911. // Consider this case:
  17912. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17913. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17914. OptionManager.prototype = {
  17915. constructor: OptionManager,
  17916. /**
  17917. * @public
  17918. * @param {Object} rawOption Raw option.
  17919. * @param {module:echarts/model/Global} ecModel
  17920. * @param {Array.<Function>} optionPreprocessorFuncs
  17921. * @return {Object} Init option
  17922. */
  17923. setOption: function (rawOption, optionPreprocessorFuncs) {
  17924. if (rawOption) {
  17925. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17926. each$1(normalizeToArray(rawOption.series), function (series) {
  17927. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17928. });
  17929. }
  17930. // Caution: some series modify option data, if do not clone,
  17931. // it should ensure that the repeat modify correctly
  17932. // (create a new object when modify itself).
  17933. rawOption = clone$3(rawOption, true);
  17934. // FIXME
  17935. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17936. var oldOptionBackup = this._optionBackup;
  17937. var newParsedOption = parseRawOption.call(
  17938. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17939. );
  17940. this._newBaseOption = newParsedOption.baseOption;
  17941. // For setOption at second time (using merge mode);
  17942. if (oldOptionBackup) {
  17943. // Only baseOption can be merged.
  17944. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17945. // For simplicity, timeline options and media options do not support merge,
  17946. // that is, if you `setOption` twice and both has timeline options, the latter
  17947. // timeline opitons will not be merged to the formers, but just substitude them.
  17948. if (newParsedOption.timelineOptions.length) {
  17949. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17950. }
  17951. if (newParsedOption.mediaList.length) {
  17952. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17953. }
  17954. if (newParsedOption.mediaDefault) {
  17955. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17956. }
  17957. }
  17958. else {
  17959. this._optionBackup = newParsedOption;
  17960. }
  17961. },
  17962. /**
  17963. * @param {boolean} isRecreate
  17964. * @return {Object}
  17965. */
  17966. mountOption: function (isRecreate) {
  17967. var optionBackup = this._optionBackup;
  17968. // TODO
  17969. // 如果没有reset功能则不clone。
  17970. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17971. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17972. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17973. this._currentMediaIndices = [];
  17974. return clone$3(isRecreate
  17975. // this._optionBackup.baseOption, which is created at the first `setOption`
  17976. // called, and is merged into every new option by inner method `mergeOption`
  17977. // each time `setOption` called, can be only used in `isRecreate`, because
  17978. // its reliability is under suspicion. In other cases option merge is
  17979. // performed by `model.mergeOption`.
  17980. ? optionBackup.baseOption : this._newBaseOption
  17981. );
  17982. },
  17983. /**
  17984. * @param {module:echarts/model/Global} ecModel
  17985. * @return {Object}
  17986. */
  17987. getTimelineOption: function (ecModel) {
  17988. var option;
  17989. var timelineOptions = this._timelineOptions;
  17990. if (timelineOptions.length) {
  17991. // getTimelineOption can only be called after ecModel inited,
  17992. // so we can get currentIndex from timelineModel.
  17993. var timelineModel = ecModel.getComponent('timeline');
  17994. if (timelineModel) {
  17995. option = clone$3(
  17996. timelineOptions[timelineModel.getCurrentIndex()],
  17997. true
  17998. );
  17999. }
  18000. }
  18001. return option;
  18002. },
  18003. /**
  18004. * @param {module:echarts/model/Global} ecModel
  18005. * @return {Array.<Object>}
  18006. */
  18007. getMediaOption: function (ecModel) {
  18008. var ecWidth = this._api.getWidth();
  18009. var ecHeight = this._api.getHeight();
  18010. var mediaList = this._mediaList;
  18011. var mediaDefault = this._mediaDefault;
  18012. var indices = [];
  18013. var result = [];
  18014. // No media defined.
  18015. if (!mediaList.length && !mediaDefault) {
  18016. return result;
  18017. }
  18018. // Multi media may be applied, the latter defined media has higher priority.
  18019. for (var i = 0, len = mediaList.length; i < len; i++) {
  18020. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18021. indices.push(i);
  18022. }
  18023. }
  18024. // FIXME
  18025. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18026. if (!indices.length && mediaDefault) {
  18027. indices = [-1];
  18028. }
  18029. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18030. result = map$1(indices, function (index) {
  18031. return clone$3(
  18032. index === -1 ? mediaDefault.option : mediaList[index].option
  18033. );
  18034. });
  18035. }
  18036. // Otherwise return nothing.
  18037. this._currentMediaIndices = indices;
  18038. return result;
  18039. }
  18040. };
  18041. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18042. var timelineOptions = [];
  18043. var mediaList = [];
  18044. var mediaDefault;
  18045. var baseOption;
  18046. // Compatible with ec2.
  18047. var timelineOpt = rawOption.timeline;
  18048. if (rawOption.baseOption) {
  18049. baseOption = rawOption.baseOption;
  18050. }
  18051. // For timeline
  18052. if (timelineOpt || rawOption.options) {
  18053. baseOption = baseOption || {};
  18054. timelineOptions = (rawOption.options || []).slice();
  18055. }
  18056. // For media query
  18057. if (rawOption.media) {
  18058. baseOption = baseOption || {};
  18059. var media = rawOption.media;
  18060. each$4(media, function (singleMedia) {
  18061. if (singleMedia && singleMedia.option) {
  18062. if (singleMedia.query) {
  18063. mediaList.push(singleMedia);
  18064. }
  18065. else if (!mediaDefault) {
  18066. // Use the first media default.
  18067. mediaDefault = singleMedia;
  18068. }
  18069. }
  18070. });
  18071. }
  18072. // For normal option
  18073. if (!baseOption) {
  18074. baseOption = rawOption;
  18075. }
  18076. // Set timelineOpt to baseOption in ec3,
  18077. // which is convenient for merge option.
  18078. if (!baseOption.timeline) {
  18079. baseOption.timeline = timelineOpt;
  18080. }
  18081. // Preprocess.
  18082. each$4([baseOption].concat(timelineOptions)
  18083. .concat(map(mediaList, function (media) {
  18084. return media.option;
  18085. })),
  18086. function (option) {
  18087. each$4(optionPreprocessorFuncs, function (preProcess) {
  18088. preProcess(option, isNew);
  18089. });
  18090. }
  18091. );
  18092. return {
  18093. baseOption: baseOption,
  18094. timelineOptions: timelineOptions,
  18095. mediaDefault: mediaDefault,
  18096. mediaList: mediaList
  18097. };
  18098. }
  18099. /**
  18100. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18101. * Support: width, height, aspectRatio
  18102. * Can use max or min as prefix.
  18103. */
  18104. function applyMediaQuery(query, ecWidth, ecHeight) {
  18105. var realMap = {
  18106. width: ecWidth,
  18107. height: ecHeight,
  18108. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18109. };
  18110. var applicatable = true;
  18111. each$1(query, function (value, attr) {
  18112. var matched = attr.match(QUERY_REG);
  18113. if (!matched || !matched[1] || !matched[2]) {
  18114. return;
  18115. }
  18116. var operator = matched[1];
  18117. var realAttr = matched[2].toLowerCase();
  18118. if (!compare(realMap[realAttr], value, operator)) {
  18119. applicatable = false;
  18120. }
  18121. });
  18122. return applicatable;
  18123. }
  18124. function compare(real, expect, operator) {
  18125. if (operator === 'min') {
  18126. return real >= expect;
  18127. }
  18128. else if (operator === 'max') {
  18129. return real <= expect;
  18130. }
  18131. else { // Equals
  18132. return real === expect;
  18133. }
  18134. }
  18135. function indicesEquals(indices1, indices2) {
  18136. // indices is always order by asc and has only finite number.
  18137. return indices1.join(',') === indices2.join(',');
  18138. }
  18139. /**
  18140. * Consider case:
  18141. * `chart.setOption(opt1);`
  18142. * Then user do some interaction like dataZoom, dataView changing.
  18143. * `chart.setOption(opt2);`
  18144. * Then user press 'reset button' in toolbox.
  18145. *
  18146. * After doing that all of the interaction effects should be reset, the
  18147. * chart should be the same as the result of invoke
  18148. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18149. *
  18150. * Although it is not able ensure that
  18151. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18152. * `chart.setOption(merge(opt1, opt2));` exactly,
  18153. * this might be the only simple way to implement that feature.
  18154. *
  18155. * MEMO: We've considered some other approaches:
  18156. * 1. Each model handle its self restoration but not uniform treatment.
  18157. * (Too complex in logic and error-prone)
  18158. * 2. Use a shadow ecModel. (Performace expensive)
  18159. */
  18160. function mergeOption(oldOption, newOption) {
  18161. newOption = newOption || {};
  18162. each$4(newOption, function (newCptOpt, mainType) {
  18163. if (newCptOpt == null) {
  18164. return;
  18165. }
  18166. var oldCptOpt = oldOption[mainType];
  18167. if (!ComponentModel.hasClass(mainType)) {
  18168. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18169. }
  18170. else {
  18171. newCptOpt = normalizeToArray(newCptOpt);
  18172. oldCptOpt = normalizeToArray(oldCptOpt);
  18173. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18174. oldOption[mainType] = map$1(mapResult, function (item) {
  18175. return (item.option && item.exist)
  18176. ? merge$1(item.exist, item.option, true)
  18177. : (item.exist || item.option);
  18178. });
  18179. }
  18180. });
  18181. }
  18182. var each$5 = each$1;
  18183. var isObject$3 = isObject$1;
  18184. var POSSIBLE_STYLES = [
  18185. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18186. 'chordStyle', 'label', 'labelLine'
  18187. ];
  18188. function compatEC2ItemStyle(opt) {
  18189. var itemStyleOpt = opt && opt.itemStyle;
  18190. if (!itemStyleOpt) {
  18191. return;
  18192. }
  18193. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18194. var styleName = POSSIBLE_STYLES[i];
  18195. var normalItemStyleOpt = itemStyleOpt.normal;
  18196. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18197. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18198. opt[styleName] = opt[styleName] || {};
  18199. if (!opt[styleName].normal) {
  18200. opt[styleName].normal = normalItemStyleOpt[styleName];
  18201. }
  18202. else {
  18203. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18204. }
  18205. normalItemStyleOpt[styleName] = null;
  18206. }
  18207. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18208. opt[styleName] = opt[styleName] || {};
  18209. if (!opt[styleName].emphasis) {
  18210. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18211. }
  18212. else {
  18213. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18214. }
  18215. emphasisItemStyleOpt[styleName] = null;
  18216. }
  18217. }
  18218. }
  18219. function convertNormalEmphasis(opt, optType, useExtend) {
  18220. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18221. var normalOpt = opt[optType].normal;
  18222. var emphasisOpt = opt[optType].emphasis;
  18223. if (normalOpt) {
  18224. // Timeline controlStyle has other properties besides normal and emphasis
  18225. if (useExtend) {
  18226. opt[optType].normal = opt[optType].emphasis = null;
  18227. defaults(opt[optType], normalOpt);
  18228. }
  18229. else {
  18230. opt[optType] = normalOpt;
  18231. }
  18232. }
  18233. if (emphasisOpt) {
  18234. opt.emphasis = opt.emphasis || {};
  18235. opt.emphasis[optType] = emphasisOpt;
  18236. }
  18237. }
  18238. }
  18239. function removeEC3NormalStatus(opt) {
  18240. convertNormalEmphasis(opt, 'itemStyle');
  18241. convertNormalEmphasis(opt, 'lineStyle');
  18242. convertNormalEmphasis(opt, 'areaStyle');
  18243. convertNormalEmphasis(opt, 'label');
  18244. convertNormalEmphasis(opt, 'labelLine');
  18245. // treemap
  18246. convertNormalEmphasis(opt, 'upperLabel');
  18247. // graph
  18248. convertNormalEmphasis(opt, 'edgeLabel');
  18249. }
  18250. function compatTextStyle(opt, propName) {
  18251. // Check whether is not object (string\null\undefined ...)
  18252. var labelOptSingle = isObject$3(opt) && opt[propName];
  18253. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18254. if (textStyle) {
  18255. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18256. var propName = TEXT_STYLE_OPTIONS[i];
  18257. if (textStyle.hasOwnProperty(propName)) {
  18258. labelOptSingle[propName] = textStyle[propName];
  18259. }
  18260. }
  18261. }
  18262. }
  18263. function compatEC3CommonStyles(opt) {
  18264. if (opt) {
  18265. removeEC3NormalStatus(opt);
  18266. compatTextStyle(opt, 'label');
  18267. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18268. }
  18269. }
  18270. function processSeries(seriesOpt) {
  18271. if (!isObject$3(seriesOpt)) {
  18272. return;
  18273. }
  18274. compatEC2ItemStyle(seriesOpt);
  18275. removeEC3NormalStatus(seriesOpt);
  18276. compatTextStyle(seriesOpt, 'label');
  18277. // treemap
  18278. compatTextStyle(seriesOpt, 'upperLabel');
  18279. // graph
  18280. compatTextStyle(seriesOpt, 'edgeLabel');
  18281. if (seriesOpt.emphasis) {
  18282. compatTextStyle(seriesOpt.emphasis, 'label');
  18283. // treemap
  18284. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18285. // graph
  18286. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18287. }
  18288. var markPoint = seriesOpt.markPoint;
  18289. if (markPoint) {
  18290. compatEC2ItemStyle(markPoint);
  18291. compatEC3CommonStyles(markPoint);
  18292. }
  18293. var markLine = seriesOpt.markLine;
  18294. if (markLine) {
  18295. compatEC2ItemStyle(markLine);
  18296. compatEC3CommonStyles(markLine);
  18297. }
  18298. var markArea = seriesOpt.markArea;
  18299. if (markArea) {
  18300. compatEC3CommonStyles(markArea);
  18301. }
  18302. var data = seriesOpt.data;
  18303. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18304. // then the backward compat based on option type will not be performed.
  18305. if (seriesOpt.type === 'graph') {
  18306. data = data || seriesOpt.nodes;
  18307. var edgeData = seriesOpt.links || seriesOpt.edges;
  18308. if (edgeData && !isTypedArray(edgeData)) {
  18309. for (var i = 0; i < edgeData.length; i++) {
  18310. compatEC3CommonStyles(edgeData[i]);
  18311. }
  18312. }
  18313. each$1(seriesOpt.categories, function (opt) {
  18314. removeEC3NormalStatus(opt);
  18315. });
  18316. }
  18317. if (data && !isTypedArray(data)) {
  18318. for (var i = 0; i < data.length; i++) {
  18319. compatEC3CommonStyles(data[i]);
  18320. }
  18321. }
  18322. // mark point data
  18323. var markPoint = seriesOpt.markPoint;
  18324. if (markPoint && markPoint.data) {
  18325. var mpData = markPoint.data;
  18326. for (var i = 0; i < mpData.length; i++) {
  18327. compatEC3CommonStyles(mpData[i]);
  18328. }
  18329. }
  18330. // mark line data
  18331. var markLine = seriesOpt.markLine;
  18332. if (markLine && markLine.data) {
  18333. var mlData = markLine.data;
  18334. for (var i = 0; i < mlData.length; i++) {
  18335. if (isArray(mlData[i])) {
  18336. compatEC3CommonStyles(mlData[i][0]);
  18337. compatEC3CommonStyles(mlData[i][1]);
  18338. }
  18339. else {
  18340. compatEC3CommonStyles(mlData[i]);
  18341. }
  18342. }
  18343. }
  18344. // Series
  18345. if (seriesOpt.type === 'gauge') {
  18346. compatTextStyle(seriesOpt, 'axisLabel');
  18347. compatTextStyle(seriesOpt, 'title');
  18348. compatTextStyle(seriesOpt, 'detail');
  18349. }
  18350. else if (seriesOpt.type === 'treemap') {
  18351. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18352. each$1(seriesOpt.levels, function (opt) {
  18353. removeEC3NormalStatus(opt);
  18354. });
  18355. }
  18356. // sunburst starts from ec4, so it does not need to compat levels.
  18357. }
  18358. function toArr(o) {
  18359. return isArray(o) ? o : o ? [o] : [];
  18360. }
  18361. function toObj(o) {
  18362. return (isArray(o) ? o[0] : o) || {};
  18363. }
  18364. var compatStyle = function (option, isTheme) {
  18365. each$5(toArr(option.series), function (seriesOpt) {
  18366. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18367. });
  18368. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18369. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18370. each$5(
  18371. axes,
  18372. function (axisName) {
  18373. each$5(toArr(option[axisName]), function (axisOpt) {
  18374. if (axisOpt) {
  18375. compatTextStyle(axisOpt, 'axisLabel');
  18376. compatTextStyle(axisOpt.axisPointer, 'label');
  18377. }
  18378. });
  18379. }
  18380. );
  18381. each$5(toArr(option.parallel), function (parallelOpt) {
  18382. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18383. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18384. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18385. });
  18386. each$5(toArr(option.calendar), function (calendarOpt) {
  18387. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18388. compatTextStyle(calendarOpt, 'dayLabel');
  18389. compatTextStyle(calendarOpt, 'monthLabel');
  18390. compatTextStyle(calendarOpt, 'yearLabel');
  18391. });
  18392. // radar.name.textStyle
  18393. each$5(toArr(option.radar), function (radarOpt) {
  18394. compatTextStyle(radarOpt, 'name');
  18395. });
  18396. each$5(toArr(option.geo), function (geoOpt) {
  18397. if (isObject$3(geoOpt)) {
  18398. compatEC3CommonStyles(geoOpt);
  18399. each$5(toArr(geoOpt.regions), function (regionObj) {
  18400. compatEC3CommonStyles(regionObj);
  18401. });
  18402. }
  18403. });
  18404. each$5(toArr(option.timeline), function (timelineOpt) {
  18405. compatEC3CommonStyles(timelineOpt);
  18406. convertNormalEmphasis(timelineOpt, 'label');
  18407. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18408. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18409. var data = timelineOpt.data;
  18410. isArray(data) && each$1(data, function (item) {
  18411. if (isObject$1(item)) {
  18412. convertNormalEmphasis(item, 'label');
  18413. convertNormalEmphasis(item, 'itemStyle');
  18414. }
  18415. });
  18416. });
  18417. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18418. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18419. each$5(toolboxOpt.feature, function (featureOpt) {
  18420. convertNormalEmphasis(featureOpt, 'iconStyle');
  18421. });
  18422. });
  18423. compatTextStyle(toObj(option.axisPointer), 'label');
  18424. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18425. };
  18426. // Compatitable with 2.0
  18427. function get(opt, path) {
  18428. path = path.split(',');
  18429. var obj = opt;
  18430. for (var i = 0; i < path.length; i++) {
  18431. obj = obj && obj[path[i]];
  18432. if (obj == null) {
  18433. break;
  18434. }
  18435. }
  18436. return obj;
  18437. }
  18438. function set$1(opt, path, val, overwrite) {
  18439. path = path.split(',');
  18440. var obj = opt;
  18441. var key;
  18442. for (var i = 0; i < path.length - 1; i++) {
  18443. key = path[i];
  18444. if (obj[key] == null) {
  18445. obj[key] = {};
  18446. }
  18447. obj = obj[key];
  18448. }
  18449. if (overwrite || obj[path[i]] == null) {
  18450. obj[path[i]] = val;
  18451. }
  18452. }
  18453. function compatLayoutProperties(option) {
  18454. each$1(LAYOUT_PROPERTIES, function (prop) {
  18455. if (prop[0] in option && !(prop[1] in option)) {
  18456. option[prop[1]] = option[prop[0]];
  18457. }
  18458. });
  18459. }
  18460. var LAYOUT_PROPERTIES = [
  18461. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18462. ];
  18463. var COMPATITABLE_COMPONENTS = [
  18464. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18465. ];
  18466. var backwardCompat = function (option, isTheme) {
  18467. compatStyle(option, isTheme);
  18468. // Make sure series array for model initialization.
  18469. option.series = normalizeToArray(option.series);
  18470. each$1(option.series, function (seriesOpt) {
  18471. if (!isObject$1(seriesOpt)) {
  18472. return;
  18473. }
  18474. var seriesType = seriesOpt.type;
  18475. if (seriesType === 'pie' || seriesType === 'gauge') {
  18476. if (seriesOpt.clockWise != null) {
  18477. seriesOpt.clockwise = seriesOpt.clockWise;
  18478. }
  18479. }
  18480. if (seriesType === 'gauge') {
  18481. var pointerColor = get(seriesOpt, 'pointer.color');
  18482. pointerColor != null
  18483. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18484. }
  18485. compatLayoutProperties(seriesOpt);
  18486. });
  18487. // dataRange has changed to visualMap
  18488. if (option.dataRange) {
  18489. option.visualMap = option.dataRange;
  18490. }
  18491. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18492. var options = option[componentName];
  18493. if (options) {
  18494. if (!isArray(options)) {
  18495. options = [options];
  18496. }
  18497. each$1(options, function (option) {
  18498. compatLayoutProperties(option);
  18499. });
  18500. }
  18501. });
  18502. };
  18503. // (1) [Caution]: the logic is correct based on the premises:
  18504. // data processing stage is blocked in stream.
  18505. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18506. // (2) Only register once when import repeatly.
  18507. // Should be executed before after series filtered and before stack calculation.
  18508. var dataStack = function (ecModel) {
  18509. var stackInfoMap = createHashMap();
  18510. ecModel.eachSeries(function (seriesModel) {
  18511. var stack = seriesModel.get('stack');
  18512. // Compatibal: when `stack` is set as '', do not stack.
  18513. if (stack) {
  18514. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18515. var data = seriesModel.getData();
  18516. var stackInfo = {
  18517. // Used for calculate axis extent automatically.
  18518. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18519. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18520. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18521. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18522. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18523. data: data,
  18524. seriesModel: seriesModel
  18525. };
  18526. // If stacked on axis that do not support data stack.
  18527. if (!stackInfo.stackedDimension
  18528. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  18529. ) {
  18530. return;
  18531. }
  18532. stackInfoList.length && data.setCalculationInfo(
  18533. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  18534. );
  18535. stackInfoList.push(stackInfo);
  18536. }
  18537. });
  18538. stackInfoMap.each(calculateStack);
  18539. };
  18540. function calculateStack(stackInfoList) {
  18541. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  18542. var resultVal = [];
  18543. var resultNaN = [NaN, NaN];
  18544. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18545. var targetData = targetStackInfo.data;
  18546. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18547. // Should not write on raw data, because stack series model list changes
  18548. // depending on legend selection.
  18549. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18550. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  18551. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18552. // should also be NaN, to draw a appropriate belt area.
  18553. if (isNaN(sum)) {
  18554. return resultNaN;
  18555. }
  18556. var byValue;
  18557. var stackedDataRawIndex;
  18558. if (isStackedByIndex) {
  18559. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18560. }
  18561. else {
  18562. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18563. }
  18564. // If stackOver is NaN, chart view will render point on value start.
  18565. var stackedOver = NaN;
  18566. for (var j = idxInStack - 1; j >= 0; j--) {
  18567. var stackInfo = stackInfoList[j];
  18568. // Has been optimized by inverted indices on `stackedByDimension`.
  18569. if (!isStackedByIndex) {
  18570. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18571. }
  18572. if (stackedDataRawIndex >= 0) {
  18573. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  18574. // Considering positive stack, negative stack and empty data
  18575. if ((sum >= 0 && val > 0) // Positive stack
  18576. || (sum <= 0 && val < 0) // Negative stack
  18577. ) {
  18578. sum += val;
  18579. stackedOver = val;
  18580. break;
  18581. }
  18582. }
  18583. }
  18584. resultVal[0] = sum;
  18585. resultVal[1] = stackedOver;
  18586. return resultVal;
  18587. });
  18588. targetData.hostModel.setData(newData);
  18589. // Update for consequent calculation
  18590. targetStackInfo.data = newData;
  18591. });
  18592. }
  18593. // TODO
  18594. // ??? refactor? check the outer usage of data provider.
  18595. // merge with defaultDimValueGetter?
  18596. /**
  18597. * If normal array used, mutable chunk size is supported.
  18598. * If typed array used, chunk size must be fixed.
  18599. */
  18600. function DefaultDataProvider(source, dimSize) {
  18601. if (!Source.isInstance(source)) {
  18602. source = Source.seriesDataToSource(source);
  18603. }
  18604. this._source = source;
  18605. var data = this._data = source.data;
  18606. var sourceFormat = source.sourceFormat;
  18607. // Typed array. TODO IE10+?
  18608. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18609. if (__DEV__) {
  18610. if (dimSize == null) {
  18611. throw new Error('Typed array data must specify dimension size');
  18612. }
  18613. }
  18614. this._offset = 0;
  18615. this._dimSize = dimSize;
  18616. this._data = data;
  18617. }
  18618. var methods = providerMethods[
  18619. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  18620. ? sourceFormat + '_' + source.seriesLayoutBy
  18621. : sourceFormat
  18622. ];
  18623. if (__DEV__) {
  18624. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18625. }
  18626. extend(this, methods);
  18627. }
  18628. var providerProto = DefaultDataProvider.prototype;
  18629. // If data is pure without style configuration
  18630. providerProto.pure = false;
  18631. // If data is persistent and will not be released after use.
  18632. providerProto.persistent = true;
  18633. // ???! FIXME legacy data provider do not has method getSource
  18634. providerProto.getSource = function () {
  18635. return this._source;
  18636. };
  18637. var providerMethods = {
  18638. 'arrayRows_column': {
  18639. pure: true,
  18640. count: function () {
  18641. return Math.max(0, this._data.length - this._source.startIndex);
  18642. },
  18643. getItem: function (idx) {
  18644. return this._data[idx + this._source.startIndex];
  18645. },
  18646. appendData: appendDataSimply
  18647. },
  18648. 'arrayRows_row': {
  18649. pure: true,
  18650. count: function () {
  18651. var row = this._data[0];
  18652. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  18653. },
  18654. getItem: function (idx) {
  18655. idx += this._source.startIndex;
  18656. var item = [];
  18657. var data = this._data;
  18658. for (var i = 0; i < data.length; i++) {
  18659. var row = data[i];
  18660. item.push(row ? row[idx] : null);
  18661. }
  18662. return item;
  18663. },
  18664. appendData: function () {
  18665. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18666. }
  18667. },
  18668. 'objectRows': {
  18669. pure: true,
  18670. count: countSimply,
  18671. getItem: getItemSimply,
  18672. appendData: appendDataSimply
  18673. },
  18674. 'keyedColumns': {
  18675. pure: true,
  18676. count: function () {
  18677. var dimName = this._source.dimensionsDefine[0].name;
  18678. var col = this._data[dimName];
  18679. return col ? col.length : 0;
  18680. },
  18681. getItem: function (idx) {
  18682. var item = [];
  18683. var dims = this._source.dimensionsDefine;
  18684. for (var i = 0; i < dims.length; i++) {
  18685. var col = this._data[dims[i].name];
  18686. item.push(col ? col[idx] : null);
  18687. }
  18688. return item;
  18689. },
  18690. appendData: function (newData) {
  18691. var data = this._data;
  18692. each$1(newData, function (newCol, key) {
  18693. var oldCol = data[key] || (data[key] = []);
  18694. for (var i = 0; i < (newCol || []).length; i++) {
  18695. oldCol.push(newCol[i]);
  18696. }
  18697. });
  18698. }
  18699. },
  18700. 'original': {
  18701. count: countSimply,
  18702. getItem: getItemSimply,
  18703. appendData: appendDataSimply
  18704. },
  18705. 'typedArray': {
  18706. persistent: false,
  18707. pure: true,
  18708. count: function () {
  18709. return this._data ? (this._data.length / this._dimSize) : 0;
  18710. },
  18711. getItem: function (idx) {
  18712. idx = idx - this._offset;
  18713. var item = [];
  18714. var offset = this._dimSize * idx;
  18715. for (var i = 0; i < this._dimSize; i++) {
  18716. item[i] = this._data[offset + i];
  18717. }
  18718. return item;
  18719. },
  18720. appendData: function (newData) {
  18721. if (__DEV__) {
  18722. assert$1(
  18723. isTypedArray(newData),
  18724. 'Added data must be TypedArray if data in initialization is TypedArray'
  18725. );
  18726. }
  18727. this._data = newData;
  18728. },
  18729. // Clean self if data is already used.
  18730. clean: function () {
  18731. // PENDING
  18732. this._offset += this.count();
  18733. this._data = null;
  18734. }
  18735. }
  18736. };
  18737. function countSimply() {
  18738. return this._data.length;
  18739. }
  18740. function getItemSimply(idx) {
  18741. return this._data[idx];
  18742. }
  18743. function appendDataSimply(newData) {
  18744. for (var i = 0; i < newData.length; i++) {
  18745. this._data.push(newData[i]);
  18746. }
  18747. }
  18748. var rawValueGetters = {
  18749. arrayRows: getRawValueSimply,
  18750. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  18751. return dimIndex != null ? dataItem[dimName] : dataItem;
  18752. },
  18753. keyedColumns: getRawValueSimply,
  18754. original: function (dataItem, dataIndex, dimIndex, dimName) {
  18755. // FIXME
  18756. // In some case (markpoint in geo (geo-map.html)), dataItem
  18757. // is {coord: [...]}
  18758. var value = getDataItemValue(dataItem);
  18759. return (dimIndex == null || !(value instanceof Array))
  18760. ? value
  18761. : value[dimIndex];
  18762. },
  18763. typedArray: getRawValueSimply
  18764. };
  18765. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18766. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18767. }
  18768. var defaultDimValueGetters = {
  18769. arrayRows: getDimValueSimply,
  18770. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18771. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18772. },
  18773. keyedColumns: getDimValueSimply,
  18774. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18775. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18776. // If dataItem is an plain object with no value field, the var `value`
  18777. // will be assigned with the object, but it will be tread correctly
  18778. // in the `convertDataValue`.
  18779. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18780. // If any dataItem is like { value: 10 }
  18781. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18782. this.hasItemOption = true;
  18783. }
  18784. return converDataValue(
  18785. (value instanceof Array)
  18786. ? value[dimIndex]
  18787. // If value is a single number or something else not array.
  18788. : value,
  18789. this._dimensionInfos[dimName]
  18790. );
  18791. },
  18792. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18793. return dataItem[dimIndex];
  18794. }
  18795. };
  18796. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18797. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18798. }
  18799. /**
  18800. * This helper method convert value in data.
  18801. * @param {string|number|Date} value
  18802. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18803. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18804. */
  18805. function converDataValue(value, dimInfo) {
  18806. // Performance sensitive.
  18807. var dimType = dimInfo && dimInfo.type;
  18808. if (dimType === 'ordinal') {
  18809. // If given value is a category string
  18810. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18811. return ordinalMeta
  18812. ? ordinalMeta.parseAndCollect(value)
  18813. : value;
  18814. }
  18815. if (dimType === 'time'
  18816. // spead up when using timestamp
  18817. && typeof value !== 'number'
  18818. && value != null
  18819. && value !== '-'
  18820. ) {
  18821. value = +parseDate(value);
  18822. }
  18823. // dimType defaults 'number'.
  18824. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18825. // parse to NaN.
  18826. return (value == null || value === '')
  18827. ? NaN
  18828. // If string (like '-'), using '+' parse to NaN
  18829. // If object, also parse to NaN
  18830. : +value;
  18831. }
  18832. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18833. // Consider persistent.
  18834. // Caution: why use raw value to display on label or tooltip?
  18835. // A reason is to avoid format. For example time value we do not know
  18836. // how to format is expected. More over, if stack is used, calculated
  18837. // value may be 0.91000000001, which have brings trouble to display.
  18838. // TODO: consider how to treat null/undefined/NaN when display?
  18839. /**
  18840. * @param {module:echarts/data/List} data
  18841. * @param {number} dataIndex
  18842. * @param {string|number} [dim] dimName or dimIndex
  18843. * @return {Array.<number>|string|number} can be null/undefined.
  18844. */
  18845. function retrieveRawValue(data, dataIndex, dim) {
  18846. if (!data) {
  18847. return;
  18848. }
  18849. // Consider data may be not persistent.
  18850. var dataItem = data.getRawDataItem(dataIndex);
  18851. if (dataItem == null) {
  18852. return;
  18853. }
  18854. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18855. var dimName;
  18856. var dimIndex;
  18857. var dimInfo = data.getDimensionInfo(dim);
  18858. if (dimInfo) {
  18859. dimName = dimInfo.name;
  18860. dimIndex = dimInfo.index;
  18861. }
  18862. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18863. }
  18864. /**
  18865. * Compatible with some cases (in pie, map) like:
  18866. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18867. * where only sourceFormat is 'original' and 'objectRows' supported.
  18868. *
  18869. * ??? TODO
  18870. * Supported detail options in data item when using 'arrayRows'.
  18871. *
  18872. * @param {module:echarts/data/List} data
  18873. * @param {number} dataIndex
  18874. * @param {string} attr like 'selected'
  18875. */
  18876. function retrieveRawAttr(data, dataIndex, attr) {
  18877. if (!data) {
  18878. return;
  18879. }
  18880. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18881. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18882. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18883. ) {
  18884. return;
  18885. }
  18886. var dataItem = data.getRawDataItem(dataIndex);
  18887. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18888. dataItem = null;
  18889. }
  18890. if (dataItem) {
  18891. return dataItem[attr];
  18892. }
  18893. }
  18894. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18895. // PENDING A little ugly
  18896. var dataFormatMixin = {
  18897. /**
  18898. * Get params for formatter
  18899. * @param {number} dataIndex
  18900. * @param {string} [dataType]
  18901. * @return {Object}
  18902. */
  18903. getDataParams: function (dataIndex, dataType) {
  18904. var data = this.getData(dataType);
  18905. var rawValue = this.getRawValue(dataIndex, dataType);
  18906. var rawDataIndex = data.getRawIndex(dataIndex);
  18907. var name = data.getName(dataIndex, true);
  18908. var itemOpt = data.getRawDataItem(dataIndex);
  18909. var color = data.getItemVisual(dataIndex, 'color');
  18910. return {
  18911. componentType: this.mainType,
  18912. componentSubType: this.subType,
  18913. seriesType: this.mainType === 'series' ? this.subType : null,
  18914. seriesIndex: this.seriesIndex,
  18915. seriesId: this.id,
  18916. seriesName: this.name,
  18917. name: name,
  18918. dataIndex: rawDataIndex,
  18919. data: itemOpt,
  18920. dataType: dataType,
  18921. value: rawValue,
  18922. color: color,
  18923. marker: getTooltipMarker(color),
  18924. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18925. $vars: ['seriesName', 'name', 'value']
  18926. };
  18927. },
  18928. /**
  18929. * Format label
  18930. * @param {number} dataIndex
  18931. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18932. * @param {string} [dataType]
  18933. * @param {number} [dimIndex]
  18934. * @param {string} [labelProp='label']
  18935. * @return {string} If not formatter, return null/undefined
  18936. */
  18937. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18938. status = status || 'normal';
  18939. var data = this.getData(dataType);
  18940. var itemModel = data.getItemModel(dataIndex);
  18941. var params = this.getDataParams(dataIndex, dataType);
  18942. if (dimIndex != null && (params.value instanceof Array)) {
  18943. params.value = params.value[dimIndex];
  18944. }
  18945. var formatter = itemModel.get(
  18946. status === 'normal'
  18947. ? [labelProp || 'label', 'formatter']
  18948. : [status, labelProp || 'label', 'formatter']
  18949. );
  18950. if (typeof formatter === 'function') {
  18951. params.status = status;
  18952. return formatter(params);
  18953. }
  18954. else if (typeof formatter === 'string') {
  18955. var str = formatTpl(formatter, params);
  18956. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18957. // Do not support '}' in dim name util have to.
  18958. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18959. var len = dim.length;
  18960. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18961. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18962. }
  18963. return retrieveRawValue(data, dataIndex, dim);
  18964. });
  18965. }
  18966. },
  18967. /**
  18968. * Get raw value in option
  18969. * @param {number} idx
  18970. * @param {string} [dataType]
  18971. * @return {Array|number|string}
  18972. */
  18973. getRawValue: function (idx, dataType) {
  18974. return retrieveRawValue(this.getData(dataType), idx);
  18975. },
  18976. /**
  18977. * Should be implemented.
  18978. * @param {number} dataIndex
  18979. * @param {boolean} [multipleSeries=false]
  18980. * @param {number} [dataType]
  18981. * @return {string} tooltip string
  18982. */
  18983. formatTooltip: function () {
  18984. // Empty function
  18985. }
  18986. };
  18987. /**
  18988. * @param {Object} define
  18989. * @return See the return of `createTask`.
  18990. */
  18991. function createTask(define) {
  18992. return new Task(define);
  18993. }
  18994. /**
  18995. * @constructor
  18996. * @param {Object} define
  18997. * @param {Function} define.reset Custom reset
  18998. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18999. * @param {Function} [define.count] count is used to determin data task.
  19000. * @param {Function} [define.onDirty] count is used to determin data task.
  19001. */
  19002. function Task(define) {
  19003. define = define || {};
  19004. this._reset = define.reset;
  19005. this._plan = define.plan;
  19006. this._count = define.count;
  19007. this._onDirty = define.onDirty;
  19008. this._dirty = true;
  19009. // Context must be specified implicitly, to
  19010. // avoid miss update context when model changed.
  19011. this.context;
  19012. }
  19013. var taskProto = Task.prototype;
  19014. /**
  19015. * @param {Object} performArgs
  19016. * @param {number} [performArgs.step] Specified step.
  19017. * @param {number} [performArgs.skip] Skip customer perform call.
  19018. */
  19019. taskProto.perform = function (performArgs) {
  19020. var upTask = this._upstream;
  19021. var skip = performArgs && performArgs.skip;
  19022. // TODO some refactor.
  19023. // Pull data. Must pull data each time, because context.data
  19024. // may be updated by Series.setData.
  19025. if (this._dirty && upTask) {
  19026. var context = this.context;
  19027. context.data = context.outputData = upTask.context.outputData;
  19028. }
  19029. if (this.__pipeline) {
  19030. this.__pipeline.currentTask = this;
  19031. }
  19032. var planResult;
  19033. if (this._plan && !skip) {
  19034. planResult = this._plan(this.context);
  19035. }
  19036. var forceFirstProgress;
  19037. if (this._dirty || planResult === 'reset') {
  19038. this._dirty = false;
  19039. forceFirstProgress = reset(this, skip);
  19040. }
  19041. var step = performArgs && performArgs.step;
  19042. if (upTask) {
  19043. if (__DEV__) {
  19044. assert$1(upTask._outputDueEnd != null);
  19045. }
  19046. // ??? FIXME move to schedueler?
  19047. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  19048. this._dueEnd = upTask._outputDueEnd;
  19049. }
  19050. // DataTask or overallTask
  19051. else {
  19052. if (__DEV__) {
  19053. assert$1(!this._progress || this._count);
  19054. }
  19055. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19056. }
  19057. // Note: Stubs, that its host overall task let it has progress, has progress.
  19058. // If no progress, pass index from upstream to downstream each time plan called.
  19059. if (this._progress) {
  19060. var start = this._dueIndex;
  19061. var end = Math.min(
  19062. step != null ? this._dueIndex + step : Infinity,
  19063. this._dueEnd
  19064. );
  19065. !skip && (forceFirstProgress || start < end) && (
  19066. this._progress({start: start, end: end}, this.context)
  19067. );
  19068. this._dueIndex = end;
  19069. // If no `outputDueEnd`, assume that output data and
  19070. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19071. var outputDueEnd = this._settedOutputEnd != null
  19072. ? this._settedOutputEnd : end;
  19073. if (__DEV__) {
  19074. // ??? Can not rollback.
  19075. assert$1(outputDueEnd >= this._outputDueEnd);
  19076. }
  19077. this._outputDueEnd = outputDueEnd;
  19078. }
  19079. else {
  19080. // (1) Some overall task has no progress.
  19081. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19082. // This should always be performed so it can be passed to downstream.
  19083. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19084. ? this._settedOutputEnd : this._dueEnd;
  19085. }
  19086. return this.unfinished();
  19087. };
  19088. taskProto.dirty = function () {
  19089. this._dirty = true;
  19090. this._onDirty && this._onDirty(this.context);
  19091. };
  19092. /**
  19093. * @param {Object} [params]
  19094. */
  19095. function reset(taskIns, skip) {
  19096. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19097. taskIns._settedOutputEnd = null;
  19098. var progress;
  19099. var forceFirstProgress;
  19100. if (!skip && taskIns._reset) {
  19101. progress = taskIns._reset(taskIns.context);
  19102. if (progress && progress.progress) {
  19103. forceFirstProgress = progress.forceFirstProgress;
  19104. progress = progress.progress;
  19105. }
  19106. }
  19107. taskIns._progress = progress;
  19108. var downstream = taskIns._downstream;
  19109. downstream && downstream.dirty();
  19110. return forceFirstProgress;
  19111. }
  19112. /**
  19113. * @return {boolean}
  19114. */
  19115. taskProto.unfinished = function () {
  19116. return this._progress && this._dueIndex < this._dueEnd;
  19117. };
  19118. /**
  19119. * @param {Object} downTask The downstream task.
  19120. * @return {Object} The downstream task.
  19121. */
  19122. taskProto.pipe = function (downTask) {
  19123. if (__DEV__) {
  19124. assert$1(downTask && !downTask._disposed && downTask !== this);
  19125. }
  19126. // If already downstream, do not dirty downTask.
  19127. if (this._downstream !== downTask || this._dirty) {
  19128. this._downstream = downTask;
  19129. downTask._upstream = this;
  19130. downTask.dirty();
  19131. }
  19132. };
  19133. taskProto.dispose = function () {
  19134. if (this._disposed) {
  19135. return;
  19136. }
  19137. this._upstream && (this._upstream._downstream = null);
  19138. this._downstream && (this._downstream._upstream = null);
  19139. this._dirty = false;
  19140. this._disposed = true;
  19141. };
  19142. taskProto.getUpstream = function () {
  19143. return this._upstream;
  19144. };
  19145. taskProto.getDownstream = function () {
  19146. return this._downstream;
  19147. };
  19148. taskProto.setOutputEnd = function (end) {
  19149. // ??? FIXME: check
  19150. // This only happend in dataTask, dataZoom, map, currently.
  19151. // where dataZoom do not set end each time, but only set
  19152. // when reset. So we should record the setted end, in case
  19153. // that the stub of dataZoom perform again and earse the
  19154. // setted end by upstream.
  19155. this._outputDueEnd = this._settedOutputEnd = end;
  19156. // this._outputDueEnd = end;
  19157. };
  19158. ///////////////////////////////////////////////////////////
  19159. // For stream debug (Should be commented out after used!)
  19160. // Usage: printTask(this, 'begin');
  19161. // Usage: printTask(this, null, {someExtraProp});
  19162. // function printTask(task, prefix, extra) {
  19163. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19164. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19165. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19166. // var props = [];
  19167. // if (task.__pipeline) {
  19168. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19169. // props.push({text: 'idx', value: val});
  19170. // } else {
  19171. // var stubCount = 0;
  19172. // task.agentStubMap.each(() => stubCount++);
  19173. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19174. // }
  19175. // props.push({text: 'uid', value: task.uidDebug});
  19176. // if (task.__pipeline) {
  19177. // props.push({text: 'pid', value: task.__pipeline.id});
  19178. // task.agent && props.push(
  19179. // {text: 'stubFor', value: task.agent.uidDebug}
  19180. // );
  19181. // }
  19182. // props.push(
  19183. // {text: 'dirty', value: task._dirty},
  19184. // {text: 'dueIndex', value: task._dueIndex},
  19185. // {text: 'dueEnd', value: task._dueEnd},
  19186. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19187. // );
  19188. // if (extra) {
  19189. // Object.keys(extra).forEach(key => {
  19190. // props.push({text: key, value: extra[key]});
  19191. // });
  19192. // }
  19193. // var args = ['color: blue'];
  19194. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19195. // args.push('color: black', 'color: red'),
  19196. // `${item.text}: %c${item.value}`
  19197. // )).join('%c, ');
  19198. // console.log.apply(console, [msg].concat(args));
  19199. // // console.log(this);
  19200. // }
  19201. var inner$4 = makeInner();
  19202. var SeriesModel = ComponentModel.extend({
  19203. type: 'series.__base__',
  19204. /**
  19205. * @readOnly
  19206. */
  19207. seriesIndex: 0,
  19208. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19209. coordinateSystem: null,
  19210. /**
  19211. * @type {Object}
  19212. * @protected
  19213. */
  19214. defaultOption: null,
  19215. /**
  19216. * Data provided for legend
  19217. * @type {Function}
  19218. */
  19219. // PENDING
  19220. legendDataProvider: null,
  19221. /**
  19222. * Access path of color for visual
  19223. */
  19224. visualColorAccessPath: 'itemStyle.color',
  19225. /**
  19226. * Support merge layout params.
  19227. * Only support 'box' now (left/right/top/bottom/width/height).
  19228. * @type {string|Object} Object can be {ignoreSize: true}
  19229. * @readOnly
  19230. */
  19231. layoutMode: null,
  19232. init: function (option, parentModel, ecModel, extraOpt) {
  19233. /**
  19234. * @type {number}
  19235. * @readOnly
  19236. */
  19237. this.seriesIndex = this.componentIndex;
  19238. this.dataTask = createTask({
  19239. count: dataTaskCount,
  19240. reset: dataTaskReset
  19241. });
  19242. this.dataTask.context = {model: this};
  19243. this.mergeDefaultAndTheme(option, ecModel);
  19244. prepareSource(this);
  19245. var data = this.getInitialData(option, ecModel);
  19246. wrapData(data, this);
  19247. this.dataTask.context.data = data;
  19248. if (__DEV__) {
  19249. assert$1(data, 'getInitialData returned invalid data.');
  19250. }
  19251. /**
  19252. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19253. * @private
  19254. */
  19255. inner$4(this).dataBeforeProcessed = data;
  19256. // If we reverse the order (make data firstly, and then make
  19257. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19258. // cause data.graph.data !== data when using
  19259. // module:echarts/data/Graph or module:echarts/data/Tree.
  19260. // See module:echarts/data/helper/linkList
  19261. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19262. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19263. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19264. // Call `seriesModel.getRawData()` instead.
  19265. // this.restoreData();
  19266. autoSeriesName(this);
  19267. },
  19268. /**
  19269. * Util for merge default and theme to option
  19270. * @param {Object} option
  19271. * @param {module:echarts/model/Global} ecModel
  19272. */
  19273. mergeDefaultAndTheme: function (option, ecModel) {
  19274. var layoutMode = this.layoutMode;
  19275. var inputPositionParams = layoutMode
  19276. ? getLayoutParams(option) : {};
  19277. // Backward compat: using subType on theme.
  19278. // But if name duplicate between series subType
  19279. // (for example: parallel) add component mainType,
  19280. // add suffix 'Series'.
  19281. var themeSubType = this.subType;
  19282. if (ComponentModel.hasClass(themeSubType)) {
  19283. themeSubType += 'Series';
  19284. }
  19285. merge(
  19286. option,
  19287. ecModel.getTheme().get(this.subType)
  19288. );
  19289. merge(option, this.getDefaultOption());
  19290. // Default label emphasis `show`
  19291. defaultEmphasis(option, 'label', ['show']);
  19292. this.fillDataTextStyle(option.data);
  19293. if (layoutMode) {
  19294. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19295. }
  19296. },
  19297. mergeOption: function (newSeriesOption, ecModel) {
  19298. // this.settingTask.dirty();
  19299. newSeriesOption = merge(this.option, newSeriesOption, true);
  19300. this.fillDataTextStyle(newSeriesOption.data);
  19301. var layoutMode = this.layoutMode;
  19302. if (layoutMode) {
  19303. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19304. }
  19305. prepareSource(this);
  19306. var data = this.getInitialData(newSeriesOption, ecModel);
  19307. wrapData(data, this);
  19308. this.dataTask.dirty();
  19309. this.dataTask.context.data = data;
  19310. inner$4(this).dataBeforeProcessed = data;
  19311. autoSeriesName(this);
  19312. },
  19313. fillDataTextStyle: function (data) {
  19314. // Default data label emphasis `show`
  19315. // FIXME Tree structure data ?
  19316. // FIXME Performance ?
  19317. if (data) {
  19318. var props = ['show'];
  19319. for (var i = 0; i < data.length; i++) {
  19320. if (data[i] && data[i].label) {
  19321. defaultEmphasis(data[i], 'label', props);
  19322. }
  19323. }
  19324. }
  19325. },
  19326. /**
  19327. * Init a data structure from data related option in series
  19328. * Must be overwritten
  19329. */
  19330. getInitialData: function () {},
  19331. /**
  19332. * Append data to list
  19333. * @param {Object} params
  19334. * @param {Array|TypedArray} params.data
  19335. */
  19336. appendData: function (params) {
  19337. // FIXME ???
  19338. // (1) If data from dataset, forbidden append.
  19339. // (2) support append data of dataset.
  19340. var data = this.getRawData();
  19341. data.appendData(params.data);
  19342. },
  19343. /**
  19344. * Consider some method like `filter`, `map` need make new data,
  19345. * We should make sure that `seriesModel.getData()` get correct
  19346. * data in the stream procedure. So we fetch data from upstream
  19347. * each time `task.perform` called.
  19348. * @param {string} [dataType]
  19349. * @return {module:echarts/data/List}
  19350. */
  19351. getData: function (dataType) {
  19352. var task = getCurrentTask(this);
  19353. if (task) {
  19354. var data = task.context.data;
  19355. return dataType == null ? data : data.getLinkedData(dataType);
  19356. }
  19357. else {
  19358. // When series is not alive (that may happen when click toolbox
  19359. // restore or setOption with not merge mode), series data may
  19360. // be still need to judge animation or something when graphic
  19361. // elements want to know whether fade out.
  19362. return inner$4(this).data;
  19363. }
  19364. },
  19365. /**
  19366. * @param {module:echarts/data/List} data
  19367. */
  19368. setData: function (data) {
  19369. var task = getCurrentTask(this);
  19370. if (task) {
  19371. var context = task.context;
  19372. // Consider case: filter, data sample.
  19373. if (context.data !== data && task.isOverallFilter) {
  19374. task.setOutputEnd(data.count());
  19375. }
  19376. context.outputData = data;
  19377. // Caution: setData should update context.data,
  19378. // Because getData may be called multiply in a
  19379. // single stage and expect to get the data just
  19380. // set. (For example, AxisProxy, x y both call
  19381. // getData and setDate sequentially).
  19382. // So the context.data should be fetched from
  19383. // upstream each time when a stage starts to be
  19384. // performed.
  19385. if (task !== this.dataTask) {
  19386. context.data = data;
  19387. }
  19388. }
  19389. inner$4(this).data = data;
  19390. },
  19391. /**
  19392. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19393. * @return {module:echarts/data/Source} source
  19394. */
  19395. getSource: function () {
  19396. return getSource(this);
  19397. },
  19398. /**
  19399. * Get data before processed
  19400. * @return {module:echarts/data/List}
  19401. */
  19402. getRawData: function () {
  19403. return inner$4(this).dataBeforeProcessed;
  19404. },
  19405. /**
  19406. * Get base axis if has coordinate system and has axis.
  19407. * By default use coordSys.getBaseAxis();
  19408. * Can be overrided for some chart.
  19409. * @return {type} description
  19410. */
  19411. getBaseAxis: function () {
  19412. var coordSys = this.coordinateSystem;
  19413. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19414. },
  19415. // FIXME
  19416. /**
  19417. * Default tooltip formatter
  19418. *
  19419. * @param {number} dataIndex
  19420. * @param {boolean} [multipleSeries=false]
  19421. * @param {number} [dataType]
  19422. */
  19423. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  19424. function formatArrayValue(value) {
  19425. // ??? TODO refactor these logic.
  19426. // check: category-no-encode-has-axis-data in dataset.html
  19427. var vertially = reduce(value, function (vertially, val, idx) {
  19428. var dimItem = data.getDimensionInfo(idx);
  19429. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19430. }, 0);
  19431. var result = [];
  19432. tooltipDims.length
  19433. ? each$1(tooltipDims, function (dim) {
  19434. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19435. })
  19436. // By default, all dims is used on tooltip.
  19437. : each$1(value, setEachItem);
  19438. function setEachItem(val, dim) {
  19439. var dimInfo = data.getDimensionInfo(dim);
  19440. // If `dimInfo.tooltip` is not set, show tooltip.
  19441. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19442. return;
  19443. }
  19444. var dimType = dimInfo.type;
  19445. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  19446. var valStr = (vertially
  19447. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  19448. : ''
  19449. )
  19450. // FIXME should not format time for raw data?
  19451. + encodeHTML(dimType === 'ordinal'
  19452. ? val + ''
  19453. : dimType === 'time'
  19454. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  19455. : addCommas(val)
  19456. );
  19457. valStr && result.push(valStr);
  19458. }
  19459. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  19460. }
  19461. function formatSingleValue(val) {
  19462. return encodeHTML(addCommas(val));
  19463. }
  19464. var data = this.getData();
  19465. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19466. var tooltipDimLen = tooltipDims.length;
  19467. var value = this.getRawValue(dataIndex);
  19468. var isValueArr = isArray(value);
  19469. var color = data.getItemVisual(dataIndex, 'color');
  19470. if (isObject$1(color) && color.colorStops) {
  19471. color = (color.colorStops[0] || {}).color;
  19472. }
  19473. color = color || 'transparent';
  19474. // Complicated rule for pretty tooltip.
  19475. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  19476. ? formatArrayValue(value)
  19477. : tooltipDimLen
  19478. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  19479. : formatSingleValue(isValueArr ? value[0] : value);
  19480. var colorEl = getTooltipMarker(color);
  19481. var name = data.getName(dataIndex);
  19482. var seriesName = this.name;
  19483. if (!isNameSpecified(this)) {
  19484. seriesName = '';
  19485. }
  19486. seriesName = seriesName
  19487. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  19488. : '';
  19489. return !multipleSeries
  19490. ? seriesName + colorEl
  19491. + (name
  19492. ? encodeHTML(name) + ': ' + formattedValue
  19493. : formattedValue
  19494. )
  19495. : colorEl + seriesName + formattedValue;
  19496. },
  19497. /**
  19498. * @return {boolean}
  19499. */
  19500. isAnimationEnabled: function () {
  19501. if (env$1.node) {
  19502. return false;
  19503. }
  19504. var animationEnabled = this.getShallow('animation');
  19505. if (animationEnabled) {
  19506. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19507. animationEnabled = false;
  19508. }
  19509. }
  19510. return animationEnabled;
  19511. },
  19512. restoreData: function () {
  19513. this.dataTask.dirty();
  19514. },
  19515. getColorFromPalette: function (name, scope, requestColorNum) {
  19516. var ecModel = this.ecModel;
  19517. // PENDING
  19518. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19519. if (!color) {
  19520. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19521. }
  19522. return color;
  19523. },
  19524. /**
  19525. * Use `data.mapDimension(coordDim, true)` instead.
  19526. * @deprecated
  19527. */
  19528. coordDimToDataDim: function (coordDim) {
  19529. return this.getRawData().mapDimension(coordDim, true);
  19530. },
  19531. /**
  19532. * Get progressive rendering count each step
  19533. * @return {number}
  19534. */
  19535. getProgressive: function () {
  19536. return this.get('progressive');
  19537. },
  19538. /**
  19539. * Get progressive rendering count each step
  19540. * @return {number}
  19541. */
  19542. getProgressiveThreshold: function () {
  19543. return this.get('progressiveThreshold');
  19544. },
  19545. /**
  19546. * Get data indices for show tooltip content. See tooltip.
  19547. * @abstract
  19548. * @param {Array.<string>|string} dim
  19549. * @param {Array.<number>} value
  19550. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  19551. * @return {Object} {dataIndices, nestestValue}.
  19552. */
  19553. getAxisTooltipData: null,
  19554. /**
  19555. * See tooltip.
  19556. * @abstract
  19557. * @param {number} dataIndex
  19558. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  19559. */
  19560. getTooltipPosition: null,
  19561. /**
  19562. * @see {module:echarts/stream/Scheduler}
  19563. */
  19564. pipeTask: null,
  19565. /**
  19566. * Convinient for override in extended class.
  19567. * @protected
  19568. * @type {Function}
  19569. */
  19570. preventIncremental: null,
  19571. /**
  19572. * @public
  19573. * @readOnly
  19574. * @type {Object}
  19575. */
  19576. pipelineContext: null
  19577. });
  19578. mixin(SeriesModel, dataFormatMixin);
  19579. mixin(SeriesModel, colorPaletteMixin);
  19580. /**
  19581. * MUST be called after `prepareSource` called
  19582. * Here we need to make auto series, especially for auto legend. But we
  19583. * do not modify series.name in option to avoid side effects.
  19584. */
  19585. function autoSeriesName(seriesModel) {
  19586. // User specified name has higher priority, otherwise it may cause
  19587. // series can not be queried unexpectedly.
  19588. var name = seriesModel.name;
  19589. if (!isNameSpecified(seriesModel)) {
  19590. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19591. }
  19592. }
  19593. function getSeriesAutoName(seriesModel) {
  19594. var data = seriesModel.getRawData();
  19595. var dataDims = data.mapDimension('seriesName', true);
  19596. var nameArr = [];
  19597. each$1(dataDims, function (dataDim) {
  19598. var dimInfo = data.getDimensionInfo(dataDim);
  19599. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19600. });
  19601. return nameArr.join(' ');
  19602. }
  19603. function dataTaskCount(context) {
  19604. return context.model.getRawData().count();
  19605. }
  19606. function dataTaskReset(context) {
  19607. var seriesModel = context.model;
  19608. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19609. return dataTaskProgress;
  19610. }
  19611. function dataTaskProgress(param, context) {
  19612. // Avoid repead cloneShallow when data just created in reset.
  19613. if (param.end > context.outputData.count()) {
  19614. context.model.getRawData().cloneShallow(context.outputData);
  19615. }
  19616. }
  19617. // TODO refactor
  19618. function wrapData(data, seriesModel) {
  19619. each$1(data.CHANGABLE_METHODS, function (methodName) {
  19620. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  19621. });
  19622. }
  19623. function onDataSelfChange(seriesModel) {
  19624. var task = getCurrentTask(seriesModel);
  19625. if (task) {
  19626. // Consider case: filter, selectRange
  19627. task.setOutputEnd(this.count());
  19628. }
  19629. }
  19630. function getCurrentTask(seriesModel) {
  19631. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19632. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19633. if (pipeline) {
  19634. // When pipline finished, the currrentTask keep the last
  19635. // task (renderTask).
  19636. var task = pipeline.currentTask;
  19637. if (task) {
  19638. var agentStubMap = task.agentStubMap;
  19639. if (agentStubMap) {
  19640. task = agentStubMap.get(seriesModel.uid);
  19641. }
  19642. }
  19643. return task;
  19644. }
  19645. }
  19646. var Component = function () {
  19647. /**
  19648. * @type {module:zrender/container/Group}
  19649. * @readOnly
  19650. */
  19651. this.group = new Group();
  19652. /**
  19653. * @type {string}
  19654. * @readOnly
  19655. */
  19656. this.uid = getUID('viewComponent');
  19657. };
  19658. Component.prototype = {
  19659. constructor: Component,
  19660. init: function (ecModel, api) {},
  19661. render: function (componentModel, ecModel, api, payload) {},
  19662. dispose: function () {}
  19663. };
  19664. var componentProto = Component.prototype;
  19665. componentProto.updateView
  19666. = componentProto.updateLayout
  19667. = componentProto.updateVisual
  19668. = function (seriesModel, ecModel, api, payload) {
  19669. // Do nothing;
  19670. };
  19671. // Enable Component.extend.
  19672. enableClassExtend(Component);
  19673. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19674. enableClassManagement(Component, {registerWhenExtend: true});
  19675. /**
  19676. * @return {string} If large mode changed, return string 'reset';
  19677. */
  19678. var createRenderPlanner = function () {
  19679. var inner = makeInner();
  19680. return function (seriesModel) {
  19681. var fields = inner(seriesModel);
  19682. var pipelineContext = seriesModel.pipelineContext;
  19683. var originalLarge = fields.large;
  19684. var originalProgressive = fields.canProgressiveRender;
  19685. var large = fields.large = pipelineContext.large;
  19686. var progressive = fields.canProgressiveRender = pipelineContext.canProgressiveRender;
  19687. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  19688. };
  19689. };
  19690. var inner$5 = makeInner();
  19691. var renderPlanner = createRenderPlanner();
  19692. function Chart() {
  19693. /**
  19694. * @type {module:zrender/container/Group}
  19695. * @readOnly
  19696. */
  19697. this.group = new Group();
  19698. /**
  19699. * @type {string}
  19700. * @readOnly
  19701. */
  19702. this.uid = getUID('viewChart');
  19703. this.renderTask = createTask({
  19704. plan: renderTaskPlan,
  19705. reset: renderTaskReset
  19706. });
  19707. this.renderTask.context = {view: this};
  19708. }
  19709. Chart.prototype = {
  19710. type: 'chart',
  19711. /**
  19712. * Init the chart.
  19713. * @param {module:echarts/model/Global} ecModel
  19714. * @param {module:echarts/ExtensionAPI} api
  19715. */
  19716. init: function (ecModel, api) {},
  19717. /**
  19718. * Render the chart.
  19719. * @param {module:echarts/model/Series} seriesModel
  19720. * @param {module:echarts/model/Global} ecModel
  19721. * @param {module:echarts/ExtensionAPI} api
  19722. * @param {Object} payload
  19723. */
  19724. render: function (seriesModel, ecModel, api, payload) {},
  19725. /**
  19726. * Highlight series or specified data item.
  19727. * @param {module:echarts/model/Series} seriesModel
  19728. * @param {module:echarts/model/Global} ecModel
  19729. * @param {module:echarts/ExtensionAPI} api
  19730. * @param {Object} payload
  19731. */
  19732. highlight: function (seriesModel, ecModel, api, payload) {
  19733. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  19734. },
  19735. /**
  19736. * Downplay series or specified data item.
  19737. * @param {module:echarts/model/Series} seriesModel
  19738. * @param {module:echarts/model/Global} ecModel
  19739. * @param {module:echarts/ExtensionAPI} api
  19740. * @param {Object} payload
  19741. */
  19742. downplay: function (seriesModel, ecModel, api, payload) {
  19743. toggleHighlight(seriesModel.getData(), payload, 'normal');
  19744. },
  19745. /**
  19746. * Remove self.
  19747. * @param {module:echarts/model/Global} ecModel
  19748. * @param {module:echarts/ExtensionAPI} api
  19749. */
  19750. remove: function (ecModel, api) {
  19751. this.group.removeAll();
  19752. },
  19753. /**
  19754. * Dispose self.
  19755. * @param {module:echarts/model/Global} ecModel
  19756. * @param {module:echarts/ExtensionAPI} api
  19757. */
  19758. dispose: function () {},
  19759. /**
  19760. * Rendering preparation in progressive mode.
  19761. * @param {module:echarts/model/Series} seriesModel
  19762. * @param {module:echarts/model/Global} ecModel
  19763. * @param {module:echarts/ExtensionAPI} api
  19764. * @param {Object} payload
  19765. */
  19766. incrementalPrepareRender: null,
  19767. /**
  19768. * Render in progressive mode.
  19769. * @param {module:echarts/model/Series} seriesModel
  19770. * @param {module:echarts/model/Global} ecModel
  19771. * @param {module:echarts/ExtensionAPI} api
  19772. * @param {Object} payload
  19773. */
  19774. incrementalRender: null,
  19775. /**
  19776. * Update transform directly.
  19777. * @param {module:echarts/model/Series} seriesModel
  19778. * @param {module:echarts/model/Global} ecModel
  19779. * @param {module:echarts/ExtensionAPI} api
  19780. * @param {Object} payload
  19781. * @return {Object} {update: true}
  19782. */
  19783. updateTransform: null
  19784. /**
  19785. * The view contains the given point.
  19786. * @interface
  19787. * @param {Array.<number>} point
  19788. * @return {boolean}
  19789. */
  19790. // containPoint: function () {}
  19791. };
  19792. var chartProto = Chart.prototype;
  19793. chartProto.updateView
  19794. = chartProto.updateLayout
  19795. = chartProto.updateVisual
  19796. = function (seriesModel, ecModel, api, payload) {
  19797. this.render(seriesModel, ecModel, api, payload);
  19798. };
  19799. /**
  19800. * Set state of single element
  19801. * @param {module:zrender/Element} el
  19802. * @param {string} state
  19803. */
  19804. function elSetState(el, state) {
  19805. if (el) {
  19806. el.trigger(state);
  19807. if (el.type === 'group') {
  19808. for (var i = 0; i < el.childCount(); i++) {
  19809. elSetState(el.childAt(i), state);
  19810. }
  19811. }
  19812. }
  19813. }
  19814. /**
  19815. * @param {module:echarts/data/List} data
  19816. * @param {Object} payload
  19817. * @param {string} state 'normal'|'emphasis'
  19818. */
  19819. function toggleHighlight(data, payload, state) {
  19820. var dataIndex = queryDataIndex(data, payload);
  19821. if (dataIndex != null) {
  19822. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19823. elSetState(data.getItemGraphicEl(dataIdx), state);
  19824. });
  19825. }
  19826. else {
  19827. data.eachItemGraphicEl(function (el) {
  19828. elSetState(el, state);
  19829. });
  19830. }
  19831. }
  19832. // Enable Chart.extend.
  19833. enableClassExtend(Chart, ['dispose']);
  19834. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19835. enableClassManagement(Chart, {registerWhenExtend: true});
  19836. Chart.markUpdateMethod = function (payload, methodName) {
  19837. inner$5(payload).updateMethod = methodName;
  19838. };
  19839. function renderTaskPlan(context) {
  19840. return renderPlanner(context.model);
  19841. }
  19842. function renderTaskReset(context) {
  19843. var seriesModel = context.model;
  19844. var ecModel = context.ecModel;
  19845. var api = context.api;
  19846. var payload = context.payload;
  19847. // ???! remove updateView updateVisual
  19848. var canProgressiveRender = seriesModel.pipelineContext.canProgressiveRender;
  19849. var view = context.view;
  19850. var updateMethod = payload && inner$5(payload).updateMethod;
  19851. var methodName = canProgressiveRender
  19852. ? 'incrementalPrepareRender'
  19853. : (updateMethod && view[updateMethod])
  19854. ? updateMethod
  19855. // `appendData` is also supported when data amount
  19856. // is less than progressive threshold.
  19857. : 'render';
  19858. if (methodName !== 'render') {
  19859. view[methodName](seriesModel, ecModel, api, payload);
  19860. }
  19861. return progressMethodMap[methodName];
  19862. }
  19863. var progressMethodMap = {
  19864. incrementalPrepareRender: {
  19865. progress: function (params, context) {
  19866. context.view.incrementalRender(
  19867. params, context.model, context.ecModel, context.api, context.payload
  19868. );
  19869. }
  19870. },
  19871. render: {
  19872. // Put view.render in `progress` to support appendData. But in this case
  19873. // view.render should not be called in reset, otherwise it will be called
  19874. // twise. Use `forceFirstProgress` to make sure that view.render is called
  19875. // in any cases.
  19876. forceFirstProgress: true,
  19877. progress: function (params, context) {
  19878. context.view.render(
  19879. context.model, context.ecModel, context.api, context.payload
  19880. );
  19881. }
  19882. }
  19883. };
  19884. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  19885. var RATE = '\0__throttleRate';
  19886. var THROTTLE_TYPE = '\0__throttleType';
  19887. /**
  19888. * @public
  19889. * @param {(Function)} fn
  19890. * @param {number} [delay=0] Unit: ms.
  19891. * @param {boolean} [debounce=false]
  19892. * true: If call interval less than `delay`, only the last call works.
  19893. * false: If call interval less than `delay, call works on fixed rate.
  19894. * @return {(Function)} throttled fn.
  19895. */
  19896. function throttle(fn, delay, debounce) {
  19897. var currCall;
  19898. var lastCall = 0;
  19899. var lastExec = 0;
  19900. var timer = null;
  19901. var diff;
  19902. var scope;
  19903. var args;
  19904. var debounceNextCall;
  19905. delay = delay || 0;
  19906. function exec() {
  19907. lastExec = (new Date()).getTime();
  19908. timer = null;
  19909. fn.apply(scope, args || []);
  19910. }
  19911. var cb = function () {
  19912. currCall = (new Date()).getTime();
  19913. scope = this;
  19914. args = arguments;
  19915. var thisDelay = debounceNextCall || delay;
  19916. var thisDebounce = debounceNextCall || debounce;
  19917. debounceNextCall = null;
  19918. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19919. clearTimeout(timer);
  19920. if (thisDebounce) {
  19921. timer = setTimeout(exec, thisDelay);
  19922. }
  19923. else {
  19924. if (diff >= 0) {
  19925. exec();
  19926. }
  19927. else {
  19928. timer = setTimeout(exec, -diff);
  19929. }
  19930. }
  19931. lastCall = currCall;
  19932. };
  19933. /**
  19934. * Clear throttle.
  19935. * @public
  19936. */
  19937. cb.clear = function () {
  19938. if (timer) {
  19939. clearTimeout(timer);
  19940. timer = null;
  19941. }
  19942. };
  19943. /**
  19944. * Enable debounce once.
  19945. */
  19946. cb.debounceNextCall = function (debounceDelay) {
  19947. debounceNextCall = debounceDelay;
  19948. };
  19949. return cb;
  19950. }
  19951. /**
  19952. * Create throttle method or update throttle rate.
  19953. *
  19954. * @example
  19955. * ComponentView.prototype.render = function () {
  19956. * ...
  19957. * throttle.createOrUpdate(
  19958. * this,
  19959. * '_dispatchAction',
  19960. * this.model.get('throttle'),
  19961. * 'fixRate'
  19962. * );
  19963. * };
  19964. * ComponentView.prototype.remove = function () {
  19965. * throttle.clear(this, '_dispatchAction');
  19966. * };
  19967. * ComponentView.prototype.dispose = function () {
  19968. * throttle.clear(this, '_dispatchAction');
  19969. * };
  19970. *
  19971. * @public
  19972. * @param {Object} obj
  19973. * @param {string} fnAttr
  19974. * @param {number} [rate]
  19975. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19976. * @return {Function} throttled function.
  19977. */
  19978. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  19979. var fn = obj[fnAttr];
  19980. if (!fn) {
  19981. return;
  19982. }
  19983. var originFn = fn[ORIGIN_METHOD] || fn;
  19984. var lastThrottleType = fn[THROTTLE_TYPE];
  19985. var lastRate = fn[RATE];
  19986. if (lastRate !== rate || lastThrottleType !== throttleType) {
  19987. if (rate == null || !throttleType) {
  19988. return (obj[fnAttr] = originFn);
  19989. }
  19990. fn = obj[fnAttr] = throttle(
  19991. originFn, rate, throttleType === 'debounce'
  19992. );
  19993. fn[ORIGIN_METHOD] = originFn;
  19994. fn[THROTTLE_TYPE] = throttleType;
  19995. fn[RATE] = rate;
  19996. }
  19997. return fn;
  19998. }
  19999. /**
  20000. * Clear throttle. Example see throttle.createOrUpdate.
  20001. *
  20002. * @public
  20003. * @param {Object} obj
  20004. * @param {string} fnAttr
  20005. */
  20006. function clear(obj, fnAttr) {
  20007. var fn = obj[fnAttr];
  20008. if (fn && fn[ORIGIN_METHOD]) {
  20009. obj[fnAttr] = fn[ORIGIN_METHOD];
  20010. }
  20011. }
  20012. var seriesColor = {
  20013. createOnAllSeries: true,
  20014. performRawSeries: true,
  20015. reset: function (seriesModel, ecModel) {
  20016. var data = seriesModel.getData();
  20017. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20018. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20019. || seriesModel.getColorFromPalette(
  20020. // TODO series count changed.
  20021. seriesModel.name, null, ecModel.getSeriesCount()
  20022. ); // Default color
  20023. // FIXME Set color function or use the platte color
  20024. data.setVisual('color', color);
  20025. // Only visible series has each data be visual encoded
  20026. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20027. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20028. data.each(function (idx) {
  20029. data.setItemVisual(
  20030. idx, 'color', color(seriesModel.getDataParams(idx))
  20031. );
  20032. });
  20033. }
  20034. // itemStyle in each data item
  20035. var dataEach = function (data, idx) {
  20036. var itemModel = data.getItemModel(idx);
  20037. var color = itemModel.get(colorAccessPath, true);
  20038. if (color != null) {
  20039. data.setItemVisual(idx, 'color', color);
  20040. }
  20041. };
  20042. return { dataEach: data.hasItemOption ? dataEach : null };
  20043. }
  20044. }
  20045. };
  20046. var lang = {
  20047. toolbox: {
  20048. brush: {
  20049. title: {
  20050. rect: '矩形选择',
  20051. polygon: '圈选',
  20052. lineX: '横向选择',
  20053. lineY: '纵向选择',
  20054. keep: '保持选择',
  20055. clear: '清除选择'
  20056. }
  20057. },
  20058. dataView: {
  20059. title: '数据视图',
  20060. lang: ['数据视图', '关闭', '刷新']
  20061. },
  20062. dataZoom: {
  20063. title: {
  20064. zoom: '区域缩放',
  20065. back: '区域缩放还原'
  20066. }
  20067. },
  20068. magicType: {
  20069. title: {
  20070. line: '切换为折线图',
  20071. bar: '切换为柱状图',
  20072. stack: '切换为堆叠',
  20073. tiled: '切换为平铺'
  20074. }
  20075. },
  20076. restore: {
  20077. title: '还原'
  20078. },
  20079. saveAsImage: {
  20080. title: '保存为图片',
  20081. lang: ['右键另存为图片']
  20082. }
  20083. },
  20084. series: {
  20085. typeNames: {
  20086. pie: '饼图',
  20087. bar: '柱状图',
  20088. line: '折线图',
  20089. scatter: '散点图',
  20090. effectScatter: '涟漪散点图',
  20091. radar: '雷达图',
  20092. tree: '树图',
  20093. treemap: '矩形树图',
  20094. boxplot: '箱型图',
  20095. candlestick: 'K线图',
  20096. k: 'K线图',
  20097. heatmap: '热力图',
  20098. map: '地图',
  20099. parallel: '平行坐标图',
  20100. lines: '线图',
  20101. graph: '关系图',
  20102. sankey: '桑基图',
  20103. funnel: '漏斗图',
  20104. gauge: '仪表盘图',
  20105. pictorialBar: '象形柱图',
  20106. themeRiver: '主题河流图',
  20107. sunburst: '旭日图'
  20108. }
  20109. },
  20110. aria: {
  20111. general: {
  20112. withTitle: '这是一个关于“{title}”的图表。',
  20113. withoutTitle: '这是一个图表,'
  20114. },
  20115. series: {
  20116. single: {
  20117. prefix: '',
  20118. withName: '图表类型是{seriesType},表示{seriesName}。',
  20119. withoutName: '图表类型是{seriesType}。'
  20120. },
  20121. multiple: {
  20122. prefix: '它由{seriesCount}个图表系列组成。',
  20123. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20124. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20125. separator: {
  20126. middle: ';',
  20127. end: '。'
  20128. }
  20129. }
  20130. },
  20131. data: {
  20132. allData: '其数据是——',
  20133. partialData: '其中,前{displayCnt}项是——',
  20134. withName: '{name}的数据是{value}',
  20135. withoutName: '{value}',
  20136. separator: {
  20137. middle: ',',
  20138. end: ''
  20139. }
  20140. }
  20141. }
  20142. };
  20143. var aria = function (dom, ecModel) {
  20144. var ariaModel = ecModel.getModel('aria');
  20145. if (!ariaModel.get('show')) {
  20146. return;
  20147. }
  20148. else if (ariaModel.get('description')) {
  20149. dom.setAttribute('aria-label', ariaModel.get('description'));
  20150. return;
  20151. }
  20152. var seriesCnt = 0;
  20153. ecModel.eachSeries(function (seriesModel, idx) {
  20154. ++seriesCnt;
  20155. }, this);
  20156. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20157. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20158. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20159. var ariaLabel;
  20160. if (seriesCnt < 1) {
  20161. // No series, no aria label
  20162. return;
  20163. }
  20164. else {
  20165. var title = getTitle();
  20166. if (title) {
  20167. ariaLabel = replace(getConfig('general.withTitle'), {
  20168. title: title
  20169. });
  20170. }
  20171. else {
  20172. ariaLabel = getConfig('general.withoutTitle');
  20173. }
  20174. var seriesLabels = [];
  20175. var prefix = seriesCnt > 1
  20176. ? 'series.multiple.prefix'
  20177. : 'series.single.prefix';
  20178. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20179. ecModel.eachSeries(function (seriesModel, idx) {
  20180. if (idx < displaySeriesCnt) {
  20181. var seriesLabel;
  20182. var seriesName = seriesModel.get('name');
  20183. var seriesTpl = 'series.'
  20184. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20185. seriesLabel = getConfig(seriesName
  20186. ? seriesTpl + 'withName'
  20187. : seriesTpl + 'withoutName');
  20188. seriesLabel = replace(seriesLabel, {
  20189. seriesId: seriesModel.seriesIndex,
  20190. seriesName: seriesModel.get('name'),
  20191. seriesType: getSeriesTypeName(seriesModel.subType)
  20192. });
  20193. var data = seriesModel.getData();
  20194. window.data = data;
  20195. if (data.count() > maxDataCnt) {
  20196. // Show part of data
  20197. seriesLabel += replace(getConfig('data.partialData'), {
  20198. displayCnt: maxDataCnt
  20199. });
  20200. }
  20201. else {
  20202. seriesLabel += getConfig('data.allData');
  20203. }
  20204. var dataLabels = [];
  20205. for (var i = 0; i < data.count(); i++) {
  20206. if (i < maxDataCnt) {
  20207. var name = data.getName(i);
  20208. var value = retrieveRawValue(data, i);
  20209. dataLabels.push(
  20210. replace(
  20211. name
  20212. ? getConfig('data.withName')
  20213. : getConfig('data.withoutName'),
  20214. {
  20215. name: name,
  20216. value: value
  20217. }
  20218. )
  20219. );
  20220. }
  20221. }
  20222. seriesLabel += dataLabels
  20223. .join(getConfig('data.separator.middle'))
  20224. + getConfig('data.separator.end');
  20225. seriesLabels.push(seriesLabel);
  20226. }
  20227. });
  20228. ariaLabel += seriesLabels
  20229. .join(getConfig('series.multiple.separator.middle'))
  20230. + getConfig('series.multiple.separator.end');
  20231. dom.setAttribute('aria-label', ariaLabel);
  20232. }
  20233. function replace(str, keyValues) {
  20234. if (typeof str !== 'string') {
  20235. return str;
  20236. }
  20237. var result = str;
  20238. each$1(keyValues, function (value, key) {
  20239. result = result.replace(
  20240. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  20241. value
  20242. );
  20243. });
  20244. return result;
  20245. }
  20246. function getConfig(path) {
  20247. var userConfig = ariaModel.get(path);
  20248. if (userConfig == null) {
  20249. var pathArr = path.split('.');
  20250. var result = lang.aria;
  20251. for (var i = 0; i < pathArr.length; ++i) {
  20252. result = result[pathArr[i]];
  20253. }
  20254. return result;
  20255. }
  20256. else {
  20257. return userConfig;
  20258. }
  20259. }
  20260. function getTitle() {
  20261. var title = ecModel.getModel('title').option;
  20262. if (title && title.length) {
  20263. title = title[0];
  20264. }
  20265. return title && title.text;
  20266. }
  20267. function getSeriesTypeName(type) {
  20268. return lang.series.typeNames[type] || '自定义图';
  20269. }
  20270. };
  20271. var PI$1 = Math.PI;
  20272. /**
  20273. * @param {module:echarts/ExtensionAPI} api
  20274. * @param {Object} [opts]
  20275. * @param {string} [opts.text]
  20276. * @param {string} [opts.color]
  20277. * @param {string} [opts.textColor]
  20278. * @return {module:zrender/Element}
  20279. */
  20280. var loadingDefault = function (api, opts) {
  20281. opts = opts || {};
  20282. defaults(opts, {
  20283. text: 'loading',
  20284. color: '#c23531',
  20285. textColor: '#000',
  20286. maskColor: 'rgba(255, 255, 255, 0.8)',
  20287. zlevel: 0
  20288. });
  20289. var mask = new Rect({
  20290. style: {
  20291. fill: opts.maskColor
  20292. },
  20293. zlevel: opts.zlevel,
  20294. z: 10000
  20295. });
  20296. var arc = new Arc({
  20297. shape: {
  20298. startAngle: -PI$1 / 2,
  20299. endAngle: -PI$1 / 2 + 0.1,
  20300. r: 10
  20301. },
  20302. style: {
  20303. stroke: opts.color,
  20304. lineCap: 'round',
  20305. lineWidth: 5
  20306. },
  20307. zlevel: opts.zlevel,
  20308. z: 10001
  20309. });
  20310. var labelRect = new Rect({
  20311. style: {
  20312. fill: 'none',
  20313. text: opts.text,
  20314. textPosition: 'right',
  20315. textDistance: 10,
  20316. textFill: opts.textColor
  20317. },
  20318. zlevel: opts.zlevel,
  20319. z: 10001
  20320. });
  20321. arc.animateShape(true)
  20322. .when(1000, {
  20323. endAngle: PI$1 * 3 / 2
  20324. })
  20325. .start('circularInOut');
  20326. arc.animateShape(true)
  20327. .when(1000, {
  20328. startAngle: PI$1 * 3 / 2
  20329. })
  20330. .delay(300)
  20331. .start('circularInOut');
  20332. var group = new Group();
  20333. group.add(arc);
  20334. group.add(labelRect);
  20335. group.add(mask);
  20336. // Inject resize
  20337. group.resize = function () {
  20338. var cx = api.getWidth() / 2;
  20339. var cy = api.getHeight() / 2;
  20340. arc.setShape({
  20341. cx: cx,
  20342. cy: cy
  20343. });
  20344. var r = arc.shape.r;
  20345. labelRect.setShape({
  20346. x: cx - r,
  20347. y: cy - r,
  20348. width: r * 2,
  20349. height: r * 2
  20350. });
  20351. mask.setShape({
  20352. x: 0,
  20353. y: 0,
  20354. width: api.getWidth(),
  20355. height: api.getHeight()
  20356. });
  20357. };
  20358. group.resize();
  20359. return group;
  20360. };
  20361. /**
  20362. * @module echarts/stream/Scheduler
  20363. */
  20364. /**
  20365. * @constructor
  20366. */
  20367. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20368. // this._pipelineMap = createHashMap();
  20369. this.ecInstance = ecInstance;
  20370. this.api = api;
  20371. this.unfinished;
  20372. // Fix current processors in case that in some rear cases that
  20373. // processors might be registered after echarts instance created.
  20374. // Register processors incrementally for a echarts instance is
  20375. // not supported by this stream architecture.
  20376. this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20377. this._visualHandlers = visualHandlers.slice();
  20378. /**
  20379. * @private
  20380. * @type {
  20381. * [handlerUID: string]: {
  20382. * seriesTaskMap?: {
  20383. * [seriesUID: string]: Task
  20384. * },
  20385. * overallTask?: Task
  20386. * }
  20387. * }
  20388. */
  20389. this._stageTaskMap = createHashMap();
  20390. }
  20391. var proto = Scheduler.prototype;
  20392. // If seriesModel provided, incremental threshold is check by series data.
  20393. proto.getPerformArgs = function (task, isBlock) {
  20394. // For overall task
  20395. if (!task.__pipeline) {
  20396. return;
  20397. }
  20398. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20399. var pCtx = pipeline.context;
  20400. var incremental = !isBlock
  20401. && pipeline.progressiveEnabled
  20402. && (!pCtx || pCtx.canProgressiveRender)
  20403. && task.__idxInPipeline > pipeline.bockIndex;
  20404. return {step: incremental ? pipeline.step : null};
  20405. };
  20406. proto.getPipeline = function (pipelineId) {
  20407. return this._pipelineMap.get(pipelineId);
  20408. };
  20409. /**
  20410. * Current, progressive rendering starts from visual and layout.
  20411. * Always detect render mode in the same stage, avoiding that incorrect
  20412. * detection caused by data filtering.
  20413. * Caution:
  20414. * `updateStreamModes` use `seriesModel.getData()`.
  20415. */
  20416. proto.updateStreamModes = function (seriesModel, view) {
  20417. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20418. var data = seriesModel.getData();
  20419. var dataLen = data.count();
  20420. // `canProgressiveRender` means that can render progressively in each
  20421. // animation frame. Note that some types of series do not provide
  20422. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  20423. // use the term `incremental` but not `progressive` to describe the
  20424. // case that `chart.appendData`.
  20425. var canProgressiveRender = pipeline.progressiveEnabled
  20426. && view.incrementalPrepareRender
  20427. && dataLen >= pipeline.threshold;
  20428. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20429. seriesModel.pipelineContext = pipeline.context = {
  20430. canProgressiveRender: canProgressiveRender,
  20431. large: large
  20432. };
  20433. };
  20434. proto.restorePipelines = function (ecModel) {
  20435. var scheduler = this;
  20436. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20437. ecModel.eachSeries(function (seriesModel) {
  20438. var progressive = seriesModel.getProgressive();
  20439. var pipelineId = seriesModel.uid;
  20440. pipelineMap.set(pipelineId, {
  20441. id: pipelineId,
  20442. head: null,
  20443. tail: null,
  20444. threshold: seriesModel.getProgressiveThreshold(),
  20445. progressiveEnabled: progressive
  20446. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20447. bockIndex: -1,
  20448. step: progressive || 700, // ??? Temporarily number
  20449. count: 0
  20450. });
  20451. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20452. });
  20453. };
  20454. proto.prepareStageTasks = function () {
  20455. var stageTaskMap = this._stageTaskMap;
  20456. var ecModel = this.ecInstance.getModel();
  20457. var api = this.api;
  20458. each$1([this._dataProcessorHandlers, this._visualHandlers], function (stageHandlers) {
  20459. each$1(stageHandlers, function (handler) {
  20460. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20461. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20462. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20463. }, this);
  20464. }, this);
  20465. };
  20466. proto.prepareView = function (view, model, ecModel, api) {
  20467. var renderTask = view.renderTask;
  20468. var context = renderTask.context;
  20469. context.model = model;
  20470. context.ecModel = ecModel;
  20471. context.api = api;
  20472. renderTask.__block = !view.incrementalPrepareRender;
  20473. pipe(this, model, renderTask);
  20474. };
  20475. proto.performDataProcessorTasks = function (ecModel, payload) {
  20476. // If we do not use `block` here, it should be considered when to update modes.
  20477. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  20478. };
  20479. // opt
  20480. // opt.visualType: 'visual' or 'layout'
  20481. // opt.setDirty
  20482. proto.performVisualTasks = function (ecModel, payload, opt) {
  20483. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  20484. };
  20485. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20486. opt = opt || {};
  20487. var unfinished;
  20488. each$1(stageHandlers, function (stageHandler, idx) {
  20489. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20490. return;
  20491. }
  20492. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20493. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20494. var overallTask = stageHandlerRecord.overallTask;
  20495. if (overallTask) {
  20496. var overallNeedDirty;
  20497. var agentStubMap = overallTask.agentStubMap;
  20498. agentStubMap.each(function (stub) {
  20499. if (needSetDirty(opt, stub)) {
  20500. stub.dirty();
  20501. overallNeedDirty = true;
  20502. }
  20503. });
  20504. overallNeedDirty && overallTask.dirty();
  20505. updatePayload(overallTask, payload);
  20506. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20507. // Execute stubs firstly, which may set the overall task dirty,
  20508. // then execute the overall task. And stub will call seriesModel.setData,
  20509. // which ensures that in the overallTask seriesModel.getData() will not
  20510. // return incorrect data.
  20511. agentStubMap.each(function (stub) {
  20512. stub.perform(performArgs);
  20513. });
  20514. unfinished |= overallTask.perform(performArgs);
  20515. }
  20516. else if (seriesTaskMap) {
  20517. seriesTaskMap.each(function (task, pipelineId) {
  20518. if (needSetDirty(opt, task)) {
  20519. task.dirty();
  20520. }
  20521. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20522. performArgs.skip = !stageHandler.performRawSeries
  20523. && ecModel.isSeriesFiltered(task.context.model);
  20524. updatePayload(task, payload);
  20525. unfinished |= task.perform(performArgs);
  20526. });
  20527. }
  20528. });
  20529. function needSetDirty(opt, task) {
  20530. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20531. }
  20532. scheduler.unfinished |= unfinished;
  20533. }
  20534. proto.performSeriesTasks = function (ecModel) {
  20535. var unfinished;
  20536. ecModel.eachSeries(function (seriesModel) {
  20537. // Progress to the end for dataInit and dataRestore.
  20538. unfinished |= seriesModel.dataTask.perform();
  20539. });
  20540. this.unfinished |= unfinished;
  20541. };
  20542. proto.plan = function () {
  20543. // Travel pipelines, check block.
  20544. this._pipelineMap.each(function (pipeline) {
  20545. var task = pipeline.tail;
  20546. do {
  20547. if (task.__block) {
  20548. pipeline.bockIndex = task.__idxInPipeline;
  20549. break;
  20550. }
  20551. task = task.getUpstream();
  20552. }
  20553. while (task);
  20554. });
  20555. };
  20556. var updatePayload = proto.updatePayload = function (task, payload) {
  20557. payload !== 'remain' && (task.context.payload = payload);
  20558. };
  20559. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20560. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20561. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20562. var seriesType = stageHandler.seriesType;
  20563. var getTargetSeries = stageHandler.getTargetSeries;
  20564. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20565. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20566. // it works but it may cause other irrelevant charts blocked.
  20567. if (stageHandler.createOnAllSeries) {
  20568. ecModel.eachRawSeries(create);
  20569. }
  20570. else if (seriesType) {
  20571. ecModel.eachRawSeriesByType(seriesType, create);
  20572. }
  20573. else if (getTargetSeries) {
  20574. getTargetSeries(ecModel, api).each(create);
  20575. }
  20576. function create(seriesModel) {
  20577. var pipelineId = seriesModel.uid;
  20578. // Init tasks for each seriesModel only once.
  20579. // Reuse original task instance.
  20580. var task = seriesTaskMap.get(pipelineId)
  20581. || seriesTaskMap.set(pipelineId, createTask({
  20582. plan: seriesTaskPlan,
  20583. reset: seriesTaskReset,
  20584. count: seriesTaskCount
  20585. }));
  20586. task.context = {
  20587. model: seriesModel,
  20588. ecModel: ecModel,
  20589. api: api,
  20590. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20591. plan: stageHandler.plan,
  20592. reset: stageHandler.reset,
  20593. scheduler: scheduler
  20594. };
  20595. pipe(scheduler, seriesModel, task);
  20596. }
  20597. // Clear unused series tasks.
  20598. var pipelineMap = scheduler._pipelineMap;
  20599. seriesTaskMap.each(function (task, pipelineId) {
  20600. if (!pipelineMap.get(pipelineId)) {
  20601. task.dispose();
  20602. seriesTaskMap.removeKey(pipelineId);
  20603. }
  20604. });
  20605. }
  20606. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20607. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20608. // For overall task, the function only be called on reset stage.
  20609. || createTask({reset: overallTaskReset});
  20610. overallTask.context = {
  20611. ecModel: ecModel,
  20612. api: api,
  20613. overallReset: stageHandler.overallReset,
  20614. scheduler: scheduler
  20615. };
  20616. // Reuse orignal stubs.
  20617. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20618. var seriesType = stageHandler.seriesType;
  20619. var getTargetSeries = stageHandler.getTargetSeries;
  20620. var overallProgress = true;
  20621. var isOverallFilter = stageHandler.isOverallFilter;
  20622. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20623. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20624. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20625. // we set the pipeline block.
  20626. if (seriesType) {
  20627. ecModel.eachRawSeriesByType(seriesType, createStub);
  20628. }
  20629. else if (getTargetSeries) {
  20630. getTargetSeries(ecModel, api).each(createStub);
  20631. }
  20632. // Otherwise, (usually it is legancy case), the overall task will only be
  20633. // executed when upstream dirty. Otherwise the progressive rendering of all
  20634. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20635. // dirty info from upsteam.
  20636. else {
  20637. overallProgress = false;
  20638. each$1(ecModel.getSeries(), createStub);
  20639. }
  20640. function createStub(seriesModel) {
  20641. var pipelineId = seriesModel.uid;
  20642. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20643. {reset: stubReset, onDirty: stubOnDirty}
  20644. ));
  20645. stub.context = {
  20646. model: seriesModel,
  20647. overallProgress: overallProgress,
  20648. isOverallFilter: isOverallFilter
  20649. };
  20650. stub.agent = overallTask;
  20651. stub.__block = overallProgress;
  20652. pipe(scheduler, seriesModel, stub);
  20653. }
  20654. // Clear unused stubs.
  20655. var pipelineMap = scheduler._pipelineMap;
  20656. agentStubMap.each(function (stub, pipelineId) {
  20657. if (!pipelineMap.get(pipelineId)) {
  20658. stub.dispose();
  20659. agentStubMap.removeKey(pipelineId);
  20660. }
  20661. });
  20662. }
  20663. function overallTaskReset(context) {
  20664. context.overallReset(
  20665. context.ecModel, context.api, context.payload
  20666. );
  20667. }
  20668. function stubReset(context, upstreamContext) {
  20669. return context.overallProgress && stubProgress;
  20670. }
  20671. function stubProgress() {
  20672. this.agent.dirty();
  20673. this.getDownstream().dirty();
  20674. }
  20675. function stubOnDirty() {
  20676. this.agent && this.agent.dirty();
  20677. }
  20678. function seriesTaskPlan(context) {
  20679. return context.plan && context.plan(
  20680. context.model, context.ecModel, context.api, context.payload
  20681. );
  20682. }
  20683. function seriesTaskReset(context) {
  20684. if (context.useClearVisual) {
  20685. context.data.clearAllVisual();
  20686. }
  20687. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20688. context.model, context.ecModel, context.api, context.payload
  20689. ));
  20690. if (resetDefines.length) {
  20691. return seriesTaskProgress;
  20692. }
  20693. }
  20694. function seriesTaskProgress(params, context) {
  20695. var data = context.data;
  20696. var resetDefines = context.resetDefines;
  20697. for (var k = 0; k < resetDefines.length; k++) {
  20698. var resetDefine = resetDefines[k];
  20699. if (resetDefine && resetDefine.dataEach) {
  20700. for (var i = params.start; i < params.end; i++) {
  20701. resetDefine.dataEach(data, i);
  20702. }
  20703. }
  20704. else if (resetDefine && resetDefine.progress) {
  20705. resetDefine.progress(params, data);
  20706. }
  20707. }
  20708. }
  20709. function seriesTaskCount(context) {
  20710. return context.data.count();
  20711. }
  20712. function pipe(scheduler, seriesModel, task) {
  20713. var pipelineId = seriesModel.uid;
  20714. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20715. !pipeline.head && (pipeline.head = task);
  20716. pipeline.tail && pipeline.tail.pipe(task);
  20717. pipeline.tail = task;
  20718. task.__idxInPipeline = pipeline.count++;
  20719. task.__pipeline = pipeline;
  20720. }
  20721. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20722. if (isFunction$1(stageHandler)) {
  20723. stageHandler = {
  20724. overallReset: stageHandler,
  20725. seriesType: detectSeriseType(stageHandler)
  20726. };
  20727. }
  20728. stageHandler.uid = getUID('stageHandler');
  20729. visualType && (stageHandler.visualType = visualType);
  20730. return stageHandler;
  20731. };
  20732. /**
  20733. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20734. * To ensure that they can work normally, they should work in block mode, that is,
  20735. * they should not be started util the previous tasks finished. So they cause the
  20736. * progressive rendering disabled. We try to detect the series type, to narrow down
  20737. * the block range to only the series type they concern, but not all series.
  20738. */
  20739. function detectSeriseType(legacyFunc) {
  20740. seriesType = null;
  20741. try {
  20742. // Assume there is no async when calling `eachSeriesByType`.
  20743. legacyFunc(ecModelMock, apiMock);
  20744. }
  20745. catch (e) {
  20746. }
  20747. return seriesType;
  20748. }
  20749. var ecModelMock = {};
  20750. var apiMock = {};
  20751. var seriesType;
  20752. mockMethods(ecModelMock, GlobalModel);
  20753. mockMethods(apiMock, ExtensionAPI);
  20754. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20755. seriesType = type;
  20756. };
  20757. ecModelMock.eachComponent = function (cond) {
  20758. if (cond.mainType === 'series' && cond.subType) {
  20759. seriesType = cond.subType;
  20760. }
  20761. };
  20762. function mockMethods(target, Clz) {
  20763. for (var name in Clz.prototype) {
  20764. // Do not use hasOwnProperty
  20765. target[name] = noop;
  20766. }
  20767. }
  20768. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20769. var lightTheme = {
  20770. color: colorAll,
  20771. colorLayer: [
  20772. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20773. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20774. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20775. colorAll
  20776. ]
  20777. };
  20778. var contrastColor = '#eee';
  20779. var axisCommon = function () {
  20780. return {
  20781. axisLine: {
  20782. lineStyle: {
  20783. color: contrastColor
  20784. }
  20785. },
  20786. axisTick: {
  20787. lineStyle: {
  20788. color: contrastColor
  20789. }
  20790. },
  20791. axisLabel: {
  20792. textStyle: {
  20793. color: contrastColor
  20794. }
  20795. },
  20796. splitLine: {
  20797. lineStyle: {
  20798. type: 'dashed',
  20799. color: '#aaa'
  20800. }
  20801. },
  20802. splitArea: {
  20803. areaStyle: {
  20804. color: contrastColor
  20805. }
  20806. }
  20807. };
  20808. };
  20809. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20810. var theme = {
  20811. color: colorPalette,
  20812. backgroundColor: '#333',
  20813. tooltip: {
  20814. axisPointer: {
  20815. lineStyle: {
  20816. color: contrastColor
  20817. },
  20818. crossStyle: {
  20819. color: contrastColor
  20820. }
  20821. }
  20822. },
  20823. legend: {
  20824. textStyle: {
  20825. color: contrastColor
  20826. }
  20827. },
  20828. textStyle: {
  20829. color: contrastColor
  20830. },
  20831. title: {
  20832. textStyle: {
  20833. color: contrastColor
  20834. }
  20835. },
  20836. toolbox: {
  20837. iconStyle: {
  20838. normal: {
  20839. borderColor: contrastColor
  20840. }
  20841. }
  20842. },
  20843. dataZoom: {
  20844. textStyle: {
  20845. color: contrastColor
  20846. }
  20847. },
  20848. visualMap: {
  20849. textStyle: {
  20850. color: contrastColor
  20851. }
  20852. },
  20853. timeline: {
  20854. lineStyle: {
  20855. color: contrastColor
  20856. },
  20857. itemStyle: {
  20858. normal: {
  20859. color: colorPalette[1]
  20860. }
  20861. },
  20862. label: {
  20863. normal: {
  20864. textStyle: {
  20865. color: contrastColor
  20866. }
  20867. }
  20868. },
  20869. controlStyle: {
  20870. normal: {
  20871. color: contrastColor,
  20872. borderColor: contrastColor
  20873. }
  20874. }
  20875. },
  20876. timeAxis: axisCommon(),
  20877. logAxis: axisCommon(),
  20878. valueAxis: axisCommon(),
  20879. categoryAxis: axisCommon(),
  20880. line: {
  20881. symbol: 'circle'
  20882. },
  20883. graph: {
  20884. color: colorPalette
  20885. },
  20886. gauge: {
  20887. title: {
  20888. textStyle: {
  20889. color: contrastColor
  20890. }
  20891. }
  20892. },
  20893. candlestick: {
  20894. itemStyle: {
  20895. normal: {
  20896. color: '#FD1050',
  20897. color0: '#0CF49B',
  20898. borderColor: '#FD1050',
  20899. borderColor0: '#0CF49B'
  20900. }
  20901. }
  20902. }
  20903. };
  20904. theme.categoryAxis.splitLine.show = false;
  20905. /*!
  20906. * ECharts, a free, powerful charting and visualization library.
  20907. *
  20908. * Copyright (c) 2017, Baidu Inc.
  20909. * All rights reserved.
  20910. *
  20911. * LICENSE
  20912. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20913. */
  20914. var assert = assert$1;
  20915. var each = each$1;
  20916. var isFunction = isFunction$1;
  20917. var isObject = isObject$1;
  20918. var parseClassType = ComponentModel.parseClassType;
  20919. var version = '4.0.4';
  20920. var dependencies = {
  20921. zrender: '4.0.3'
  20922. };
  20923. var TEST_FRAME_REMAIN_TIME = 1;
  20924. var PRIORITY_PROCESSOR_FILTER = 1000;
  20925. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20926. var PRIORITY_VISUAL_LAYOUT = 1000;
  20927. var PRIORITY_VISUAL_GLOBAL = 2000;
  20928. var PRIORITY_VISUAL_CHART = 3000;
  20929. var PRIORITY_VISUAL_COMPONENT = 4000;
  20930. // FIXME
  20931. // necessary?
  20932. var PRIORITY_VISUAL_BRUSH = 5000;
  20933. var PRIORITY = {
  20934. PROCESSOR: {
  20935. FILTER: PRIORITY_PROCESSOR_FILTER,
  20936. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20937. },
  20938. VISUAL: {
  20939. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20940. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20941. CHART: PRIORITY_VISUAL_CHART,
  20942. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20943. BRUSH: PRIORITY_VISUAL_BRUSH
  20944. }
  20945. };
  20946. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20947. // where they must not be invoked nestedly, except the only case: invoke
  20948. // dispatchAction with updateMethod "none" in main process.
  20949. // This flag is used to carry out this rule.
  20950. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20951. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20952. var OPTION_UPDATED = '__optionUpdated';
  20953. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20954. function createRegisterEventWithLowercaseName(method) {
  20955. return function (eventName, handler, context) {
  20956. // Event name is all lowercase
  20957. eventName = eventName && eventName.toLowerCase();
  20958. Eventful.prototype[method].call(this, eventName, handler, context);
  20959. };
  20960. }
  20961. /**
  20962. * @module echarts~MessageCenter
  20963. */
  20964. function MessageCenter() {
  20965. Eventful.call(this);
  20966. }
  20967. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20968. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20969. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20970. mixin(MessageCenter, Eventful);
  20971. /**
  20972. * @module echarts~ECharts
  20973. */
  20974. function ECharts(dom, theme$$1, opts) {
  20975. opts = opts || {};
  20976. // Get theme by name
  20977. if (typeof theme$$1 === 'string') {
  20978. theme$$1 = themeStorage[theme$$1];
  20979. }
  20980. /**
  20981. * @type {string}
  20982. */
  20983. this.id;
  20984. /**
  20985. * Group id
  20986. * @type {string}
  20987. */
  20988. this.group;
  20989. /**
  20990. * @type {HTMLElement}
  20991. * @private
  20992. */
  20993. this._dom = dom;
  20994. var defaultRenderer = 'canvas';
  20995. if (__DEV__) {
  20996. defaultRenderer = (
  20997. typeof window === 'undefined' ? global : window
  20998. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20999. }
  21000. /**
  21001. * @type {module:zrender/ZRender}
  21002. * @private
  21003. */
  21004. var zr = this._zr = init$1(dom, {
  21005. renderer: opts.renderer || defaultRenderer,
  21006. devicePixelRatio: opts.devicePixelRatio,
  21007. width: opts.width,
  21008. height: opts.height
  21009. });
  21010. /**
  21011. * Expect 60 pfs.
  21012. * @type {Function}
  21013. * @private
  21014. */
  21015. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  21016. var theme$$1 = clone(theme$$1);
  21017. theme$$1 && backwardCompat(theme$$1, true);
  21018. /**
  21019. * @type {Object}
  21020. * @private
  21021. */
  21022. this._theme = theme$$1;
  21023. /**
  21024. * @type {Array.<module:echarts/view/Chart>}
  21025. * @private
  21026. */
  21027. this._chartsViews = [];
  21028. /**
  21029. * @type {Object.<string, module:echarts/view/Chart>}
  21030. * @private
  21031. */
  21032. this._chartsMap = {};
  21033. /**
  21034. * @type {Array.<module:echarts/view/Component>}
  21035. * @private
  21036. */
  21037. this._componentsViews = [];
  21038. /**
  21039. * @type {Object.<string, module:echarts/view/Component>}
  21040. * @private
  21041. */
  21042. this._componentsMap = {};
  21043. /**
  21044. * @type {module:echarts/CoordinateSystem}
  21045. * @private
  21046. */
  21047. this._coordSysMgr = new CoordinateSystemManager();
  21048. /**
  21049. * @type {module:echarts/ExtensionAPI}
  21050. * @private
  21051. */
  21052. var api = this._api = createExtensionAPI(this);
  21053. // Sort on demand
  21054. function prioritySortFunc(a, b) {
  21055. return a.__prio - b.__prio;
  21056. }
  21057. sort(visualFuncs, prioritySortFunc);
  21058. sort(dataProcessorFuncs, prioritySortFunc);
  21059. /**
  21060. * @type {module:echarts/stream/Scheduler}
  21061. */
  21062. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  21063. Eventful.call(this);
  21064. /**
  21065. * @type {module:echarts~MessageCenter}
  21066. * @private
  21067. */
  21068. this._messageCenter = new MessageCenter();
  21069. // Init mouse events
  21070. this._initEvents();
  21071. // In case some people write `window.onresize = chart.resize`
  21072. this.resize = bind(this.resize, this);
  21073. // Can't dispatch action during rendering procedure
  21074. this._pendingActions = [];
  21075. zr.animation.on('frame', this._onframe, this);
  21076. bindRenderedEvent(zr, this);
  21077. // ECharts instance can be used as value.
  21078. setAsPrimitive(this);
  21079. }
  21080. var echartsProto = ECharts.prototype;
  21081. echartsProto._onframe = function () {
  21082. if (this._disposed) {
  21083. return;
  21084. }
  21085. var scheduler = this._scheduler;
  21086. // Lazy update
  21087. if (this[OPTION_UPDATED]) {
  21088. var silent = this[OPTION_UPDATED].silent;
  21089. this[IN_MAIN_PROCESS] = true;
  21090. prepare(this);
  21091. updateMethods.update.call(this);
  21092. this[IN_MAIN_PROCESS] = false;
  21093. this[OPTION_UPDATED] = false;
  21094. flushPendingActions.call(this, silent);
  21095. triggerUpdatedEvent.call(this, silent);
  21096. }
  21097. // Avoid do both lazy update and progress in one frame.
  21098. else if (scheduler.unfinished) {
  21099. // Stream progress.
  21100. var remainTime = TEST_FRAME_REMAIN_TIME;
  21101. var ecModel = this._model;
  21102. var api = this._api;
  21103. scheduler.unfinished = false;
  21104. do {
  21105. var startTime = +new Date();
  21106. scheduler.performSeriesTasks(ecModel);
  21107. // Currently dataProcessorFuncs do not check threshold.
  21108. scheduler.performDataProcessorTasks(ecModel);
  21109. updateStreamModes(this, ecModel);
  21110. // Do not update coordinate system here. Because that coord system update in
  21111. // each frame is not a good user experience. So we follow the rule that
  21112. // the extent of the coordinate system is determin in the first frame (the
  21113. // frame is executed immedietely after task reset.
  21114. // this._coordSysMgr.update(ecModel, api);
  21115. // console.log('--- ec frame visual ---', remainTime);
  21116. scheduler.performVisualTasks(ecModel);
  21117. renderSeries(this, this._model, api, 'remain');
  21118. remainTime -= (+new Date() - startTime);
  21119. }
  21120. while (remainTime > 0 && scheduler.unfinished);
  21121. // Call flush explicitly for trigger finished event.
  21122. if (!scheduler.unfinished) {
  21123. this._zr.flush();
  21124. }
  21125. // Else, zr flushing be ensue within the same frame,
  21126. // because zr flushing is after onframe event.
  21127. }
  21128. };
  21129. /**
  21130. * @return {HTMLElement}
  21131. */
  21132. echartsProto.getDom = function () {
  21133. return this._dom;
  21134. };
  21135. /**
  21136. * @return {module:zrender~ZRender}
  21137. */
  21138. echartsProto.getZr = function () {
  21139. return this._zr;
  21140. };
  21141. /**
  21142. * Usage:
  21143. * chart.setOption(option, notMerge, lazyUpdate);
  21144. * chart.setOption(option, {
  21145. * notMerge: ...,
  21146. * lazyUpdate: ...,
  21147. * silent: ...
  21148. * });
  21149. *
  21150. * @param {Object} option
  21151. * @param {Object|boolean} [opts] opts or notMerge.
  21152. * @param {boolean} [opts.notMerge=false]
  21153. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  21154. */
  21155. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  21156. if (__DEV__) {
  21157. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  21158. }
  21159. var silent;
  21160. if (isObject(notMerge)) {
  21161. lazyUpdate = notMerge.lazyUpdate;
  21162. silent = notMerge.silent;
  21163. notMerge = notMerge.notMerge;
  21164. }
  21165. this[IN_MAIN_PROCESS] = true;
  21166. if (!this._model || notMerge) {
  21167. var optionManager = new OptionManager(this._api);
  21168. var theme$$1 = this._theme;
  21169. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  21170. ecModel.scheduler = this._scheduler;
  21171. ecModel.init(null, null, theme$$1, optionManager);
  21172. }
  21173. this._model.setOption(option, optionPreprocessorFuncs);
  21174. if (lazyUpdate) {
  21175. this[OPTION_UPDATED] = {silent: silent};
  21176. this[IN_MAIN_PROCESS] = false;
  21177. }
  21178. else {
  21179. prepare(this);
  21180. updateMethods.update.call(this);
  21181. // Ensure zr refresh sychronously, and then pixel in canvas can be
  21182. // fetched after `setOption`.
  21183. this._zr.flush();
  21184. this[OPTION_UPDATED] = false;
  21185. this[IN_MAIN_PROCESS] = false;
  21186. flushPendingActions.call(this, silent);
  21187. triggerUpdatedEvent.call(this, silent);
  21188. }
  21189. };
  21190. /**
  21191. * @DEPRECATED
  21192. */
  21193. echartsProto.setTheme = function () {
  21194. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  21195. };
  21196. /**
  21197. * @return {module:echarts/model/Global}
  21198. */
  21199. echartsProto.getModel = function () {
  21200. return this._model;
  21201. };
  21202. /**
  21203. * @return {Object}
  21204. */
  21205. echartsProto.getOption = function () {
  21206. return this._model && this._model.getOption();
  21207. };
  21208. /**
  21209. * @return {number}
  21210. */
  21211. echartsProto.getWidth = function () {
  21212. return this._zr.getWidth();
  21213. };
  21214. /**
  21215. * @return {number}
  21216. */
  21217. echartsProto.getHeight = function () {
  21218. return this._zr.getHeight();
  21219. };
  21220. /**
  21221. * @return {number}
  21222. */
  21223. echartsProto.getDevicePixelRatio = function () {
  21224. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  21225. };
  21226. /**
  21227. * Get canvas which has all thing rendered
  21228. * @param {Object} opts
  21229. * @param {string} [opts.backgroundColor]
  21230. * @return {string}
  21231. */
  21232. echartsProto.getRenderedCanvas = function (opts) {
  21233. if (!env$1.canvasSupported) {
  21234. return;
  21235. }
  21236. opts = opts || {};
  21237. opts.pixelRatio = opts.pixelRatio || 1;
  21238. opts.backgroundColor = opts.backgroundColor
  21239. || this._model.get('backgroundColor');
  21240. var zr = this._zr;
  21241. // var list = zr.storage.getDisplayList();
  21242. // Stop animations
  21243. // Never works before in init animation, so remove it.
  21244. // zrUtil.each(list, function (el) {
  21245. // el.stopAnimation(true);
  21246. // });
  21247. return zr.painter.getRenderedCanvas(opts);
  21248. };
  21249. /**
  21250. * Get svg data url
  21251. * @return {string}
  21252. */
  21253. echartsProto.getSvgDataUrl = function () {
  21254. if (!env$1.svgSupported) {
  21255. return;
  21256. }
  21257. var zr = this._zr;
  21258. var list = zr.storage.getDisplayList();
  21259. // Stop animations
  21260. each$1(list, function (el) {
  21261. el.stopAnimation(true);
  21262. });
  21263. return zr.painter.pathToDataUrl();
  21264. };
  21265. /**
  21266. * @return {string}
  21267. * @param {Object} opts
  21268. * @param {string} [opts.type='png']
  21269. * @param {string} [opts.pixelRatio=1]
  21270. * @param {string} [opts.backgroundColor]
  21271. * @param {string} [opts.excludeComponents]
  21272. */
  21273. echartsProto.getDataURL = function (opts) {
  21274. opts = opts || {};
  21275. var excludeComponents = opts.excludeComponents;
  21276. var ecModel = this._model;
  21277. var excludesComponentViews = [];
  21278. var self = this;
  21279. each(excludeComponents, function (componentType) {
  21280. ecModel.eachComponent({
  21281. mainType: componentType
  21282. }, function (component) {
  21283. var view = self._componentsMap[component.__viewId];
  21284. if (!view.group.ignore) {
  21285. excludesComponentViews.push(view);
  21286. view.group.ignore = true;
  21287. }
  21288. });
  21289. });
  21290. var url = this._zr.painter.getType() === 'svg'
  21291. ? this.getSvgDataUrl()
  21292. : this.getRenderedCanvas(opts).toDataURL(
  21293. 'image/' + (opts && opts.type || 'png')
  21294. );
  21295. each(excludesComponentViews, function (view) {
  21296. view.group.ignore = false;
  21297. });
  21298. return url;
  21299. };
  21300. /**
  21301. * @return {string}
  21302. * @param {Object} opts
  21303. * @param {string} [opts.type='png']
  21304. * @param {string} [opts.pixelRatio=1]
  21305. * @param {string} [opts.backgroundColor]
  21306. */
  21307. echartsProto.getConnectedDataURL = function (opts) {
  21308. if (!env$1.canvasSupported) {
  21309. return;
  21310. }
  21311. var groupId = this.group;
  21312. var mathMin = Math.min;
  21313. var mathMax = Math.max;
  21314. var MAX_NUMBER = Infinity;
  21315. if (connectedGroups[groupId]) {
  21316. var left = MAX_NUMBER;
  21317. var top = MAX_NUMBER;
  21318. var right = -MAX_NUMBER;
  21319. var bottom = -MAX_NUMBER;
  21320. var canvasList = [];
  21321. var dpr = (opts && opts.pixelRatio) || 1;
  21322. each$1(instances, function (chart, id) {
  21323. if (chart.group === groupId) {
  21324. var canvas = chart.getRenderedCanvas(
  21325. clone(opts)
  21326. );
  21327. var boundingRect = chart.getDom().getBoundingClientRect();
  21328. left = mathMin(boundingRect.left, left);
  21329. top = mathMin(boundingRect.top, top);
  21330. right = mathMax(boundingRect.right, right);
  21331. bottom = mathMax(boundingRect.bottom, bottom);
  21332. canvasList.push({
  21333. dom: canvas,
  21334. left: boundingRect.left,
  21335. top: boundingRect.top
  21336. });
  21337. }
  21338. });
  21339. left *= dpr;
  21340. top *= dpr;
  21341. right *= dpr;
  21342. bottom *= dpr;
  21343. var width = right - left;
  21344. var height = bottom - top;
  21345. var targetCanvas = createCanvas();
  21346. targetCanvas.width = width;
  21347. targetCanvas.height = height;
  21348. var zr = init$1(targetCanvas);
  21349. each(canvasList, function (item) {
  21350. var img = new ZImage({
  21351. style: {
  21352. x: item.left * dpr - left,
  21353. y: item.top * dpr - top,
  21354. image: item.dom
  21355. }
  21356. });
  21357. zr.add(img);
  21358. });
  21359. zr.refreshImmediately();
  21360. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21361. }
  21362. else {
  21363. return this.getDataURL(opts);
  21364. }
  21365. };
  21366. /**
  21367. * Convert from logical coordinate system to pixel coordinate system.
  21368. * See CoordinateSystem#convertToPixel.
  21369. * @param {string|Object} finder
  21370. * If string, e.g., 'geo', means {geoIndex: 0}.
  21371. * If Object, could contain some of these properties below:
  21372. * {
  21373. * seriesIndex / seriesId / seriesName,
  21374. * geoIndex / geoId, geoName,
  21375. * bmapIndex / bmapId / bmapName,
  21376. * xAxisIndex / xAxisId / xAxisName,
  21377. * yAxisIndex / yAxisId / yAxisName,
  21378. * gridIndex / gridId / gridName,
  21379. * ... (can be extended)
  21380. * }
  21381. * @param {Array|number} value
  21382. * @return {Array|number} result
  21383. */
  21384. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21385. /**
  21386. * Convert from pixel coordinate system to logical coordinate system.
  21387. * See CoordinateSystem#convertFromPixel.
  21388. * @param {string|Object} finder
  21389. * If string, e.g., 'geo', means {geoIndex: 0}.
  21390. * If Object, could contain some of these properties below:
  21391. * {
  21392. * seriesIndex / seriesId / seriesName,
  21393. * geoIndex / geoId / geoName,
  21394. * bmapIndex / bmapId / bmapName,
  21395. * xAxisIndex / xAxisId / xAxisName,
  21396. * yAxisIndex / yAxisId / yAxisName
  21397. * gridIndex / gridId / gridName,
  21398. * ... (can be extended)
  21399. * }
  21400. * @param {Array|number} value
  21401. * @return {Array|number} result
  21402. */
  21403. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21404. function doConvertPixel(methodName, finder, value) {
  21405. var ecModel = this._model;
  21406. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21407. var result;
  21408. finder = parseFinder(ecModel, finder);
  21409. for (var i = 0; i < coordSysList.length; i++) {
  21410. var coordSys = coordSysList[i];
  21411. if (coordSys[methodName]
  21412. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21413. ) {
  21414. return result;
  21415. }
  21416. }
  21417. if (__DEV__) {
  21418. console.warn(
  21419. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21420. );
  21421. }
  21422. }
  21423. /**
  21424. * Is the specified coordinate systems or components contain the given pixel point.
  21425. * @param {string|Object} finder
  21426. * If string, e.g., 'geo', means {geoIndex: 0}.
  21427. * If Object, could contain some of these properties below:
  21428. * {
  21429. * seriesIndex / seriesId / seriesName,
  21430. * geoIndex / geoId / geoName,
  21431. * bmapIndex / bmapId / bmapName,
  21432. * xAxisIndex / xAxisId / xAxisName,
  21433. * yAxisIndex / yAxisId / yAxisName,
  21434. * gridIndex / gridId / gridName,
  21435. * ... (can be extended)
  21436. * }
  21437. * @param {Array|number} value
  21438. * @return {boolean} result
  21439. */
  21440. echartsProto.containPixel = function (finder, value) {
  21441. var ecModel = this._model;
  21442. var result;
  21443. finder = parseFinder(ecModel, finder);
  21444. each$1(finder, function (models, key) {
  21445. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21446. var coordSys = model.coordinateSystem;
  21447. if (coordSys && coordSys.containPoint) {
  21448. result |= !!coordSys.containPoint(value);
  21449. }
  21450. else if (key === 'seriesModels') {
  21451. var view = this._chartsMap[model.__viewId];
  21452. if (view && view.containPoint) {
  21453. result |= view.containPoint(value, model);
  21454. }
  21455. else {
  21456. if (__DEV__) {
  21457. console.warn(key + ': ' + (view
  21458. ? 'The found component do not support containPoint.'
  21459. : 'No view mapping to the found component.'
  21460. ));
  21461. }
  21462. }
  21463. }
  21464. else {
  21465. if (__DEV__) {
  21466. console.warn(key + ': containPoint is not supported');
  21467. }
  21468. }
  21469. }, this);
  21470. }, this);
  21471. return !!result;
  21472. };
  21473. /**
  21474. * Get visual from series or data.
  21475. * @param {string|Object} finder
  21476. * If string, e.g., 'series', means {seriesIndex: 0}.
  21477. * If Object, could contain some of these properties below:
  21478. * {
  21479. * seriesIndex / seriesId / seriesName,
  21480. * dataIndex / dataIndexInside
  21481. * }
  21482. * If dataIndex is not specified, series visual will be fetched,
  21483. * but not data item visual.
  21484. * If all of seriesIndex, seriesId, seriesName are not specified,
  21485. * visual will be fetched from first series.
  21486. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21487. */
  21488. echartsProto.getVisual = function (finder, visualType) {
  21489. var ecModel = this._model;
  21490. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21491. var seriesModel = finder.seriesModel;
  21492. if (__DEV__) {
  21493. if (!seriesModel) {
  21494. console.warn('There is no specified seires model');
  21495. }
  21496. }
  21497. var data = seriesModel.getData();
  21498. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21499. ? finder.dataIndexInside
  21500. : finder.hasOwnProperty('dataIndex')
  21501. ? data.indexOfRawIndex(finder.dataIndex)
  21502. : null;
  21503. return dataIndexInside != null
  21504. ? data.getItemVisual(dataIndexInside, visualType)
  21505. : data.getVisual(visualType);
  21506. };
  21507. /**
  21508. * Get view of corresponding component model
  21509. * @param {module:echarts/model/Component} componentModel
  21510. * @return {module:echarts/view/Component}
  21511. */
  21512. echartsProto.getViewOfComponentModel = function (componentModel) {
  21513. return this._componentsMap[componentModel.__viewId];
  21514. };
  21515. /**
  21516. * Get view of corresponding series model
  21517. * @param {module:echarts/model/Series} seriesModel
  21518. * @return {module:echarts/view/Chart}
  21519. */
  21520. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21521. return this._chartsMap[seriesModel.__viewId];
  21522. };
  21523. var updateMethods = {
  21524. prepareAndUpdate: function (payload) {
  21525. prepare(this);
  21526. updateMethods.update.call(this, payload);
  21527. },
  21528. /**
  21529. * @param {Object} payload
  21530. * @private
  21531. */
  21532. update: function (payload) {
  21533. // console.profile && console.profile('update');
  21534. var ecModel = this._model;
  21535. var api = this._api;
  21536. var zr = this._zr;
  21537. var coordSysMgr = this._coordSysMgr;
  21538. var scheduler = this._scheduler;
  21539. // update before setOption
  21540. if (!ecModel) {
  21541. return;
  21542. }
  21543. ecModel.restoreData(payload);
  21544. scheduler.performSeriesTasks(ecModel);
  21545. // TODO
  21546. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21547. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21548. // Create new coordinate system each update
  21549. // In LineView may save the old coordinate system and use it to get the orignal point
  21550. coordSysMgr.create(ecModel, api);
  21551. scheduler.performDataProcessorTasks(ecModel, payload);
  21552. // Current stream render is not supported in data process. So we can update
  21553. // stream modes after data processing, where the filtered data is used to
  21554. // deteming whether use progressive rendering.
  21555. updateStreamModes(this, ecModel);
  21556. // stackSeriesData(ecModel);
  21557. coordSysMgr.update(ecModel, api);
  21558. clearColorPalette(ecModel);
  21559. scheduler.performVisualTasks(ecModel, payload);
  21560. render(this, ecModel, api, payload);
  21561. // Set background
  21562. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21563. // In IE8
  21564. if (!env$1.canvasSupported) {
  21565. var colorArr = parse(backgroundColor);
  21566. backgroundColor = stringify(colorArr, 'rgb');
  21567. if (colorArr[3] === 0) {
  21568. backgroundColor = 'transparent';
  21569. }
  21570. }
  21571. else {
  21572. zr.setBackgroundColor(backgroundColor);
  21573. }
  21574. performPostUpdateFuncs(ecModel, api);
  21575. // console.profile && console.profileEnd('update');
  21576. },
  21577. /**
  21578. * @param {Object} payload
  21579. * @private
  21580. */
  21581. updateTransform: function (payload) {
  21582. var ecModel = this._model;
  21583. var ecIns = this;
  21584. var api = this._api;
  21585. // update before setOption
  21586. if (!ecModel) {
  21587. return;
  21588. }
  21589. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21590. var componentDirtyList = [];
  21591. ecModel.eachComponent(function (componentType, componentModel) {
  21592. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21593. if (componentView && componentView.__alive) {
  21594. if (componentView.updateTransform) {
  21595. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21596. result && result.update && componentDirtyList.push(componentView);
  21597. }
  21598. else {
  21599. componentDirtyList.push(componentView);
  21600. }
  21601. }
  21602. });
  21603. var seriesDirtyMap = createHashMap();
  21604. ecModel.eachSeries(function (seriesModel) {
  21605. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21606. if (chartView.updateTransform) {
  21607. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21608. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21609. }
  21610. else {
  21611. seriesDirtyMap.set(seriesModel.uid, 1);
  21612. }
  21613. });
  21614. clearColorPalette(ecModel);
  21615. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21616. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21617. this._scheduler.performVisualTasks(
  21618. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21619. );
  21620. // Currently, not call render of components. Geo render cost a lot.
  21621. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21622. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21623. performPostUpdateFuncs(ecModel, this._api);
  21624. },
  21625. /**
  21626. * @param {Object} payload
  21627. * @private
  21628. */
  21629. updateView: function (payload) {
  21630. var ecModel = this._model;
  21631. // update before setOption
  21632. if (!ecModel) {
  21633. return;
  21634. }
  21635. Chart.markUpdateMethod(payload, 'updateView');
  21636. clearColorPalette(ecModel);
  21637. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21638. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21639. render(this, this._model, this._api, payload);
  21640. performPostUpdateFuncs(ecModel, this._api);
  21641. },
  21642. /**
  21643. * @param {Object} payload
  21644. * @private
  21645. */
  21646. updateVisual: function (payload) {
  21647. updateMethods.update.call(this, payload);
  21648. // var ecModel = this._model;
  21649. // // update before setOption
  21650. // if (!ecModel) {
  21651. // return;
  21652. // }
  21653. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21654. // clearColorPalette(ecModel);
  21655. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21656. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  21657. // render(this, this._model, this._api, payload);
  21658. // performPostUpdateFuncs(ecModel, this._api);
  21659. },
  21660. /**
  21661. * @param {Object} payload
  21662. * @private
  21663. */
  21664. updateLayout: function (payload) {
  21665. updateMethods.update.call(this, payload);
  21666. // var ecModel = this._model;
  21667. // // update before setOption
  21668. // if (!ecModel) {
  21669. // return;
  21670. // }
  21671. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21672. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21673. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21674. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21675. // render(this, this._model, this._api, payload);
  21676. // performPostUpdateFuncs(ecModel, this._api);
  21677. }
  21678. };
  21679. function prepare(ecIns) {
  21680. var ecModel = ecIns._model;
  21681. var scheduler = ecIns._scheduler;
  21682. scheduler.restorePipelines(ecModel);
  21683. scheduler.prepareStageTasks();
  21684. prepareView(ecIns, 'component', ecModel, scheduler);
  21685. prepareView(ecIns, 'chart', ecModel, scheduler);
  21686. scheduler.plan();
  21687. }
  21688. /**
  21689. * @private
  21690. */
  21691. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21692. var ecModel = ecIns._model;
  21693. // broadcast
  21694. if (!mainType) {
  21695. // FIXME
  21696. // Chart will not be update directly here, except set dirty.
  21697. // But there is no such scenario now.
  21698. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21699. return;
  21700. }
  21701. var query = {};
  21702. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21703. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21704. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21705. var condition = {mainType: mainType, query: query};
  21706. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21707. // If dispatchAction before setOption, do nothing.
  21708. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21709. callView(ecIns[
  21710. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21711. ][model.__viewId]);
  21712. }, ecIns);
  21713. function callView(view) {
  21714. view && view.__alive && view[method] && view[method](
  21715. view.__model, ecModel, ecIns._api, payload
  21716. );
  21717. }
  21718. }
  21719. /**
  21720. * Resize the chart
  21721. * @param {Object} opts
  21722. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21723. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21724. * @param {boolean} [opts.silent=false]
  21725. */
  21726. echartsProto.resize = function (opts) {
  21727. if (__DEV__) {
  21728. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21729. }
  21730. this._zr.resize(opts);
  21731. var ecModel = this._model;
  21732. // Resize loading effect
  21733. this._loadingFX && this._loadingFX.resize();
  21734. if (!ecModel) {
  21735. return;
  21736. }
  21737. var optionChanged = ecModel.resetOption('media');
  21738. var silent = opts && opts.silent;
  21739. this[IN_MAIN_PROCESS] = true;
  21740. optionChanged && prepare(this);
  21741. updateMethods.update.call(this);
  21742. this[IN_MAIN_PROCESS] = false;
  21743. flushPendingActions.call(this, silent);
  21744. triggerUpdatedEvent.call(this, silent);
  21745. };
  21746. function updateStreamModes(ecIns, ecModel) {
  21747. var chartsMap = ecIns._chartsMap;
  21748. var scheduler = ecIns._scheduler;
  21749. ecModel.eachSeries(function (seriesModel) {
  21750. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21751. });
  21752. }
  21753. /**
  21754. * Show loading effect
  21755. * @param {string} [name='default']
  21756. * @param {Object} [cfg]
  21757. */
  21758. echartsProto.showLoading = function (name, cfg) {
  21759. if (isObject(name)) {
  21760. cfg = name;
  21761. name = '';
  21762. }
  21763. name = name || 'default';
  21764. this.hideLoading();
  21765. if (!loadingEffects[name]) {
  21766. if (__DEV__) {
  21767. console.warn('Loading effects ' + name + ' not exists.');
  21768. }
  21769. return;
  21770. }
  21771. var el = loadingEffects[name](this._api, cfg);
  21772. var zr = this._zr;
  21773. this._loadingFX = el;
  21774. zr.add(el);
  21775. };
  21776. /**
  21777. * Hide loading effect
  21778. */
  21779. echartsProto.hideLoading = function () {
  21780. this._loadingFX && this._zr.remove(this._loadingFX);
  21781. this._loadingFX = null;
  21782. };
  21783. /**
  21784. * @param {Object} eventObj
  21785. * @return {Object}
  21786. */
  21787. echartsProto.makeActionFromEvent = function (eventObj) {
  21788. var payload = extend({}, eventObj);
  21789. payload.type = eventActionMap[eventObj.type];
  21790. return payload;
  21791. };
  21792. /**
  21793. * @pubilc
  21794. * @param {Object} payload
  21795. * @param {string} [payload.type] Action type
  21796. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21797. * @param {boolean} [opt.silent=false] Whether trigger events.
  21798. * @param {boolean} [opt.flush=undefined]
  21799. * true: Flush immediately, and then pixel in canvas can be fetched
  21800. * immediately. Caution: it might affect performance.
  21801. * false: Not not flush.
  21802. * undefined: Auto decide whether perform flush.
  21803. */
  21804. echartsProto.dispatchAction = function (payload, opt) {
  21805. if (!isObject(opt)) {
  21806. opt = {silent: !!opt};
  21807. }
  21808. if (!actions[payload.type]) {
  21809. return;
  21810. }
  21811. // Avoid dispatch action before setOption. Especially in `connect`.
  21812. if (!this._model) {
  21813. return;
  21814. }
  21815. // May dispatchAction in rendering procedure
  21816. if (this[IN_MAIN_PROCESS]) {
  21817. this._pendingActions.push(payload);
  21818. return;
  21819. }
  21820. doDispatchAction.call(this, payload, opt.silent);
  21821. if (opt.flush) {
  21822. this._zr.flush(true);
  21823. }
  21824. else if (opt.flush !== false && env$1.browser.weChat) {
  21825. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21826. // hang when sliding page (on touch event), which cause that zr does not
  21827. // refresh util user interaction finished, which is not expected.
  21828. // But `dispatchAction` may be called too frequently when pan on touch
  21829. // screen, which impacts performance if do not throttle them.
  21830. this._throttledZrFlush();
  21831. }
  21832. flushPendingActions.call(this, opt.silent);
  21833. triggerUpdatedEvent.call(this, opt.silent);
  21834. };
  21835. function doDispatchAction(payload, silent) {
  21836. var payloadType = payload.type;
  21837. var escapeConnect = payload.escapeConnect;
  21838. var actionWrap = actions[payloadType];
  21839. var actionInfo = actionWrap.actionInfo;
  21840. var cptType = (actionInfo.update || 'update').split(':');
  21841. var updateMethod = cptType.pop();
  21842. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21843. this[IN_MAIN_PROCESS] = true;
  21844. var payloads = [payload];
  21845. var batched = false;
  21846. // Batch action
  21847. if (payload.batch) {
  21848. batched = true;
  21849. payloads = map(payload.batch, function (item) {
  21850. item = defaults(extend({}, item), payload);
  21851. item.batch = null;
  21852. return item;
  21853. });
  21854. }
  21855. var eventObjBatch = [];
  21856. var eventObj;
  21857. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21858. each(payloads, function (batchItem) {
  21859. // Action can specify the event by return it.
  21860. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21861. // Emit event outside
  21862. eventObj = eventObj || extend({}, batchItem);
  21863. // Convert type to eventType
  21864. eventObj.type = actionInfo.event || eventObj.type;
  21865. eventObjBatch.push(eventObj);
  21866. // light update does not perform data process, layout and visual.
  21867. if (isHighDown) {
  21868. // method, payload, mainType, subType
  21869. updateDirectly(this, updateMethod, batchItem, 'series');
  21870. }
  21871. else if (cptType) {
  21872. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21873. }
  21874. }, this);
  21875. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21876. // Still dirty
  21877. if (this[OPTION_UPDATED]) {
  21878. // FIXME Pass payload ?
  21879. prepare(this);
  21880. updateMethods.update.call(this, payload);
  21881. this[OPTION_UPDATED] = false;
  21882. }
  21883. else {
  21884. updateMethods[updateMethod].call(this, payload);
  21885. }
  21886. }
  21887. // Follow the rule of action batch
  21888. if (batched) {
  21889. eventObj = {
  21890. type: actionInfo.event || payloadType,
  21891. escapeConnect: escapeConnect,
  21892. batch: eventObjBatch
  21893. };
  21894. }
  21895. else {
  21896. eventObj = eventObjBatch[0];
  21897. }
  21898. this[IN_MAIN_PROCESS] = false;
  21899. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21900. }
  21901. function flushPendingActions(silent) {
  21902. var pendingActions = this._pendingActions;
  21903. while (pendingActions.length) {
  21904. var payload = pendingActions.shift();
  21905. doDispatchAction.call(this, payload, silent);
  21906. }
  21907. }
  21908. function triggerUpdatedEvent(silent) {
  21909. !silent && this.trigger('updated');
  21910. }
  21911. /**
  21912. * Event `rendered` is triggered when zr
  21913. * rendered. It is useful for realtime
  21914. * snapshot (reflect animation).
  21915. *
  21916. * Event `finished` is triggered when:
  21917. * (1) zrender rendering finished.
  21918. * (2) initial animation finished.
  21919. * (3) progressive rendering finished.
  21920. * (4) no pending action.
  21921. * (5) no delayed setOption needs to be processed.
  21922. */
  21923. function bindRenderedEvent(zr, ecIns) {
  21924. zr.on('rendered', function () {
  21925. ecIns.trigger('rendered');
  21926. // The `finished` event should not be triggered repeatly,
  21927. // so it should only be triggered when rendering indeed happend
  21928. // in zrender. (Consider the case that dipatchAction is keep
  21929. // triggering when mouse move).
  21930. if (
  21931. // Although zr is dirty if initial animation is not finished
  21932. // and this checking is called on frame, we also check
  21933. // animation finished for robustness.
  21934. zr.animation.isFinished()
  21935. && !ecIns[OPTION_UPDATED]
  21936. && !ecIns._scheduler.unfinished
  21937. && !ecIns._pendingActions.length
  21938. ) {
  21939. ecIns.trigger('finished');
  21940. }
  21941. });
  21942. }
  21943. /**
  21944. * @param {Object} params
  21945. * @param {number} params.seriesIndex
  21946. * @param {Array|TypedArray} params.data
  21947. */
  21948. echartsProto.appendData = function (params) {
  21949. var seriesIndex = params.seriesIndex;
  21950. var ecModel = this.getModel();
  21951. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21952. if (__DEV__) {
  21953. assert(params.data && seriesModel);
  21954. }
  21955. seriesModel.appendData(params);
  21956. // Note: `appendData` does not support that update extent of coordinate
  21957. // system, util some scenario require that. In the expected usage of
  21958. // `appendData`, the initial extent of coordinate system should better
  21959. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  21960. // the extent changed while `appendData`, the location of the painted
  21961. // graphic elements have to be changed, which make the usage of
  21962. // `appendData` meaningless.
  21963. this._scheduler.unfinished = true;
  21964. };
  21965. /**
  21966. * Register event
  21967. * @method
  21968. */
  21969. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21970. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21971. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21972. /**
  21973. * Prepare view instances of charts and components
  21974. * @param {module:echarts/model/Global} ecModel
  21975. * @private
  21976. */
  21977. function prepareView(ecIns, type, ecModel, scheduler) {
  21978. var isComponent = type === 'component';
  21979. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21980. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21981. var zr = ecIns._zr;
  21982. var api = ecIns._api;
  21983. for (var i = 0; i < viewList.length; i++) {
  21984. viewList[i].__alive = false;
  21985. }
  21986. isComponent
  21987. ? ecModel.eachComponent(function (componentType, model) {
  21988. componentType !== 'series' && doPrepare(model);
  21989. })
  21990. : ecModel.eachSeries(doPrepare);
  21991. function doPrepare(model) {
  21992. // Consider: id same and type changed.
  21993. var viewId = '_ec_' + model.id + '_' + model.type;
  21994. var view = viewMap[viewId];
  21995. if (!view) {
  21996. var classType = parseClassType(model.type);
  21997. var Clazz = isComponent
  21998. ? Component.getClass(classType.main, classType.sub)
  21999. : Chart.getClass(classType.sub);
  22000. if (__DEV__) {
  22001. assert(Clazz, classType.sub + ' does not exist.');
  22002. }
  22003. view = new Clazz();
  22004. view.init(ecModel, api);
  22005. viewMap[viewId] = view;
  22006. viewList.push(view);
  22007. zr.add(view.group);
  22008. }
  22009. model.__viewId = view.__id = viewId;
  22010. view.__alive = true;
  22011. view.__model = model;
  22012. view.group.__ecComponentInfo = {
  22013. mainType: model.mainType,
  22014. index: model.componentIndex
  22015. };
  22016. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  22017. }
  22018. for (var i = 0; i < viewList.length;) {
  22019. var view = viewList[i];
  22020. if (!view.__alive) {
  22021. !isComponent && view.renderTask.dispose();
  22022. zr.remove(view.group);
  22023. view.dispose(ecModel, api);
  22024. viewList.splice(i, 1);
  22025. delete viewMap[view.__id];
  22026. view.__id = view.group.__ecComponentInfo = null;
  22027. }
  22028. else {
  22029. i++;
  22030. }
  22031. }
  22032. }
  22033. // /**
  22034. // * Encode visual infomation from data after data processing
  22035. // *
  22036. // * @param {module:echarts/model/Global} ecModel
  22037. // * @param {object} layout
  22038. // * @param {boolean} [layoutFilter] `true`: only layout,
  22039. // * `false`: only not layout,
  22040. // * `null`/`undefined`: all.
  22041. // * @param {string} taskBaseTag
  22042. // * @private
  22043. // */
  22044. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  22045. // each(visualFuncs, function (visual, index) {
  22046. // var isLayout = visual.isLayout;
  22047. // if (layoutFilter == null
  22048. // || (layoutFilter === false && !isLayout)
  22049. // || (layoutFilter === true && isLayout)
  22050. // ) {
  22051. // visual.func(ecModel, api, payload);
  22052. // }
  22053. // });
  22054. // }
  22055. function clearColorPalette(ecModel) {
  22056. ecModel.clearColorPalette();
  22057. ecModel.eachSeries(function (seriesModel) {
  22058. seriesModel.clearColorPalette();
  22059. });
  22060. }
  22061. function render(ecIns, ecModel, api, payload) {
  22062. renderComponents(ecIns, ecModel, api, payload);
  22063. each(ecIns._chartsViews, function (chart) {
  22064. chart.__alive = false;
  22065. });
  22066. renderSeries(ecIns, ecModel, api, payload);
  22067. // Remove groups of unrendered charts
  22068. each(ecIns._chartsViews, function (chart) {
  22069. if (!chart.__alive) {
  22070. chart.remove(ecModel, api);
  22071. }
  22072. });
  22073. }
  22074. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  22075. each(dirtyList || ecIns._componentsViews, function (componentView) {
  22076. var componentModel = componentView.__model;
  22077. componentView.render(componentModel, ecModel, api, payload);
  22078. updateZ(componentModel, componentView);
  22079. });
  22080. }
  22081. /**
  22082. * Render each chart and component
  22083. * @private
  22084. */
  22085. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  22086. // Render all charts
  22087. var scheduler = ecIns._scheduler;
  22088. var unfinished;
  22089. ecModel.eachSeries(function (seriesModel) {
  22090. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22091. chartView.__alive = true;
  22092. var renderTask = chartView.renderTask;
  22093. scheduler.updatePayload(renderTask, payload);
  22094. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  22095. renderTask.dirty();
  22096. }
  22097. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  22098. chartView.group.silent = !!seriesModel.get('silent');
  22099. updateZ(seriesModel, chartView);
  22100. updateBlend(seriesModel, chartView);
  22101. });
  22102. scheduler.unfinished |= unfinished;
  22103. // If use hover layer
  22104. updateHoverLayerStatus(ecIns._zr, ecModel);
  22105. // Add aria
  22106. aria(ecIns._zr.dom, ecModel);
  22107. }
  22108. function performPostUpdateFuncs(ecModel, api) {
  22109. each(postUpdateFuncs, function (func) {
  22110. func(ecModel, api);
  22111. });
  22112. }
  22113. var MOUSE_EVENT_NAMES = [
  22114. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  22115. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  22116. ];
  22117. /**
  22118. * @private
  22119. */
  22120. echartsProto._initEvents = function () {
  22121. each(MOUSE_EVENT_NAMES, function (eveName) {
  22122. this._zr.on(eveName, function (e) {
  22123. var ecModel = this.getModel();
  22124. var el = e.target;
  22125. var params;
  22126. // no e.target when 'globalout'.
  22127. if (eveName === 'globalout') {
  22128. params = {};
  22129. }
  22130. else if (el && el.dataIndex != null) {
  22131. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  22132. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  22133. }
  22134. // If element has custom eventData of components
  22135. else if (el && el.eventData) {
  22136. params = extend({}, el.eventData);
  22137. }
  22138. if (params) {
  22139. params.event = e;
  22140. params.type = eveName;
  22141. this.trigger(eveName, params);
  22142. }
  22143. }, this);
  22144. }, this);
  22145. each(eventActionMap, function (actionType, eventType) {
  22146. this._messageCenter.on(eventType, function (event) {
  22147. this.trigger(eventType, event);
  22148. }, this);
  22149. }, this);
  22150. };
  22151. /**
  22152. * @return {boolean}
  22153. */
  22154. echartsProto.isDisposed = function () {
  22155. return this._disposed;
  22156. };
  22157. /**
  22158. * Clear
  22159. */
  22160. echartsProto.clear = function () {
  22161. this.setOption({ series: [] }, true);
  22162. };
  22163. /**
  22164. * Dispose instance
  22165. */
  22166. echartsProto.dispose = function () {
  22167. if (this._disposed) {
  22168. if (__DEV__) {
  22169. console.warn('Instance ' + this.id + ' has been disposed');
  22170. }
  22171. return;
  22172. }
  22173. this._disposed = true;
  22174. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  22175. var api = this._api;
  22176. var ecModel = this._model;
  22177. each(this._componentsViews, function (component) {
  22178. component.dispose(ecModel, api);
  22179. });
  22180. each(this._chartsViews, function (chart) {
  22181. chart.dispose(ecModel, api);
  22182. });
  22183. // Dispose after all views disposed
  22184. this._zr.dispose();
  22185. delete instances[this.id];
  22186. };
  22187. mixin(ECharts, Eventful);
  22188. function updateHoverLayerStatus(zr, ecModel) {
  22189. var storage = zr.storage;
  22190. var elCount = 0;
  22191. storage.traverse(function (el) {
  22192. if (!el.isGroup) {
  22193. elCount++;
  22194. }
  22195. });
  22196. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  22197. storage.traverse(function (el) {
  22198. if (!el.isGroup) {
  22199. // Don't switch back.
  22200. el.useHoverLayer = true;
  22201. }
  22202. });
  22203. }
  22204. }
  22205. /**
  22206. * Update chart progressive and blend.
  22207. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22208. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22209. */
  22210. function updateBlend(seriesModel, chartView) {
  22211. var blendMode = seriesModel.get('blendMode') || null;
  22212. if (__DEV__) {
  22213. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  22214. console.warn('Only canvas support blendMode');
  22215. }
  22216. }
  22217. chartView.group.traverse(function (el) {
  22218. // FIXME marker and other components
  22219. if (!el.isGroup) {
  22220. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  22221. if (el.style.blend !== blendMode) {
  22222. el.setStyle('blend', blendMode);
  22223. }
  22224. }
  22225. if (el.eachPendingDisplayable) {
  22226. el.eachPendingDisplayable(function (displayable) {
  22227. displayable.setStyle('blend', blendMode);
  22228. });
  22229. }
  22230. });
  22231. }
  22232. /**
  22233. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22234. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22235. */
  22236. function updateZ(model, view) {
  22237. var z = model.get('z');
  22238. var zlevel = model.get('zlevel');
  22239. // Set z and zlevel
  22240. view.group.traverse(function (el) {
  22241. if (el.type !== 'group') {
  22242. z != null && (el.z = z);
  22243. zlevel != null && (el.zlevel = zlevel);
  22244. }
  22245. });
  22246. }
  22247. function createExtensionAPI(ecInstance) {
  22248. var coordSysMgr = ecInstance._coordSysMgr;
  22249. return extend(new ExtensionAPI(ecInstance), {
  22250. // Inject methods
  22251. getCoordinateSystems: bind(
  22252. coordSysMgr.getCoordinateSystems, coordSysMgr
  22253. ),
  22254. getComponentByElement: function (el) {
  22255. while (el) {
  22256. var modelInfo = el.__ecComponentInfo;
  22257. if (modelInfo != null) {
  22258. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  22259. }
  22260. el = el.parent;
  22261. }
  22262. }
  22263. });
  22264. }
  22265. /**
  22266. * @type {Object} key: actionType.
  22267. * @inner
  22268. */
  22269. var actions = {};
  22270. /**
  22271. * Map eventType to actionType
  22272. * @type {Object}
  22273. */
  22274. var eventActionMap = {};
  22275. /**
  22276. * Data processor functions of each stage
  22277. * @type {Array.<Object.<string, Function>>}
  22278. * @inner
  22279. */
  22280. var dataProcessorFuncs = [];
  22281. /**
  22282. * @type {Array.<Function>}
  22283. * @inner
  22284. */
  22285. var optionPreprocessorFuncs = [];
  22286. /**
  22287. * @type {Array.<Function>}
  22288. * @inner
  22289. */
  22290. var postUpdateFuncs = [];
  22291. /**
  22292. * Visual encoding functions of each stage
  22293. * @type {Array.<Object.<string, Function>>}
  22294. */
  22295. var visualFuncs = [];
  22296. /**
  22297. * Theme storage
  22298. * @type {Object.<key, Object>}
  22299. */
  22300. var themeStorage = {};
  22301. /**
  22302. * Loading effects
  22303. */
  22304. var loadingEffects = {};
  22305. var instances = {};
  22306. var connectedGroups = {};
  22307. var idBase = new Date() - 0;
  22308. var groupIdBase = new Date() - 0;
  22309. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  22310. var mapDataStores = {};
  22311. function enableConnect(chart) {
  22312. var STATUS_PENDING = 0;
  22313. var STATUS_UPDATING = 1;
  22314. var STATUS_UPDATED = 2;
  22315. var STATUS_KEY = '__connectUpdateStatus';
  22316. function updateConnectedChartsStatus(charts, status) {
  22317. for (var i = 0; i < charts.length; i++) {
  22318. var otherChart = charts[i];
  22319. otherChart[STATUS_KEY] = status;
  22320. }
  22321. }
  22322. each(eventActionMap, function (actionType, eventType) {
  22323. chart._messageCenter.on(eventType, function (event) {
  22324. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  22325. if (event && event.escapeConnect) {
  22326. return;
  22327. }
  22328. var action = chart.makeActionFromEvent(event);
  22329. var otherCharts = [];
  22330. each(instances, function (otherChart) {
  22331. if (otherChart !== chart && otherChart.group === chart.group) {
  22332. otherCharts.push(otherChart);
  22333. }
  22334. });
  22335. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22336. each(otherCharts, function (otherChart) {
  22337. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22338. otherChart.dispatchAction(action);
  22339. }
  22340. });
  22341. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22342. }
  22343. });
  22344. });
  22345. }
  22346. /**
  22347. * @param {HTMLElement} dom
  22348. * @param {Object} [theme]
  22349. * @param {Object} opts
  22350. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22351. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22352. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22353. * Can be 'auto' (the same as null/undefined)
  22354. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22355. * Can be 'auto' (the same as null/undefined)
  22356. */
  22357. function init(dom, theme$$1, opts) {
  22358. if (__DEV__) {
  22359. // Check version
  22360. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22361. throw new Error(
  22362. 'zrender/src ' + version$1
  22363. + ' is too old for ECharts ' + version
  22364. + '. Current version need ZRender '
  22365. + dependencies.zrender + '+'
  22366. );
  22367. }
  22368. if (!dom) {
  22369. throw new Error('Initialize failed: invalid dom.');
  22370. }
  22371. }
  22372. var existInstance = getInstanceByDom(dom);
  22373. if (existInstance) {
  22374. if (__DEV__) {
  22375. console.warn('There is a chart instance already initialized on the dom.');
  22376. }
  22377. return existInstance;
  22378. }
  22379. if (__DEV__) {
  22380. if (isDom(dom)
  22381. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22382. && (
  22383. (!dom.clientWidth && (!opts || opts.width == null))
  22384. || (!dom.clientHeight && (!opts || opts.height == null))
  22385. )
  22386. ) {
  22387. console.warn('Can\'t get dom width or height');
  22388. }
  22389. }
  22390. var chart = new ECharts(dom, theme$$1, opts);
  22391. chart.id = 'ec_' + idBase++;
  22392. instances[chart.id] = chart;
  22393. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22394. enableConnect(chart);
  22395. return chart;
  22396. }
  22397. /**
  22398. * @return {string|Array.<module:echarts~ECharts>} groupId
  22399. */
  22400. function connect(groupId) {
  22401. // Is array of charts
  22402. if (isArray(groupId)) {
  22403. var charts = groupId;
  22404. groupId = null;
  22405. // If any chart has group
  22406. each(charts, function (chart) {
  22407. if (chart.group != null) {
  22408. groupId = chart.group;
  22409. }
  22410. });
  22411. groupId = groupId || ('g_' + groupIdBase++);
  22412. each(charts, function (chart) {
  22413. chart.group = groupId;
  22414. });
  22415. }
  22416. connectedGroups[groupId] = true;
  22417. return groupId;
  22418. }
  22419. /**
  22420. * @DEPRECATED
  22421. * @return {string} groupId
  22422. */
  22423. function disConnect(groupId) {
  22424. connectedGroups[groupId] = false;
  22425. }
  22426. /**
  22427. * @return {string} groupId
  22428. */
  22429. var disconnect = disConnect;
  22430. /**
  22431. * Dispose a chart instance
  22432. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22433. */
  22434. function dispose(chart) {
  22435. if (typeof chart === 'string') {
  22436. chart = instances[chart];
  22437. }
  22438. else if (!(chart instanceof ECharts)){
  22439. // Try to treat as dom
  22440. chart = getInstanceByDom(chart);
  22441. }
  22442. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22443. chart.dispose();
  22444. }
  22445. }
  22446. /**
  22447. * @param {HTMLElement} dom
  22448. * @return {echarts~ECharts}
  22449. */
  22450. function getInstanceByDom(dom) {
  22451. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22452. }
  22453. /**
  22454. * @param {string} key
  22455. * @return {echarts~ECharts}
  22456. */
  22457. function getInstanceById(key) {
  22458. return instances[key];
  22459. }
  22460. /**
  22461. * Register theme
  22462. */
  22463. function registerTheme(name, theme$$1) {
  22464. themeStorage[name] = theme$$1;
  22465. }
  22466. /**
  22467. * Register option preprocessor
  22468. * @param {Function} preprocessorFunc
  22469. */
  22470. function registerPreprocessor(preprocessorFunc) {
  22471. optionPreprocessorFuncs.push(preprocessorFunc);
  22472. }
  22473. /**
  22474. * @param {number} [priority=1000]
  22475. * @param {Object|Function} processor
  22476. */
  22477. function registerProcessor(priority, processor) {
  22478. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22479. }
  22480. /**
  22481. * Register postUpdater
  22482. * @param {Function} postUpdateFunc
  22483. */
  22484. function registerPostUpdate(postUpdateFunc) {
  22485. postUpdateFuncs.push(postUpdateFunc);
  22486. }
  22487. /**
  22488. * Usage:
  22489. * registerAction('someAction', 'someEvent', function () { ... });
  22490. * registerAction('someAction', function () { ... });
  22491. * registerAction(
  22492. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22493. * function () { ... }
  22494. * );
  22495. *
  22496. * @param {(string|Object)} actionInfo
  22497. * @param {string} actionInfo.type
  22498. * @param {string} [actionInfo.event]
  22499. * @param {string} [actionInfo.update]
  22500. * @param {string} [eventName]
  22501. * @param {Function} action
  22502. */
  22503. function registerAction(actionInfo, eventName, action) {
  22504. if (typeof eventName === 'function') {
  22505. action = eventName;
  22506. eventName = '';
  22507. }
  22508. var actionType = isObject(actionInfo)
  22509. ? actionInfo.type
  22510. : ([actionInfo, actionInfo = {
  22511. event: eventName
  22512. }][0]);
  22513. // Event name is all lowercase
  22514. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22515. eventName = actionInfo.event;
  22516. // Validate action type and event name.
  22517. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22518. if (!actions[actionType]) {
  22519. actions[actionType] = {action: action, actionInfo: actionInfo};
  22520. }
  22521. eventActionMap[eventName] = actionType;
  22522. }
  22523. /**
  22524. * @param {string} type
  22525. * @param {*} CoordinateSystem
  22526. */
  22527. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22528. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22529. }
  22530. /**
  22531. * Get dimensions of specified coordinate system.
  22532. * @param {string} type
  22533. * @return {Array.<string|Object>}
  22534. */
  22535. function getCoordinateSystemDimensions(type) {
  22536. var coordSysCreator = CoordinateSystemManager.get(type);
  22537. if (coordSysCreator) {
  22538. return coordSysCreator.getDimensionsInfo
  22539. ? coordSysCreator.getDimensionsInfo()
  22540. : coordSysCreator.dimensions.slice();
  22541. }
  22542. }
  22543. /**
  22544. * Layout is a special stage of visual encoding
  22545. * Most visual encoding like color are common for different chart
  22546. * But each chart has it's own layout algorithm
  22547. *
  22548. * @param {number} [priority=1000]
  22549. * @param {Function} layoutTask
  22550. */
  22551. function registerLayout(priority, layoutTask) {
  22552. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22553. }
  22554. /**
  22555. * @param {number} [priority=3000]
  22556. * @param {module:echarts/stream/Task} visualTask
  22557. */
  22558. function registerVisual(priority, visualTask) {
  22559. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22560. }
  22561. /**
  22562. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22563. */
  22564. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22565. if (isFunction(priority) || isObject(priority)) {
  22566. fn = priority;
  22567. priority = defaultPriority;
  22568. }
  22569. if (__DEV__) {
  22570. if (isNaN(priority) || priority == null) {
  22571. throw new Error('Illegal priority');
  22572. }
  22573. // Check duplicate
  22574. each(targetList, function (wrap) {
  22575. assert(wrap.__raw !== fn);
  22576. });
  22577. }
  22578. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22579. stageHandler.__prio = priority;
  22580. stageHandler.__raw = fn;
  22581. targetList.push(stageHandler);
  22582. return stageHandler;
  22583. }
  22584. /**
  22585. * @param {string} name
  22586. */
  22587. function registerLoading(name, loadingFx) {
  22588. loadingEffects[name] = loadingFx;
  22589. }
  22590. /**
  22591. * @param {Object} opts
  22592. * @param {string} [superClass]
  22593. */
  22594. function extendComponentModel(opts/*, superClass*/) {
  22595. // var Clazz = ComponentModel;
  22596. // if (superClass) {
  22597. // var classType = parseClassType(superClass);
  22598. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22599. // }
  22600. return ComponentModel.extend(opts);
  22601. }
  22602. /**
  22603. * @param {Object} opts
  22604. * @param {string} [superClass]
  22605. */
  22606. function extendComponentView(opts/*, superClass*/) {
  22607. // var Clazz = ComponentView;
  22608. // if (superClass) {
  22609. // var classType = parseClassType(superClass);
  22610. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22611. // }
  22612. return Component.extend(opts);
  22613. }
  22614. /**
  22615. * @param {Object} opts
  22616. * @param {string} [superClass]
  22617. */
  22618. function extendSeriesModel(opts/*, superClass*/) {
  22619. // var Clazz = SeriesModel;
  22620. // if (superClass) {
  22621. // superClass = 'series.' + superClass.replace('series.', '');
  22622. // var classType = parseClassType(superClass);
  22623. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22624. // }
  22625. return SeriesModel.extend(opts);
  22626. }
  22627. /**
  22628. * @param {Object} opts
  22629. * @param {string} [superClass]
  22630. */
  22631. function extendChartView(opts/*, superClass*/) {
  22632. // var Clazz = ChartView;
  22633. // if (superClass) {
  22634. // superClass = superClass.replace('series.', '');
  22635. // var classType = parseClassType(superClass);
  22636. // Clazz = ChartView.getClass(classType.main, true);
  22637. // }
  22638. return Chart.extend(opts);
  22639. }
  22640. /**
  22641. * ZRender need a canvas context to do measureText.
  22642. * But in node environment canvas may be created by node-canvas.
  22643. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22644. *
  22645. * Be careful of using it in the browser.
  22646. *
  22647. * @param {Function} creator
  22648. * @example
  22649. * var Canvas = require('canvas');
  22650. * var echarts = require('echarts');
  22651. * echarts.setCanvasCreator(function () {
  22652. * // Small size is enough.
  22653. * return new Canvas(32, 32);
  22654. * });
  22655. */
  22656. function setCanvasCreator(creator) {
  22657. $override('createCanvas', creator);
  22658. }
  22659. /**
  22660. * @param {string} mapName
  22661. * @param {Object|string} geoJson
  22662. * @param {Object} [specialAreas]
  22663. *
  22664. * @example
  22665. * $.get('USA.json', function (geoJson) {
  22666. * echarts.registerMap('USA', geoJson);
  22667. * // Or
  22668. * echarts.registerMap('USA', {
  22669. * geoJson: geoJson,
  22670. * specialAreas: {}
  22671. * })
  22672. * });
  22673. */
  22674. function registerMap(mapName, geoJson, specialAreas) {
  22675. if (geoJson.geoJson && !geoJson.features) {
  22676. specialAreas = geoJson.specialAreas;
  22677. geoJson = geoJson.geoJson;
  22678. }
  22679. if (typeof geoJson === 'string') {
  22680. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22681. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22682. }
  22683. mapDataStores[mapName] = {
  22684. geoJson: geoJson,
  22685. specialAreas: specialAreas
  22686. };
  22687. }
  22688. /**
  22689. * @param {string} mapName
  22690. * @return {Object}
  22691. */
  22692. function getMap(mapName) {
  22693. return mapDataStores[mapName];
  22694. }
  22695. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22696. registerPreprocessor(backwardCompat);
  22697. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  22698. registerLoading('default', loadingDefault);
  22699. // Default actions
  22700. registerAction({
  22701. type: 'highlight',
  22702. event: 'highlight',
  22703. update: 'highlight'
  22704. }, noop);
  22705. registerAction({
  22706. type: 'downplay',
  22707. event: 'downplay',
  22708. update: 'downplay'
  22709. }, noop);
  22710. // Default theme
  22711. registerTheme('light', lightTheme);
  22712. registerTheme('dark', theme);
  22713. // For backward compatibility, where the namespace `dataTool` will
  22714. // be mounted on `echarts` is the extension `dataTool` is imported.
  22715. var dataTool = {};
  22716. function defaultKeyGetter(item) {
  22717. return item;
  22718. }
  22719. /**
  22720. * @param {Array} oldArr
  22721. * @param {Array} newArr
  22722. * @param {Function} oldKeyGetter
  22723. * @param {Function} newKeyGetter
  22724. * @param {Object} [context] Can be visited by this.context in callback.
  22725. */
  22726. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22727. this._old = oldArr;
  22728. this._new = newArr;
  22729. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22730. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22731. this.context = context;
  22732. }
  22733. DataDiffer.prototype = {
  22734. constructor: DataDiffer,
  22735. /**
  22736. * Callback function when add a data
  22737. */
  22738. add: function (func) {
  22739. this._add = func;
  22740. return this;
  22741. },
  22742. /**
  22743. * Callback function when update a data
  22744. */
  22745. update: function (func) {
  22746. this._update = func;
  22747. return this;
  22748. },
  22749. /**
  22750. * Callback function when remove a data
  22751. */
  22752. remove: function (func) {
  22753. this._remove = func;
  22754. return this;
  22755. },
  22756. execute: function () {
  22757. var oldArr = this._old;
  22758. var newArr = this._new;
  22759. var oldDataIndexMap = {};
  22760. var newDataIndexMap = {};
  22761. var oldDataKeyArr = [];
  22762. var newDataKeyArr = [];
  22763. var i;
  22764. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22765. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22766. // Travel by inverted order to make sure order consistency
  22767. // when duplicate keys exists (consider newDataIndex.pop() below).
  22768. // For performance consideration, these code below do not look neat.
  22769. for (i = 0; i < oldArr.length; i++) {
  22770. var key = oldDataKeyArr[i];
  22771. var idx = newDataIndexMap[key];
  22772. // idx can never be empty array here. see 'set null' logic below.
  22773. if (idx != null) {
  22774. // Consider there is duplicate key (for example, use dataItem.name as key).
  22775. // We should make sure every item in newArr and oldArr can be visited.
  22776. var len = idx.length;
  22777. if (len) {
  22778. len === 1 && (newDataIndexMap[key] = null);
  22779. idx = idx.unshift();
  22780. }
  22781. else {
  22782. newDataIndexMap[key] = null;
  22783. }
  22784. this._update && this._update(idx, i);
  22785. }
  22786. else {
  22787. this._remove && this._remove(i);
  22788. }
  22789. }
  22790. for (var i = 0; i < newDataKeyArr.length; i++) {
  22791. var key = newDataKeyArr[i];
  22792. if (newDataIndexMap.hasOwnProperty(key)) {
  22793. var idx = newDataIndexMap[key];
  22794. if (idx == null) {
  22795. continue;
  22796. }
  22797. // idx can never be empty array here. see 'set null' logic above.
  22798. if (!idx.length) {
  22799. this._add && this._add(idx);
  22800. }
  22801. else {
  22802. for (var j = 0, len = idx.length; j < len; j++) {
  22803. this._add && this._add(idx[j]);
  22804. }
  22805. }
  22806. }
  22807. }
  22808. }
  22809. };
  22810. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22811. for (var i = 0; i < arr.length; i++) {
  22812. // Add prefix to avoid conflict with Object.prototype.
  22813. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22814. var existence = map[key];
  22815. if (existence == null) {
  22816. keyArr.push(key);
  22817. map[key] = i;
  22818. }
  22819. else {
  22820. if (!existence.length) {
  22821. map[key] = existence = [existence];
  22822. }
  22823. existence.push(i);
  22824. }
  22825. }
  22826. }
  22827. var OTHER_DIMENSIONS = createHashMap([
  22828. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22829. ]);
  22830. function summarizeDimensions(data) {
  22831. var summary = {};
  22832. var encode = summary.encode = {};
  22833. var notExtraCoordDimMap = createHashMap();
  22834. var defaultedLabel = [];
  22835. each$1(data.dimensions, function (dimName) {
  22836. var dimItem = data.getDimensionInfo(dimName);
  22837. var coordDim = dimItem.coordDim;
  22838. if (coordDim) {
  22839. if (__DEV__) {
  22840. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22841. }
  22842. var coordDimArr = encode[coordDim];
  22843. if (!encode.hasOwnProperty(coordDim)) {
  22844. coordDimArr = encode[coordDim] = [];
  22845. }
  22846. coordDimArr[dimItem.coordDimIndex] = dimName;
  22847. if (!dimItem.isExtraCoord) {
  22848. notExtraCoordDimMap.set(coordDim, 1);
  22849. // Use the last coord dim (and label friendly) as default label,
  22850. // because when dataset is used, it is hard to guess which dimension
  22851. // can be value dimension. If both show x, y on label is not look good,
  22852. // and conventionally y axis is focused more.
  22853. if (mayLabelDimType(dimItem.type)) {
  22854. defaultedLabel[0] = dimName;
  22855. }
  22856. }
  22857. }
  22858. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22859. var otherDimArr = encode[otherDim];
  22860. if (!encode.hasOwnProperty(otherDim)) {
  22861. otherDimArr = encode[otherDim] = [];
  22862. }
  22863. var dimIndex = dimItem.otherDims[otherDim];
  22864. if (dimIndex != null && dimIndex !== false) {
  22865. otherDimArr[dimIndex] = dimItem.name;
  22866. }
  22867. });
  22868. });
  22869. var dataDimsOnCoord = [];
  22870. var encodeFirstDimNotExtra = {};
  22871. notExtraCoordDimMap.each(function (v, coordDim) {
  22872. var dimArr = encode[coordDim];
  22873. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  22874. // But should fix the case that radar axes: simplify the logic
  22875. // of `completeDimension`, remove `extraPrefix`.
  22876. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  22877. // Not necessary to remove duplicate, because a data
  22878. // dim canot on more than one coordDim.
  22879. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  22880. });
  22881. summary.dataDimsOnCoord = dataDimsOnCoord;
  22882. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  22883. var encodeLabel = encode.label;
  22884. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22885. // in this way. Use label.formatter instead. May be remove this approach someday.
  22886. if (encodeLabel && encodeLabel.length) {
  22887. defaultedLabel = encodeLabel.slice();
  22888. }
  22889. var defaultedTooltip = defaultedLabel.slice();
  22890. var encodeTooltip = encode.tooltip;
  22891. if (encodeTooltip && encodeTooltip.length) {
  22892. defaultedTooltip = encodeTooltip.slice();
  22893. }
  22894. encode.defaultedLabel = defaultedLabel;
  22895. encode.defaultedTooltip = defaultedTooltip;
  22896. return summary;
  22897. }
  22898. function getDimensionTypeByAxis(axisType) {
  22899. return axisType === 'category'
  22900. ? 'ordinal'
  22901. : axisType === 'time'
  22902. ? 'time'
  22903. : 'float';
  22904. }
  22905. function mayLabelDimType(dimType) {
  22906. // In most cases, ordinal and time do not suitable for label.
  22907. // Ordinal info can be displayed on axis. Time is too long.
  22908. return !(dimType === 'ordinal' || dimType === 'time');
  22909. }
  22910. // function findTheLastDimMayLabel(data) {
  22911. // // Get last value dim
  22912. // var dimensions = data.dimensions.slice();
  22913. // var valueType;
  22914. // var valueDim;
  22915. // while (dimensions.length && (
  22916. // valueDim = dimensions.pop(),
  22917. // valueType = data.getDimensionInfo(valueDim).type,
  22918. // valueType === 'ordinal' || valueType === 'time'
  22919. // )) {} // jshint ignore:line
  22920. // return valueDim;
  22921. // }
  22922. /**
  22923. * List for data storage
  22924. * @module echarts/data/List
  22925. */
  22926. var isObject$4 = isObject$1;
  22927. var UNDEFINED = 'undefined';
  22928. var globalObj = typeof window === UNDEFINED ? global : window;
  22929. // Use prefix to avoid index to be the same as otherIdList[idx],
  22930. // which will cause weird udpate animation.
  22931. var ID_PREFIX = 'e\0\0';
  22932. var dataCtors = {
  22933. 'float': typeof globalObj.Float64Array === UNDEFINED
  22934. ? Array : globalObj.Float64Array,
  22935. 'int': typeof globalObj.Int32Array === UNDEFINED
  22936. ? Array : globalObj.Int32Array,
  22937. // Ordinal data type can be string or int
  22938. 'ordinal': Array,
  22939. 'number': Array,
  22940. 'time': Array
  22941. };
  22942. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22943. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22944. function getIndicesCtor(list) {
  22945. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22946. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22947. }
  22948. function cloneChunk(originalChunk) {
  22949. var Ctor = originalChunk.constructor;
  22950. // Only shallow clone is enough when Array.
  22951. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22952. }
  22953. var TRANSFERABLE_PROPERTIES = [
  22954. 'hasItemOption', '_nameList', '_idList', '_calculationInfo', '_invertedIndicesMap',
  22955. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22956. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22957. ];
  22958. function transferProperties(a, b) {
  22959. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22960. if (b.hasOwnProperty(propName)) {
  22961. a[propName] = b[propName];
  22962. }
  22963. });
  22964. a.__wrappedMethods = b.__wrappedMethods;
  22965. }
  22966. /**
  22967. * @constructor
  22968. * @alias module:echarts/data/List
  22969. *
  22970. * @param {Array.<string|Object>} dimensions
  22971. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22972. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22973. * Spetial fields: {
  22974. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22975. * createInvertedIndices: <boolean>
  22976. * }
  22977. * @param {module:echarts/model/Model} hostModel
  22978. */
  22979. var List = function (dimensions, hostModel) {
  22980. dimensions = dimensions || ['x', 'y'];
  22981. var dimensionInfos = {};
  22982. var dimensionNames = [];
  22983. var invertedIndicesMap = {};
  22984. for (var i = 0; i < dimensions.length; i++) {
  22985. // Use the original dimensions[i], where other flag props may exists.
  22986. var dimensionInfo = dimensions[i];
  22987. if (isString(dimensionInfo)) {
  22988. dimensionInfo = {name: dimensionInfo};
  22989. }
  22990. var dimensionName = dimensionInfo.name;
  22991. dimensionInfo.type = dimensionInfo.type || 'float';
  22992. if (!dimensionInfo.coordDim) {
  22993. dimensionInfo.coordDim = dimensionName;
  22994. dimensionInfo.coordDimIndex = 0;
  22995. }
  22996. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22997. dimensionNames.push(dimensionName);
  22998. dimensionInfos[dimensionName] = dimensionInfo;
  22999. dimensionInfo.index = i;
  23000. if (dimensionInfo.createInvertedIndices) {
  23001. invertedIndicesMap[dimensionName] = [];
  23002. }
  23003. }
  23004. /**
  23005. * @readOnly
  23006. * @type {Array.<string>}
  23007. */
  23008. this.dimensions = dimensionNames;
  23009. /**
  23010. * Infomation of each data dimension, like data type.
  23011. * @type {Object}
  23012. */
  23013. this._dimensionInfos = dimensionInfos;
  23014. /**
  23015. * @type {module:echarts/model/Model}
  23016. */
  23017. this.hostModel = hostModel;
  23018. /**
  23019. * @type {module:echarts/model/Model}
  23020. */
  23021. this.dataType;
  23022. /**
  23023. * Indices stores the indices of data subset after filtered.
  23024. * This data subset will be used in chart.
  23025. * @type {Array.<number>}
  23026. * @readOnly
  23027. */
  23028. this._indices = null;
  23029. this._count = 0;
  23030. this._rawCount = 0;
  23031. /**
  23032. * Data storage
  23033. * @type {Object.<key, Array.<TypedArray|Array>>}
  23034. * @private
  23035. */
  23036. this._storage = {};
  23037. /**
  23038. * @type {Array.<string>}
  23039. */
  23040. this._nameList = [];
  23041. /**
  23042. * @type {Array.<string>}
  23043. */
  23044. this._idList = [];
  23045. /**
  23046. * Models of data option is stored sparse for optimizing memory cost
  23047. * @type {Array.<module:echarts/model/Model>}
  23048. * @private
  23049. */
  23050. this._optionModels = [];
  23051. /**
  23052. * Global visual properties after visual coding
  23053. * @type {Object}
  23054. * @private
  23055. */
  23056. this._visual = {};
  23057. /**
  23058. * Globel layout properties.
  23059. * @type {Object}
  23060. * @private
  23061. */
  23062. this._layout = {};
  23063. /**
  23064. * Item visual properties after visual coding
  23065. * @type {Array.<Object>}
  23066. * @private
  23067. */
  23068. this._itemVisuals = [];
  23069. /**
  23070. * Key: visual type, Value: boolean
  23071. * @type {Object}
  23072. * @readOnly
  23073. */
  23074. this.hasItemVisual = {};
  23075. /**
  23076. * Item layout properties after layout
  23077. * @type {Array.<Object>}
  23078. * @private
  23079. */
  23080. this._itemLayouts = [];
  23081. /**
  23082. * Graphic elemnents
  23083. * @type {Array.<module:zrender/Element>}
  23084. * @private
  23085. */
  23086. this._graphicEls = [];
  23087. /**
  23088. * Max size of each chunk.
  23089. * @type {number}
  23090. * @private
  23091. */
  23092. this._chunkSize = 1e5;
  23093. /**
  23094. * @type {number}
  23095. * @private
  23096. */
  23097. this._chunkCount = 0;
  23098. /**
  23099. * @type {Array.<Array|Object>}
  23100. * @private
  23101. */
  23102. this._rawData;
  23103. /**
  23104. * Raw extent will not be cloned, but only transfered.
  23105. * It will not be calculated util needed.
  23106. * key: dim,
  23107. * value: {end: number, extent: Array.<number>}
  23108. * @type {Object}
  23109. * @private
  23110. */
  23111. this._rawExtent = {};
  23112. /**
  23113. * @type {Object}
  23114. * @private
  23115. */
  23116. this._extent = {};
  23117. /**
  23118. * key: dim
  23119. * value: extent
  23120. * @type {Object}
  23121. * @private
  23122. */
  23123. this._approximateExtent = {};
  23124. /**
  23125. * Cache summary info for fast visit. See "dimensionHelper".
  23126. * @type {Object}
  23127. * @private
  23128. */
  23129. this._dimensionsSummary = summarizeDimensions(this);
  23130. /**
  23131. * @type {Object.<Array|TypedArray>}
  23132. * @private
  23133. */
  23134. this._invertedIndicesMap = invertedIndicesMap;
  23135. /**
  23136. * @type {Object}
  23137. * @private
  23138. */
  23139. this._calculationInfo = {};
  23140. };
  23141. var listProto = List.prototype;
  23142. listProto.type = 'list';
  23143. /**
  23144. * If each data item has it's own option
  23145. * @type {boolean}
  23146. */
  23147. listProto.hasItemOption = true;
  23148. /**
  23149. * Get dimension name
  23150. * @param {string|number} dim
  23151. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23152. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23153. * @return {string} Concrete dim name.
  23154. */
  23155. listProto.getDimension = function (dim) {
  23156. if (!isNaN(dim)) {
  23157. dim = this.dimensions[dim] || dim;
  23158. }
  23159. return dim;
  23160. };
  23161. /**
  23162. * Get type and calculation info of particular dimension
  23163. * @param {string|number} dim
  23164. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23165. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23166. */
  23167. listProto.getDimensionInfo = function (dim) {
  23168. // Do not clone, because there may be categories in dimInfo.
  23169. return this._dimensionInfos[this.getDimension(dim)];
  23170. };
  23171. /**
  23172. * @return {Array.<string>} concrete dimension name list on coord.
  23173. */
  23174. listProto.getDimensionsOnCoord = function () {
  23175. return this._dimensionsSummary.dataDimsOnCoord.slice();
  23176. };
  23177. /**
  23178. * @param {string} coordDim
  23179. * @param {number} [idx] A coordDim may map to more than one data dim.
  23180. * If idx is `true`, return a array of all mapped dims.
  23181. * If idx is not specified, return the first dim not extra.
  23182. * @return {string|Array.<string>} concrete data dim.
  23183. * If idx is number, and not found, return null/undefined.
  23184. * If idx is `true`, and not found, return empty array (always return array).
  23185. */
  23186. listProto.mapDimension = function (coordDim, idx) {
  23187. var dimensionsSummary = this._dimensionsSummary;
  23188. if (idx == null) {
  23189. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  23190. }
  23191. var dims = dimensionsSummary.encode[coordDim];
  23192. return idx === true
  23193. // always return array if idx is `true`
  23194. ? (dims || []).slice()
  23195. : (dims && dims[idx]);
  23196. };
  23197. /**
  23198. * Initialize from data
  23199. * @param {Array.<Object|number|Array>} data source or data or data provider.
  23200. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  23201. * defualt label/tooltip.
  23202. * A name can be specified in encode.itemName,
  23203. * or dataItem.name (only for series option data),
  23204. * or provided in nameList from outside.
  23205. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  23206. */
  23207. listProto.initData = function (data, nameList, dimValueGetter) {
  23208. var notProvider = Source.isInstance(data) || isArrayLike(data);
  23209. if (notProvider) {
  23210. data = new DefaultDataProvider(data, this.dimensions.length);
  23211. }
  23212. if (__DEV__) {
  23213. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  23214. throw new Error('Inavlid data provider.');
  23215. }
  23216. }
  23217. this._rawData = data;
  23218. // Clear
  23219. this._storage = {};
  23220. this._indices = null;
  23221. this._nameList = nameList || [];
  23222. this._idList = [];
  23223. this._nameRepeatCount = {};
  23224. if (!dimValueGetter) {
  23225. this.hasItemOption = false;
  23226. }
  23227. /**
  23228. * @readOnly
  23229. */
  23230. this.defaultDimValueGetter = defaultDimValueGetters[
  23231. this._rawData.getSource().sourceFormat
  23232. ];
  23233. // Default dim value getter
  23234. this._dimValueGetter = dimValueGetter = dimValueGetter
  23235. || this.defaultDimValueGetter;
  23236. // Reset raw extent.
  23237. this._rawExtent = {};
  23238. this._initDataFromProvider(0, data.count());
  23239. // If data has no item option.
  23240. if (data.pure) {
  23241. this.hasItemOption = false;
  23242. }
  23243. };
  23244. listProto.getProvider = function () {
  23245. return this._rawData;
  23246. };
  23247. listProto.appendData = function (data) {
  23248. if (__DEV__) {
  23249. assert$1(!this._indices, 'appendData can only be called on raw data.');
  23250. }
  23251. var rawData = this._rawData;
  23252. var start = this.count();
  23253. rawData.appendData(data);
  23254. var end = rawData.count();
  23255. if (!rawData.persistent) {
  23256. end += start;
  23257. }
  23258. this._initDataFromProvider(start, end);
  23259. };
  23260. listProto._initDataFromProvider = function (start, end) {
  23261. // Optimize.
  23262. if (start >= end) {
  23263. return;
  23264. }
  23265. var chunkSize = this._chunkSize;
  23266. var rawData = this._rawData;
  23267. var storage = this._storage;
  23268. var dimensions = this.dimensions;
  23269. var dimensionInfoMap = this._dimensionInfos;
  23270. var nameList = this._nameList;
  23271. var idList = this._idList;
  23272. var rawExtent = this._rawExtent;
  23273. var nameRepeatCount = this._nameRepeatCount = {};
  23274. var nameDimIdx;
  23275. var chunkCount = this._chunkCount;
  23276. var lastChunkIndex = chunkCount - 1;
  23277. for (var i = 0; i < dimensions.length; i++) {
  23278. var dim = dimensions[i];
  23279. if (!rawExtent[dim]) {
  23280. rawExtent[dim] = getInitialExtent();
  23281. }
  23282. var dimInfo = dimensionInfoMap[dim];
  23283. if (dimInfo.otherDims.itemName === 0) {
  23284. nameDimIdx = this._nameDimIdx = i;
  23285. }
  23286. if (dimInfo.otherDims.itemId === 0) {
  23287. this._idDimIdx = i;
  23288. }
  23289. var DataCtor = dataCtors[dimInfo.type];
  23290. if (!storage[dim]) {
  23291. storage[dim] = [];
  23292. }
  23293. var resizeChunkArray = storage[dim][lastChunkIndex];
  23294. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  23295. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  23296. // The cost of the copy is probably inconsiderable
  23297. // within the initial chunkSize.
  23298. for (var j = 0; j < resizeChunkArray.length; j++) {
  23299. newStore[j] = resizeChunkArray[j];
  23300. }
  23301. storage[dim][lastChunkIndex] = newStore;
  23302. }
  23303. // Create new chunks.
  23304. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  23305. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  23306. }
  23307. this._chunkCount = storage[dim].length;
  23308. }
  23309. for (var idx = start; idx < end; idx++) {
  23310. // NOTICE: Try not to write things into dataItem
  23311. var dataItem = rawData.getItem(idx);
  23312. // Each data item is value
  23313. // [1, 2]
  23314. // 2
  23315. // Bar chart, line chart which uses category axis
  23316. // only gives the 'y' value. 'x' value is the indices of category
  23317. // Use a tempValue to normalize the value to be a (x, y) value
  23318. var chunkIndex = Math.floor(idx / chunkSize);
  23319. var chunkOffset = idx % chunkSize;
  23320. // Store the data by dimensions
  23321. for (var k = 0; k < dimensions.length; k++) {
  23322. var dim = dimensions[k];
  23323. var dimStorage = storage[dim][chunkIndex];
  23324. // PENDING NULL is empty or zero
  23325. var val = this._dimValueGetter(dataItem, dim, idx, k);
  23326. dimStorage[chunkOffset] = val;
  23327. if (val < rawExtent[dim][0]) {
  23328. rawExtent[dim][0] = val;
  23329. }
  23330. if (val > rawExtent[dim][1]) {
  23331. rawExtent[dim][1] = val;
  23332. }
  23333. }
  23334. // ??? FIXME not check by pure but sourceFormat?
  23335. // TODO refactor these logic.
  23336. if (!rawData.pure) {
  23337. var name = nameList[idx];
  23338. if (dataItem && !name) {
  23339. if (nameDimIdx != null) {
  23340. name = this._getNameFromStore(idx);
  23341. }
  23342. else if (dataItem.name != null) {
  23343. // There is no other place to persistent dataItem.name,
  23344. // so save it to nameList.
  23345. nameList[idx] = name = dataItem.name;
  23346. }
  23347. }
  23348. // Try using the id in option
  23349. // id or name is used on dynamical data, mapping old and new items.
  23350. var id = dataItem == null ? null : dataItem.id;
  23351. if (id == null && name != null) {
  23352. // Use name as id and add counter to avoid same name
  23353. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23354. id = name;
  23355. if (nameRepeatCount[name] > 0) {
  23356. id += '__ec__' + nameRepeatCount[name];
  23357. }
  23358. nameRepeatCount[name]++;
  23359. }
  23360. id != null && (idList[idx] = id);
  23361. }
  23362. }
  23363. if (!rawData.persistent && rawData.clean) {
  23364. // Clean unused data if data source is typed array.
  23365. rawData.clean();
  23366. }
  23367. this._rawCount = this._count = end;
  23368. // Reset data extent
  23369. this._extent = {};
  23370. prepareInvertedIndex(this);
  23371. };
  23372. function prepareInvertedIndex(list) {
  23373. var invertedIndicesMap = list._invertedIndicesMap;
  23374. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  23375. var dimInfo = list._dimensionInfos[dim];
  23376. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  23377. var ordinalMeta = dimInfo.ordinalMeta;
  23378. if (ordinalMeta) {
  23379. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  23380. ordinalMeta.categories.length
  23381. );
  23382. // The default value of TypedArray is 0. To avoid miss
  23383. // mapping to 0, we should set it as NaN.
  23384. for (var i = 0; i < invertedIndices.length; i++) {
  23385. invertedIndices[i] = NaN;
  23386. }
  23387. for (var i = 0; i < list._count; i++) {
  23388. // Only support the case that all values are distinct.
  23389. invertedIndices[list.get(dim, i)] = i;
  23390. }
  23391. }
  23392. });
  23393. }
  23394. // TODO refactor
  23395. listProto._getNameFromStore = function (rawIndex) {
  23396. var nameDimIdx = this._nameDimIdx;
  23397. if (nameDimIdx != null) {
  23398. var chunkSize = this._chunkSize;
  23399. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23400. var chunkOffset = rawIndex % chunkSize;
  23401. var dim = this.dimensions[nameDimIdx];
  23402. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23403. if (ordinalMeta) {
  23404. return ordinalMeta.categories[rawIndex];
  23405. }
  23406. else {
  23407. var chunk = this._storage[dim][chunkIndex];
  23408. return chunk && chunk[chunkOffset];
  23409. }
  23410. }
  23411. };
  23412. // TODO refactor
  23413. listProto._getIdFromStore = function (rawIndex) {
  23414. var idDimIdx = this._idDimIdx;
  23415. if (idDimIdx != null) {
  23416. var chunkSize = this._chunkSize;
  23417. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23418. var chunkOffset = rawIndex % chunkSize;
  23419. var dim = this.dimensions[idDimIdx];
  23420. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23421. if (ordinalMeta) {
  23422. return ordinalMeta.categories[rawIndex];
  23423. }
  23424. else {
  23425. var chunk = this._storage[dim][chunkIndex];
  23426. return chunk && chunk[chunkOffset];
  23427. }
  23428. }
  23429. };
  23430. /**
  23431. * @return {number}
  23432. */
  23433. listProto.count = function () {
  23434. return this._count;
  23435. };
  23436. listProto.getIndices = function () {
  23437. if (this._indices) {
  23438. var Ctor = this._indices.constructor;
  23439. return new Ctor(this._indices.buffer, 0, this._count);
  23440. }
  23441. var Ctor = getIndicesCtor(this);
  23442. var arr = new Ctor(this.count());
  23443. for (var i = 0; i < arr.length; i++) {
  23444. arr[i] = i;
  23445. }
  23446. return arr;
  23447. };
  23448. /**
  23449. * Get value. Return NaN if idx is out of range.
  23450. * @param {string} dim Dim must be concrete name.
  23451. * @param {number} idx
  23452. * @param {boolean} stack
  23453. * @return {number}
  23454. */
  23455. listProto.get = function (dim, idx /*, stack */) {
  23456. if (!(idx >= 0 && idx < this._count)) {
  23457. return NaN;
  23458. }
  23459. var storage = this._storage;
  23460. if (!storage[dim]) {
  23461. // TODO Warn ?
  23462. return NaN;
  23463. }
  23464. idx = this.getRawIndex(idx);
  23465. var chunkIndex = Math.floor(idx / this._chunkSize);
  23466. var chunkOffset = idx % this._chunkSize;
  23467. var chunkStore = storage[dim][chunkIndex];
  23468. var value = chunkStore[chunkOffset];
  23469. // FIXME ordinal data type is not stackable
  23470. // if (stack) {
  23471. // var dimensionInfo = this._dimensionInfos[dim];
  23472. // if (dimensionInfo && dimensionInfo.stackable) {
  23473. // var stackedOn = this.stackedOn;
  23474. // while (stackedOn) {
  23475. // // Get no stacked data of stacked on
  23476. // var stackedValue = stackedOn.get(dim, idx);
  23477. // // Considering positive stack, negative stack and empty data
  23478. // if ((value >= 0 && stackedValue > 0) // Positive stack
  23479. // || (value <= 0 && stackedValue < 0) // Negative stack
  23480. // ) {
  23481. // value += stackedValue;
  23482. // }
  23483. // stackedOn = stackedOn.stackedOn;
  23484. // }
  23485. // }
  23486. // }
  23487. return value;
  23488. };
  23489. /**
  23490. * @param {string} dim concrete dim
  23491. * @param {number} rawIndex
  23492. * @return {number|string}
  23493. */
  23494. listProto.getByRawIndex = function (dim, rawIdx) {
  23495. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  23496. return NaN;
  23497. }
  23498. var dimStore = this._storage[dim];
  23499. if (!dimStore) {
  23500. // TODO Warn ?
  23501. return NaN;
  23502. }
  23503. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23504. var chunkOffset = rawIdx % this._chunkSize;
  23505. var chunkStore = dimStore[chunkIndex];
  23506. return chunkStore[chunkOffset];
  23507. };
  23508. /**
  23509. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23510. * Hack a much simpler _getFast
  23511. * @private
  23512. */
  23513. listProto._getFast = function (dim, rawIdx) {
  23514. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23515. var chunkOffset = rawIdx % this._chunkSize;
  23516. var chunkStore = this._storage[dim][chunkIndex];
  23517. return chunkStore[chunkOffset];
  23518. };
  23519. /**
  23520. * Get value for multi dimensions.
  23521. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23522. * @param {number} idx
  23523. * @return {number}
  23524. */
  23525. listProto.getValues = function (dimensions, idx /*, stack */) {
  23526. var values = [];
  23527. if (!isArray(dimensions)) {
  23528. // stack = idx;
  23529. idx = dimensions;
  23530. dimensions = this.dimensions;
  23531. }
  23532. for (var i = 0, len = dimensions.length; i < len; i++) {
  23533. values.push(this.get(dimensions[i], idx /*, stack */));
  23534. }
  23535. return values;
  23536. };
  23537. /**
  23538. * If value is NaN. Inlcuding '-'
  23539. * Only check the coord dimensions.
  23540. * @param {string} dim
  23541. * @param {number} idx
  23542. * @return {number}
  23543. */
  23544. listProto.hasValue = function (idx) {
  23545. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23546. var dimensionInfos = this._dimensionInfos;
  23547. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23548. if (
  23549. // Ordinal type can be string or number
  23550. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23551. // FIXME check ordinal when using index?
  23552. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23553. ) {
  23554. return false;
  23555. }
  23556. }
  23557. return true;
  23558. };
  23559. /**
  23560. * Get extent of data in one dimension
  23561. * @param {string} dim
  23562. * @param {boolean} stack
  23563. */
  23564. listProto.getDataExtent = function (dim /*, stack */) {
  23565. // Make sure use concrete dim as cache name.
  23566. dim = this.getDimension(dim);
  23567. var dimData = this._storage[dim];
  23568. var initialExtent = getInitialExtent();
  23569. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  23570. if (!dimData) {
  23571. return initialExtent;
  23572. }
  23573. // Make more strict checkings to ensure hitting cache.
  23574. var currEnd = this.count();
  23575. // var cacheName = [dim, !!stack].join('_');
  23576. // var cacheName = dim;
  23577. // Consider the most cases when using data zoom, `getDataExtent`
  23578. // happened before filtering. We cache raw extent, which is not
  23579. // necessary to be cleared and recalculated when restore data.
  23580. var useRaw = !this._indices; // && !stack;
  23581. var dimExtent;
  23582. if (useRaw) {
  23583. return this._rawExtent[dim].slice();
  23584. }
  23585. dimExtent = this._extent[dim];
  23586. if (dimExtent) {
  23587. return dimExtent.slice();
  23588. }
  23589. dimExtent = initialExtent;
  23590. var min = dimExtent[0];
  23591. var max = dimExtent[1];
  23592. for (var i = 0; i < currEnd; i++) {
  23593. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23594. var value = this._getFast(dim, this.getRawIndex(i));
  23595. value < min && (min = value);
  23596. value > max && (max = value);
  23597. }
  23598. dimExtent = [min, max];
  23599. this._extent[dim] = dimExtent;
  23600. return dimExtent;
  23601. };
  23602. /**
  23603. * Optimize for the scenario that data is filtered by a given extent.
  23604. * Consider that if data amount is more than hundreds of thousand,
  23605. * extent calculation will cost more than 10ms and the cache will
  23606. * be erased because of the filtering.
  23607. */
  23608. listProto.getApproximateExtent = function (dim /*, stack */) {
  23609. dim = this.getDimension(dim);
  23610. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  23611. };
  23612. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  23613. dim = this.getDimension(dim);
  23614. this._approximateExtent[dim] = extent.slice();
  23615. };
  23616. /**
  23617. * @param {string} key
  23618. * @return {*}
  23619. */
  23620. listProto.getCalculationInfo = function (key) {
  23621. return this._calculationInfo[key];
  23622. };
  23623. /**
  23624. * @param {string|Object} key or k-v object
  23625. * @param {*} [value]
  23626. */
  23627. listProto.setCalculationInfo = function (key, value) {
  23628. isObject$4(key)
  23629. ? extend(this._calculationInfo, key)
  23630. : (this._calculationInfo[key] = value);
  23631. };
  23632. /**
  23633. * Get sum of data in one dimension
  23634. * @param {string} dim
  23635. */
  23636. listProto.getSum = function (dim /*, stack */) {
  23637. var dimData = this._storage[dim];
  23638. var sum = 0;
  23639. if (dimData) {
  23640. for (var i = 0, len = this.count(); i < len; i++) {
  23641. var value = this.get(dim, i /*, stack */);
  23642. if (!isNaN(value)) {
  23643. sum += value;
  23644. }
  23645. }
  23646. }
  23647. return sum;
  23648. };
  23649. // /**
  23650. // * Retreive the index with given value
  23651. // * @param {string} dim Concrete dimension.
  23652. // * @param {number} value
  23653. // * @return {number}
  23654. // */
  23655. // Currently incorrect: should return dataIndex but not rawIndex.
  23656. // Do not fix it until this method is to be used somewhere.
  23657. // FIXME Precision of float value
  23658. // listProto.indexOf = function (dim, value) {
  23659. // var storage = this._storage;
  23660. // var dimData = storage[dim];
  23661. // var chunkSize = this._chunkSize;
  23662. // if (dimData) {
  23663. // for (var i = 0, len = this.count(); i < len; i++) {
  23664. // var chunkIndex = Math.floor(i / chunkSize);
  23665. // var chunkOffset = i % chunkSize;
  23666. // if (dimData[chunkIndex][chunkOffset] === value) {
  23667. // return i;
  23668. // }
  23669. // }
  23670. // }
  23671. // return -1;
  23672. // };
  23673. /**
  23674. * Only support the dimension which inverted index created.
  23675. * Do not support other cases until required.
  23676. * @param {string} concrete dim
  23677. * @param {number|string} value
  23678. * @return {number} rawIndex
  23679. */
  23680. listProto.rawIndexOf = function (dim, value) {
  23681. var invertedIndices = dim && this._invertedIndicesMap[dim];
  23682. if (__DEV__) {
  23683. if (!invertedIndices) {
  23684. throw new Error('Do not supported yet');
  23685. }
  23686. }
  23687. var rawIndex = invertedIndices[value];
  23688. if (rawIndex == null || isNaN(rawIndex)) {
  23689. return -1;
  23690. }
  23691. return rawIndex;
  23692. };
  23693. /**
  23694. * Retreive the index with given name
  23695. * @param {number} idx
  23696. * @param {number} name
  23697. * @return {number}
  23698. */
  23699. listProto.indexOfName = function (name) {
  23700. for (var i = 0, len = this.count(); i < len; i++) {
  23701. if (this.getName(i) === name) {
  23702. return i;
  23703. }
  23704. }
  23705. return -1;
  23706. };
  23707. /**
  23708. * Retreive the index with given raw data index
  23709. * @param {number} idx
  23710. * @param {number} name
  23711. * @return {number}
  23712. */
  23713. listProto.indexOfRawIndex = function (rawIndex) {
  23714. if (!this._indices) {
  23715. return rawIndex;
  23716. }
  23717. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23718. return -1;
  23719. }
  23720. // Indices are ascending
  23721. var indices = this._indices;
  23722. // If rawIndex === dataIndex
  23723. var rawDataIndex = indices[rawIndex];
  23724. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23725. return rawIndex;
  23726. }
  23727. var left = 0;
  23728. var right = this._count - 1;
  23729. while (left <= right) {
  23730. var mid = (left + right) / 2 | 0;
  23731. if (indices[mid] < rawIndex) {
  23732. left = mid + 1;
  23733. }
  23734. else if (indices[mid] > rawIndex) {
  23735. right = mid - 1;
  23736. }
  23737. else {
  23738. return mid;
  23739. }
  23740. }
  23741. return -1;
  23742. };
  23743. /**
  23744. * Retreive the index of nearest value
  23745. * @param {string} dim
  23746. * @param {number} value
  23747. * @param {number} [maxDistance=Infinity]
  23748. * @return {Array.<number>} Considere multiple points has the same value.
  23749. */
  23750. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  23751. var storage = this._storage;
  23752. var dimData = storage[dim];
  23753. var nearestIndices = [];
  23754. if (!dimData) {
  23755. return nearestIndices;
  23756. }
  23757. if (maxDistance == null) {
  23758. maxDistance = Infinity;
  23759. }
  23760. var minDist = Number.MAX_VALUE;
  23761. var minDiff = -1;
  23762. for (var i = 0, len = this.count(); i < len; i++) {
  23763. var diff = value - this.get(dim, i /*, stack */);
  23764. var dist = Math.abs(diff);
  23765. if (diff <= maxDistance && dist <= minDist) {
  23766. // For the case of two data are same on xAxis, which has sequence data.
  23767. // Show the nearest index
  23768. // https://github.com/ecomfe/echarts/issues/2869
  23769. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23770. minDist = dist;
  23771. minDiff = diff;
  23772. nearestIndices.length = 0;
  23773. }
  23774. nearestIndices.push(i);
  23775. }
  23776. }
  23777. return nearestIndices;
  23778. };
  23779. /**
  23780. * Get raw data index
  23781. * @param {number} idx
  23782. * @return {number}
  23783. */
  23784. listProto.getRawIndex = getRawIndexWithoutIndices;
  23785. function getRawIndexWithoutIndices(idx) {
  23786. return idx;
  23787. }
  23788. function getRawIndexWithIndices(idx) {
  23789. if (idx < this._count && idx >= 0) {
  23790. return this._indices[idx];
  23791. }
  23792. return -1;
  23793. }
  23794. /**
  23795. * Get raw data item
  23796. * @param {number} idx
  23797. * @return {number}
  23798. */
  23799. listProto.getRawDataItem = function (idx) {
  23800. if (!this._rawData.persistent) {
  23801. var val = [];
  23802. for (var i = 0; i < this.dimensions.length; i++) {
  23803. var dim = this.dimensions[i];
  23804. val.push(this.get(dim, idx));
  23805. }
  23806. return val;
  23807. }
  23808. else {
  23809. return this._rawData.getItem(this.getRawIndex(idx));
  23810. }
  23811. };
  23812. /**
  23813. * @param {number} idx
  23814. * @param {boolean} [notDefaultIdx=false]
  23815. * @return {string}
  23816. */
  23817. listProto.getName = function (idx) {
  23818. var rawIndex = this.getRawIndex(idx);
  23819. return this._nameList[rawIndex]
  23820. || this._getNameFromStore(rawIndex)
  23821. || '';
  23822. };
  23823. /**
  23824. * @param {number} idx
  23825. * @param {boolean} [notDefaultIdx=false]
  23826. * @return {string}
  23827. */
  23828. listProto.getId = function (idx) {
  23829. return getId(this, this.getRawIndex(idx));
  23830. };
  23831. function getId(list, rawIndex) {
  23832. var id = list._idList[rawIndex];
  23833. if (id == null) {
  23834. id = list._getIdFromStore(rawIndex);
  23835. }
  23836. if (id == null) {
  23837. // FIXME Check the usage in graph, should not use prefix.
  23838. id = ID_PREFIX + rawIndex;
  23839. }
  23840. return id;
  23841. }
  23842. function normalizeDimensions(dimensions) {
  23843. if (!isArray(dimensions)) {
  23844. dimensions = [dimensions];
  23845. }
  23846. return dimensions;
  23847. }
  23848. function validateDimensions(list, dims) {
  23849. for (var i = 0; i < dims.length; i++) {
  23850. // stroage may be empty when no data, so use
  23851. // dimensionInfos to check.
  23852. if (!list._dimensionInfos[dims[i]]) {
  23853. console.error('Unkown dimension ' + dims[i]);
  23854. }
  23855. }
  23856. }
  23857. /**
  23858. * Data iteration
  23859. * @param {string|Array.<string>}
  23860. * @param {Function} cb
  23861. * @param {*} [context=this]
  23862. *
  23863. * @example
  23864. * list.each('x', function (x, idx) {});
  23865. * list.each(['x', 'y'], function (x, y, idx) {});
  23866. * list.each(function (idx) {})
  23867. */
  23868. listProto.each = function (dims, cb, context, contextCompat) {
  23869. 'use strict';
  23870. if (!this._count) {
  23871. return;
  23872. }
  23873. if (typeof dims === 'function') {
  23874. contextCompat = context;
  23875. context = cb;
  23876. cb = dims;
  23877. dims = [];
  23878. }
  23879. // contextCompat just for compat echarts3
  23880. context = context || contextCompat || this;
  23881. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23882. if (__DEV__) {
  23883. validateDimensions(this, dims);
  23884. }
  23885. var dimSize = dims.length;
  23886. for (var i = 0; i < this.count(); i++) {
  23887. // Simple optimization
  23888. switch (dimSize) {
  23889. case 0:
  23890. cb.call(context, i);
  23891. break;
  23892. case 1:
  23893. cb.call(context, this.get(dims[0], i), i);
  23894. break;
  23895. case 2:
  23896. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  23897. break;
  23898. default:
  23899. var k = 0;
  23900. var value = [];
  23901. for (; k < dimSize; k++) {
  23902. value[k] = this.get(dims[k], i);
  23903. }
  23904. // Index
  23905. value[k] = i;
  23906. cb.apply(context, value);
  23907. }
  23908. }
  23909. };
  23910. /**
  23911. * Data filter
  23912. * @param {string|Array.<string>}
  23913. * @param {Function} cb
  23914. * @param {*} [context=this]
  23915. */
  23916. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  23917. 'use strict';
  23918. if (!this._count) {
  23919. return;
  23920. }
  23921. if (typeof dimensions === 'function') {
  23922. contextCompat = context;
  23923. context = cb;
  23924. cb = dimensions;
  23925. dimensions = [];
  23926. }
  23927. // contextCompat just for compat echarts3
  23928. context = context || contextCompat || this;
  23929. dimensions = map(
  23930. normalizeDimensions(dimensions), this.getDimension, this
  23931. );
  23932. if (__DEV__) {
  23933. validateDimensions(this, dimensions);
  23934. }
  23935. var count = this.count();
  23936. var Ctor = getIndicesCtor(this);
  23937. var newIndices = new Ctor(count);
  23938. var value = [];
  23939. var dimSize = dimensions.length;
  23940. var offset = 0;
  23941. var dim0 = dimensions[0];
  23942. for (var i = 0; i < count; i++) {
  23943. var keep;
  23944. var rawIdx = this.getRawIndex(i);
  23945. // Simple optimization
  23946. if (dimSize === 0) {
  23947. keep = cb.call(context, i);
  23948. }
  23949. else if (dimSize === 1) {
  23950. var val = this._getFast(dim0, rawIdx);
  23951. keep = cb.call(context, val, i);
  23952. }
  23953. else {
  23954. for (var k = 0; k < dimSize; k++) {
  23955. value[k] = this._getFast(dim0, rawIdx);
  23956. }
  23957. value[k] = i;
  23958. keep = cb.apply(context, value);
  23959. }
  23960. if (keep) {
  23961. newIndices[offset++] = rawIdx;
  23962. }
  23963. }
  23964. // Set indices after filtered.
  23965. if (offset < count) {
  23966. this._indices = newIndices;
  23967. }
  23968. this._count = offset;
  23969. // Reset data extent
  23970. this._extent = {};
  23971. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23972. return this;
  23973. };
  23974. /**
  23975. * Select data in range. (For optimization of filter)
  23976. * (Manually inline code, support 5 million data filtering in data zoom.)
  23977. */
  23978. listProto.selectRange = function (range /*, stack */) {
  23979. 'use strict';
  23980. if (!this._count) {
  23981. return;
  23982. }
  23983. // stack = stack || false;
  23984. var dimensions = [];
  23985. for (var dim in range) {
  23986. if (range.hasOwnProperty(dim)) {
  23987. dimensions.push(dim);
  23988. }
  23989. }
  23990. if (__DEV__) {
  23991. validateDimensions(this, dimensions);
  23992. }
  23993. var dimSize = dimensions.length;
  23994. if (!dimSize) {
  23995. return;
  23996. }
  23997. var originalCount = this.count();
  23998. var Ctor = getIndicesCtor(this);
  23999. var newIndices = new Ctor(originalCount);
  24000. var offset = 0;
  24001. var dim0 = dimensions[0];
  24002. var min = range[dim0][0];
  24003. var max = range[dim0][1];
  24004. var quickFinished = false;
  24005. if (!this._indices /* && !stack */) {
  24006. // Extreme optimization for common case. About 2x faster in chrome.
  24007. var idx = 0;
  24008. if (dimSize === 1) {
  24009. var dimStorage = this._storage[dimensions[0]];
  24010. for (var k = 0; k < this._chunkCount; k++) {
  24011. var chunkStorage = dimStorage[k];
  24012. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  24013. for (var i = 0; i < len; i++) {
  24014. var val = chunkStorage[i];
  24015. if (val >= min && val <= max) {
  24016. newIndices[offset++] = idx;
  24017. }
  24018. idx++;
  24019. }
  24020. }
  24021. quickFinished = true;
  24022. }
  24023. else if (dimSize === 2) {
  24024. var dimStorage = this._storage[dim0];
  24025. var dimStorage2 = this._storage[dimensions[1]];
  24026. var min2 = range[dimensions[1]][0];
  24027. var max2 = range[dimensions[1]][1];
  24028. for (var k = 0; k < this._chunkCount; k++) {
  24029. var chunkStorage = dimStorage[k];
  24030. var chunkStorage2= dimStorage2[k];
  24031. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  24032. for (var i = 0; i < len; i++) {
  24033. var val = chunkStorage[i];
  24034. var val2 = chunkStorage2[i];
  24035. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  24036. newIndices[offset++] = idx;
  24037. }
  24038. idx++;
  24039. }
  24040. }
  24041. quickFinished = true;
  24042. }
  24043. }
  24044. if (!quickFinished) {
  24045. if (dimSize === 1) {
  24046. // stack = stack || !!this.getCalculationInfo(dim0);
  24047. for (var i = 0; i < originalCount; i++) {
  24048. var rawIndex = this.getRawIndex(i);
  24049. // var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  24050. var val = this._getFast(dim0, rawIndex);
  24051. if (val >= min && val <= max) {
  24052. newIndices[offset++] = rawIndex;
  24053. }
  24054. }
  24055. }
  24056. else {
  24057. for (var i = 0; i < originalCount; i++) {
  24058. var keep = true;
  24059. var rawIndex = this.getRawIndex(i);
  24060. for (var k = 0; k < dimSize; k++) {
  24061. var dimk = dimensions[k];
  24062. // var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  24063. var val = this._getFast(dim, rawIndex);
  24064. if (val < range[dimk][0] || val > range[dimk][1]) {
  24065. keep = false;
  24066. }
  24067. }
  24068. if (keep) {
  24069. newIndices[offset++] = this.getRawIndex(i);
  24070. }
  24071. }
  24072. }
  24073. }
  24074. // Set indices after filtered.
  24075. if (offset < originalCount) {
  24076. this._indices = newIndices;
  24077. }
  24078. this._count = offset;
  24079. // Reset data extent
  24080. this._extent = {};
  24081. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24082. return this;
  24083. };
  24084. /**
  24085. * Data mapping to a plain array
  24086. * @param {string|Array.<string>} [dimensions]
  24087. * @param {Function} cb
  24088. * @param {*} [context=this]
  24089. * @return {Array}
  24090. */
  24091. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  24092. 'use strict';
  24093. if (typeof dimensions === 'function') {
  24094. contextCompat = context;
  24095. context = cb;
  24096. cb = dimensions;
  24097. dimensions = [];
  24098. }
  24099. // contextCompat just for compat echarts3
  24100. context = context || contextCompat || this;
  24101. var result = [];
  24102. this.each(dimensions, function () {
  24103. result.push(cb && cb.apply(this, arguments));
  24104. }, context);
  24105. return result;
  24106. };
  24107. // Data in excludeDimensions is copied, otherwise transfered.
  24108. function cloneListForMapAndSample(original, excludeDimensions) {
  24109. var allDimensions = original.dimensions;
  24110. var list = new List(
  24111. map(allDimensions, original.getDimensionInfo, original),
  24112. original.hostModel
  24113. );
  24114. // FIXME If needs stackedOn, value may already been stacked
  24115. transferProperties(list, original);
  24116. var storage = list._storage = {};
  24117. var originalStorage = original._storage;
  24118. var rawExtent = extend({}, original._rawExtent);
  24119. // Init storage
  24120. for (var i = 0; i < allDimensions.length; i++) {
  24121. var dim = allDimensions[i];
  24122. if (originalStorage[dim]) {
  24123. if (indexOf(excludeDimensions, dim) >= 0) {
  24124. storage[dim] = cloneDimStore(originalStorage[dim]);
  24125. rawExtent[dim] = getInitialExtent();
  24126. }
  24127. else {
  24128. // Direct reference for other dimensions
  24129. storage[dim] = originalStorage[dim];
  24130. }
  24131. }
  24132. }
  24133. return list;
  24134. }
  24135. function cloneDimStore(originalDimStore) {
  24136. var newDimStore = new Array(originalDimStore.length);
  24137. for (var j = 0; j < originalDimStore.length; j++) {
  24138. newDimStore[j] = cloneChunk(originalDimStore[j]);
  24139. }
  24140. return newDimStore;
  24141. }
  24142. function getInitialExtent() {
  24143. return [Infinity, -Infinity];
  24144. }
  24145. /**
  24146. * Data mapping to a new List with given dimensions
  24147. * @param {string|Array.<string>} dimensions
  24148. * @param {Function} cb
  24149. * @param {*} [context=this]
  24150. * @return {Array}
  24151. */
  24152. listProto.map = function (dimensions, cb, context, contextCompat) {
  24153. 'use strict';
  24154. // contextCompat just for compat echarts3
  24155. context = context || contextCompat || this;
  24156. dimensions = map(
  24157. normalizeDimensions(dimensions), this.getDimension, this
  24158. );
  24159. if (__DEV__) {
  24160. validateDimensions(this, dimensions);
  24161. }
  24162. var list = cloneListForMapAndSample(this, dimensions);
  24163. // Following properties are all immutable.
  24164. // So we can reference to the same value
  24165. list._indices = this._indices;
  24166. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24167. var storage = list._storage;
  24168. var tmpRetValue = [];
  24169. var chunkSize = this._chunkSize;
  24170. var dimSize = dimensions.length;
  24171. var dataCount = this.count();
  24172. var values = [];
  24173. var rawExtent = list._rawExtent;
  24174. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  24175. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  24176. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  24177. }
  24178. values[dimSize] = dataIndex;
  24179. var retValue = cb && cb.apply(context, values);
  24180. if (retValue != null) {
  24181. // a number or string (in oridinal dimension)?
  24182. if (typeof retValue !== 'object') {
  24183. tmpRetValue[0] = retValue;
  24184. retValue = tmpRetValue;
  24185. }
  24186. var rawIndex = this.getRawIndex(dataIndex);
  24187. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24188. var chunkOffset = rawIndex % chunkSize;
  24189. for (var i = 0; i < retValue.length; i++) {
  24190. var dim = dimensions[i];
  24191. var val = retValue[i];
  24192. var rawExtentOnDim = rawExtent[dim];
  24193. var dimStore = storage[dim];
  24194. if (dimStore) {
  24195. dimStore[chunkIndex][chunkOffset] = val;
  24196. }
  24197. if (val < rawExtentOnDim[0]) {
  24198. rawExtentOnDim[0] = val;
  24199. }
  24200. if (val > rawExtentOnDim[1]) {
  24201. rawExtentOnDim[1] = val;
  24202. }
  24203. }
  24204. }
  24205. }
  24206. return list;
  24207. };
  24208. /**
  24209. * Large data down sampling on given dimension
  24210. * @param {string} dimension
  24211. * @param {number} rate
  24212. * @param {Function} sampleValue
  24213. * @param {Function} sampleIndex Sample index for name and id
  24214. */
  24215. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  24216. var list = cloneListForMapAndSample(this, [dimension]);
  24217. var targetStorage = list._storage;
  24218. var frameValues = [];
  24219. var frameSize = Math.floor(1 / rate);
  24220. var dimStore = targetStorage[dimension];
  24221. var len = this.count();
  24222. var chunkSize = this._chunkSize;
  24223. var rawExtentOnDim = list._rawExtent[dimension];
  24224. var newIndices = new (getIndicesCtor(this))(len);
  24225. var offset = 0;
  24226. for (var i = 0; i < len; i += frameSize) {
  24227. // Last frame
  24228. if (frameSize > len - i) {
  24229. frameSize = len - i;
  24230. frameValues.length = frameSize;
  24231. }
  24232. for (var k = 0; k < frameSize; k++) {
  24233. var dataIdx = this.getRawIndex(i + k);
  24234. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  24235. var originalChunkOffset = dataIdx % chunkSize;
  24236. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  24237. }
  24238. var value = sampleValue(frameValues);
  24239. var sampleFrameIdx = this.getRawIndex(
  24240. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  24241. );
  24242. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  24243. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  24244. // Only write value on the filtered data
  24245. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  24246. if (value < rawExtentOnDim[0]) {
  24247. rawExtentOnDim[0] = value;
  24248. }
  24249. if (value > rawExtentOnDim[1]) {
  24250. rawExtentOnDim[1] = value;
  24251. }
  24252. newIndices[offset++] = sampleFrameIdx;
  24253. }
  24254. list._count = offset;
  24255. list._indices = newIndices;
  24256. list.getRawIndex = getRawIndexWithIndices;
  24257. return list;
  24258. };
  24259. /**
  24260. * Get model of one data item.
  24261. *
  24262. * @param {number} idx
  24263. */
  24264. // FIXME Model proxy ?
  24265. listProto.getItemModel = function (idx) {
  24266. var hostModel = this.hostModel;
  24267. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  24268. };
  24269. /**
  24270. * Create a data differ
  24271. * @param {module:echarts/data/List} otherList
  24272. * @return {module:echarts/data/DataDiffer}
  24273. */
  24274. listProto.diff = function (otherList) {
  24275. var thisList = this;
  24276. return new DataDiffer(
  24277. otherList ? otherList.getIndices() : [],
  24278. this.getIndices(),
  24279. function (idx) {
  24280. return getId(otherList, idx);
  24281. },
  24282. function (idx) {
  24283. return getId(thisList, idx);
  24284. }
  24285. );
  24286. };
  24287. /**
  24288. * Get visual property.
  24289. * @param {string} key
  24290. */
  24291. listProto.getVisual = function (key) {
  24292. var visual = this._visual;
  24293. return visual && visual[key];
  24294. };
  24295. /**
  24296. * Set visual property
  24297. * @param {string|Object} key
  24298. * @param {*} [value]
  24299. *
  24300. * @example
  24301. * setVisual('color', color);
  24302. * setVisual({
  24303. * 'color': color
  24304. * });
  24305. */
  24306. listProto.setVisual = function (key, val) {
  24307. if (isObject$4(key)) {
  24308. for (var name in key) {
  24309. if (key.hasOwnProperty(name)) {
  24310. this.setVisual(name, key[name]);
  24311. }
  24312. }
  24313. return;
  24314. }
  24315. this._visual = this._visual || {};
  24316. this._visual[key] = val;
  24317. };
  24318. /**
  24319. * Set layout property.
  24320. * @param {string|Object} key
  24321. * @param {*} [val]
  24322. */
  24323. listProto.setLayout = function (key, val) {
  24324. if (isObject$4(key)) {
  24325. for (var name in key) {
  24326. if (key.hasOwnProperty(name)) {
  24327. this.setLayout(name, key[name]);
  24328. }
  24329. }
  24330. return;
  24331. }
  24332. this._layout[key] = val;
  24333. };
  24334. /**
  24335. * Get layout property.
  24336. * @param {string} key.
  24337. * @return {*}
  24338. */
  24339. listProto.getLayout = function (key) {
  24340. return this._layout[key];
  24341. };
  24342. /**
  24343. * Get layout of single data item
  24344. * @param {number} idx
  24345. */
  24346. listProto.getItemLayout = function (idx) {
  24347. return this._itemLayouts[idx];
  24348. };
  24349. /**
  24350. * Set layout of single data item
  24351. * @param {number} idx
  24352. * @param {Object} layout
  24353. * @param {boolean=} [merge=false]
  24354. */
  24355. listProto.setItemLayout = function (idx, layout, merge$$1) {
  24356. this._itemLayouts[idx] = merge$$1
  24357. ? extend(this._itemLayouts[idx] || {}, layout)
  24358. : layout;
  24359. };
  24360. /**
  24361. * Clear all layout of single data item
  24362. */
  24363. listProto.clearItemLayouts = function () {
  24364. this._itemLayouts.length = 0;
  24365. };
  24366. /**
  24367. * Get visual property of single data item
  24368. * @param {number} idx
  24369. * @param {string} key
  24370. * @param {boolean} [ignoreParent=false]
  24371. */
  24372. listProto.getItemVisual = function (idx, key, ignoreParent) {
  24373. var itemVisual = this._itemVisuals[idx];
  24374. var val = itemVisual && itemVisual[key];
  24375. if (val == null && !ignoreParent) {
  24376. // Use global visual property
  24377. return this.getVisual(key);
  24378. }
  24379. return val;
  24380. };
  24381. /**
  24382. * Set visual property of single data item
  24383. *
  24384. * @param {number} idx
  24385. * @param {string|Object} key
  24386. * @param {*} [value]
  24387. *
  24388. * @example
  24389. * setItemVisual(0, 'color', color);
  24390. * setItemVisual(0, {
  24391. * 'color': color
  24392. * });
  24393. */
  24394. listProto.setItemVisual = function (idx, key, value) {
  24395. var itemVisual = this._itemVisuals[idx] || {};
  24396. var hasItemVisual = this.hasItemVisual;
  24397. this._itemVisuals[idx] = itemVisual;
  24398. if (isObject$4(key)) {
  24399. for (var name in key) {
  24400. if (key.hasOwnProperty(name)) {
  24401. itemVisual[name] = key[name];
  24402. hasItemVisual[name] = true;
  24403. }
  24404. }
  24405. return;
  24406. }
  24407. itemVisual[key] = value;
  24408. hasItemVisual[key] = true;
  24409. };
  24410. /**
  24411. * Clear itemVisuals and list visual.
  24412. */
  24413. listProto.clearAllVisual = function () {
  24414. this._visual = {};
  24415. this._itemVisuals = [];
  24416. this.hasItemVisual = {};
  24417. };
  24418. var setItemDataAndSeriesIndex = function (child) {
  24419. child.seriesIndex = this.seriesIndex;
  24420. child.dataIndex = this.dataIndex;
  24421. child.dataType = this.dataType;
  24422. };
  24423. /**
  24424. * Set graphic element relative to data. It can be set as null
  24425. * @param {number} idx
  24426. * @param {module:zrender/Element} [el]
  24427. */
  24428. listProto.setItemGraphicEl = function (idx, el) {
  24429. var hostModel = this.hostModel;
  24430. if (el) {
  24431. // Add data index and series index for indexing the data by element
  24432. // Useful in tooltip
  24433. el.dataIndex = idx;
  24434. el.dataType = this.dataType;
  24435. el.seriesIndex = hostModel && hostModel.seriesIndex;
  24436. if (el.type === 'group') {
  24437. el.traverse(setItemDataAndSeriesIndex, el);
  24438. }
  24439. }
  24440. this._graphicEls[idx] = el;
  24441. };
  24442. /**
  24443. * @param {number} idx
  24444. * @return {module:zrender/Element}
  24445. */
  24446. listProto.getItemGraphicEl = function (idx) {
  24447. return this._graphicEls[idx];
  24448. };
  24449. /**
  24450. * @param {Function} cb
  24451. * @param {*} context
  24452. */
  24453. listProto.eachItemGraphicEl = function (cb, context) {
  24454. each$1(this._graphicEls, function (el, idx) {
  24455. if (el) {
  24456. cb && cb.call(context, el, idx);
  24457. }
  24458. });
  24459. };
  24460. /**
  24461. * Shallow clone a new list except visual and layout properties, and graph elements.
  24462. * New list only change the indices.
  24463. */
  24464. listProto.cloneShallow = function (list) {
  24465. if (!list) {
  24466. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24467. list = new List(dimensionInfoList, this.hostModel);
  24468. }
  24469. // FIXME
  24470. list._storage = this._storage;
  24471. transferProperties(list, this);
  24472. // Clone will not change the data extent and indices
  24473. if (this._indices) {
  24474. var Ctor = this._indices.constructor;
  24475. list._indices = new Ctor(this._indices);
  24476. }
  24477. else {
  24478. list._indices = null;
  24479. }
  24480. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24481. list._extent = clone(this._extent);
  24482. list._approximateExtent = clone(this._approximateExtent);
  24483. return list;
  24484. };
  24485. /**
  24486. * Wrap some method to add more feature
  24487. * @param {string} methodName
  24488. * @param {Function} injectFunction
  24489. */
  24490. listProto.wrapMethod = function (methodName, injectFunction) {
  24491. var originalMethod = this[methodName];
  24492. if (typeof originalMethod !== 'function') {
  24493. return;
  24494. }
  24495. this.__wrappedMethods = this.__wrappedMethods || [];
  24496. this.__wrappedMethods.push(methodName);
  24497. this[methodName] = function () {
  24498. var res = originalMethod.apply(this, arguments);
  24499. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24500. };
  24501. };
  24502. // Methods that create a new list based on this list should be listed here.
  24503. // Notice that those method should `RETURN` the new list.
  24504. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24505. // Methods that change indices of this list should be listed here.
  24506. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24507. /**
  24508. * @deprecated
  24509. * Use `echarts/data/helper/createDimensions` instead.
  24510. */
  24511. /**
  24512. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24513. *
  24514. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24515. * and guessing from the data structure.
  24516. * If no 'value' dimension specified, the first no-named dimension will be
  24517. * named as 'value'.
  24518. *
  24519. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24520. * provides not only dim template, but also default order.
  24521. * properties: 'name', 'type', 'displayName'.
  24522. * `name` of each item provides default coord name.
  24523. * [{dimsDef: [string...]}, ...] dimsDef of sysDim item provides default dim name, and
  24524. * provide dims count that the sysDim required.
  24525. * [{ordinalMeta}] can be specified.
  24526. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24527. * @param {Object} [opt]
  24528. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24529. * For example: ['asdf', {name, type}, ...].
  24530. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24531. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  24532. * If not specified, extra dim names will be:
  24533. * 'value', 'value0', 'value1', ...
  24534. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  24535. * If `generateCoordCount` specified, the generated dim names will be:
  24536. * `generateCoord` + 0, `generateCoord` + 1, ...
  24537. * can be Infinity, indicate that use all of the remain columns.
  24538. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24539. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24540. * @return {Array.<Object>} [{
  24541. * name: string mandatory,
  24542. * displayName: string, the origin name in dimsDef, see source helper.
  24543. * If displayName given, the tooltip will displayed vertically.
  24544. * coordDim: string mandatory,
  24545. * coordDimIndex: number mandatory,
  24546. * type: string optional,
  24547. * otherDims: { never null/undefined
  24548. * tooltip: number optional,
  24549. * label: number optional,
  24550. * itemName: number optional,
  24551. * seriesName: number optional,
  24552. * },
  24553. * isExtraCoord: boolean true if coord is generated
  24554. * (not specified in encode and not series specified)
  24555. * other props ...
  24556. * }]
  24557. */
  24558. function completeDimensions(sysDims, source, opt) {
  24559. if (!Source.isInstance(source)) {
  24560. source = Source.seriesDataToSource(source);
  24561. }
  24562. opt = opt || {};
  24563. sysDims = (sysDims || []).slice();
  24564. var dimsDef = (opt.dimsDef || []).slice();
  24565. var encodeDef = createHashMap(opt.encodeDef);
  24566. var dataDimNameMap = createHashMap();
  24567. var coordDimNameMap = createHashMap();
  24568. // var valueCandidate;
  24569. var result = [];
  24570. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24571. // Apply user defined dims (`name` and `type`) and init result.
  24572. for (var i = 0; i < dimCount; i++) {
  24573. var dimDefItem = dimsDef[i] = extend(
  24574. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24575. );
  24576. var userDimName = dimDefItem.name;
  24577. var resultItem = result[i] = {otherDims: {}};
  24578. // Name will be applied later for avoiding duplication.
  24579. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24580. // Only if `series.dimensions` is defined in option
  24581. // displayName, will be set, and dimension will be diplayed vertically in
  24582. // tooltip by default.
  24583. resultItem.name = resultItem.displayName = userDimName;
  24584. dataDimNameMap.set(userDimName, i);
  24585. }
  24586. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24587. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24588. }
  24589. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24590. encodeDef.each(function (dataDims, coordDim) {
  24591. dataDims = normalizeToArray(dataDims).slice();
  24592. var validDataDims = encodeDef.set(coordDim, []);
  24593. each$1(dataDims, function (resultDimIdx, idx) {
  24594. // The input resultDimIdx can be dim name or index.
  24595. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24596. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24597. validDataDims[idx] = resultDimIdx;
  24598. applyDim(result[resultDimIdx], coordDim, idx);
  24599. }
  24600. });
  24601. });
  24602. // Apply templetes and default order from `sysDims`.
  24603. var availDimIdx = 0;
  24604. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24605. var coordDim;
  24606. var sysDimItem;
  24607. var sysDimItemDimsDef;
  24608. var sysDimItemOtherDims;
  24609. if (isString(sysDimItem)) {
  24610. coordDim = sysDimItem;
  24611. sysDimItem = {};
  24612. }
  24613. else {
  24614. coordDim = sysDimItem.name;
  24615. var ordinalMeta = sysDimItem.ordinalMeta;
  24616. sysDimItem.ordinalMeta = null;
  24617. sysDimItem = clone(sysDimItem);
  24618. sysDimItem.ordinalMeta = ordinalMeta;
  24619. // `coordDimIndex` should not be set directly.
  24620. sysDimItemDimsDef = sysDimItem.dimsDef;
  24621. sysDimItemOtherDims = sysDimItem.otherDims;
  24622. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24623. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24624. }
  24625. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24626. // dimensions provides default dim sequences.
  24627. if (!dataDims.length) {
  24628. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24629. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24630. availDimIdx++;
  24631. }
  24632. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24633. }
  24634. }
  24635. // Apply templates.
  24636. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24637. var resultItem = result[resultDimIdx];
  24638. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24639. if (resultItem.name == null && sysDimItemDimsDef) {
  24640. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24641. }
  24642. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24643. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24644. });
  24645. });
  24646. function applyDim(resultItem, coordDim, coordDimIndex) {
  24647. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24648. resultItem.otherDims[coordDim] = coordDimIndex;
  24649. }
  24650. else {
  24651. resultItem.coordDim = coordDim;
  24652. resultItem.coordDimIndex = coordDimIndex;
  24653. coordDimNameMap.set(coordDim, true);
  24654. }
  24655. }
  24656. // Make sure the first extra dim is 'value'.
  24657. var generateCoord = opt.generateCoord;
  24658. var generateCoordCount = opt.generateCoordCount;
  24659. var fromZero = generateCoordCount != null;
  24660. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  24661. var extra = generateCoord || 'value';
  24662. // Set dim `name` and other `coordDim` and other props.
  24663. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24664. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24665. var coordDim = resultItem.coordDim;
  24666. if (coordDim == null) {
  24667. resultItem.coordDim = genName(
  24668. extra, coordDimNameMap, fromZero
  24669. );
  24670. resultItem.coordDimIndex = 0;
  24671. if (!generateCoord || generateCoordCount <= 0) {
  24672. resultItem.isExtraCoord = true;
  24673. }
  24674. generateCoordCount--;
  24675. }
  24676. resultItem.name == null && (resultItem.name = genName(
  24677. resultItem.coordDim,
  24678. dataDimNameMap
  24679. ));
  24680. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24681. resultItem.type = 'ordinal';
  24682. }
  24683. }
  24684. return result;
  24685. }
  24686. // ??? TODO
  24687. // Originally detect dimCount by data[0]. Should we
  24688. // optimize it to only by sysDims and dimensions and encode.
  24689. // So only necessary dims will be initialized.
  24690. // But
  24691. // (1) custom series should be considered. where other dims
  24692. // may be visited.
  24693. // (2) sometimes user need to calcualte bubble size or use visualMap
  24694. // on other dimensions besides coordSys needed.
  24695. // So, dims that is not used by system, should be shared in storage?
  24696. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  24697. // Note that the result dimCount should not small than columns count
  24698. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  24699. var dimCount = Math.max(
  24700. source.dimensionsDetectCount || 1,
  24701. sysDims.length,
  24702. dimsDef.length,
  24703. optDimCount || 0
  24704. );
  24705. each$1(sysDims, function (sysDimItem) {
  24706. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24707. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24708. });
  24709. return dimCount;
  24710. }
  24711. function genName(name, map$$1, fromZero) {
  24712. if (fromZero || map$$1.get(name) != null) {
  24713. var i = 0;
  24714. while (map$$1.get(name + i) != null) {
  24715. i++;
  24716. }
  24717. name += i;
  24718. }
  24719. map$$1.set(name, true);
  24720. return name;
  24721. }
  24722. /**
  24723. * Substitute `completeDimensions`.
  24724. * `completeDimensions` is to be deprecated.
  24725. */
  24726. /**
  24727. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24728. * @param {Object|Array} [opt]
  24729. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24730. * @param {number} [opt.dimensionsCount]
  24731. * @param {string} [opt.generateCoord]
  24732. * @param {string} [opt.generateCoordCount]
  24733. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24734. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24735. * @return {Array.<Object>} dimensionsInfo
  24736. */
  24737. var createDimensions = function (source, opt) {
  24738. opt = opt || {};
  24739. return completeDimensions(opt.coordDimensions || [], source, {
  24740. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24741. encodeDef: opt.encodeDefine || source.encodeDefine,
  24742. dimCount: opt.dimensionsCount,
  24743. generateCoord: opt.generateCoord,
  24744. generateCoordCount: opt.generateCoordCount
  24745. });
  24746. };
  24747. /**
  24748. * Note that it is too complicated to support 3d stack by value
  24749. * (have to create two-dimension inverted index), so in 3d case
  24750. * we just support that stacked by index.
  24751. *
  24752. * @param {module:echarts/model/Series} seriesModel
  24753. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  24754. * The input dimensionInfoList will be modified.
  24755. * @param {Object} [opt]
  24756. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  24757. * @param {boolean} [opt.byIndex=false]
  24758. * @return {Object} calculationInfo
  24759. * {
  24760. * stackedDimension: string
  24761. * stackedByDimension: string
  24762. * isStackedByIndex: boolean
  24763. * stackedOverDimension: string
  24764. * stackResultDimension: string
  24765. * }
  24766. */
  24767. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  24768. opt = opt || {};
  24769. var byIndex = opt.byIndex;
  24770. var stackedCoordDimension = opt.stackedCoordDimension;
  24771. // Compatibal: when `stack` is set as '', do not stack.
  24772. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  24773. var stackedByDimInfo;
  24774. var stackedDimInfo;
  24775. var stackResultDimension;
  24776. var stackedOverDimension;
  24777. each$1(dimensionInfoList, function (dimensionInfo, index) {
  24778. if (isString(dimensionInfo)) {
  24779. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  24780. }
  24781. if (mayStack && !dimensionInfo.isExtraCoord) {
  24782. // Find the first ordinal dimension as the stackedByDimInfo.
  24783. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  24784. stackedByDimInfo = dimensionInfo;
  24785. }
  24786. // Find the first stackable dimension as the stackedDimInfo.
  24787. if (!stackedDimInfo
  24788. && dimensionInfo.type !== 'ordinal'
  24789. && dimensionInfo.type !== 'time'
  24790. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  24791. ) {
  24792. stackedDimInfo = dimensionInfo;
  24793. }
  24794. }
  24795. });
  24796. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  24797. // That put stack logic in List is for using conveniently in echarts extensions, but it
  24798. // might not be a good way.
  24799. if (stackedDimInfo && (byIndex || stackedByDimInfo)) {
  24800. // Use a weird name that not duplicated with other names.
  24801. stackResultDimension = '__\0ecstackresult';
  24802. stackedOverDimension = '__\0ecstackedover';
  24803. // Create inverted index to fast query index by value.
  24804. if (stackedByDimInfo) {
  24805. stackedByDimInfo.createInvertedIndices = true;
  24806. }
  24807. var stackedDimCoordDim = stackedDimInfo.coordDim;
  24808. var stackedDimType = stackedDimInfo.type;
  24809. var stackedDimCoordIndex = 0;
  24810. each$1(dimensionInfoList, function (dimensionInfo) {
  24811. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  24812. stackedDimCoordIndex++;
  24813. }
  24814. });
  24815. dimensionInfoList.push({
  24816. name: stackResultDimension,
  24817. coordDim: stackedDimCoordDim,
  24818. coordDimIndex: stackedDimCoordIndex,
  24819. type: stackedDimType,
  24820. isExtraCoord: true,
  24821. isCalculationCoord: true
  24822. });
  24823. stackedDimCoordIndex++;
  24824. dimensionInfoList.push({
  24825. name: stackedOverDimension,
  24826. // This dimension contains stack base (generally, 0), so do not set it as
  24827. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  24828. coordDim: stackedOverDimension,
  24829. coordDimIndex: stackedDimCoordIndex,
  24830. type: stackedDimType,
  24831. isExtraCoord: true,
  24832. isCalculationCoord: true
  24833. });
  24834. }
  24835. return {
  24836. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  24837. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  24838. isStackedByIndex: byIndex,
  24839. stackedOverDimension: stackedOverDimension,
  24840. stackResultDimension: stackResultDimension
  24841. };
  24842. }
  24843. /**
  24844. * @param {module:echarts/data/List} data
  24845. * @param {string} stackedDim
  24846. * @param {string} [stackedByDim] If not input this parameter, check whether
  24847. * stacked by index.
  24848. */
  24849. function isDimensionStacked(data, stackedDim, stackedByDim) {
  24850. return stackedDim
  24851. && stackedDim === data.getCalculationInfo('stackedDimension')
  24852. && (
  24853. stackedByDim != null
  24854. ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  24855. : data.getCalculationInfo('isStackedByIndex')
  24856. );
  24857. }
  24858. /**
  24859. * @param {module:echarts/data/Source|Array} source Or raw data.
  24860. * @param {module:echarts/model/Series} seriesModel
  24861. * @param {Object} [opt]
  24862. * @param {string} [opt.generateCoord]
  24863. */
  24864. function createListFromArray(source, seriesModel, opt) {
  24865. opt = opt || {};
  24866. if (!Source.isInstance(source)) {
  24867. source = Source.seriesDataToSource(source);
  24868. }
  24869. var coordSysName = seriesModel.get('coordinateSystem');
  24870. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24871. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24872. var coordSysDimDefs;
  24873. if (coordSysDefine) {
  24874. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24875. var dimInfo = {name: dim};
  24876. var axisModel = coordSysDefine.axisMap.get(dim);
  24877. if (axisModel) {
  24878. var axisType = axisModel.get('type');
  24879. dimInfo.type = getDimensionTypeByAxis(axisType);
  24880. // dimInfo.stackable = isStackable(axisType);
  24881. }
  24882. return dimInfo;
  24883. });
  24884. }
  24885. if (!coordSysDimDefs) {
  24886. // Get dimensions from registered coordinate system
  24887. coordSysDimDefs = (registeredCoordSys && (
  24888. registeredCoordSys.getDimensionsInfo
  24889. ? registeredCoordSys.getDimensionsInfo()
  24890. : registeredCoordSys.dimensions.slice()
  24891. )) || ['x', 'y'];
  24892. }
  24893. var dimInfoList = createDimensions(source, {
  24894. coordDimensions: coordSysDimDefs,
  24895. generateCoord: opt.generateCoord
  24896. });
  24897. var firstCategoryDimIndex;
  24898. var hasNameEncode;
  24899. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24900. var coordDim = dimInfo.coordDim;
  24901. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24902. if (categoryAxisModel) {
  24903. if (firstCategoryDimIndex == null) {
  24904. firstCategoryDimIndex = dimIndex;
  24905. }
  24906. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24907. }
  24908. if (dimInfo.otherDims.itemName != null) {
  24909. hasNameEncode = true;
  24910. }
  24911. });
  24912. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24913. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24914. }
  24915. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  24916. var list = new List(dimInfoList, seriesModel);
  24917. list.setCalculationInfo(stackCalculationInfo);
  24918. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24919. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24920. // Use dataIndex as ordinal value in categoryAxis
  24921. return dimIndex === firstCategoryDimIndex
  24922. ? dataIndex
  24923. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24924. }
  24925. : null;
  24926. list.hasItemOption = false;
  24927. list.initData(source, null, dimValueGetter);
  24928. return list;
  24929. }
  24930. function isNeedCompleteOrdinalData(source) {
  24931. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24932. var sampleItem = firstDataNotNull(source.data || []);
  24933. return sampleItem != null
  24934. && !isArray(getDataItemValue(sampleItem));
  24935. }
  24936. }
  24937. function firstDataNotNull(data) {
  24938. var i = 0;
  24939. while (i < data.length && data[i] == null) {
  24940. i++;
  24941. }
  24942. return data[i];
  24943. }
  24944. /**
  24945. * // Scale class management
  24946. * @module echarts/scale/Scale
  24947. */
  24948. /**
  24949. * @param {Object} [setting]
  24950. */
  24951. function Scale(setting) {
  24952. this._setting = setting || {};
  24953. /**
  24954. * Extent
  24955. * @type {Array.<number>}
  24956. * @protected
  24957. */
  24958. this._extent = [Infinity, -Infinity];
  24959. /**
  24960. * Step is calculated in adjustExtent
  24961. * @type {Array.<number>}
  24962. * @protected
  24963. */
  24964. this._interval = 0;
  24965. this.init && this.init.apply(this, arguments);
  24966. }
  24967. /**
  24968. * Parse input val to valid inner number.
  24969. * @param {*} val
  24970. * @return {number}
  24971. */
  24972. Scale.prototype.parse = function (val) {
  24973. // Notice: This would be a trap here, If the implementation
  24974. // of this method depends on extent, and this method is used
  24975. // before extent set (like in dataZoom), it would be wrong.
  24976. // Nevertheless, parse does not depend on extent generally.
  24977. return val;
  24978. };
  24979. Scale.prototype.getSetting = function (name) {
  24980. return this._setting[name];
  24981. };
  24982. Scale.prototype.contain = function (val) {
  24983. var extent = this._extent;
  24984. return val >= extent[0] && val <= extent[1];
  24985. };
  24986. /**
  24987. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24988. * @param {number} val
  24989. * @return {number}
  24990. */
  24991. Scale.prototype.normalize = function (val) {
  24992. var extent = this._extent;
  24993. if (extent[1] === extent[0]) {
  24994. return 0.5;
  24995. }
  24996. return (val - extent[0]) / (extent[1] - extent[0]);
  24997. };
  24998. /**
  24999. * Scale normalized value
  25000. * @param {number} val
  25001. * @return {number}
  25002. */
  25003. Scale.prototype.scale = function (val) {
  25004. var extent = this._extent;
  25005. return val * (extent[1] - extent[0]) + extent[0];
  25006. };
  25007. /**
  25008. * Set extent from data
  25009. * @param {Array.<number>} other
  25010. */
  25011. Scale.prototype.unionExtent = function (other) {
  25012. var extent = this._extent;
  25013. other[0] < extent[0] && (extent[0] = other[0]);
  25014. other[1] > extent[1] && (extent[1] = other[1]);
  25015. // not setExtent because in log axis it may transformed to power
  25016. // this.setExtent(extent[0], extent[1]);
  25017. };
  25018. /**
  25019. * Set extent from data
  25020. * @param {module:echarts/data/List} data
  25021. * @param {string} dim
  25022. */
  25023. Scale.prototype.unionExtentFromData = function (data, dim) {
  25024. this.unionExtent(data.getApproximateExtent(dim));
  25025. };
  25026. /**
  25027. * Get extent
  25028. * @return {Array.<number>}
  25029. */
  25030. Scale.prototype.getExtent = function () {
  25031. return this._extent.slice();
  25032. };
  25033. /**
  25034. * Set extent
  25035. * @param {number} start
  25036. * @param {number} end
  25037. */
  25038. Scale.prototype.setExtent = function (start, end) {
  25039. var thisExtent = this._extent;
  25040. if (!isNaN(start)) {
  25041. thisExtent[0] = start;
  25042. }
  25043. if (!isNaN(end)) {
  25044. thisExtent[1] = end;
  25045. }
  25046. };
  25047. /**
  25048. * @return {Array.<string>}
  25049. */
  25050. Scale.prototype.getTicksLabels = function () {
  25051. var labels = [];
  25052. var ticks = this.getTicks();
  25053. for (var i = 0; i < ticks.length; i++) {
  25054. labels.push(this.getLabel(ticks[i]));
  25055. }
  25056. return labels;
  25057. };
  25058. /**
  25059. * When axis extent depends on data and no data exists,
  25060. * axis ticks should not be drawn, which is named 'blank'.
  25061. */
  25062. Scale.prototype.isBlank = function () {
  25063. return this._isBlank;
  25064. },
  25065. /**
  25066. * When axis extent depends on data and no data exists,
  25067. * axis ticks should not be drawn, which is named 'blank'.
  25068. */
  25069. Scale.prototype.setBlank = function (isBlank) {
  25070. this._isBlank = isBlank;
  25071. };
  25072. enableClassExtend(Scale);
  25073. enableClassManagement(Scale, {
  25074. registerWhenExtend: true
  25075. });
  25076. /**
  25077. * @constructor
  25078. * @param {Object} [opt]
  25079. * @param {Object} [opt.categories=[]]
  25080. * @param {Object} [opt.needCollect=false]
  25081. * @param {Object} [opt.deduplication=false]
  25082. */
  25083. function OrdinalMeta(opt) {
  25084. /**
  25085. * @readOnly
  25086. * @type {Array.<string>}
  25087. */
  25088. this.categories = opt.categories || [];
  25089. /**
  25090. * @private
  25091. * @type {boolean}
  25092. */
  25093. this._needCollect = opt.needCollect;
  25094. /**
  25095. * @private
  25096. * @type {boolean}
  25097. */
  25098. this._deduplication = opt.deduplication;
  25099. /**
  25100. * @private
  25101. * @type {boolean}
  25102. */
  25103. this._map;
  25104. }
  25105. /**
  25106. * @param {module:echarts/model/Model} axisModel
  25107. * @return {module:echarts/data/OrdinalMeta}
  25108. */
  25109. OrdinalMeta.createByAxisModel = function (axisModel) {
  25110. var option = axisModel.option;
  25111. var data = option.data;
  25112. var categories = data && map(data, getName);
  25113. return new OrdinalMeta({
  25114. categories: categories,
  25115. needCollect: !categories,
  25116. // deduplication is default in axis.
  25117. deduplication: option.dedplication !== false
  25118. });
  25119. };
  25120. var proto$1 = OrdinalMeta.prototype;
  25121. /**
  25122. * @param {string} category
  25123. * @return {number} ordinal
  25124. */
  25125. proto$1.getOrdinal = function (category) {
  25126. return getOrCreateMap(this).get(category);
  25127. };
  25128. /**
  25129. * @param {*} category
  25130. * @return {number} The ordinal. If not found, return NaN.
  25131. */
  25132. proto$1.parseAndCollect = function (category) {
  25133. var index;
  25134. var needCollect = this._needCollect;
  25135. // The value of category dim can be the index of the given category set.
  25136. // This feature is only supported when !needCollect, because we should
  25137. // consider a common case: a value is 2017, which is a number but is
  25138. // expected to be tread as a category. This case usually happen in dataset,
  25139. // where it happent to be no need of the index feature.
  25140. if (typeof category !== 'string' && !needCollect) {
  25141. return category;
  25142. }
  25143. // Optimize for the scenario:
  25144. // category is ['2012-01-01', '2012-01-02', ...], where the input
  25145. // data has been ensured not duplicate and is large data.
  25146. // Notice, if a dataset dimension provide categroies, usually echarts
  25147. // should remove duplication except user tell echarts dont do that
  25148. // (set axis.deduplication = false), because echarts do not know whether
  25149. // the values in the category dimension has duplication (consider the
  25150. // parallel-aqi example)
  25151. if (needCollect && !this._deduplication) {
  25152. index = this.categories.length;
  25153. this.categories[index] = category;
  25154. return index;
  25155. }
  25156. var map$$1 = getOrCreateMap(this);
  25157. index = map$$1.get(category);
  25158. if (index == null) {
  25159. if (needCollect) {
  25160. index = this.categories.length;
  25161. this.categories[index] = category;
  25162. map$$1.set(category, index);
  25163. }
  25164. else {
  25165. index = NaN;
  25166. }
  25167. }
  25168. return index;
  25169. };
  25170. // Consider big data, do not create map until needed.
  25171. function getOrCreateMap(ordinalMeta) {
  25172. return ordinalMeta._map || (
  25173. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  25174. );
  25175. }
  25176. function getName(obj) {
  25177. if (isObject$1(obj) && obj.value != null) {
  25178. return obj.value;
  25179. }
  25180. else {
  25181. return obj + '';
  25182. }
  25183. }
  25184. /**
  25185. * Linear continuous scale
  25186. * @module echarts/coord/scale/Ordinal
  25187. *
  25188. * http://en.wikipedia.org/wiki/Level_of_measurement
  25189. */
  25190. // FIXME only one data
  25191. var scaleProto = Scale.prototype;
  25192. var OrdinalScale = Scale.extend({
  25193. type: 'ordinal',
  25194. /**
  25195. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  25196. */
  25197. init: function (ordinalMeta, extent) {
  25198. // Caution: Should not use instanceof, consider ec-extensions using
  25199. // import approach to get OrdinalMeta class.
  25200. if (!ordinalMeta || isArray(ordinalMeta)) {
  25201. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  25202. }
  25203. this._ordinalMeta = ordinalMeta;
  25204. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  25205. },
  25206. parse: function (val) {
  25207. return typeof val === 'string'
  25208. ? this._ordinalMeta.getOrdinal(val)
  25209. // val might be float.
  25210. : Math.round(val);
  25211. },
  25212. contain: function (rank) {
  25213. rank = this.parse(rank);
  25214. return scaleProto.contain.call(this, rank)
  25215. && this._ordinalMeta.categories[rank] != null;
  25216. },
  25217. /**
  25218. * Normalize given rank or name to linear [0, 1]
  25219. * @param {number|string} [val]
  25220. * @return {number}
  25221. */
  25222. normalize: function (val) {
  25223. return scaleProto.normalize.call(this, this.parse(val));
  25224. },
  25225. scale: function (val) {
  25226. return Math.round(scaleProto.scale.call(this, val));
  25227. },
  25228. /**
  25229. * @return {Array}
  25230. */
  25231. getTicks: function () {
  25232. var ticks = [];
  25233. var extent = this._extent;
  25234. var rank = extent[0];
  25235. while (rank <= extent[1]) {
  25236. ticks.push(rank);
  25237. rank++;
  25238. }
  25239. return ticks;
  25240. },
  25241. /**
  25242. * Get item on rank n
  25243. * @param {number} n
  25244. * @return {string}
  25245. */
  25246. getLabel: function (n) {
  25247. return this._ordinalMeta.categories[n];
  25248. },
  25249. /**
  25250. * @return {number}
  25251. */
  25252. count: function () {
  25253. return this._extent[1] - this._extent[0] + 1;
  25254. },
  25255. /**
  25256. * @override
  25257. */
  25258. unionExtentFromData: function (data, dim) {
  25259. this.unionExtent(data.getApproximateExtent(dim));
  25260. },
  25261. niceTicks: noop,
  25262. niceExtent: noop
  25263. });
  25264. /**
  25265. * @return {module:echarts/scale/Time}
  25266. */
  25267. OrdinalScale.create = function () {
  25268. return new OrdinalScale();
  25269. };
  25270. /**
  25271. * For testable.
  25272. */
  25273. var roundNumber$1 = round$1;
  25274. /**
  25275. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  25276. * Should be extent[0] < extent[1].
  25277. * @param {number} splitNumber splitNumber should be >= 1.
  25278. * @param {number} [minInterval]
  25279. * @param {number} [maxInterval]
  25280. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  25281. */
  25282. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  25283. var result = {};
  25284. var span = extent[1] - extent[0];
  25285. var interval = result.interval = nice(span / splitNumber, true);
  25286. if (minInterval != null && interval < minInterval) {
  25287. interval = result.interval = minInterval;
  25288. }
  25289. if (maxInterval != null && interval > maxInterval) {
  25290. interval = result.interval = maxInterval;
  25291. }
  25292. // Tow more digital for tick.
  25293. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  25294. // Niced extent inside original extent
  25295. var niceTickExtent = result.niceTickExtent = [
  25296. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  25297. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  25298. ];
  25299. fixExtent(niceTickExtent, extent);
  25300. return result;
  25301. }
  25302. /**
  25303. * @param {number} interval
  25304. * @return {number} interval precision
  25305. */
  25306. function getIntervalPrecision(interval) {
  25307. // Tow more digital for tick.
  25308. return getPrecisionSafe(interval) + 2;
  25309. }
  25310. function clamp(niceTickExtent, idx, extent) {
  25311. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  25312. }
  25313. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  25314. function fixExtent(niceTickExtent, extent) {
  25315. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  25316. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  25317. clamp(niceTickExtent, 0, extent);
  25318. clamp(niceTickExtent, 1, extent);
  25319. if (niceTickExtent[0] > niceTickExtent[1]) {
  25320. niceTickExtent[0] = niceTickExtent[1];
  25321. }
  25322. }
  25323. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  25324. var ticks = [];
  25325. // If interval is 0, return [];
  25326. if (!interval) {
  25327. return ticks;
  25328. }
  25329. // Consider this case: using dataZoom toolbox, zoom and zoom.
  25330. var safeLimit = 10000;
  25331. if (extent[0] < niceTickExtent[0]) {
  25332. ticks.push(extent[0]);
  25333. }
  25334. var tick = niceTickExtent[0];
  25335. while (tick <= niceTickExtent[1]) {
  25336. ticks.push(tick);
  25337. // Avoid rounding error
  25338. tick = roundNumber$1(tick + interval, intervalPrecision);
  25339. if (tick === ticks[ticks.length - 1]) {
  25340. // Consider out of safe float point, e.g.,
  25341. // -3711126.9907707 + 2e-10 === -3711126.9907707
  25342. break;
  25343. }
  25344. if (ticks.length > safeLimit) {
  25345. return [];
  25346. }
  25347. }
  25348. // Consider this case: the last item of ticks is smaller
  25349. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  25350. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  25351. ticks.push(extent[1]);
  25352. }
  25353. return ticks;
  25354. }
  25355. /**
  25356. * Interval scale
  25357. * @module echarts/scale/Interval
  25358. */
  25359. var roundNumber = round$1;
  25360. /**
  25361. * @alias module:echarts/coord/scale/Interval
  25362. * @constructor
  25363. */
  25364. var IntervalScale = Scale.extend({
  25365. type: 'interval',
  25366. _interval: 0,
  25367. _intervalPrecision: 2,
  25368. setExtent: function (start, end) {
  25369. var thisExtent = this._extent;
  25370. //start,end may be a Number like '25',so...
  25371. if (!isNaN(start)) {
  25372. thisExtent[0] = parseFloat(start);
  25373. }
  25374. if (!isNaN(end)) {
  25375. thisExtent[1] = parseFloat(end);
  25376. }
  25377. },
  25378. unionExtent: function (other) {
  25379. var extent = this._extent;
  25380. other[0] < extent[0] && (extent[0] = other[0]);
  25381. other[1] > extent[1] && (extent[1] = other[1]);
  25382. // unionExtent may called by it's sub classes
  25383. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  25384. },
  25385. /**
  25386. * Get interval
  25387. */
  25388. getInterval: function () {
  25389. return this._interval;
  25390. },
  25391. /**
  25392. * Set interval
  25393. */
  25394. setInterval: function (interval) {
  25395. this._interval = interval;
  25396. // Dropped auto calculated niceExtent and use user setted extent
  25397. // We assume user wan't to set both interval, min, max to get a better result
  25398. this._niceExtent = this._extent.slice();
  25399. this._intervalPrecision = getIntervalPrecision(interval);
  25400. },
  25401. /**
  25402. * @return {Array.<number>}
  25403. */
  25404. getTicks: function () {
  25405. return intervalScaleGetTicks(
  25406. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  25407. );
  25408. },
  25409. /**
  25410. * @return {Array.<string>}
  25411. */
  25412. getTicksLabels: function () {
  25413. var labels = [];
  25414. var ticks = this.getTicks();
  25415. for (var i = 0; i < ticks.length; i++) {
  25416. labels.push(this.getLabel(ticks[i]));
  25417. }
  25418. return labels;
  25419. },
  25420. /**
  25421. * @param {number} data
  25422. * @param {Object} [opt]
  25423. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  25424. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  25425. * @return {string}
  25426. */
  25427. getLabel: function (data, opt) {
  25428. if (data == null) {
  25429. return '';
  25430. }
  25431. var precision = opt && opt.precision;
  25432. if (precision == null) {
  25433. precision = getPrecisionSafe(data) || 0;
  25434. }
  25435. else if (precision === 'auto') {
  25436. // Should be more precise then tick.
  25437. precision = this._intervalPrecision;
  25438. }
  25439. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  25440. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  25441. data = roundNumber(data, precision, true);
  25442. return addCommas(data);
  25443. },
  25444. /**
  25445. * Update interval and extent of intervals for nice ticks
  25446. *
  25447. * @param {number} [splitNumber = 5] Desired number of ticks
  25448. * @param {number} [minInterval]
  25449. * @param {number} [maxInterval]
  25450. */
  25451. niceTicks: function (splitNumber, minInterval, maxInterval) {
  25452. splitNumber = splitNumber || 5;
  25453. var extent = this._extent;
  25454. var span = extent[1] - extent[0];
  25455. if (!isFinite(span)) {
  25456. return;
  25457. }
  25458. // User may set axis min 0 and data are all negative
  25459. // FIXME If it needs to reverse ?
  25460. if (span < 0) {
  25461. span = -span;
  25462. extent.reverse();
  25463. }
  25464. var result = intervalScaleNiceTicks(
  25465. extent, splitNumber, minInterval, maxInterval
  25466. );
  25467. this._intervalPrecision = result.intervalPrecision;
  25468. this._interval = result.interval;
  25469. this._niceExtent = result.niceTickExtent;
  25470. },
  25471. /**
  25472. * Nice extent.
  25473. * @param {Object} opt
  25474. * @param {number} [opt.splitNumber = 5] Given approx tick number
  25475. * @param {boolean} [opt.fixMin=false]
  25476. * @param {boolean} [opt.fixMax=false]
  25477. * @param {boolean} [opt.minInterval]
  25478. * @param {boolean} [opt.maxInterval]
  25479. */
  25480. niceExtent: function (opt) {
  25481. var extent = this._extent;
  25482. // If extent start and end are same, expand them
  25483. if (extent[0] === extent[1]) {
  25484. if (extent[0] !== 0) {
  25485. // Expand extent
  25486. var expandSize = extent[0];
  25487. // In the fowllowing case
  25488. // Axis has been fixed max 100
  25489. // Plus data are all 100 and axis extent are [100, 100].
  25490. // Extend to the both side will cause expanded max is larger than fixed max.
  25491. // So only expand to the smaller side.
  25492. if (!opt.fixMax) {
  25493. extent[1] += expandSize / 2;
  25494. extent[0] -= expandSize / 2;
  25495. }
  25496. else {
  25497. extent[0] -= expandSize / 2;
  25498. }
  25499. }
  25500. else {
  25501. extent[1] = 1;
  25502. }
  25503. }
  25504. var span = extent[1] - extent[0];
  25505. // If there are no data and extent are [Infinity, -Infinity]
  25506. if (!isFinite(span)) {
  25507. extent[0] = 0;
  25508. extent[1] = 1;
  25509. }
  25510. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25511. // var extent = this._extent;
  25512. var interval = this._interval;
  25513. if (!opt.fixMin) {
  25514. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  25515. }
  25516. if (!opt.fixMax) {
  25517. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  25518. }
  25519. }
  25520. });
  25521. /**
  25522. * @return {module:echarts/scale/Time}
  25523. */
  25524. IntervalScale.create = function () {
  25525. return new IntervalScale();
  25526. };
  25527. var STACK_PREFIX = '__ec_stack_';
  25528. function getSeriesStackId(seriesModel) {
  25529. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  25530. }
  25531. function getAxisKey(axis) {
  25532. return axis.dim + axis.index;
  25533. }
  25534. /**
  25535. * @param {Object} opt
  25536. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  25537. * @param {number} opt.count Positive interger.
  25538. * @param {number} [opt.barWidth]
  25539. * @param {number} [opt.barMaxWidth]
  25540. * @param {number} [opt.barGap]
  25541. * @param {number} [opt.barCategoryGap]
  25542. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  25543. */
  25544. function getLayoutOnAxis(opt, api) {
  25545. var params = [];
  25546. var baseAxis = opt.axis;
  25547. var axisKey = 'axis0';
  25548. if (baseAxis.type !== 'category') {
  25549. return;
  25550. }
  25551. var bandWidth = baseAxis.getBandWidth();
  25552. for (var i = 0; i < opt.count || 0; i++) {
  25553. params.push(defaults({
  25554. bandWidth: bandWidth,
  25555. axisKey: axisKey,
  25556. stackId: STACK_PREFIX + i
  25557. }, opt));
  25558. }
  25559. var widthAndOffsets = doCalBarWidthAndOffset(params, api);
  25560. var result = [];
  25561. for (var i = 0; i < opt.count; i++) {
  25562. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  25563. item.offsetCenter = item.offset + item.width / 2;
  25564. result.push(item);
  25565. }
  25566. return result;
  25567. }
  25568. function calBarWidthAndOffset(barSeries, api) {
  25569. var seriesInfoList = map(barSeries, function (seriesModel) {
  25570. var data = seriesModel.getData();
  25571. var cartesian = seriesModel.coordinateSystem;
  25572. var baseAxis = cartesian.getBaseAxis();
  25573. var axisExtent = baseAxis.getExtent();
  25574. var bandWidth = baseAxis.type === 'category'
  25575. ? baseAxis.getBandWidth()
  25576. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  25577. var barWidth = parsePercent$1(
  25578. seriesModel.get('barWidth'), bandWidth
  25579. );
  25580. var barMaxWidth = parsePercent$1(
  25581. seriesModel.get('barMaxWidth'), bandWidth
  25582. );
  25583. var barGap = seriesModel.get('barGap');
  25584. var barCategoryGap = seriesModel.get('barCategoryGap');
  25585. return {
  25586. bandWidth: bandWidth,
  25587. barWidth: barWidth,
  25588. barMaxWidth: barMaxWidth,
  25589. barGap: barGap,
  25590. barCategoryGap: barCategoryGap,
  25591. axisKey: getAxisKey(baseAxis),
  25592. stackId: getSeriesStackId(seriesModel)
  25593. };
  25594. });
  25595. return doCalBarWidthAndOffset(seriesInfoList, api);
  25596. }
  25597. function doCalBarWidthAndOffset(seriesInfoList, api) {
  25598. // Columns info on each category axis. Key is cartesian name
  25599. var columnsMap = {};
  25600. each$1(seriesInfoList, function (seriesInfo, idx) {
  25601. var axisKey = seriesInfo.axisKey;
  25602. var bandWidth = seriesInfo.bandWidth;
  25603. var columnsOnAxis = columnsMap[axisKey] || {
  25604. bandWidth: bandWidth,
  25605. remainedWidth: bandWidth,
  25606. autoWidthCount: 0,
  25607. categoryGap: '20%',
  25608. gap: '30%',
  25609. stacks: {}
  25610. };
  25611. var stacks = columnsOnAxis.stacks;
  25612. columnsMap[axisKey] = columnsOnAxis;
  25613. var stackId = seriesInfo.stackId;
  25614. if (!stacks[stackId]) {
  25615. columnsOnAxis.autoWidthCount++;
  25616. }
  25617. stacks[stackId] = stacks[stackId] || {
  25618. width: 0,
  25619. maxWidth: 0
  25620. };
  25621. // Caution: In a single coordinate system, these barGrid attributes
  25622. // will be shared by series. Consider that they have default values,
  25623. // only the attributes set on the last series will work.
  25624. // Do not change this fact unless there will be a break change.
  25625. // TODO
  25626. var barWidth = seriesInfo.barWidth;
  25627. if (barWidth && !stacks[stackId].width) {
  25628. // See #6312, do not restrict width.
  25629. stacks[stackId].width = barWidth;
  25630. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25631. columnsOnAxis.remainedWidth -= barWidth;
  25632. }
  25633. var barMaxWidth = seriesInfo.barMaxWidth;
  25634. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25635. var barGap = seriesInfo.barGap;
  25636. (barGap != null) && (columnsOnAxis.gap = barGap);
  25637. var barCategoryGap = seriesInfo.barCategoryGap;
  25638. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25639. });
  25640. var result = {};
  25641. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25642. result[coordSysName] = {};
  25643. var stacks = columnsOnAxis.stacks;
  25644. var bandWidth = columnsOnAxis.bandWidth;
  25645. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25646. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25647. var remainedWidth = columnsOnAxis.remainedWidth;
  25648. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25649. var autoWidth = (remainedWidth - categoryGap)
  25650. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25651. autoWidth = Math.max(autoWidth, 0);
  25652. // Find if any auto calculated bar exceeded maxBarWidth
  25653. each$1(stacks, function (column, stack) {
  25654. var maxWidth = column.maxWidth;
  25655. if (maxWidth && maxWidth < autoWidth) {
  25656. maxWidth = Math.min(maxWidth, remainedWidth);
  25657. if (column.width) {
  25658. maxWidth = Math.min(maxWidth, column.width);
  25659. }
  25660. remainedWidth -= maxWidth;
  25661. column.width = maxWidth;
  25662. autoWidthCount--;
  25663. }
  25664. });
  25665. // Recalculate width again
  25666. autoWidth = (remainedWidth - categoryGap)
  25667. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25668. autoWidth = Math.max(autoWidth, 0);
  25669. var widthSum = 0;
  25670. var lastColumn;
  25671. each$1(stacks, function (column, idx) {
  25672. if (!column.width) {
  25673. column.width = autoWidth;
  25674. }
  25675. lastColumn = column;
  25676. widthSum += column.width * (1 + barGapPercent);
  25677. });
  25678. if (lastColumn) {
  25679. widthSum -= lastColumn.width * barGapPercent;
  25680. }
  25681. var offset = -widthSum / 2;
  25682. each$1(stacks, function (column, stackId) {
  25683. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25684. offset: offset,
  25685. width: column.width
  25686. };
  25687. offset += column.width * (1 + barGapPercent);
  25688. });
  25689. });
  25690. return result;
  25691. }
  25692. /**
  25693. * @param {string} seriesType
  25694. * @param {module:echarts/model/Global} ecModel
  25695. * @param {module:echarts/ExtensionAPI} api
  25696. */
  25697. function layout(seriesType, ecModel, api) {
  25698. var seriesModels = [];
  25699. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25700. // Check series coordinate, do layout for cartesian2d only
  25701. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  25702. seriesModels.push(seriesModel);
  25703. }
  25704. });
  25705. var barWidthAndOffset = calBarWidthAndOffset(seriesModels);
  25706. var lastStackCoords = {};
  25707. each$1(seriesModels, function (seriesModel) {
  25708. var data = seriesModel.getData();
  25709. var cartesian = seriesModel.coordinateSystem;
  25710. var baseAxis = cartesian.getBaseAxis();
  25711. var stackId = getSeriesStackId(seriesModel);
  25712. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25713. var columnOffset = columnLayoutInfo.offset;
  25714. var columnWidth = columnLayoutInfo.width;
  25715. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25716. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25717. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25718. data.setLayout({
  25719. offset: columnOffset,
  25720. size: columnWidth
  25721. });
  25722. var valueDim = data.mapDimension(valueAxis.dim);
  25723. var baseDim = data.mapDimension(baseAxis.dim);
  25724. var stacked = isDimensionStacked(data, valueDim, baseDim);
  25725. var isValueAxisH = valueAxis.isHorizontal();
  25726. var valueAxisStart = (baseAxis.onZero || stacked)
  25727. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25728. : valueAxis.getGlobalExtent()[0];
  25729. for (var idx = 0, len = data.count(); idx < len; idx++) {
  25730. var value = data.get(valueDim, idx);
  25731. var baseValue = data.get(baseDim, idx);
  25732. if (isNaN(value)) {
  25733. continue;
  25734. }
  25735. var sign = value >= 0 ? 'p' : 'n';
  25736. var baseCoord = valueAxisStart;
  25737. // Because of the barMinHeight, we can not use the value in
  25738. // stackResultDimension directly.
  25739. if (stacked) {
  25740. // Only ordinal axis can be stacked.
  25741. if (!lastStackCoords[stackId][baseValue]) {
  25742. lastStackCoords[stackId][baseValue] = {
  25743. p: valueAxisStart, // Positive stack
  25744. n: valueAxisStart // Negative stack
  25745. };
  25746. }
  25747. // Should also consider #4243
  25748. baseCoord = lastStackCoords[stackId][baseValue][sign];
  25749. }
  25750. var x;
  25751. var y;
  25752. var width;
  25753. var height;
  25754. if (isValueAxisH) {
  25755. var coord = cartesian.dataToPoint([value, baseValue]);
  25756. x = baseCoord;
  25757. y = coord[1] + columnOffset;
  25758. width = coord[0] - valueAxisStart;
  25759. height = columnWidth;
  25760. if (Math.abs(width) < barMinHeight) {
  25761. width = (width < 0 ? -1 : 1) * barMinHeight;
  25762. }
  25763. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  25764. }
  25765. else {
  25766. var coord = cartesian.dataToPoint([baseValue, value]);
  25767. x = coord[0] + columnOffset;
  25768. y = baseCoord;
  25769. width = columnWidth;
  25770. height = coord[1] - valueAxisStart;
  25771. if (Math.abs(height) < barMinHeight) {
  25772. // Include zero to has a positive bar
  25773. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25774. }
  25775. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  25776. }
  25777. data.setItemLayout(idx, {
  25778. x: x,
  25779. y: y,
  25780. width: width,
  25781. height: height
  25782. });
  25783. }
  25784. }, this);
  25785. }
  25786. // [About UTC and local time zone]:
  25787. // In most cases, `number.parseDate` will treat input data string as local time
  25788. // (except time zone is specified in time string). And `format.formateTime` returns
  25789. // local time by default. option.useUTC is false by default. This design have
  25790. // concidered these common case:
  25791. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25792. // in local time by default.
  25793. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25794. // as its original time, without any time difference.
  25795. var intervalScaleProto = IntervalScale.prototype;
  25796. var mathCeil = Math.ceil;
  25797. var mathFloor = Math.floor;
  25798. var ONE_SECOND = 1000;
  25799. var ONE_MINUTE = ONE_SECOND * 60;
  25800. var ONE_HOUR = ONE_MINUTE * 60;
  25801. var ONE_DAY = ONE_HOUR * 24;
  25802. // FIXME 公用?
  25803. var bisect = function (a, x, lo, hi) {
  25804. while (lo < hi) {
  25805. var mid = lo + hi >>> 1;
  25806. if (a[mid][1] < x) {
  25807. lo = mid + 1;
  25808. }
  25809. else {
  25810. hi = mid;
  25811. }
  25812. }
  25813. return lo;
  25814. };
  25815. /**
  25816. * @alias module:echarts/coord/scale/Time
  25817. * @constructor
  25818. */
  25819. var TimeScale = IntervalScale.extend({
  25820. type: 'time',
  25821. /**
  25822. * @override
  25823. */
  25824. getLabel: function (val) {
  25825. var stepLvl = this._stepLvl;
  25826. var date = new Date(val);
  25827. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25828. },
  25829. /**
  25830. * @override
  25831. */
  25832. niceExtent: function (opt) {
  25833. var extent = this._extent;
  25834. // If extent start and end are same, expand them
  25835. if (extent[0] === extent[1]) {
  25836. // Expand extent
  25837. extent[0] -= ONE_DAY;
  25838. extent[1] += ONE_DAY;
  25839. }
  25840. // If there are no data and extent are [Infinity, -Infinity]
  25841. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25842. var d = new Date();
  25843. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25844. extent[0] = extent[1] - ONE_DAY;
  25845. }
  25846. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25847. // var extent = this._extent;
  25848. var interval = this._interval;
  25849. if (!opt.fixMin) {
  25850. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25851. }
  25852. if (!opt.fixMax) {
  25853. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25854. }
  25855. },
  25856. /**
  25857. * @override
  25858. */
  25859. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25860. approxTickNum = approxTickNum || 10;
  25861. var extent = this._extent;
  25862. var span = extent[1] - extent[0];
  25863. var approxInterval = span / approxTickNum;
  25864. if (minInterval != null && approxInterval < minInterval) {
  25865. approxInterval = minInterval;
  25866. }
  25867. if (maxInterval != null && approxInterval > maxInterval) {
  25868. approxInterval = maxInterval;
  25869. }
  25870. var scaleLevelsLen = scaleLevels.length;
  25871. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25872. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25873. var interval = level[1];
  25874. // Same with interval scale if span is much larger than 1 year
  25875. if (level[0] === 'year') {
  25876. var yearSpan = span / interval;
  25877. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25878. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25879. var yearStep = nice(yearSpan / approxTickNum, true);
  25880. interval *= yearStep;
  25881. }
  25882. var timezoneOffset = this.getSetting('useUTC')
  25883. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25884. var niceExtent = [
  25885. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25886. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25887. ];
  25888. fixExtent(niceExtent, extent);
  25889. this._stepLvl = level;
  25890. // Interval will be used in getTicks
  25891. this._interval = interval;
  25892. this._niceExtent = niceExtent;
  25893. },
  25894. parse: function (val) {
  25895. // val might be float.
  25896. return +parseDate(val);
  25897. }
  25898. });
  25899. each$1(['contain', 'normalize'], function (methodName) {
  25900. TimeScale.prototype[methodName] = function (val) {
  25901. return intervalScaleProto[methodName].call(this, this.parse(val));
  25902. };
  25903. });
  25904. // Steps from d3
  25905. var scaleLevels = [
  25906. // Format interval
  25907. ['hh:mm:ss', ONE_SECOND], // 1s
  25908. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25909. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25910. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25911. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25912. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25913. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25914. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25915. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25916. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25917. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25918. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25919. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25920. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25921. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25922. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25923. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25924. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25925. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25926. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25927. ['week', ONE_DAY * 7], // 7d
  25928. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25929. ['week', ONE_DAY * 14], // 2w
  25930. ['week', ONE_DAY * 21], // 3w
  25931. ['month', ONE_DAY * 31], // 1M
  25932. ['week', ONE_DAY * 42], // 6w
  25933. ['month', ONE_DAY * 62], // 2M
  25934. ['week', ONE_DAY * 42], // 10w
  25935. ['quarter', ONE_DAY * 380 / 4], // 3M
  25936. ['month', ONE_DAY * 31 * 4], // 4M
  25937. ['month', ONE_DAY * 31 * 5], // 5M
  25938. ['half-year', ONE_DAY * 380 / 2], // 6M
  25939. ['month', ONE_DAY * 31 * 8], // 8M
  25940. ['month', ONE_DAY * 31 * 10], // 10M
  25941. ['year', ONE_DAY * 380] // 1Y
  25942. ];
  25943. /**
  25944. * @param {module:echarts/model/Model}
  25945. * @return {module:echarts/scale/Time}
  25946. */
  25947. TimeScale.create = function (model) {
  25948. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25949. };
  25950. /**
  25951. * Log scale
  25952. * @module echarts/scale/Log
  25953. */
  25954. // Use some method of IntervalScale
  25955. var scaleProto$1 = Scale.prototype;
  25956. var intervalScaleProto$1 = IntervalScale.prototype;
  25957. var getPrecisionSafe$1 = getPrecisionSafe;
  25958. var roundingErrorFix = round$1;
  25959. var mathFloor$1 = Math.floor;
  25960. var mathCeil$1 = Math.ceil;
  25961. var mathPow$1 = Math.pow;
  25962. var mathLog = Math.log;
  25963. var LogScale = Scale.extend({
  25964. type: 'log',
  25965. base: 10,
  25966. $constructor: function () {
  25967. Scale.apply(this, arguments);
  25968. this._originalScale = new IntervalScale();
  25969. },
  25970. /**
  25971. * @return {Array.<number>}
  25972. */
  25973. getTicks: function () {
  25974. var originalScale = this._originalScale;
  25975. var extent = this._extent;
  25976. var originalExtent = originalScale.getExtent();
  25977. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25978. var powVal = round$1(mathPow$1(this.base, val));
  25979. // Fix #4158
  25980. powVal = (val === extent[0] && originalScale.__fixMin)
  25981. ? fixRoundingError(powVal, originalExtent[0])
  25982. : powVal;
  25983. powVal = (val === extent[1] && originalScale.__fixMax)
  25984. ? fixRoundingError(powVal, originalExtent[1])
  25985. : powVal;
  25986. return powVal;
  25987. }, this);
  25988. },
  25989. /**
  25990. * @param {number} val
  25991. * @return {string}
  25992. */
  25993. getLabel: intervalScaleProto$1.getLabel,
  25994. /**
  25995. * @param {number} val
  25996. * @return {number}
  25997. */
  25998. scale: function (val) {
  25999. val = scaleProto$1.scale.call(this, val);
  26000. return mathPow$1(this.base, val);
  26001. },
  26002. /**
  26003. * @param {number} start
  26004. * @param {number} end
  26005. */
  26006. setExtent: function (start, end) {
  26007. var base = this.base;
  26008. start = mathLog(start) / mathLog(base);
  26009. end = mathLog(end) / mathLog(base);
  26010. intervalScaleProto$1.setExtent.call(this, start, end);
  26011. },
  26012. /**
  26013. * @return {number} end
  26014. */
  26015. getExtent: function () {
  26016. var base = this.base;
  26017. var extent = scaleProto$1.getExtent.call(this);
  26018. extent[0] = mathPow$1(base, extent[0]);
  26019. extent[1] = mathPow$1(base, extent[1]);
  26020. // Fix #4158
  26021. var originalScale = this._originalScale;
  26022. var originalExtent = originalScale.getExtent();
  26023. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  26024. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  26025. return extent;
  26026. },
  26027. /**
  26028. * @param {Array.<number>} extent
  26029. */
  26030. unionExtent: function (extent) {
  26031. this._originalScale.unionExtent(extent);
  26032. var base = this.base;
  26033. extent[0] = mathLog(extent[0]) / mathLog(base);
  26034. extent[1] = mathLog(extent[1]) / mathLog(base);
  26035. scaleProto$1.unionExtent.call(this, extent);
  26036. },
  26037. /**
  26038. * @override
  26039. */
  26040. unionExtentFromData: function (data, dim) {
  26041. // TODO
  26042. // filter value that <= 0
  26043. this.unionExtent(data.getApproximateExtent(dim));
  26044. },
  26045. /**
  26046. * Update interval and extent of intervals for nice ticks
  26047. * @param {number} [approxTickNum = 10] Given approx tick number
  26048. */
  26049. niceTicks: function (approxTickNum) {
  26050. approxTickNum = approxTickNum || 10;
  26051. var extent = this._extent;
  26052. var span = extent[1] - extent[0];
  26053. if (span === Infinity || span <= 0) {
  26054. return;
  26055. }
  26056. var interval = quantity(span);
  26057. var err = approxTickNum / span * interval;
  26058. // Filter ticks to get closer to the desired count.
  26059. if (err <= 0.5) {
  26060. interval *= 10;
  26061. }
  26062. // Interval should be integer
  26063. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  26064. interval *= 10;
  26065. }
  26066. var niceExtent = [
  26067. round$1(mathCeil$1(extent[0] / interval) * interval),
  26068. round$1(mathFloor$1(extent[1] / interval) * interval)
  26069. ];
  26070. this._interval = interval;
  26071. this._niceExtent = niceExtent;
  26072. },
  26073. /**
  26074. * Nice extent.
  26075. * @override
  26076. */
  26077. niceExtent: function (opt) {
  26078. intervalScaleProto$1.niceExtent.call(this, opt);
  26079. var originalScale = this._originalScale;
  26080. originalScale.__fixMin = opt.fixMin;
  26081. originalScale.__fixMax = opt.fixMax;
  26082. }
  26083. });
  26084. each$1(['contain', 'normalize'], function (methodName) {
  26085. LogScale.prototype[methodName] = function (val) {
  26086. val = mathLog(val) / mathLog(this.base);
  26087. return scaleProto$1[methodName].call(this, val);
  26088. };
  26089. });
  26090. LogScale.create = function () {
  26091. return new LogScale();
  26092. };
  26093. function fixRoundingError(val, originalVal) {
  26094. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  26095. }
  26096. /**
  26097. * Get axis scale extent before niced.
  26098. * Item of returned array can only be number (including Infinity and NaN).
  26099. */
  26100. function getScaleExtent(scale, model) {
  26101. var scaleType = scale.type;
  26102. var min = model.getMin();
  26103. var max = model.getMax();
  26104. var fixMin = min != null;
  26105. var fixMax = max != null;
  26106. var originalExtent = scale.getExtent();
  26107. var axisDataLen;
  26108. var boundaryGap;
  26109. var span;
  26110. if (scaleType === 'ordinal') {
  26111. axisDataLen = model.getCategories().length;
  26112. }
  26113. else {
  26114. boundaryGap = model.get('boundaryGap');
  26115. if (!isArray(boundaryGap)) {
  26116. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  26117. }
  26118. if (typeof boundaryGap[0] === 'boolean') {
  26119. if (__DEV__) {
  26120. console.warn('Boolean type for boundaryGap is only '
  26121. + 'allowed for ordinal axis. Please use string in '
  26122. + 'percentage instead, e.g., "20%". Currently, '
  26123. + 'boundaryGap is set to be 0.');
  26124. }
  26125. boundaryGap = [0, 0];
  26126. }
  26127. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  26128. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  26129. span = (originalExtent[1] - originalExtent[0])
  26130. || Math.abs(originalExtent[0]);
  26131. }
  26132. // Notice: When min/max is not set (that is, when there are null/undefined,
  26133. // which is the most common case), these cases should be ensured:
  26134. // (1) For 'ordinal', show all axis.data.
  26135. // (2) For others:
  26136. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  26137. // disabled).
  26138. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  26139. // be the result that originalExtent enlarged by boundaryGap.
  26140. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  26141. // FIXME
  26142. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  26143. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  26144. // that the results processed by boundaryGap are positive/negative?
  26145. if (min == null) {
  26146. min = scaleType === 'ordinal'
  26147. ? (axisDataLen ? 0 : NaN)
  26148. : originalExtent[0] - boundaryGap[0] * span;
  26149. }
  26150. if (max == null) {
  26151. max = scaleType === 'ordinal'
  26152. ? (axisDataLen ? axisDataLen - 1 : NaN)
  26153. : originalExtent[1] + boundaryGap[1] * span;
  26154. }
  26155. if (min === 'dataMin') {
  26156. min = originalExtent[0];
  26157. }
  26158. else if (typeof min === 'function') {
  26159. min = min({
  26160. min: originalExtent[0],
  26161. max: originalExtent[1]
  26162. });
  26163. }
  26164. if (max === 'dataMax') {
  26165. max = originalExtent[1];
  26166. }
  26167. else if (typeof max === 'function') {
  26168. max = max({
  26169. min: originalExtent[0],
  26170. max: originalExtent[1]
  26171. });
  26172. }
  26173. (min == null || !isFinite(min)) && (min = NaN);
  26174. (max == null || !isFinite(max)) && (max = NaN);
  26175. scale.setBlank(eqNaN(min) || eqNaN(max));
  26176. // Evaluate if axis needs cross zero
  26177. if (model.getNeedCrossZero()) {
  26178. // Axis is over zero and min is not set
  26179. if (min > 0 && max > 0 && !fixMin) {
  26180. min = 0;
  26181. }
  26182. // Axis is under zero and max is not set
  26183. if (min < 0 && max < 0 && !fixMax) {
  26184. max = 0;
  26185. }
  26186. }
  26187. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  26188. // is base axis
  26189. // FIXME
  26190. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  26191. // (2) Refactor the logic with `barGrid`. Is it not need to `calBarWidthAndOffset` twice with different extent?
  26192. // Should not depend on series type `bar`?
  26193. // (3) Fix that might overlap when using dataZoom.
  26194. // (4) Consider other chart types using `barGrid`?
  26195. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  26196. var ecModel = model.ecModel;
  26197. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  26198. var barSeriesModels = [];
  26199. var isBaseAxisAndHasBarSeries;
  26200. ecModel.eachSeriesByType('bar', function (seriesModel) {
  26201. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  26202. barSeriesModels.push(seriesModel);
  26203. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  26204. }
  26205. });
  26206. if (isBaseAxisAndHasBarSeries) {
  26207. // Adjust axis min and max to account for overflow
  26208. var adjustedScale = adjustScaleForOverflow(min, max, model, barSeriesModels);
  26209. min = adjustedScale.min;
  26210. max = adjustedScale.max;
  26211. }
  26212. }
  26213. return [min, max];
  26214. }
  26215. function adjustScaleForOverflow(min, max, model, barSeriesModels) {
  26216. // Get Axis Length
  26217. var axisExtent = model.axis.getExtent();
  26218. var axisLength = axisExtent[1] - axisExtent[0];
  26219. // Calculate placement of bars on axis
  26220. var barWidthAndOffset = calBarWidthAndOffset(barSeriesModels);
  26221. // Get bars on current base axis and calculate min and max overflow
  26222. var baseAxisKey = model.axis.dim + model.axis.index;
  26223. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  26224. if (barsOnCurrentAxis === undefined) {
  26225. return {min: min, max: max};
  26226. }
  26227. var minOverflow = Infinity;
  26228. each$1(barsOnCurrentAxis, function (item) {
  26229. minOverflow = Math.min(item.offset, minOverflow);
  26230. });
  26231. var maxOverflow = -Infinity;
  26232. each$1(barsOnCurrentAxis, function (item) {
  26233. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  26234. });
  26235. minOverflow = Math.abs(minOverflow);
  26236. maxOverflow = Math.abs(maxOverflow);
  26237. var totalOverFlow = minOverflow + maxOverflow;
  26238. // Calulate required buffer based on old range and overflow
  26239. var oldRange = max - min;
  26240. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  26241. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  26242. max += overflowBuffer * (maxOverflow / totalOverFlow);
  26243. min -= overflowBuffer * (minOverflow / totalOverFlow);
  26244. return {min: min, max: max};
  26245. }
  26246. function niceScaleExtent(scale, model) {
  26247. var extent = getScaleExtent(scale, model);
  26248. var fixMin = model.getMin() != null;
  26249. var fixMax = model.getMax() != null;
  26250. var splitNumber = model.get('splitNumber');
  26251. if (scale.type === 'log') {
  26252. scale.base = model.get('logBase');
  26253. }
  26254. var scaleType = scale.type;
  26255. scale.setExtent(extent[0], extent[1]);
  26256. scale.niceExtent({
  26257. splitNumber: splitNumber,
  26258. fixMin: fixMin,
  26259. fixMax: fixMax,
  26260. minInterval: (scaleType === 'interval' || scaleType === 'time')
  26261. ? model.get('minInterval') : null,
  26262. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  26263. ? model.get('maxInterval') : null
  26264. });
  26265. // If some one specified the min, max. And the default calculated interval
  26266. // is not good enough. He can specify the interval. It is often appeared
  26267. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  26268. // to be 60.
  26269. // FIXME
  26270. var interval = model.get('interval');
  26271. if (interval != null) {
  26272. scale.setInterval && scale.setInterval(interval);
  26273. }
  26274. }
  26275. /**
  26276. * @param {module:echarts/model/Model} model
  26277. * @param {string} [axisType] Default retrieve from model.type
  26278. * @return {module:echarts/scale/*}
  26279. */
  26280. function createScaleByModel(model, axisType) {
  26281. axisType = axisType || model.get('type');
  26282. if (axisType) {
  26283. switch (axisType) {
  26284. // Buildin scale
  26285. case 'category':
  26286. return new OrdinalScale(
  26287. model.getOrdinalMeta
  26288. ? model.getOrdinalMeta()
  26289. : model.getCategories(),
  26290. [Infinity, -Infinity]
  26291. );
  26292. case 'value':
  26293. return new IntervalScale();
  26294. // Extended scale, like time and log
  26295. default:
  26296. return (Scale.getClass(axisType) || IntervalScale).create(model);
  26297. }
  26298. }
  26299. }
  26300. /**
  26301. * Check if the axis corss 0
  26302. */
  26303. function ifAxisCrossZero(axis) {
  26304. var dataExtent = axis.scale.getExtent();
  26305. var min = dataExtent[0];
  26306. var max = dataExtent[1];
  26307. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  26308. }
  26309. /**
  26310. * @param {Array.<number>} tickCoords In axis self coordinate.
  26311. * @param {Array.<string>} labels
  26312. * @param {string} font
  26313. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  26314. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  26315. * @return {number}
  26316. */
  26317. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  26318. var textSpaceTakenRect;
  26319. var autoLabelInterval = 0;
  26320. var accumulatedLabelInterval = 0;
  26321. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  26322. var step = 1;
  26323. if (labels.length > 40) {
  26324. // Simple optimization for large amount of labels
  26325. step = Math.floor(labels.length / 40);
  26326. }
  26327. for (var i = 0; i < tickCoords.length; i += step) {
  26328. var tickCoord = tickCoords[i];
  26329. // Not precise, do not consider align and vertical align
  26330. // and each distance from axis line yet.
  26331. var rect = getBoundingRect(
  26332. labels[i], font, 'center', 'top'
  26333. );
  26334. rect.x += tickCoord * Math.cos(rotation);
  26335. rect.y += tickCoord * Math.sin(rotation);
  26336. // Magic number
  26337. rect.width *= 1.3;
  26338. rect.height *= 1.3;
  26339. if (!textSpaceTakenRect) {
  26340. textSpaceTakenRect = rect.clone();
  26341. }
  26342. // There is no space for current label;
  26343. else if (textSpaceTakenRect.intersect(rect)) {
  26344. accumulatedLabelInterval++;
  26345. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  26346. }
  26347. else {
  26348. textSpaceTakenRect.union(rect);
  26349. // Reset
  26350. accumulatedLabelInterval = 0;
  26351. }
  26352. }
  26353. if (autoLabelInterval === 0 && step > 1) {
  26354. return step;
  26355. }
  26356. return (autoLabelInterval + 1) * step - 1;
  26357. }
  26358. /**
  26359. * @param {Object} axis
  26360. * @param {Function} labelFormatter
  26361. * @return {Array.<string>}
  26362. */
  26363. function getFormattedLabels(axis, labelFormatter) {
  26364. var scale = axis.scale;
  26365. var labels = scale.getTicksLabels();
  26366. var ticks = scale.getTicks();
  26367. if (typeof labelFormatter === 'string') {
  26368. labelFormatter = (function (tpl) {
  26369. return function (val) {
  26370. return tpl.replace('{value}', val != null ? val : '');
  26371. };
  26372. })(labelFormatter);
  26373. // Consider empty array
  26374. return map(labels, labelFormatter);
  26375. }
  26376. else if (typeof labelFormatter === 'function') {
  26377. return map(ticks, function (tick, idx) {
  26378. return labelFormatter(
  26379. getAxisRawValue(axis, tick),
  26380. idx
  26381. );
  26382. }, this);
  26383. }
  26384. else {
  26385. return labels;
  26386. }
  26387. }
  26388. function getAxisRawValue(axis, value) {
  26389. // In category axis with data zoom, tick is not the original
  26390. // index of axis.data. So tick should not be exposed to user
  26391. // in category axis.
  26392. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  26393. }
  26394. var axisModelCommonMixin = {
  26395. /**
  26396. * Format labels
  26397. * @return {Array.<string>}
  26398. */
  26399. getFormattedLabels: function () {
  26400. return getFormattedLabels(
  26401. this.axis,
  26402. this.get('axisLabel.formatter')
  26403. );
  26404. },
  26405. /**
  26406. * @param {boolean} origin
  26407. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  26408. */
  26409. getMin: function (origin) {
  26410. var option = this.option;
  26411. var min = (!origin && option.rangeStart != null)
  26412. ? option.rangeStart : option.min;
  26413. if (this.axis
  26414. && min != null
  26415. && min !== 'dataMin'
  26416. && typeof min !== 'function'
  26417. && !eqNaN(min)
  26418. ) {
  26419. min = this.axis.scale.parse(min);
  26420. }
  26421. return min;
  26422. },
  26423. /**
  26424. * @param {boolean} origin
  26425. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  26426. */
  26427. getMax: function (origin) {
  26428. var option = this.option;
  26429. var max = (!origin && option.rangeEnd != null)
  26430. ? option.rangeEnd : option.max;
  26431. if (this.axis
  26432. && max != null
  26433. && max !== 'dataMax'
  26434. && typeof max !== 'function'
  26435. && !eqNaN(max)
  26436. ) {
  26437. max = this.axis.scale.parse(max);
  26438. }
  26439. return max;
  26440. },
  26441. /**
  26442. * @return {boolean}
  26443. */
  26444. getNeedCrossZero: function () {
  26445. var option = this.option;
  26446. return (option.rangeStart != null || option.rangeEnd != null)
  26447. ? false : !option.scale;
  26448. },
  26449. /**
  26450. * Should be implemented by each axis model if necessary.
  26451. * @return {module:echarts/model/Component} coordinate system model
  26452. */
  26453. getCoordSysModel: noop,
  26454. /**
  26455. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  26456. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  26457. */
  26458. setRange: function (rangeStart, rangeEnd) {
  26459. this.option.rangeStart = rangeStart;
  26460. this.option.rangeEnd = rangeEnd;
  26461. },
  26462. /**
  26463. * Reset range
  26464. */
  26465. resetRange: function () {
  26466. // rangeStart and rangeEnd is readonly.
  26467. this.option.rangeStart = this.option.rangeEnd = null;
  26468. }
  26469. };
  26470. // Symbol factory
  26471. /**
  26472. * Triangle shape
  26473. * @inner
  26474. */
  26475. var Triangle = extendShape({
  26476. type: 'triangle',
  26477. shape: {
  26478. cx: 0,
  26479. cy: 0,
  26480. width: 0,
  26481. height: 0
  26482. },
  26483. buildPath: function (path, shape) {
  26484. var cx = shape.cx;
  26485. var cy = shape.cy;
  26486. var width = shape.width / 2;
  26487. var height = shape.height / 2;
  26488. path.moveTo(cx, cy - height);
  26489. path.lineTo(cx + width, cy + height);
  26490. path.lineTo(cx - width, cy + height);
  26491. path.closePath();
  26492. }
  26493. });
  26494. /**
  26495. * Diamond shape
  26496. * @inner
  26497. */
  26498. var Diamond = extendShape({
  26499. type: 'diamond',
  26500. shape: {
  26501. cx: 0,
  26502. cy: 0,
  26503. width: 0,
  26504. height: 0
  26505. },
  26506. buildPath: function (path, shape) {
  26507. var cx = shape.cx;
  26508. var cy = shape.cy;
  26509. var width = shape.width / 2;
  26510. var height = shape.height / 2;
  26511. path.moveTo(cx, cy - height);
  26512. path.lineTo(cx + width, cy);
  26513. path.lineTo(cx, cy + height);
  26514. path.lineTo(cx - width, cy);
  26515. path.closePath();
  26516. }
  26517. });
  26518. /**
  26519. * Pin shape
  26520. * @inner
  26521. */
  26522. var Pin = extendShape({
  26523. type: 'pin',
  26524. shape: {
  26525. // x, y on the cusp
  26526. x: 0,
  26527. y: 0,
  26528. width: 0,
  26529. height: 0
  26530. },
  26531. buildPath: function (path, shape) {
  26532. var x = shape.x;
  26533. var y = shape.y;
  26534. var w = shape.width / 5 * 3;
  26535. // Height must be larger than width
  26536. var h = Math.max(w, shape.height);
  26537. var r = w / 2;
  26538. // Dist on y with tangent point and circle center
  26539. var dy = r * r / (h - r);
  26540. var cy = y - h + r + dy;
  26541. var angle = Math.asin(dy / r);
  26542. // Dist on x with tangent point and circle center
  26543. var dx = Math.cos(angle) * r;
  26544. var tanX = Math.sin(angle);
  26545. var tanY = Math.cos(angle);
  26546. var cpLen = r * 0.6;
  26547. var cpLen2 = r * 0.7;
  26548. path.moveTo(x - dx, cy + dy);
  26549. path.arc(
  26550. x, cy, r,
  26551. Math.PI - angle,
  26552. Math.PI * 2 + angle
  26553. );
  26554. path.bezierCurveTo(
  26555. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  26556. x, y - cpLen2,
  26557. x, y
  26558. );
  26559. path.bezierCurveTo(
  26560. x, y - cpLen2,
  26561. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  26562. x - dx, cy + dy
  26563. );
  26564. path.closePath();
  26565. }
  26566. });
  26567. /**
  26568. * Arrow shape
  26569. * @inner
  26570. */
  26571. var Arrow = extendShape({
  26572. type: 'arrow',
  26573. shape: {
  26574. x: 0,
  26575. y: 0,
  26576. width: 0,
  26577. height: 0
  26578. },
  26579. buildPath: function (ctx, shape) {
  26580. var height = shape.height;
  26581. var width = shape.width;
  26582. var x = shape.x;
  26583. var y = shape.y;
  26584. var dx = width / 3 * 2;
  26585. ctx.moveTo(x, y);
  26586. ctx.lineTo(x + dx, y + height);
  26587. ctx.lineTo(x, y + height / 4 * 3);
  26588. ctx.lineTo(x - dx, y + height);
  26589. ctx.lineTo(x, y);
  26590. ctx.closePath();
  26591. }
  26592. });
  26593. /**
  26594. * Map of path contructors
  26595. * @type {Object.<string, module:zrender/graphic/Path>}
  26596. */
  26597. var symbolCtors = {
  26598. line: Line,
  26599. rect: Rect,
  26600. roundRect: Rect,
  26601. square: Rect,
  26602. circle: Circle,
  26603. diamond: Diamond,
  26604. pin: Pin,
  26605. arrow: Arrow,
  26606. triangle: Triangle
  26607. };
  26608. var symbolShapeMakers = {
  26609. line: function (x, y, w, h, shape) {
  26610. // FIXME
  26611. shape.x1 = x;
  26612. shape.y1 = y + h / 2;
  26613. shape.x2 = x + w;
  26614. shape.y2 = y + h / 2;
  26615. },
  26616. rect: function (x, y, w, h, shape) {
  26617. shape.x = x;
  26618. shape.y = y;
  26619. shape.width = w;
  26620. shape.height = h;
  26621. },
  26622. roundRect: function (x, y, w, h, shape) {
  26623. shape.x = x;
  26624. shape.y = y;
  26625. shape.width = w;
  26626. shape.height = h;
  26627. shape.r = Math.min(w, h) / 4;
  26628. },
  26629. square: function (x, y, w, h, shape) {
  26630. var size = Math.min(w, h);
  26631. shape.x = x;
  26632. shape.y = y;
  26633. shape.width = size;
  26634. shape.height = size;
  26635. },
  26636. circle: function (x, y, w, h, shape) {
  26637. // Put circle in the center of square
  26638. shape.cx = x + w / 2;
  26639. shape.cy = y + h / 2;
  26640. shape.r = Math.min(w, h) / 2;
  26641. },
  26642. diamond: function (x, y, w, h, shape) {
  26643. shape.cx = x + w / 2;
  26644. shape.cy = y + h / 2;
  26645. shape.width = w;
  26646. shape.height = h;
  26647. },
  26648. pin: function (x, y, w, h, shape) {
  26649. shape.x = x + w / 2;
  26650. shape.y = y + h / 2;
  26651. shape.width = w;
  26652. shape.height = h;
  26653. },
  26654. arrow: function (x, y, w, h, shape) {
  26655. shape.x = x + w / 2;
  26656. shape.y = y + h / 2;
  26657. shape.width = w;
  26658. shape.height = h;
  26659. },
  26660. triangle: function (x, y, w, h, shape) {
  26661. shape.cx = x + w / 2;
  26662. shape.cy = y + h / 2;
  26663. shape.width = w;
  26664. shape.height = h;
  26665. }
  26666. };
  26667. var symbolBuildProxies = {};
  26668. each$1(symbolCtors, function (Ctor, name) {
  26669. symbolBuildProxies[name] = new Ctor();
  26670. });
  26671. var SymbolClz = extendShape({
  26672. type: 'symbol',
  26673. shape: {
  26674. symbolType: '',
  26675. x: 0,
  26676. y: 0,
  26677. width: 0,
  26678. height: 0
  26679. },
  26680. beforeBrush: function () {
  26681. var style = this.style;
  26682. var shape = this.shape;
  26683. // FIXME
  26684. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26685. style.textPosition = ['50%', '40%'];
  26686. style.textAlign = 'center';
  26687. style.textVerticalAlign = 'middle';
  26688. }
  26689. },
  26690. buildPath: function (ctx, shape, inBundle) {
  26691. var symbolType = shape.symbolType;
  26692. var proxySymbol = symbolBuildProxies[symbolType];
  26693. if (shape.symbolType !== 'none') {
  26694. if (!proxySymbol) {
  26695. // Default rect
  26696. symbolType = 'rect';
  26697. proxySymbol = symbolBuildProxies[symbolType];
  26698. }
  26699. symbolShapeMakers[symbolType](
  26700. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26701. );
  26702. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26703. }
  26704. }
  26705. });
  26706. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26707. function symbolPathSetColor(color, innerColor) {
  26708. if (this.type !== 'image') {
  26709. var symbolStyle = this.style;
  26710. var symbolShape = this.shape;
  26711. if (symbolShape && symbolShape.symbolType === 'line') {
  26712. symbolStyle.stroke = color;
  26713. }
  26714. else if (this.__isEmptyBrush) {
  26715. symbolStyle.stroke = color;
  26716. symbolStyle.fill = innerColor || '#fff';
  26717. }
  26718. else {
  26719. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26720. symbolStyle.fill && (symbolStyle.fill = color);
  26721. symbolStyle.stroke && (symbolStyle.stroke = color);
  26722. }
  26723. this.dirty(false);
  26724. }
  26725. }
  26726. /**
  26727. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26728. * @param {string} symbolType
  26729. * @param {number} x
  26730. * @param {number} y
  26731. * @param {number} w
  26732. * @param {number} h
  26733. * @param {string} color
  26734. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26735. * for path and image only.
  26736. */
  26737. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26738. // TODO Support image object, DynamicImage.
  26739. var isEmpty = symbolType.indexOf('empty') === 0;
  26740. if (isEmpty) {
  26741. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26742. }
  26743. var symbolPath;
  26744. if (symbolType.indexOf('image://') === 0) {
  26745. symbolPath = makeImage(
  26746. symbolType.slice(8),
  26747. new BoundingRect(x, y, w, h),
  26748. keepAspect ? 'center' : 'cover'
  26749. );
  26750. }
  26751. else if (symbolType.indexOf('path://') === 0) {
  26752. symbolPath = makePath(
  26753. symbolType.slice(7),
  26754. {},
  26755. new BoundingRect(x, y, w, h),
  26756. keepAspect ? 'center' : 'cover'
  26757. );
  26758. }
  26759. else {
  26760. symbolPath = new SymbolClz({
  26761. shape: {
  26762. symbolType: symbolType,
  26763. x: x,
  26764. y: y,
  26765. width: w,
  26766. height: h
  26767. }
  26768. });
  26769. }
  26770. symbolPath.__isEmptyBrush = isEmpty;
  26771. symbolPath.setColor = symbolPathSetColor;
  26772. symbolPath.setColor(color);
  26773. return symbolPath;
  26774. }
  26775. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26776. /**
  26777. * Create a muti dimension List structure from seriesModel.
  26778. * @param {module:echarts/model/Model} seriesModel
  26779. * @return {module:echarts/data/List} list
  26780. */
  26781. function createList(seriesModel) {
  26782. return createListFromArray(seriesModel.getSource(), seriesModel);
  26783. }
  26784. var dataStack$1 = {
  26785. isDimensionStacked: isDimensionStacked,
  26786. enableDataStack: enableDataStack
  26787. };
  26788. /**
  26789. * Create scale
  26790. * @param {Array.<number>} dataExtent
  26791. * @param {Object|module:echarts/Model} option
  26792. */
  26793. function createScale(dataExtent, option) {
  26794. var axisModel = option;
  26795. if (!Model.isInstance(option)) {
  26796. axisModel = new Model(option);
  26797. mixin(axisModel, axisModelCommonMixin);
  26798. }
  26799. var scale = createScaleByModel(axisModel);
  26800. scale.setExtent(dataExtent[0], dataExtent[1]);
  26801. niceScaleExtent(scale, axisModel);
  26802. return scale;
  26803. }
  26804. /**
  26805. * Mixin common methods to axis model,
  26806. *
  26807. * Inlcude methods
  26808. * `getFormattedLabels() => Array.<string>`
  26809. * `getCategories() => Array.<string>`
  26810. * `getMin(origin: boolean) => number`
  26811. * `getMax(origin: boolean) => number`
  26812. * `getNeedCrossZero() => boolean`
  26813. * `setRange(start: number, end: number)`
  26814. * `resetRange()`
  26815. */
  26816. function mixinAxisModelCommonMethods(Model$$1) {
  26817. mixin(Model$$1, axisModelCommonMixin);
  26818. }
  26819. var helper = (Object.freeze || Object)({
  26820. createList: createList,
  26821. getLayoutRect: getLayoutRect,
  26822. dataStack: dataStack$1,
  26823. createScale: createScale,
  26824. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26825. completeDimensions: completeDimensions,
  26826. createDimensions: createDimensions,
  26827. createSymbol: createSymbol
  26828. });
  26829. var EPSILON$3 = 1e-8;
  26830. function isAroundEqual$1(a, b) {
  26831. return Math.abs(a - b) < EPSILON$3;
  26832. }
  26833. function contain$1(points, x, y) {
  26834. var w = 0;
  26835. var p = points[0];
  26836. if (!p) {
  26837. return false;
  26838. }
  26839. for (var i = 1; i < points.length; i++) {
  26840. var p2 = points[i];
  26841. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26842. p = p2;
  26843. }
  26844. // Close polygon
  26845. var p0 = points[0];
  26846. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26847. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26848. }
  26849. return w !== 0;
  26850. }
  26851. /**
  26852. * @module echarts/coord/geo/Region
  26853. */
  26854. /**
  26855. * @param {string} name
  26856. * @param {Array} geometries
  26857. * @param {Array.<number>} cp
  26858. */
  26859. function Region(name, geometries, cp) {
  26860. /**
  26861. * @type {string}
  26862. * @readOnly
  26863. */
  26864. this.name = name;
  26865. /**
  26866. * @type {Array.<Array>}
  26867. * @readOnly
  26868. */
  26869. this.geometries = geometries;
  26870. if (!cp) {
  26871. var rect = this.getBoundingRect();
  26872. cp = [
  26873. rect.x + rect.width / 2,
  26874. rect.y + rect.height / 2
  26875. ];
  26876. }
  26877. else {
  26878. cp = [cp[0], cp[1]];
  26879. }
  26880. /**
  26881. * @type {Array.<number>}
  26882. */
  26883. this.center = cp;
  26884. }
  26885. Region.prototype = {
  26886. constructor: Region,
  26887. properties: null,
  26888. /**
  26889. * @return {module:zrender/core/BoundingRect}
  26890. */
  26891. getBoundingRect: function () {
  26892. var rect = this._rect;
  26893. if (rect) {
  26894. return rect;
  26895. }
  26896. var MAX_NUMBER = Number.MAX_VALUE;
  26897. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26898. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26899. var min2 = [];
  26900. var max2 = [];
  26901. var geometries = this.geometries;
  26902. for (var i = 0; i < geometries.length; i++) {
  26903. // Only support polygon
  26904. if (geometries[i].type !== 'polygon') {
  26905. continue;
  26906. }
  26907. // Doesn't consider hole
  26908. var exterior = geometries[i].exterior;
  26909. fromPoints(exterior, min2, max2);
  26910. min(min$$1, min$$1, min2);
  26911. max(max$$1, max$$1, max2);
  26912. }
  26913. // No data
  26914. if (i === 0) {
  26915. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26916. }
  26917. return (this._rect = new BoundingRect(
  26918. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26919. ));
  26920. },
  26921. /**
  26922. * @param {<Array.<number>} coord
  26923. * @return {boolean}
  26924. */
  26925. contain: function (coord) {
  26926. var rect = this.getBoundingRect();
  26927. var geometries = this.geometries;
  26928. if (!rect.contain(coord[0], coord[1])) {
  26929. return false;
  26930. }
  26931. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26932. // Only support polygon.
  26933. if (geometries[i].type !== 'polygon') {
  26934. continue;
  26935. }
  26936. var exterior = geometries[i].exterior;
  26937. var interiors = geometries[i].interiors;
  26938. if (contain$1(exterior, coord[0], coord[1])) {
  26939. // Not in the region if point is in the hole.
  26940. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26941. if (contain$1(interiors[k])) {
  26942. continue loopGeo;
  26943. }
  26944. }
  26945. return true;
  26946. }
  26947. }
  26948. return false;
  26949. },
  26950. transformTo: function (x, y, width, height) {
  26951. var rect = this.getBoundingRect();
  26952. var aspect = rect.width / rect.height;
  26953. if (!width) {
  26954. width = aspect * height;
  26955. }
  26956. else if (!height) {
  26957. height = width / aspect ;
  26958. }
  26959. var target = new BoundingRect(x, y, width, height);
  26960. var transform = rect.calculateTransform(target);
  26961. var geometries = this.geometries;
  26962. for (var i = 0; i < geometries.length; i++) {
  26963. // Only support polygon.
  26964. if (geometries[i].type !== 'polygon') {
  26965. continue;
  26966. }
  26967. var exterior = geometries[i].exterior;
  26968. var interiors = geometries[i].interiors;
  26969. for (var p = 0; p < exterior.length; p++) {
  26970. applyTransform(exterior[p], exterior[p], transform);
  26971. }
  26972. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26973. for (var p = 0; p < interiors[h].length; p++) {
  26974. applyTransform(interiors[h][p], interiors[h][p], transform);
  26975. }
  26976. }
  26977. }
  26978. rect = this._rect;
  26979. rect.copy(target);
  26980. // Update center
  26981. this.center = [
  26982. rect.x + rect.width / 2,
  26983. rect.y + rect.height / 2
  26984. ];
  26985. }
  26986. };
  26987. /**
  26988. * Parse and decode geo json
  26989. * @module echarts/coord/geo/parseGeoJson
  26990. */
  26991. function decode(json) {
  26992. if (!json.UTF8Encoding) {
  26993. return json;
  26994. }
  26995. var encodeScale = json.UTF8Scale;
  26996. if (encodeScale == null) {
  26997. encodeScale = 1024;
  26998. }
  26999. var features = json.features;
  27000. for (var f = 0; f < features.length; f++) {
  27001. var feature = features[f];
  27002. var geometry = feature.geometry;
  27003. var coordinates = geometry.coordinates;
  27004. var encodeOffsets = geometry.encodeOffsets;
  27005. for (var c = 0; c < coordinates.length; c++) {
  27006. var coordinate = coordinates[c];
  27007. if (geometry.type === 'Polygon') {
  27008. coordinates[c] = decodePolygon(
  27009. coordinate,
  27010. encodeOffsets[c],
  27011. encodeScale
  27012. );
  27013. }
  27014. else if (geometry.type === 'MultiPolygon') {
  27015. for (var c2 = 0; c2 < coordinate.length; c2++) {
  27016. var polygon = coordinate[c2];
  27017. coordinate[c2] = decodePolygon(
  27018. polygon,
  27019. encodeOffsets[c][c2],
  27020. encodeScale
  27021. );
  27022. }
  27023. }
  27024. }
  27025. }
  27026. // Has been decoded
  27027. json.UTF8Encoding = false;
  27028. return json;
  27029. }
  27030. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  27031. var result = [];
  27032. var prevX = encodeOffsets[0];
  27033. var prevY = encodeOffsets[1];
  27034. for (var i = 0; i < coordinate.length; i += 2) {
  27035. var x = coordinate.charCodeAt(i) - 64;
  27036. var y = coordinate.charCodeAt(i + 1) - 64;
  27037. // ZigZag decoding
  27038. x = (x >> 1) ^ (-(x & 1));
  27039. y = (y >> 1) ^ (-(y & 1));
  27040. // Delta deocding
  27041. x += prevX;
  27042. y += prevY;
  27043. prevX = x;
  27044. prevY = y;
  27045. // Dequantize
  27046. result.push([x / encodeScale, y / encodeScale]);
  27047. }
  27048. return result;
  27049. }
  27050. /**
  27051. * @alias module:echarts/coord/geo/parseGeoJson
  27052. * @param {Object} geoJson
  27053. * @return {module:zrender/container/Group}
  27054. */
  27055. var parseGeoJson$1 = function (geoJson) {
  27056. decode(geoJson);
  27057. return map(filter(geoJson.features, function (featureObj) {
  27058. // Output of mapshaper may have geometry null
  27059. return featureObj.geometry
  27060. && featureObj.properties
  27061. && featureObj.geometry.coordinates.length > 0;
  27062. }), function (featureObj) {
  27063. var properties = featureObj.properties;
  27064. var geo = featureObj.geometry;
  27065. var coordinates = geo.coordinates;
  27066. var geometries = [];
  27067. if (geo.type === 'Polygon') {
  27068. geometries.push({
  27069. type: 'polygon',
  27070. // According to the GeoJSON specification.
  27071. // First must be exterior, and the rest are all interior(holes).
  27072. exterior: coordinates[0],
  27073. interiors: coordinates.slice(1)
  27074. });
  27075. }
  27076. if (geo.type === 'MultiPolygon') {
  27077. each$1(coordinates, function (item) {
  27078. if (item[0]) {
  27079. geometries.push({
  27080. type: 'polygon',
  27081. exterior: item[0],
  27082. interiors: item.slice(1)
  27083. });
  27084. }
  27085. });
  27086. }
  27087. var region = new Region(
  27088. properties.name,
  27089. geometries,
  27090. properties.cp
  27091. );
  27092. region.properties = properties;
  27093. return region;
  27094. });
  27095. };
  27096. var linearMap$1 = linearMap;
  27097. function fixExtentWithBands(extent, nTick) {
  27098. var size = extent[1] - extent[0];
  27099. var len = nTick;
  27100. var margin = size / len / 2;
  27101. extent[0] += margin;
  27102. extent[1] -= margin;
  27103. }
  27104. var normalizedExtent = [0, 1];
  27105. /**
  27106. * @name module:echarts/coord/CartesianAxis
  27107. * @constructor
  27108. */
  27109. var Axis = function (dim, scale, extent) {
  27110. /**
  27111. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  27112. * @type {string}
  27113. */
  27114. this.dim = dim;
  27115. /**
  27116. * Axis scale
  27117. * @type {module:echarts/coord/scale/*}
  27118. */
  27119. this.scale = scale;
  27120. /**
  27121. * @type {Array.<number>}
  27122. * @private
  27123. */
  27124. this._extent = extent || [0, 0];
  27125. /**
  27126. * @type {boolean}
  27127. */
  27128. this.inverse = false;
  27129. /**
  27130. * Usually true when axis has a ordinal scale
  27131. * @type {boolean}
  27132. */
  27133. this.onBand = false;
  27134. /**
  27135. * @private
  27136. * @type {number}
  27137. */
  27138. this._labelInterval;
  27139. };
  27140. Axis.prototype = {
  27141. constructor: Axis,
  27142. /**
  27143. * If axis extent contain given coord
  27144. * @param {number} coord
  27145. * @return {boolean}
  27146. */
  27147. contain: function (coord) {
  27148. var extent = this._extent;
  27149. var min = Math.min(extent[0], extent[1]);
  27150. var max = Math.max(extent[0], extent[1]);
  27151. return coord >= min && coord <= max;
  27152. },
  27153. /**
  27154. * If axis extent contain given data
  27155. * @param {number} data
  27156. * @return {boolean}
  27157. */
  27158. containData: function (data) {
  27159. return this.contain(this.dataToCoord(data));
  27160. },
  27161. /**
  27162. * Get coord extent.
  27163. * @return {Array.<number>}
  27164. */
  27165. getExtent: function () {
  27166. return this._extent.slice();
  27167. },
  27168. /**
  27169. * Get precision used for formatting
  27170. * @param {Array.<number>} [dataExtent]
  27171. * @return {number}
  27172. */
  27173. getPixelPrecision: function (dataExtent) {
  27174. return getPixelPrecision(
  27175. dataExtent || this.scale.getExtent(),
  27176. this._extent
  27177. );
  27178. },
  27179. /**
  27180. * Set coord extent
  27181. * @param {number} start
  27182. * @param {number} end
  27183. */
  27184. setExtent: function (start, end) {
  27185. var extent = this._extent;
  27186. extent[0] = start;
  27187. extent[1] = end;
  27188. },
  27189. /**
  27190. * Convert data to coord. Data is the rank if it has an ordinal scale
  27191. * @param {number} data
  27192. * @param {boolean} clamp
  27193. * @return {number}
  27194. */
  27195. dataToCoord: function (data, clamp) {
  27196. var extent = this._extent;
  27197. var scale = this.scale;
  27198. data = scale.normalize(data);
  27199. if (this.onBand && scale.type === 'ordinal') {
  27200. extent = extent.slice();
  27201. fixExtentWithBands(extent, scale.count());
  27202. }
  27203. return linearMap$1(data, normalizedExtent, extent, clamp);
  27204. },
  27205. /**
  27206. * Convert coord to data. Data is the rank if it has an ordinal scale
  27207. * @param {number} coord
  27208. * @param {boolean} clamp
  27209. * @return {number}
  27210. */
  27211. coordToData: function (coord, clamp) {
  27212. var extent = this._extent;
  27213. var scale = this.scale;
  27214. if (this.onBand && scale.type === 'ordinal') {
  27215. extent = extent.slice();
  27216. fixExtentWithBands(extent, scale.count());
  27217. }
  27218. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  27219. return this.scale.scale(t);
  27220. },
  27221. /**
  27222. * Convert pixel point to data in axis
  27223. * @param {Array.<number>} point
  27224. * @param {boolean} clamp
  27225. * @return {number} data
  27226. */
  27227. pointToData: function (point, clamp) {
  27228. // Should be implemented in derived class if necessary.
  27229. },
  27230. /**
  27231. * @return {Array.<number>}
  27232. */
  27233. getTicksCoords: function (alignWithLabel) {
  27234. if (this.onBand && !alignWithLabel) {
  27235. var bands = this.getBands();
  27236. var coords = [];
  27237. for (var i = 0; i < bands.length; i++) {
  27238. coords.push(bands[i][0]);
  27239. }
  27240. if (bands[i - 1]) {
  27241. coords.push(bands[i - 1][1]);
  27242. }
  27243. return coords;
  27244. }
  27245. else {
  27246. return map(this.scale.getTicks(), this.dataToCoord, this);
  27247. }
  27248. },
  27249. /**
  27250. * Coords of labels are on the ticks or on the middle of bands
  27251. * @return {Array.<number>}
  27252. */
  27253. getLabelsCoords: function () {
  27254. return map(this.scale.getTicks(), this.dataToCoord, this);
  27255. },
  27256. /**
  27257. * Get bands.
  27258. *
  27259. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  27260. * |---1---|---2---|---3---|---4---|.
  27261. *
  27262. * @return {Array}
  27263. */
  27264. // FIXME Situation when labels is on ticks
  27265. getBands: function () {
  27266. var extent = this.getExtent();
  27267. var bands = [];
  27268. var len = this.scale.count();
  27269. var start = extent[0];
  27270. var end = extent[1];
  27271. var span = end - start;
  27272. for (var i = 0; i < len; i++) {
  27273. bands.push([
  27274. span * i / len + start,
  27275. span * (i + 1) / len + start
  27276. ]);
  27277. }
  27278. return bands;
  27279. },
  27280. /**
  27281. * Get width of band
  27282. * @return {number}
  27283. */
  27284. getBandWidth: function () {
  27285. var axisExtent = this._extent;
  27286. var dataExtent = this.scale.getExtent();
  27287. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  27288. // Fix #2728, avoid NaN when only one data.
  27289. len === 0 && (len = 1);
  27290. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  27291. return Math.abs(size) / len;
  27292. },
  27293. /**
  27294. * @abstract
  27295. * @return {boolean} Is horizontal
  27296. */
  27297. isHorizontal: null,
  27298. /**
  27299. * @abstract
  27300. * @return {number} Get axis rotate, by degree.
  27301. */
  27302. getRotate: null,
  27303. /**
  27304. * Get interval of the axis label.
  27305. * To get precise result, at least one of `getRotate` and `isHorizontal`
  27306. * should be implemented.
  27307. * @return {number}
  27308. */
  27309. getLabelInterval: function () {
  27310. var labelInterval = this._labelInterval;
  27311. if (!labelInterval) {
  27312. var axisModel = this.model;
  27313. var labelModel = axisModel.getModel('axisLabel');
  27314. labelInterval = labelModel.get('interval');
  27315. if (this.type === 'category'
  27316. && (labelInterval == null || labelInterval === 'auto')
  27317. ) {
  27318. labelInterval = getAxisLabelInterval(
  27319. map(this.scale.getTicks(), this.dataToCoord, this),
  27320. axisModel.getFormattedLabels(),
  27321. labelModel.getFont(),
  27322. this.getRotate
  27323. ? this.getRotate()
  27324. : (this.isHorizontal && !this.isHorizontal())
  27325. ? 90
  27326. : 0,
  27327. labelModel.get('rotate')
  27328. );
  27329. }
  27330. this._labelInterval = labelInterval;
  27331. }
  27332. return labelInterval;
  27333. }
  27334. };
  27335. /**
  27336. * Do not mount those modules on 'src/echarts' for better tree shaking.
  27337. */
  27338. var parseGeoJson = parseGeoJson$1;
  27339. var ecUtil = {};
  27340. each$1([
  27341. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  27342. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  27343. 'extend', 'defaults', 'clone', 'merge'
  27344. ],
  27345. function (name) {
  27346. ecUtil[name] = zrUtil[name];
  27347. }
  27348. );
  27349. var DatasetModel = extendComponentModel({
  27350. type: 'dataset',
  27351. /**
  27352. * @protected
  27353. */
  27354. defaultOption: {
  27355. // 'row', 'column'
  27356. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  27357. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  27358. sourceHeader: null,
  27359. dimensions: null,
  27360. source: null
  27361. },
  27362. optionUpdated: function () {
  27363. detectSourceFormat(this);
  27364. }
  27365. });
  27366. extendComponentView({type: 'dataset'});
  27367. SeriesModel.extend({
  27368. type: 'series.line',
  27369. dependencies: ['grid', 'polar'],
  27370. getInitialData: function (option, ecModel) {
  27371. if (__DEV__) {
  27372. var coordSys = option.coordinateSystem;
  27373. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27374. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27375. }
  27376. }
  27377. return createListFromArray(this.getSource(), this);
  27378. },
  27379. defaultOption: {
  27380. zlevel: 0, // 一级层叠
  27381. z: 2, // 二级层叠
  27382. coordinateSystem: 'cartesian2d',
  27383. legendHoverLink: true,
  27384. hoverAnimation: true,
  27385. // stack: null
  27386. // xAxisIndex: 0,
  27387. // yAxisIndex: 0,
  27388. // polarIndex: 0,
  27389. // If clip the overflow value
  27390. clipOverflow: true,
  27391. // cursor: null,
  27392. label: {
  27393. position: 'top'
  27394. },
  27395. // itemStyle: {
  27396. // },
  27397. lineStyle: {
  27398. width: 2,
  27399. type: 'solid'
  27400. },
  27401. // areaStyle: {
  27402. // origin of areaStyle. Valid values:
  27403. // `'auto'/null/undefined`: from axisLine to data
  27404. // `'start'`: from min to data
  27405. // `'end'`: from data to max
  27406. // origin: 'auto'
  27407. // },
  27408. // false, 'start', 'end', 'middle'
  27409. step: false,
  27410. // Disabled if step is true
  27411. smooth: false,
  27412. smoothMonotone: null,
  27413. // 拐点图形类型
  27414. symbol: 'emptyCircle',
  27415. // 拐点图形大小
  27416. symbolSize: 4,
  27417. // 拐点图形旋转控制
  27418. symbolRotate: null,
  27419. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  27420. showSymbol: true,
  27421. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  27422. showAllSymbol: false,
  27423. // 是否连接断点
  27424. connectNulls: false,
  27425. // 数据过滤,'average', 'max', 'min', 'sum'
  27426. sampling: 'none',
  27427. animationEasing: 'linear',
  27428. // Disable progressive
  27429. progressive: 0,
  27430. hoverLayerThreshold: Infinity
  27431. }
  27432. });
  27433. /**
  27434. * @param {module:echarts/data/List} data
  27435. * @param {number} dataIndex
  27436. * @return {string} label string. Not null/undefined
  27437. */
  27438. function getDefaultLabel(data, dataIndex) {
  27439. var labelDims = data.mapDimension('defaultedLabel', true);
  27440. var len = labelDims.length;
  27441. // Simple optimization (in lots of cases, label dims length is 1)
  27442. if (len === 1) {
  27443. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27444. }
  27445. else if (len) {
  27446. var vals = [];
  27447. for (var i = 0; i < labelDims.length; i++) {
  27448. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27449. vals.push(val);
  27450. }
  27451. return vals.join(' ');
  27452. }
  27453. }
  27454. /**
  27455. * @module echarts/chart/helper/Symbol
  27456. */
  27457. function getSymbolSize(data, idx) {
  27458. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27459. return symbolSize instanceof Array
  27460. ? symbolSize.slice()
  27461. : [+symbolSize, +symbolSize];
  27462. }
  27463. function getScale(symbolSize) {
  27464. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27465. }
  27466. /**
  27467. * @constructor
  27468. * @alias {module:echarts/chart/helper/Symbol}
  27469. * @param {module:echarts/data/List} data
  27470. * @param {number} idx
  27471. * @extends {module:zrender/graphic/Group}
  27472. */
  27473. function SymbolClz$1(data, idx, seriesScope) {
  27474. Group.call(this);
  27475. this.updateData(data, idx, seriesScope);
  27476. }
  27477. var symbolProto = SymbolClz$1.prototype;
  27478. function driftSymbol(dx, dy) {
  27479. this.parent.drift(dx, dy);
  27480. }
  27481. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  27482. // Remove paths created before
  27483. this.removeAll();
  27484. var color = data.getItemVisual(idx, 'color');
  27485. // var symbolPath = createSymbol(
  27486. // symbolType, -0.5, -0.5, 1, 1, color
  27487. // );
  27488. // If width/height are set too small (e.g., set to 1) on ios10
  27489. // and macOS Sierra, a circle stroke become a rect, no matter what
  27490. // the scale is set. So we set width/height as 2. See #4150.
  27491. var symbolPath = createSymbol(
  27492. symbolType, -1, -1, 2, 2, color
  27493. );
  27494. symbolPath.attr({
  27495. z2: 100,
  27496. culling: true,
  27497. scale: getScale(symbolSize)
  27498. });
  27499. // Rewrite drift method
  27500. symbolPath.drift = driftSymbol;
  27501. this._symbolType = symbolType;
  27502. this.add(symbolPath);
  27503. };
  27504. /**
  27505. * Stop animation
  27506. * @param {boolean} toLastFrame
  27507. */
  27508. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27509. this.childAt(0).stopAnimation(toLastFrame);
  27510. };
  27511. /**
  27512. * FIXME:
  27513. * Caution: This method breaks the encapsulation of this module,
  27514. * but it indeed brings convenience. So do not use the method
  27515. * unless you detailedly know all the implements of `Symbol`,
  27516. * especially animation.
  27517. *
  27518. * Get symbol path element.
  27519. */
  27520. symbolProto.getSymbolPath = function () {
  27521. return this.childAt(0);
  27522. };
  27523. /**
  27524. * Get scale(aka, current symbol size).
  27525. * Including the change caused by animation
  27526. */
  27527. symbolProto.getScale = function () {
  27528. return this.childAt(0).scale;
  27529. };
  27530. /**
  27531. * Highlight symbol
  27532. */
  27533. symbolProto.highlight = function () {
  27534. this.childAt(0).trigger('emphasis');
  27535. };
  27536. /**
  27537. * Downplay symbol
  27538. */
  27539. symbolProto.downplay = function () {
  27540. this.childAt(0).trigger('normal');
  27541. };
  27542. /**
  27543. * @param {number} zlevel
  27544. * @param {number} z
  27545. */
  27546. symbolProto.setZ = function (zlevel, z) {
  27547. var symbolPath = this.childAt(0);
  27548. symbolPath.zlevel = zlevel;
  27549. symbolPath.z = z;
  27550. };
  27551. symbolProto.setDraggable = function (draggable) {
  27552. var symbolPath = this.childAt(0);
  27553. symbolPath.draggable = draggable;
  27554. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27555. };
  27556. /**
  27557. * Update symbol properties
  27558. * @param {module:echarts/data/List} data
  27559. * @param {number} idx
  27560. * @param {Object} [seriesScope]
  27561. * @param {Object} [seriesScope.itemStyle]
  27562. * @param {Object} [seriesScope.hoverItemStyle]
  27563. * @param {Object} [seriesScope.symbolRotate]
  27564. * @param {Object} [seriesScope.symbolOffset]
  27565. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27566. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27567. * @param {boolean} [seriesScope.hoverAnimation]
  27568. * @param {Object} [seriesScope.cursorStyle]
  27569. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27570. * @param {string} [seriesScope.symbolInnerColor]
  27571. * @param {Object} [seriesScope.fadeIn=false]
  27572. */
  27573. symbolProto.updateData = function (data, idx, seriesScope) {
  27574. this.silent = false;
  27575. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27576. var seriesModel = data.hostModel;
  27577. var symbolSize = getSymbolSize(data, idx);
  27578. var isInit = symbolType !== this._symbolType;
  27579. if (isInit) {
  27580. this._createSymbol(symbolType, data, idx, symbolSize);
  27581. }
  27582. else {
  27583. var symbolPath = this.childAt(0);
  27584. symbolPath.silent = false;
  27585. updateProps(symbolPath, {
  27586. scale: getScale(symbolSize)
  27587. }, seriesModel, idx);
  27588. }
  27589. this._updateCommon(data, idx, symbolSize, seriesScope);
  27590. if (isInit) {
  27591. var symbolPath = this.childAt(0);
  27592. var fadeIn = seriesScope && seriesScope.fadeIn;
  27593. var target = {scale: symbolPath.scale.slice()};
  27594. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27595. symbolPath.scale = [0, 0];
  27596. fadeIn && (symbolPath.style.opacity = 0);
  27597. initProps(symbolPath, target, seriesModel, idx);
  27598. }
  27599. this._seriesModel = seriesModel;
  27600. };
  27601. // Update common properties
  27602. var normalStyleAccessPath = ['itemStyle'];
  27603. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27604. var normalLabelAccessPath = ['label'];
  27605. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27606. /**
  27607. * @param {module:echarts/data/List} data
  27608. * @param {number} idx
  27609. * @param {Array.<number>} symbolSize
  27610. * @param {Object} [seriesScope]
  27611. */
  27612. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27613. var symbolPath = this.childAt(0);
  27614. var seriesModel = data.hostModel;
  27615. var color = data.getItemVisual(idx, 'color');
  27616. // Reset style
  27617. if (symbolPath.type !== 'image') {
  27618. symbolPath.useStyle({
  27619. strokeNoScale: true
  27620. });
  27621. }
  27622. var itemStyle = seriesScope && seriesScope.itemStyle;
  27623. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27624. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27625. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27626. var labelModel = seriesScope && seriesScope.labelModel;
  27627. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27628. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27629. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27630. if (!seriesScope || data.hasItemOption) {
  27631. var itemModel = (seriesScope && seriesScope.itemModel)
  27632. ? seriesScope.itemModel : data.getItemModel(idx);
  27633. // Color must be excluded.
  27634. // Because symbol provide setColor individually to set fill and stroke
  27635. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27636. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27637. symbolRotate = itemModel.getShallow('symbolRotate');
  27638. symbolOffset = itemModel.getShallow('symbolOffset');
  27639. labelModel = itemModel.getModel(normalLabelAccessPath);
  27640. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27641. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27642. cursorStyle = itemModel.getShallow('cursor');
  27643. }
  27644. else {
  27645. hoverItemStyle = extend({}, hoverItemStyle);
  27646. }
  27647. var elStyle = symbolPath.style;
  27648. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27649. if (symbolOffset) {
  27650. symbolPath.attr('position', [
  27651. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27652. parsePercent$1(symbolOffset[1], symbolSize[1])
  27653. ]);
  27654. }
  27655. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27656. // PENDING setColor before setStyle!!!
  27657. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27658. symbolPath.setStyle(itemStyle);
  27659. var opacity = data.getItemVisual(idx, 'opacity');
  27660. if (opacity != null) {
  27661. elStyle.opacity = opacity;
  27662. }
  27663. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27664. setLabelStyle(
  27665. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27666. {
  27667. labelFetcher: seriesModel,
  27668. labelDataIndex: idx,
  27669. defaultText: getLabelDefaultText,
  27670. isRectText: true,
  27671. autoColor: color
  27672. }
  27673. );
  27674. // Do not execute util needed.
  27675. function getLabelDefaultText(idx, opt) {
  27676. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27677. }
  27678. symbolPath.off('mouseover')
  27679. .off('mouseout')
  27680. .off('emphasis')
  27681. .off('normal');
  27682. symbolPath.hoverStyle = hoverItemStyle;
  27683. // FIXME
  27684. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27685. setHoverStyle(symbolPath);
  27686. var scale = getScale(symbolSize);
  27687. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27688. var onEmphasis = function() {
  27689. // Do not support this hover animation util some scenario required.
  27690. // Animation can only be supported in hover layer when using `el.incremetal`.
  27691. if (this.incremental) {
  27692. return;
  27693. }
  27694. var ratio = scale[1] / scale[0];
  27695. this.animateTo({
  27696. scale: [
  27697. Math.max(scale[0] * 1.1, scale[0] + 3),
  27698. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27699. ]
  27700. }, 400, 'elasticOut');
  27701. };
  27702. var onNormal = function() {
  27703. if (this.incremental) {
  27704. return;
  27705. }
  27706. this.animateTo({
  27707. scale: scale
  27708. }, 400, 'elasticOut');
  27709. };
  27710. symbolPath.on('mouseover', onEmphasis)
  27711. .on('mouseout', onNormal)
  27712. .on('emphasis', onEmphasis)
  27713. .on('normal', onNormal);
  27714. }
  27715. };
  27716. /**
  27717. * @param {Function} cb
  27718. * @param {Object} [opt]
  27719. * @param {Object} [opt.keepLabel=true]
  27720. */
  27721. symbolProto.fadeOut = function (cb, opt) {
  27722. var symbolPath = this.childAt(0);
  27723. // Avoid mistaken hover when fading out
  27724. this.silent = symbolPath.silent = true;
  27725. // Not show text when animating
  27726. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27727. updateProps(
  27728. symbolPath,
  27729. {
  27730. style: {opacity: 0},
  27731. scale: [0, 0]
  27732. },
  27733. this._seriesModel,
  27734. this.dataIndex,
  27735. cb
  27736. );
  27737. };
  27738. inherits(SymbolClz$1, Group);
  27739. /**
  27740. * @module echarts/chart/helper/SymbolDraw
  27741. */
  27742. /**
  27743. * @constructor
  27744. * @alias module:echarts/chart/helper/SymbolDraw
  27745. * @param {module:zrender/graphic/Group} [symbolCtor]
  27746. */
  27747. function SymbolDraw(symbolCtor) {
  27748. this.group = new Group();
  27749. this._symbolCtor = symbolCtor || SymbolClz$1;
  27750. }
  27751. var symbolDrawProto = SymbolDraw.prototype;
  27752. function symbolNeedsDraw(data, point, idx, opt) {
  27753. return point && !isNaN(point[0]) && !isNaN(point[1])
  27754. && !(opt.isIgnore && opt.isIgnore(idx))
  27755. // We do not set clipShape on group, because it will
  27756. // cut part of the symbol element shape.
  27757. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  27758. && data.getItemVisual(idx, 'symbol') !== 'none';
  27759. }
  27760. /**
  27761. * Update symbols draw by new data
  27762. * @param {module:echarts/data/List} data
  27763. * @param {Object} [opt] Or isIgnore
  27764. * @param {Function} [opt.isIgnore]
  27765. * @param {Object} [opt.clipShape]
  27766. */
  27767. symbolDrawProto.updateData = function (data, opt) {
  27768. opt = normalizeUpdateOpt(opt);
  27769. var group = this.group;
  27770. var seriesModel = data.hostModel;
  27771. var oldData = this._data;
  27772. var SymbolCtor = this._symbolCtor;
  27773. var seriesScope = makeSeriesScope(data);
  27774. // There is no oldLineData only when first rendering or switching from
  27775. // stream mode to normal mode, where previous elements should be removed.
  27776. if (!oldData) {
  27777. group.removeAll();
  27778. }
  27779. data.diff(oldData)
  27780. .add(function (newIdx) {
  27781. var point = data.getItemLayout(newIdx);
  27782. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  27783. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27784. symbolEl.attr('position', point);
  27785. data.setItemGraphicEl(newIdx, symbolEl);
  27786. group.add(symbolEl);
  27787. }
  27788. })
  27789. .update(function (newIdx, oldIdx) {
  27790. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27791. var point = data.getItemLayout(newIdx);
  27792. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  27793. group.remove(symbolEl);
  27794. return;
  27795. }
  27796. if (!symbolEl) {
  27797. symbolEl = new SymbolCtor(data, newIdx);
  27798. symbolEl.attr('position', point);
  27799. }
  27800. else {
  27801. symbolEl.updateData(data, newIdx, seriesScope);
  27802. updateProps(symbolEl, {
  27803. position: point
  27804. }, seriesModel);
  27805. }
  27806. // Add back
  27807. group.add(symbolEl);
  27808. data.setItemGraphicEl(newIdx, symbolEl);
  27809. })
  27810. .remove(function (oldIdx) {
  27811. var el = oldData.getItemGraphicEl(oldIdx);
  27812. el && el.fadeOut(function () {
  27813. group.remove(el);
  27814. });
  27815. })
  27816. .execute();
  27817. this._data = data;
  27818. };
  27819. symbolDrawProto.isPersistent = function () {
  27820. return true;
  27821. };
  27822. symbolDrawProto.updateLayout = function () {
  27823. var data = this._data;
  27824. if (data) {
  27825. // Not use animation
  27826. data.eachItemGraphicEl(function (el, idx) {
  27827. var point = data.getItemLayout(idx);
  27828. el.attr('position', point);
  27829. });
  27830. }
  27831. };
  27832. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27833. this._seriesScope = makeSeriesScope(data);
  27834. this._data = null;
  27835. this.group.removeAll();
  27836. };
  27837. /**
  27838. * Update symbols draw by new data
  27839. * @param {module:echarts/data/List} data
  27840. * @param {Object} [opt] Or isIgnore
  27841. * @param {Function} [opt.isIgnore]
  27842. * @param {Object} [opt.clipShape]
  27843. */
  27844. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  27845. opt = normalizeUpdateOpt(opt);
  27846. function updateIncrementalAndHover(el) {
  27847. if (!el.isGroup) {
  27848. el.incremental = el.useHoverLayer = true;
  27849. }
  27850. }
  27851. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27852. var point = data.getItemLayout(idx);
  27853. if (symbolNeedsDraw(data, point, idx, opt)) {
  27854. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27855. el.traverse(updateIncrementalAndHover);
  27856. el.attr('position', point);
  27857. this.group.add(el);
  27858. data.setItemGraphicEl(idx, el);
  27859. }
  27860. }
  27861. };
  27862. function normalizeUpdateOpt(opt) {
  27863. if (opt != null && !isObject$1(opt)) {
  27864. opt = {isIgnore: opt};
  27865. }
  27866. return opt || {};
  27867. }
  27868. symbolDrawProto.remove = function (enableAnimation) {
  27869. var group = this.group;
  27870. var data = this._data;
  27871. // Incremental model do not have this._data.
  27872. if (data && enableAnimation) {
  27873. data.eachItemGraphicEl(function (el) {
  27874. el.fadeOut(function () {
  27875. group.remove(el);
  27876. });
  27877. });
  27878. }
  27879. else {
  27880. group.removeAll();
  27881. }
  27882. };
  27883. function makeSeriesScope(data) {
  27884. var seriesModel = data.hostModel;
  27885. return {
  27886. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27887. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27888. symbolRotate: seriesModel.get('symbolRotate'),
  27889. symbolOffset: seriesModel.get('symbolOffset'),
  27890. hoverAnimation: seriesModel.get('hoverAnimation'),
  27891. labelModel: seriesModel.getModel('label'),
  27892. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27893. cursorStyle: seriesModel.get('cursor')
  27894. };
  27895. }
  27896. /**
  27897. * @param {Object} coordSys
  27898. * @param {module:echarts/data/List} data
  27899. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  27900. */
  27901. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  27902. var baseAxis = coordSys.getBaseAxis();
  27903. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27904. var valueStart = getValueStart(valueAxis, valueOrigin);
  27905. var baseAxisDim = baseAxis.dim;
  27906. var valueAxisDim = valueAxis.dim;
  27907. var valueDim = data.mapDimension(valueAxisDim);
  27908. var baseDim = data.mapDimension(baseAxisDim);
  27909. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  27910. var stacked = isDimensionStacked(data, valueDim, baseDim);
  27911. var dataDimsForPoint = map(coordSys.dimensions, function (coordDim) {
  27912. return data.mapDimension(coordDim);
  27913. });
  27914. return {
  27915. dataDimsForPoint: dataDimsForPoint,
  27916. valueStart: valueStart,
  27917. valueAxisDim: valueAxisDim,
  27918. baseAxisDim: baseAxisDim,
  27919. stacked: stacked,
  27920. valueDim: valueDim,
  27921. baseDim: baseDim,
  27922. baseDataOffset: baseDataOffset,
  27923. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  27924. };
  27925. }
  27926. function getValueStart(valueAxis, valueOrigin) {
  27927. var valueStart = 0;
  27928. var extent = valueAxis.scale.getExtent();
  27929. if (valueOrigin === 'start') {
  27930. valueStart = extent[0];
  27931. }
  27932. else if (valueOrigin === 'end') {
  27933. valueStart = extent[1];
  27934. }
  27935. // auto
  27936. else {
  27937. // Both positive
  27938. if (extent[0] > 0) {
  27939. valueStart = extent[0];
  27940. }
  27941. // Both negative
  27942. else if (extent[1] < 0) {
  27943. valueStart = extent[1];
  27944. }
  27945. // If is one positive, and one negative, onZero shall be true
  27946. }
  27947. return valueStart;
  27948. }
  27949. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  27950. var value = NaN;
  27951. if (dataCoordInfo.stacked) {
  27952. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  27953. }
  27954. if (isNaN(value)) {
  27955. value = dataCoordInfo.valueStart;
  27956. }
  27957. var baseDataOffset = dataCoordInfo.baseDataOffset;
  27958. var stackedData = [];
  27959. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  27960. stackedData[1 - baseDataOffset] = value;
  27961. return coordSys.dataToPoint(stackedData);
  27962. }
  27963. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27964. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27965. // not do well in performance when roam with fixed dataZoom window.
  27966. // function convertToIntId(newIdList, oldIdList) {
  27967. // // Generate int id instead of string id.
  27968. // // Compare string maybe slow in score function of arrDiff
  27969. // // Assume id in idList are all unique
  27970. // var idIndicesMap = {};
  27971. // var idx = 0;
  27972. // for (var i = 0; i < newIdList.length; i++) {
  27973. // idIndicesMap[newIdList[i]] = idx;
  27974. // newIdList[i] = idx++;
  27975. // }
  27976. // for (var i = 0; i < oldIdList.length; i++) {
  27977. // var oldId = oldIdList[i];
  27978. // // Same with newIdList
  27979. // if (idIndicesMap[oldId]) {
  27980. // oldIdList[i] = idIndicesMap[oldId];
  27981. // }
  27982. // else {
  27983. // oldIdList[i] = idx++;
  27984. // }
  27985. // }
  27986. // }
  27987. function diffData(oldData, newData) {
  27988. var diffResult = [];
  27989. newData.diff(oldData)
  27990. .add(function (idx) {
  27991. diffResult.push({cmd: '+', idx: idx});
  27992. })
  27993. .update(function (newIdx, oldIdx) {
  27994. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27995. })
  27996. .remove(function (idx) {
  27997. diffResult.push({cmd: '-', idx: idx});
  27998. })
  27999. .execute();
  28000. return diffResult;
  28001. }
  28002. var lineAnimationDiff = function (
  28003. oldData, newData,
  28004. oldStackedOnPoints, newStackedOnPoints,
  28005. oldCoordSys, newCoordSys,
  28006. oldValueOrigin, newValueOrigin
  28007. ) {
  28008. var diff = diffData(oldData, newData);
  28009. // var newIdList = newData.mapArray(newData.getId);
  28010. // var oldIdList = oldData.mapArray(oldData.getId);
  28011. // convertToIntId(newIdList, oldIdList);
  28012. // // FIXME One data ?
  28013. // diff = arrayDiff(oldIdList, newIdList);
  28014. var currPoints = [];
  28015. var nextPoints = [];
  28016. // Points for stacking base line
  28017. var currStackedPoints = [];
  28018. var nextStackedPoints = [];
  28019. var status = [];
  28020. var sortedIndices = [];
  28021. var rawIndices = [];
  28022. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  28023. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  28024. for (var i = 0; i < diff.length; i++) {
  28025. var diffItem = diff[i];
  28026. var pointAdded = true;
  28027. // FIXME, animation is not so perfect when dataZoom window moves fast
  28028. // Which is in case remvoing or add more than one data in the tail or head
  28029. switch (diffItem.cmd) {
  28030. case '=':
  28031. var currentPt = oldData.getItemLayout(diffItem.idx);
  28032. var nextPt = newData.getItemLayout(diffItem.idx1);
  28033. // If previous data is NaN, use next point directly
  28034. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  28035. currentPt = nextPt.slice();
  28036. }
  28037. currPoints.push(currentPt);
  28038. nextPoints.push(nextPt);
  28039. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  28040. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  28041. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  28042. break;
  28043. case '+':
  28044. var idx = diffItem.idx;
  28045. currPoints.push(
  28046. oldCoordSys.dataToPoint([
  28047. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  28048. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  28049. ])
  28050. );
  28051. nextPoints.push(newData.getItemLayout(idx).slice());
  28052. currStackedPoints.push(
  28053. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  28054. );
  28055. nextStackedPoints.push(newStackedOnPoints[idx]);
  28056. rawIndices.push(newData.getRawIndex(idx));
  28057. break;
  28058. case '-':
  28059. var idx = diffItem.idx;
  28060. var rawIndex = oldData.getRawIndex(idx);
  28061. // Data is replaced. In the case of dynamic data queue
  28062. // FIXME FIXME FIXME
  28063. if (rawIndex !== idx) {
  28064. currPoints.push(oldData.getItemLayout(idx));
  28065. nextPoints.push(newCoordSys.dataToPoint([
  28066. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  28067. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  28068. ]));
  28069. currStackedPoints.push(oldStackedOnPoints[idx]);
  28070. nextStackedPoints.push(
  28071. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  28072. );
  28073. rawIndices.push(rawIndex);
  28074. }
  28075. else {
  28076. pointAdded = false;
  28077. }
  28078. }
  28079. // Original indices
  28080. if (pointAdded) {
  28081. status.push(diffItem);
  28082. sortedIndices.push(sortedIndices.length);
  28083. }
  28084. }
  28085. // Diff result may be crossed if all items are changed
  28086. // Sort by data index
  28087. sortedIndices.sort(function (a, b) {
  28088. return rawIndices[a] - rawIndices[b];
  28089. });
  28090. var sortedCurrPoints = [];
  28091. var sortedNextPoints = [];
  28092. var sortedCurrStackedPoints = [];
  28093. var sortedNextStackedPoints = [];
  28094. var sortedStatus = [];
  28095. for (var i = 0; i < sortedIndices.length; i++) {
  28096. var idx = sortedIndices[i];
  28097. sortedCurrPoints[i] = currPoints[idx];
  28098. sortedNextPoints[i] = nextPoints[idx];
  28099. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  28100. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  28101. sortedStatus[i] = status[idx];
  28102. }
  28103. return {
  28104. current: sortedCurrPoints,
  28105. next: sortedNextPoints,
  28106. stackedOnCurrent: sortedCurrStackedPoints,
  28107. stackedOnNext: sortedNextStackedPoints,
  28108. status: sortedStatus
  28109. };
  28110. };
  28111. // Poly path support NaN point
  28112. var vec2Min = min;
  28113. var vec2Max = max;
  28114. var scaleAndAdd$1 = scaleAndAdd;
  28115. var v2Copy = copy;
  28116. // Temporary variable
  28117. var v = [];
  28118. var cp0 = [];
  28119. var cp1 = [];
  28120. function isPointNull(p) {
  28121. return isNaN(p[0]) || isNaN(p[1]);
  28122. }
  28123. function drawSegment(
  28124. ctx, points, start, segLen, allLen,
  28125. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28126. ) {
  28127. if (smoothMonotone == null) {
  28128. if (isMono(points, 'x')) {
  28129. return drawMono(ctx, points, start, segLen, allLen,
  28130. dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  28131. }
  28132. else if (isMono(points, 'y')) {
  28133. return drawMono(ctx, points, start, segLen, allLen,
  28134. dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  28135. }
  28136. else {
  28137. return drawNonMono.apply(this, arguments);
  28138. }
  28139. }
  28140. else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  28141. return drawMono.apply(this, arguments);
  28142. }
  28143. else {
  28144. return drawNonMono.apply(this, arguments);
  28145. }
  28146. }
  28147. /**
  28148. * Check if points is in monotone.
  28149. *
  28150. * @param {number[][]} points Array of points which is in [x, y] form
  28151. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28152. * dimension that is checking.
  28153. * If is 'none', `drawNonMono` should be
  28154. * called.
  28155. * If is undefined, either being monotone
  28156. * in 'x' or 'y' will call `drawMono`.
  28157. */
  28158. function isMono(points, smoothMonotone) {
  28159. if (points.length <= 1) {
  28160. return true;
  28161. }
  28162. var dim = smoothMonotone === 'x' ? 0 : 1;
  28163. var last = points[0][dim];
  28164. var lastDiff = 0;
  28165. for (var i = 1; i < points.length; ++i) {
  28166. var diff = points[i][dim] - last;
  28167. if (!isNaN(diff) && !isNaN(lastDiff)
  28168. && diff !== 0 && lastDiff !== 0
  28169. && ((diff >= 0) !== (lastDiff >= 0))
  28170. ) {
  28171. return false;
  28172. }
  28173. if (!isNaN(diff) && diff !== 0) {
  28174. lastDiff = diff;
  28175. last = points[i][dim];
  28176. }
  28177. }
  28178. return true;
  28179. }
  28180. /**
  28181. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28182. * control points will be used. This should be used when points are monotone
  28183. * either in x or y dimension.
  28184. */
  28185. function drawMono(
  28186. ctx, points, start, segLen, allLen,
  28187. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28188. ) {
  28189. var prevIdx = 0;
  28190. var idx = start;
  28191. for (var k = 0; k < segLen; k++) {
  28192. var p = points[idx];
  28193. if (idx >= allLen || idx < 0) {
  28194. break;
  28195. }
  28196. if (isPointNull(p)) {
  28197. if (connectNulls) {
  28198. idx += dir;
  28199. continue;
  28200. }
  28201. break;
  28202. }
  28203. if (idx === start) {
  28204. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28205. }
  28206. else {
  28207. if (smooth > 0) {
  28208. var prevP = points[prevIdx];
  28209. var dim = smoothMonotone === 'y' ? 1 : 0;
  28210. // Length of control point to p, either in x or y, but not both
  28211. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28212. v2Copy(cp0, prevP);
  28213. cp0[dim] = prevP[dim] + ctrlLen;
  28214. v2Copy(cp1, p);
  28215. cp1[dim] = p[dim] - ctrlLen;
  28216. ctx.bezierCurveTo(
  28217. cp0[0], cp0[1],
  28218. cp1[0], cp1[1],
  28219. p[0], p[1]
  28220. );
  28221. }
  28222. else {
  28223. ctx.lineTo(p[0], p[1]);
  28224. }
  28225. }
  28226. prevIdx = idx;
  28227. idx += dir;
  28228. }
  28229. return k;
  28230. }
  28231. /**
  28232. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28233. * situations. This should be used when points are non-monotone neither in x or
  28234. * y dimension.
  28235. */
  28236. function drawNonMono(
  28237. ctx, points, start, segLen, allLen,
  28238. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28239. ) {
  28240. var prevIdx = 0;
  28241. var idx = start;
  28242. for (var k = 0; k < segLen; k++) {
  28243. var p = points[idx];
  28244. if (idx >= allLen || idx < 0) {
  28245. break;
  28246. }
  28247. if (isPointNull(p)) {
  28248. if (connectNulls) {
  28249. idx += dir;
  28250. continue;
  28251. }
  28252. break;
  28253. }
  28254. if (idx === start) {
  28255. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28256. v2Copy(cp0, p);
  28257. }
  28258. else {
  28259. if (smooth > 0) {
  28260. var nextIdx = idx + dir;
  28261. var nextP = points[nextIdx];
  28262. if (connectNulls) {
  28263. // Find next point not null
  28264. while (nextP && isPointNull(points[nextIdx])) {
  28265. nextIdx += dir;
  28266. nextP = points[nextIdx];
  28267. }
  28268. }
  28269. var ratioNextSeg = 0.5;
  28270. var prevP = points[prevIdx];
  28271. var nextP = points[nextIdx];
  28272. // Last point
  28273. if (!nextP || isPointNull(nextP)) {
  28274. v2Copy(cp1, p);
  28275. }
  28276. else {
  28277. // If next data is null in not connect case
  28278. if (isPointNull(nextP) && !connectNulls) {
  28279. nextP = p;
  28280. }
  28281. sub(v, nextP, prevP);
  28282. var lenPrevSeg;
  28283. var lenNextSeg;
  28284. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28285. var dim = smoothMonotone === 'x' ? 0 : 1;
  28286. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28287. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28288. }
  28289. else {
  28290. lenPrevSeg = dist(p, prevP);
  28291. lenNextSeg = dist(p, nextP);
  28292. }
  28293. // Use ratio of seg length
  28294. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28295. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28296. }
  28297. // Smooth constraint
  28298. vec2Min(cp0, cp0, smoothMax);
  28299. vec2Max(cp0, cp0, smoothMin);
  28300. vec2Min(cp1, cp1, smoothMax);
  28301. vec2Max(cp1, cp1, smoothMin);
  28302. ctx.bezierCurveTo(
  28303. cp0[0], cp0[1],
  28304. cp1[0], cp1[1],
  28305. p[0], p[1]
  28306. );
  28307. // cp0 of next segment
  28308. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28309. }
  28310. else {
  28311. ctx.lineTo(p[0], p[1]);
  28312. }
  28313. }
  28314. prevIdx = idx;
  28315. idx += dir;
  28316. }
  28317. return k;
  28318. }
  28319. function getBoundingBox(points, smoothConstraint) {
  28320. var ptMin = [Infinity, Infinity];
  28321. var ptMax = [-Infinity, -Infinity];
  28322. if (smoothConstraint) {
  28323. for (var i = 0; i < points.length; i++) {
  28324. var pt = points[i];
  28325. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  28326. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  28327. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  28328. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  28329. }
  28330. }
  28331. return {
  28332. min: smoothConstraint ? ptMin : ptMax,
  28333. max: smoothConstraint ? ptMax : ptMin
  28334. };
  28335. }
  28336. var Polyline$1 = Path.extend({
  28337. type: 'ec-polyline',
  28338. shape: {
  28339. points: [],
  28340. smooth: 0,
  28341. smoothConstraint: true,
  28342. smoothMonotone: null,
  28343. connectNulls: false
  28344. },
  28345. style: {
  28346. fill: null,
  28347. stroke: '#000'
  28348. },
  28349. brush: fixClipWithShadow(Path.prototype.brush),
  28350. buildPath: function (ctx, shape) {
  28351. var points = shape.points;
  28352. var i = 0;
  28353. var len$$1 = points.length;
  28354. var result = getBoundingBox(points, shape.smoothConstraint);
  28355. if (shape.connectNulls) {
  28356. // Must remove first and last null values avoid draw error in polygon
  28357. for (; len$$1 > 0; len$$1--) {
  28358. if (!isPointNull(points[len$$1 - 1])) {
  28359. break;
  28360. }
  28361. }
  28362. for (; i < len$$1; i++) {
  28363. if (!isPointNull(points[i])) {
  28364. break;
  28365. }
  28366. }
  28367. }
  28368. while (i < len$$1) {
  28369. i += drawSegment(
  28370. ctx, points, i, len$$1, len$$1,
  28371. 1, result.min, result.max, shape.smooth,
  28372. shape.smoothMonotone, shape.connectNulls
  28373. ) + 1;
  28374. }
  28375. }
  28376. });
  28377. var Polygon$1 = Path.extend({
  28378. type: 'ec-polygon',
  28379. shape: {
  28380. points: [],
  28381. // Offset between stacked base points and points
  28382. stackedOnPoints: [],
  28383. smooth: 0,
  28384. stackedOnSmooth: 0,
  28385. smoothConstraint: true,
  28386. smoothMonotone: null,
  28387. connectNulls: false
  28388. },
  28389. brush: fixClipWithShadow(Path.prototype.brush),
  28390. buildPath: function (ctx, shape) {
  28391. var points = shape.points;
  28392. var stackedOnPoints = shape.stackedOnPoints;
  28393. var i = 0;
  28394. var len$$1 = points.length;
  28395. var smoothMonotone = shape.smoothMonotone;
  28396. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28397. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28398. if (shape.connectNulls) {
  28399. // Must remove first and last null values avoid draw error in polygon
  28400. for (; len$$1 > 0; len$$1--) {
  28401. if (!isPointNull(points[len$$1 - 1])) {
  28402. break;
  28403. }
  28404. }
  28405. for (; i < len$$1; i++) {
  28406. if (!isPointNull(points[i])) {
  28407. break;
  28408. }
  28409. }
  28410. }
  28411. while (i < len$$1) {
  28412. var k = drawSegment(
  28413. ctx, points, i, len$$1, len$$1,
  28414. 1, bbox.min, bbox.max, shape.smooth,
  28415. smoothMonotone, shape.connectNulls
  28416. );
  28417. drawSegment(
  28418. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28419. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28420. smoothMonotone, shape.connectNulls
  28421. );
  28422. i += k + 1;
  28423. ctx.closePath();
  28424. }
  28425. }
  28426. });
  28427. // FIXME step not support polar
  28428. function isPointsSame(points1, points2) {
  28429. if (points1.length !== points2.length) {
  28430. return;
  28431. }
  28432. for (var i = 0; i < points1.length; i++) {
  28433. var p1 = points1[i];
  28434. var p2 = points2[i];
  28435. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28436. return;
  28437. }
  28438. }
  28439. return true;
  28440. }
  28441. function getSmooth(smooth) {
  28442. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28443. }
  28444. function getAxisExtentWithGap(axis) {
  28445. var extent = axis.getGlobalExtent();
  28446. if (axis.onBand) {
  28447. // Remove extra 1px to avoid line miter in clipped edge
  28448. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28449. var dir = extent[1] > extent[0] ? 1 : -1;
  28450. extent[0] += dir * halfBandWidth;
  28451. extent[1] -= dir * halfBandWidth;
  28452. }
  28453. return extent;
  28454. }
  28455. /**
  28456. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28457. * @param {module:echarts/data/List} data
  28458. * @param {Object} dataCoordInfo
  28459. * @param {Array.<Array.<number>>} points
  28460. */
  28461. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28462. if (!dataCoordInfo.valueDim) {
  28463. return [];
  28464. }
  28465. var points = [];
  28466. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28467. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28468. }
  28469. return points;
  28470. }
  28471. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  28472. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28473. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28474. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28475. var x = Math.min(xExtent[0], xExtent[1]);
  28476. var y = Math.min(yExtent[0], yExtent[1]);
  28477. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28478. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28479. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28480. // Expand clip shape to avoid clipping when line value exceeds axis
  28481. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28482. if (isHorizontal) {
  28483. y -= expandSize;
  28484. height += expandSize * 2;
  28485. }
  28486. else {
  28487. x -= expandSize;
  28488. width += expandSize * 2;
  28489. }
  28490. var clipPath = new Rect({
  28491. shape: {
  28492. x: x,
  28493. y: y,
  28494. width: width,
  28495. height: height
  28496. }
  28497. });
  28498. if (hasAnimation) {
  28499. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28500. initProps(clipPath, {
  28501. shape: {
  28502. width: width,
  28503. height: height
  28504. }
  28505. }, seriesModel);
  28506. }
  28507. return clipPath;
  28508. }
  28509. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  28510. var angleAxis = polar.getAngleAxis();
  28511. var radiusAxis = polar.getRadiusAxis();
  28512. var radiusExtent = radiusAxis.getExtent();
  28513. var angleExtent = angleAxis.getExtent();
  28514. var RADIAN = Math.PI / 180;
  28515. var clipPath = new Sector({
  28516. shape: {
  28517. cx: polar.cx,
  28518. cy: polar.cy,
  28519. r0: radiusExtent[0],
  28520. r: radiusExtent[1],
  28521. startAngle: -angleExtent[0] * RADIAN,
  28522. endAngle: -angleExtent[1] * RADIAN,
  28523. clockwise: angleAxis.inverse
  28524. }
  28525. });
  28526. if (hasAnimation) {
  28527. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28528. initProps(clipPath, {
  28529. shape: {
  28530. endAngle: -angleExtent[1] * RADIAN
  28531. }
  28532. }, seriesModel);
  28533. }
  28534. return clipPath;
  28535. }
  28536. function createClipShape(coordSys, hasAnimation, seriesModel) {
  28537. return coordSys.type === 'polar'
  28538. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  28539. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  28540. }
  28541. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28542. var baseAxis = coordSys.getBaseAxis();
  28543. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28544. var stepPoints = [];
  28545. for (var i = 0; i < points.length - 1; i++) {
  28546. var nextPt = points[i + 1];
  28547. var pt = points[i];
  28548. stepPoints.push(pt);
  28549. var stepPt = [];
  28550. switch (stepTurnAt) {
  28551. case 'end':
  28552. stepPt[baseIndex] = nextPt[baseIndex];
  28553. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28554. // default is start
  28555. stepPoints.push(stepPt);
  28556. break;
  28557. case 'middle':
  28558. // default is start
  28559. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28560. var stepPt2 = [];
  28561. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28562. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28563. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28564. stepPoints.push(stepPt);
  28565. stepPoints.push(stepPt2);
  28566. break;
  28567. default:
  28568. stepPt[baseIndex] = pt[baseIndex];
  28569. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28570. // default is start
  28571. stepPoints.push(stepPt);
  28572. }
  28573. }
  28574. // Last points
  28575. points[i] && stepPoints.push(points[i]);
  28576. return stepPoints;
  28577. }
  28578. function getVisualGradient(data, coordSys) {
  28579. var visualMetaList = data.getVisual('visualMeta');
  28580. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  28581. // When data.count() is 0, gradient range can not be calculated.
  28582. return;
  28583. }
  28584. if (coordSys.type !== 'cartesian2d') {
  28585. if (__DEV__) {
  28586. console.warn('Visual map on line style is only supported on cartesian2d.');
  28587. }
  28588. return;
  28589. }
  28590. var coordDim;
  28591. var visualMeta;
  28592. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  28593. var dimIndex = visualMetaList[i].dimension;
  28594. var dimName = data.dimensions[dimIndex];
  28595. var dimInfo = data.getDimensionInfo(dimName);
  28596. coordDim = dimInfo && dimInfo.coordDim;
  28597. // Can only be x or y
  28598. if (coordDim === 'x' || coordDim === 'y') {
  28599. visualMeta = visualMetaList[i];
  28600. break;
  28601. }
  28602. }
  28603. if (!visualMeta) {
  28604. if (__DEV__) {
  28605. console.warn('Visual map on line style only support x or y dimension.');
  28606. }
  28607. return;
  28608. }
  28609. // If the area to be rendered is bigger than area defined by LinearGradient,
  28610. // the canvas spec prescribes that the color of the first stop and the last
  28611. // stop should be used. But if two stops are added at offset 0, in effect
  28612. // browsers use the color of the second stop to render area outside
  28613. // LinearGradient. So we can only infinitesimally extend area defined in
  28614. // LinearGradient to render `outerColors`.
  28615. var axis = coordSys.getAxis(coordDim);
  28616. // dataToCoor mapping may not be linear, but must be monotonic.
  28617. var colorStops = map(visualMeta.stops, function (stop) {
  28618. return {
  28619. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  28620. color: stop.color
  28621. };
  28622. });
  28623. var stopLen = colorStops.length;
  28624. var outerColors = visualMeta.outerColors.slice();
  28625. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  28626. colorStops.reverse();
  28627. outerColors.reverse();
  28628. }
  28629. var tinyExtent = 10; // Arbitrary value: 10px
  28630. var minCoord = colorStops[0].coord - tinyExtent;
  28631. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  28632. var coordSpan = maxCoord - minCoord;
  28633. if (coordSpan < 1e-3) {
  28634. return 'transparent';
  28635. }
  28636. each$1(colorStops, function (stop) {
  28637. stop.offset = (stop.coord - minCoord) / coordSpan;
  28638. });
  28639. colorStops.push({
  28640. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  28641. color: outerColors[1] || 'transparent'
  28642. });
  28643. colorStops.unshift({ // notice colorStops.length have been changed.
  28644. offset: stopLen ? colorStops[0].offset : 0.5,
  28645. color: outerColors[0] || 'transparent'
  28646. });
  28647. // zrUtil.each(colorStops, function (colorStop) {
  28648. // // Make sure each offset has rounded px to avoid not sharp edge
  28649. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  28650. // });
  28651. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  28652. gradient[coordDim] = minCoord;
  28653. gradient[coordDim + '2'] = maxCoord;
  28654. return gradient;
  28655. }
  28656. Chart.extend({
  28657. type: 'line',
  28658. init: function () {
  28659. var lineGroup = new Group();
  28660. var symbolDraw = new SymbolDraw();
  28661. this.group.add(symbolDraw.group);
  28662. this._symbolDraw = symbolDraw;
  28663. this._lineGroup = lineGroup;
  28664. },
  28665. render: function (seriesModel, ecModel, api) {
  28666. var coordSys = seriesModel.coordinateSystem;
  28667. var group = this.group;
  28668. var data = seriesModel.getData();
  28669. var lineStyleModel = seriesModel.getModel('lineStyle');
  28670. var areaStyleModel = seriesModel.getModel('areaStyle');
  28671. var points = data.mapArray(data.getItemLayout);
  28672. var isCoordSysPolar = coordSys.type === 'polar';
  28673. var prevCoordSys = this._coordSys;
  28674. var symbolDraw = this._symbolDraw;
  28675. var polyline = this._polyline;
  28676. var polygon = this._polygon;
  28677. var lineGroup = this._lineGroup;
  28678. var hasAnimation = seriesModel.get('animation');
  28679. var isAreaChart = !areaStyleModel.isEmpty();
  28680. var valueOrigin = areaStyleModel.get('origin');
  28681. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  28682. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  28683. var showSymbol = seriesModel.get('showSymbol');
  28684. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  28685. && this._getSymbolIgnoreFunc(data, coordSys);
  28686. // Remove temporary symbols
  28687. var oldData = this._data;
  28688. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28689. if (el.__temp) {
  28690. group.remove(el);
  28691. oldData.setItemGraphicEl(idx, null);
  28692. }
  28693. });
  28694. // Remove previous created symbols if showSymbol changed to false
  28695. if (!showSymbol) {
  28696. symbolDraw.remove();
  28697. }
  28698. group.add(lineGroup);
  28699. // FIXME step not support polar
  28700. var step = !isCoordSysPolar && seriesModel.get('step');
  28701. // Initialization animation or coordinate system changed
  28702. if (
  28703. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  28704. ) {
  28705. showSymbol && symbolDraw.updateData(data, {
  28706. isIgnore: isSymbolIgnore,
  28707. clipShape: createClipShape(coordSys, false, seriesModel)
  28708. });
  28709. if (step) {
  28710. // TODO If stacked series is not step
  28711. points = turnPointsIntoStep(points, coordSys, step);
  28712. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28713. }
  28714. polyline = this._newPolyline(points, coordSys, hasAnimation);
  28715. if (isAreaChart) {
  28716. polygon = this._newPolygon(
  28717. points, stackedOnPoints,
  28718. coordSys, hasAnimation
  28719. );
  28720. }
  28721. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  28722. }
  28723. else {
  28724. if (isAreaChart && !polygon) {
  28725. // If areaStyle is added
  28726. polygon = this._newPolygon(
  28727. points, stackedOnPoints,
  28728. coordSys, hasAnimation
  28729. );
  28730. }
  28731. else if (polygon && !isAreaChart) {
  28732. // If areaStyle is removed
  28733. lineGroup.remove(polygon);
  28734. polygon = this._polygon = null;
  28735. }
  28736. var coordSysClipShape = createClipShape(coordSys, false, seriesModel);
  28737. // Update clipPath
  28738. lineGroup.setClipPath(coordSysClipShape);
  28739. // Always update, or it is wrong in the case turning on legend
  28740. // because points are not changed
  28741. showSymbol && symbolDraw.updateData(data, {
  28742. isIgnore: isSymbolIgnore,
  28743. clipShape: coordSysClipShape
  28744. });
  28745. // Stop symbol animation and sync with line points
  28746. // FIXME performance?
  28747. data.eachItemGraphicEl(function (el) {
  28748. el.stopAnimation(true);
  28749. });
  28750. // In the case data zoom triggerred refreshing frequently
  28751. // Data may not change if line has a category axis. So it should animate nothing
  28752. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  28753. || !isPointsSame(this._points, points)
  28754. ) {
  28755. if (hasAnimation) {
  28756. this._updateAnimation(
  28757. data, stackedOnPoints, coordSys, api, step, valueOrigin
  28758. );
  28759. }
  28760. else {
  28761. // Not do it in update with animation
  28762. if (step) {
  28763. // TODO If stacked series is not step
  28764. points = turnPointsIntoStep(points, coordSys, step);
  28765. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28766. }
  28767. polyline.setShape({
  28768. points: points
  28769. });
  28770. polygon && polygon.setShape({
  28771. points: points,
  28772. stackedOnPoints: stackedOnPoints
  28773. });
  28774. }
  28775. }
  28776. }
  28777. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28778. polyline.useStyle(defaults(
  28779. // Use color in lineStyle first
  28780. lineStyleModel.getLineStyle(),
  28781. {
  28782. fill: 'none',
  28783. stroke: visualColor,
  28784. lineJoin: 'bevel'
  28785. }
  28786. ));
  28787. var smooth = seriesModel.get('smooth');
  28788. smooth = getSmooth(seriesModel.get('smooth'));
  28789. polyline.setShape({
  28790. smooth: smooth,
  28791. smoothMonotone: seriesModel.get('smoothMonotone'),
  28792. connectNulls: seriesModel.get('connectNulls')
  28793. });
  28794. if (polygon) {
  28795. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  28796. var stackedOnSmooth = 0;
  28797. polygon.useStyle(defaults(
  28798. areaStyleModel.getAreaStyle(),
  28799. {
  28800. fill: visualColor,
  28801. opacity: 0.7,
  28802. lineJoin: 'bevel'
  28803. }
  28804. ));
  28805. if (stackedOnSeries) {
  28806. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28807. }
  28808. polygon.setShape({
  28809. smooth: smooth,
  28810. stackedOnSmooth: stackedOnSmooth,
  28811. smoothMonotone: seriesModel.get('smoothMonotone'),
  28812. connectNulls: seriesModel.get('connectNulls')
  28813. });
  28814. }
  28815. this._data = data;
  28816. // Save the coordinate system for transition animation when data changed
  28817. this._coordSys = coordSys;
  28818. this._stackedOnPoints = stackedOnPoints;
  28819. this._points = points;
  28820. this._step = step;
  28821. this._valueOrigin = valueOrigin;
  28822. },
  28823. dispose: function () {},
  28824. highlight: function (seriesModel, ecModel, api, payload) {
  28825. var data = seriesModel.getData();
  28826. var dataIndex = queryDataIndex(data, payload);
  28827. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28828. var symbol = data.getItemGraphicEl(dataIndex);
  28829. if (!symbol) {
  28830. // Create a temporary symbol if it is not exists
  28831. var pt = data.getItemLayout(dataIndex);
  28832. if (!pt) {
  28833. // Null data
  28834. return;
  28835. }
  28836. symbol = new SymbolClz$1(data, dataIndex);
  28837. symbol.position = pt;
  28838. symbol.setZ(
  28839. seriesModel.get('zlevel'),
  28840. seriesModel.get('z')
  28841. );
  28842. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28843. symbol.__temp = true;
  28844. data.setItemGraphicEl(dataIndex, symbol);
  28845. // Stop scale animation
  28846. symbol.stopSymbolAnimation(true);
  28847. this.group.add(symbol);
  28848. }
  28849. symbol.highlight();
  28850. }
  28851. else {
  28852. // Highlight whole series
  28853. Chart.prototype.highlight.call(
  28854. this, seriesModel, ecModel, api, payload
  28855. );
  28856. }
  28857. },
  28858. downplay: function (seriesModel, ecModel, api, payload) {
  28859. var data = seriesModel.getData();
  28860. var dataIndex = queryDataIndex(data, payload);
  28861. if (dataIndex != null && dataIndex >= 0) {
  28862. var symbol = data.getItemGraphicEl(dataIndex);
  28863. if (symbol) {
  28864. if (symbol.__temp) {
  28865. data.setItemGraphicEl(dataIndex, null);
  28866. this.group.remove(symbol);
  28867. }
  28868. else {
  28869. symbol.downplay();
  28870. }
  28871. }
  28872. }
  28873. else {
  28874. // FIXME
  28875. // can not downplay completely.
  28876. // Downplay whole series
  28877. Chart.prototype.downplay.call(
  28878. this, seriesModel, ecModel, api, payload
  28879. );
  28880. }
  28881. },
  28882. /**
  28883. * @param {module:zrender/container/Group} group
  28884. * @param {Array.<Array.<number>>} points
  28885. * @private
  28886. */
  28887. _newPolyline: function (points) {
  28888. var polyline = this._polyline;
  28889. // Remove previous created polyline
  28890. if (polyline) {
  28891. this._lineGroup.remove(polyline);
  28892. }
  28893. polyline = new Polyline$1({
  28894. shape: {
  28895. points: points
  28896. },
  28897. silent: true,
  28898. z2: 10
  28899. });
  28900. this._lineGroup.add(polyline);
  28901. this._polyline = polyline;
  28902. return polyline;
  28903. },
  28904. /**
  28905. * @param {module:zrender/container/Group} group
  28906. * @param {Array.<Array.<number>>} stackedOnPoints
  28907. * @param {Array.<Array.<number>>} points
  28908. * @private
  28909. */
  28910. _newPolygon: function (points, stackedOnPoints) {
  28911. var polygon = this._polygon;
  28912. // Remove previous created polygon
  28913. if (polygon) {
  28914. this._lineGroup.remove(polygon);
  28915. }
  28916. polygon = new Polygon$1({
  28917. shape: {
  28918. points: points,
  28919. stackedOnPoints: stackedOnPoints
  28920. },
  28921. silent: true
  28922. });
  28923. this._lineGroup.add(polygon);
  28924. this._polygon = polygon;
  28925. return polygon;
  28926. },
  28927. /**
  28928. * @private
  28929. */
  28930. _getSymbolIgnoreFunc: function (data, coordSys) {
  28931. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28932. // `getLabelInterval` is provided by echarts/component/axis
  28933. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28934. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28935. }
  28936. },
  28937. /**
  28938. * @private
  28939. */
  28940. // FIXME Two value axis
  28941. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  28942. var polyline = this._polyline;
  28943. var polygon = this._polygon;
  28944. var seriesModel = data.hostModel;
  28945. var diff = lineAnimationDiff(
  28946. this._data, data,
  28947. this._stackedOnPoints, stackedOnPoints,
  28948. this._coordSys, coordSys,
  28949. this._valueOrigin, valueOrigin
  28950. );
  28951. var current = diff.current;
  28952. var stackedOnCurrent = diff.stackedOnCurrent;
  28953. var next = diff.next;
  28954. var stackedOnNext = diff.stackedOnNext;
  28955. if (step) {
  28956. // TODO If stacked series is not step
  28957. current = turnPointsIntoStep(diff.current, coordSys, step);
  28958. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28959. next = turnPointsIntoStep(diff.next, coordSys, step);
  28960. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28961. }
  28962. // `diff.current` is subset of `current` (which should be ensured by
  28963. // turnPointsIntoStep), so points in `__points` can be updated when
  28964. // points in `current` are update during animation.
  28965. polyline.shape.__points = diff.current;
  28966. polyline.shape.points = current;
  28967. updateProps(polyline, {
  28968. shape: {
  28969. points: next
  28970. }
  28971. }, seriesModel);
  28972. if (polygon) {
  28973. polygon.setShape({
  28974. points: current,
  28975. stackedOnPoints: stackedOnCurrent
  28976. });
  28977. updateProps(polygon, {
  28978. shape: {
  28979. points: next,
  28980. stackedOnPoints: stackedOnNext
  28981. }
  28982. }, seriesModel);
  28983. }
  28984. var updatedDataInfo = [];
  28985. var diffStatus = diff.status;
  28986. for (var i = 0; i < diffStatus.length; i++) {
  28987. var cmd = diffStatus[i].cmd;
  28988. if (cmd === '=') {
  28989. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28990. if (el) {
  28991. updatedDataInfo.push({
  28992. el: el,
  28993. ptIdx: i // Index of points
  28994. });
  28995. }
  28996. }
  28997. }
  28998. if (polyline.animators && polyline.animators.length) {
  28999. polyline.animators[0].during(function () {
  29000. for (var i = 0; i < updatedDataInfo.length; i++) {
  29001. var el = updatedDataInfo[i].el;
  29002. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  29003. }
  29004. });
  29005. }
  29006. },
  29007. remove: function (ecModel) {
  29008. var group = this.group;
  29009. var oldData = this._data;
  29010. this._lineGroup.removeAll();
  29011. this._symbolDraw.remove(true);
  29012. // Remove temporary created elements when highlighting
  29013. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  29014. if (el.__temp) {
  29015. group.remove(el);
  29016. oldData.setItemGraphicEl(idx, null);
  29017. }
  29018. });
  29019. this._polyline =
  29020. this._polygon =
  29021. this._coordSys =
  29022. this._points =
  29023. this._stackedOnPoints =
  29024. this._data = null;
  29025. }
  29026. });
  29027. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  29028. // Encoding visual for all series include which is filtered for legend drawing
  29029. return {
  29030. seriesType: seriesType,
  29031. performRawSeries: true,
  29032. reset: function (seriesModel, ecModel, api) {
  29033. var data = seriesModel.getData();
  29034. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  29035. var symbolSize = seriesModel.get('symbolSize');
  29036. data.setVisual({
  29037. legendSymbol: legendSymbol || symbolType,
  29038. symbol: symbolType,
  29039. symbolSize: symbolSize
  29040. });
  29041. // Only visible series has each data be visual encoded
  29042. if (ecModel.isSeriesFiltered(seriesModel)) {
  29043. return;
  29044. }
  29045. var hasCallback = typeof symbolSize === 'function';
  29046. function dataEach(data, idx) {
  29047. if (typeof symbolSize === 'function') {
  29048. var rawValue = seriesModel.getRawValue(idx);
  29049. // FIXME
  29050. var params = seriesModel.getDataParams(idx);
  29051. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  29052. }
  29053. if (data.hasItemOption) {
  29054. var itemModel = data.getItemModel(idx);
  29055. var itemSymbolType = itemModel.getShallow('symbol', true);
  29056. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  29057. // If has item symbol
  29058. if (itemSymbolType != null) {
  29059. data.setItemVisual(idx, 'symbol', itemSymbolType);
  29060. }
  29061. if (itemSymbolSize != null) {
  29062. // PENDING Transform symbolSize ?
  29063. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  29064. }
  29065. }
  29066. }
  29067. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  29068. }
  29069. };
  29070. };
  29071. var pointsLayout = function (seriesType) {
  29072. return {
  29073. seriesType: seriesType,
  29074. plan: createRenderPlanner(),
  29075. reset: function (seriesModel) {
  29076. var data = seriesModel.getData();
  29077. var coordSys = seriesModel.coordinateSystem;
  29078. var pipelineContext = seriesModel.pipelineContext;
  29079. var isLargeRender = pipelineContext.large;
  29080. if (!coordSys) {
  29081. return;
  29082. }
  29083. var dims = map(coordSys.dimensions, function (dim) {
  29084. return data.mapDimension(dim);
  29085. }).slice(0, 2);
  29086. var dimLen = dims.length;
  29087. if (isDimensionStacked(data, dims[0], dims[1])) {
  29088. dims[0] = data.getCalculationInfo('stackResultDimension');
  29089. }
  29090. if (isDimensionStacked(data, dims[1], dims[0])) {
  29091. dims[1] = data.getCalculationInfo('stackResultDimension');
  29092. }
  29093. function progress(params, data) {
  29094. var segCount = params.end - params.start;
  29095. var points = isLargeRender && new Float32Array(segCount * dimLen);
  29096. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  29097. var point;
  29098. if (dimLen === 1) {
  29099. var x = data.get(dims[0], i, true);
  29100. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  29101. }
  29102. else {
  29103. var x = tmpIn[0] = data.get(dims[0], i, true);
  29104. var y = tmpIn[1] = data.get(dims[1], i, true);
  29105. // Also {Array.<number>}, not undefined to avoid if...else... statement
  29106. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  29107. }
  29108. if (isLargeRender) {
  29109. points[offset++] = point ? point[0] : NaN;
  29110. points[offset++] = point ? point[1] : NaN;
  29111. }
  29112. else {
  29113. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  29114. }
  29115. }
  29116. isLargeRender && data.setLayout('symbolPoints', points);
  29117. }
  29118. return dimLen && {progress: progress};
  29119. }
  29120. };
  29121. };
  29122. var samplers = {
  29123. average: function (frame) {
  29124. var sum = 0;
  29125. var count = 0;
  29126. for (var i = 0; i < frame.length; i++) {
  29127. if (!isNaN(frame[i])) {
  29128. sum += frame[i];
  29129. count++;
  29130. }
  29131. }
  29132. // Return NaN if count is 0
  29133. return count === 0 ? NaN : sum / count;
  29134. },
  29135. sum: function (frame) {
  29136. var sum = 0;
  29137. for (var i = 0; i < frame.length; i++) {
  29138. // Ignore NaN
  29139. sum += frame[i] || 0;
  29140. }
  29141. return sum;
  29142. },
  29143. max: function (frame) {
  29144. var max = -Infinity;
  29145. for (var i = 0; i < frame.length; i++) {
  29146. frame[i] > max && (max = frame[i]);
  29147. }
  29148. return max;
  29149. },
  29150. min: function (frame) {
  29151. var min = Infinity;
  29152. for (var i = 0; i < frame.length; i++) {
  29153. frame[i] < min && (min = frame[i]);
  29154. }
  29155. return min;
  29156. },
  29157. // TODO
  29158. // Median
  29159. nearest: function (frame) {
  29160. return frame[0];
  29161. }
  29162. };
  29163. var indexSampler = function (frame, value) {
  29164. return Math.round(frame.length / 2);
  29165. };
  29166. var dataSample = function (seriesType) {
  29167. return {
  29168. seriesType: seriesType,
  29169. reset: function (seriesModel, ecModel, api) {
  29170. var data = seriesModel.getData();
  29171. var sampling = seriesModel.get('sampling');
  29172. var coordSys = seriesModel.coordinateSystem;
  29173. // Only cartesian2d support down sampling
  29174. if (coordSys.type === 'cartesian2d' && sampling) {
  29175. var baseAxis = coordSys.getBaseAxis();
  29176. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29177. var extent = baseAxis.getExtent();
  29178. // Coordinste system has been resized
  29179. var size = extent[1] - extent[0];
  29180. var rate = Math.round(data.count() / size);
  29181. if (rate > 1) {
  29182. var sampler;
  29183. if (typeof sampling === 'string') {
  29184. sampler = samplers[sampling];
  29185. }
  29186. else if (typeof sampling === 'function') {
  29187. sampler = sampling;
  29188. }
  29189. if (sampler) {
  29190. seriesModel.setData(data.downSample(
  29191. valueAxis.dim, 1 / rate, sampler, indexSampler
  29192. ));
  29193. }
  29194. }
  29195. }
  29196. }
  29197. };
  29198. };
  29199. /**
  29200. * Cartesian coordinate system
  29201. * @module echarts/coord/Cartesian
  29202. *
  29203. */
  29204. function dimAxisMapper(dim) {
  29205. return this._axes[dim];
  29206. }
  29207. /**
  29208. * @alias module:echarts/coord/Cartesian
  29209. * @constructor
  29210. */
  29211. var Cartesian = function (name) {
  29212. this._axes = {};
  29213. this._dimList = [];
  29214. /**
  29215. * @type {string}
  29216. */
  29217. this.name = name || '';
  29218. };
  29219. Cartesian.prototype = {
  29220. constructor: Cartesian,
  29221. type: 'cartesian',
  29222. /**
  29223. * Get axis
  29224. * @param {number|string} dim
  29225. * @return {module:echarts/coord/Cartesian~Axis}
  29226. */
  29227. getAxis: function (dim) {
  29228. return this._axes[dim];
  29229. },
  29230. /**
  29231. * Get axes list
  29232. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  29233. */
  29234. getAxes: function () {
  29235. return map(this._dimList, dimAxisMapper, this);
  29236. },
  29237. /**
  29238. * Get axes list by given scale type
  29239. */
  29240. getAxesByScale: function (scaleType) {
  29241. scaleType = scaleType.toLowerCase();
  29242. return filter(
  29243. this.getAxes(),
  29244. function (axis) {
  29245. return axis.scale.type === scaleType;
  29246. }
  29247. );
  29248. },
  29249. /**
  29250. * Add axis
  29251. * @param {module:echarts/coord/Cartesian.Axis}
  29252. */
  29253. addAxis: function (axis) {
  29254. var dim = axis.dim;
  29255. this._axes[dim] = axis;
  29256. this._dimList.push(dim);
  29257. },
  29258. /**
  29259. * Convert data to coord in nd space
  29260. * @param {Array.<number>|Object.<string, number>} val
  29261. * @return {Array.<number>|Object.<string, number>}
  29262. */
  29263. dataToCoord: function (val) {
  29264. return this._dataCoordConvert(val, 'dataToCoord');
  29265. },
  29266. /**
  29267. * Convert coord in nd space to data
  29268. * @param {Array.<number>|Object.<string, number>} val
  29269. * @return {Array.<number>|Object.<string, number>}
  29270. */
  29271. coordToData: function (val) {
  29272. return this._dataCoordConvert(val, 'coordToData');
  29273. },
  29274. _dataCoordConvert: function (input, method) {
  29275. var dimList = this._dimList;
  29276. var output = input instanceof Array ? [] : {};
  29277. for (var i = 0; i < dimList.length; i++) {
  29278. var dim = dimList[i];
  29279. var axis = this._axes[dim];
  29280. output[dim] = axis[method](input[dim]);
  29281. }
  29282. return output;
  29283. }
  29284. };
  29285. function Cartesian2D(name) {
  29286. Cartesian.call(this, name);
  29287. }
  29288. Cartesian2D.prototype = {
  29289. constructor: Cartesian2D,
  29290. type: 'cartesian2d',
  29291. /**
  29292. * @type {Array.<string>}
  29293. * @readOnly
  29294. */
  29295. dimensions: ['x', 'y'],
  29296. /**
  29297. * Base axis will be used on stacking.
  29298. *
  29299. * @return {module:echarts/coord/cartesian/Axis2D}
  29300. */
  29301. getBaseAxis: function () {
  29302. return this.getAxesByScale('ordinal')[0]
  29303. || this.getAxesByScale('time')[0]
  29304. || this.getAxis('x');
  29305. },
  29306. /**
  29307. * If contain point
  29308. * @param {Array.<number>} point
  29309. * @return {boolean}
  29310. */
  29311. containPoint: function (point) {
  29312. var axisX = this.getAxis('x');
  29313. var axisY = this.getAxis('y');
  29314. return axisX.contain(axisX.toLocalCoord(point[0]))
  29315. && axisY.contain(axisY.toLocalCoord(point[1]));
  29316. },
  29317. /**
  29318. * If contain data
  29319. * @param {Array.<number>} data
  29320. * @return {boolean}
  29321. */
  29322. containData: function (data) {
  29323. return this.getAxis('x').containData(data[0])
  29324. && this.getAxis('y').containData(data[1]);
  29325. },
  29326. /**
  29327. * @param {Array.<number>} data
  29328. * @param {Array.<number>} out
  29329. * @return {Array.<number>}
  29330. */
  29331. dataToPoint: function (data, reserved, out) {
  29332. var xAxis = this.getAxis('x');
  29333. var yAxis = this.getAxis('y');
  29334. out = out || [];
  29335. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  29336. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  29337. return out;
  29338. },
  29339. /**
  29340. * @param {Array.<number>} data
  29341. * @param {Array.<number>} out
  29342. * @return {Array.<number>}
  29343. */
  29344. clampData: function (data, out) {
  29345. var xAxisExtent = this.getAxis('x').scale.getExtent();
  29346. var yAxisExtent = this.getAxis('y').scale.getExtent();
  29347. out = out || [];
  29348. out[0] = Math.min(
  29349. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  29350. Math.max(xAxisExtent[0], xAxisExtent[1])
  29351. );
  29352. out[1] = Math.min(
  29353. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  29354. Math.max(yAxisExtent[0], yAxisExtent[1])
  29355. );
  29356. return out;
  29357. },
  29358. /**
  29359. * @param {Array.<number>} point
  29360. * @param {Array.<number>} out
  29361. * @return {Array.<number>}
  29362. */
  29363. pointToData: function (point, out) {
  29364. var xAxis = this.getAxis('x');
  29365. var yAxis = this.getAxis('y');
  29366. out = out || [];
  29367. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  29368. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  29369. return out;
  29370. },
  29371. /**
  29372. * Get other axis
  29373. * @param {module:echarts/coord/cartesian/Axis2D} axis
  29374. */
  29375. getOtherAxis: function (axis) {
  29376. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  29377. }
  29378. };
  29379. inherits(Cartesian2D, Cartesian);
  29380. /**
  29381. * Extend axis 2d
  29382. * @constructor module:echarts/coord/cartesian/Axis2D
  29383. * @extends {module:echarts/coord/cartesian/Axis}
  29384. * @param {string} dim
  29385. * @param {*} scale
  29386. * @param {Array.<number>} coordExtent
  29387. * @param {string} axisType
  29388. * @param {string} position
  29389. */
  29390. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  29391. Axis.call(this, dim, scale, coordExtent);
  29392. /**
  29393. * Axis type
  29394. * - 'category'
  29395. * - 'value'
  29396. * - 'time'
  29397. * - 'log'
  29398. * @type {string}
  29399. */
  29400. this.type = axisType || 'value';
  29401. /**
  29402. * Axis position
  29403. * - 'top'
  29404. * - 'bottom'
  29405. * - 'left'
  29406. * - 'right'
  29407. */
  29408. this.position = position || 'bottom';
  29409. };
  29410. Axis2D.prototype = {
  29411. constructor: Axis2D,
  29412. /**
  29413. * Index of axis, can be used as key
  29414. */
  29415. index: 0,
  29416. /**
  29417. * If axis is on the zero position of the other axis
  29418. * @type {boolean}
  29419. */
  29420. onZero: false,
  29421. /**
  29422. * Axis model
  29423. * @param {module:echarts/coord/cartesian/AxisModel}
  29424. */
  29425. model: null,
  29426. isHorizontal: function () {
  29427. var position = this.position;
  29428. return position === 'top' || position === 'bottom';
  29429. },
  29430. /**
  29431. * Each item cooresponds to this.getExtent(), which
  29432. * means globalExtent[0] may greater than globalExtent[1],
  29433. * unless `asc` is input.
  29434. *
  29435. * @param {boolean} [asc]
  29436. * @return {Array.<number>}
  29437. */
  29438. getGlobalExtent: function (asc) {
  29439. var ret = this.getExtent();
  29440. ret[0] = this.toGlobalCoord(ret[0]);
  29441. ret[1] = this.toGlobalCoord(ret[1]);
  29442. asc && ret[0] > ret[1] && ret.reverse();
  29443. return ret;
  29444. },
  29445. getOtherAxis: function () {
  29446. this.grid.getOtherAxis();
  29447. },
  29448. /**
  29449. * If label is ignored.
  29450. * Automatically used when axis is category and label can not be all shown
  29451. * @param {number} idx
  29452. * @return {boolean}
  29453. */
  29454. isLabelIgnored: function (idx) {
  29455. if (this.type === 'category') {
  29456. var labelInterval = this.getLabelInterval();
  29457. return ((typeof labelInterval === 'function')
  29458. && !labelInterval(idx, this.scale.getLabel(idx)))
  29459. || idx % (labelInterval + 1);
  29460. }
  29461. },
  29462. /**
  29463. * @override
  29464. */
  29465. pointToData: function (point, clamp) {
  29466. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  29467. },
  29468. /**
  29469. * Transform global coord to local coord,
  29470. * i.e. var localCoord = axis.toLocalCoord(80);
  29471. * designate by module:echarts/coord/cartesian/Grid.
  29472. * @type {Function}
  29473. */
  29474. toLocalCoord: null,
  29475. /**
  29476. * Transform global coord to local coord,
  29477. * i.e. var globalCoord = axis.toLocalCoord(40);
  29478. * designate by module:echarts/coord/cartesian/Grid.
  29479. * @type {Function}
  29480. */
  29481. toGlobalCoord: null
  29482. };
  29483. inherits(Axis2D, Axis);
  29484. var defaultOption = {
  29485. show: true,
  29486. zlevel: 0, // 一级层叠
  29487. z: 0, // 二级层叠
  29488. // 反向坐标轴
  29489. inverse: false,
  29490. // 坐标轴名字,默认为空
  29491. name: '',
  29492. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  29493. nameLocation: 'end',
  29494. // 坐标轴名字旋转,degree。
  29495. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  29496. nameTruncate: {
  29497. maxWidth: null,
  29498. ellipsis: '...',
  29499. placeholder: '.'
  29500. },
  29501. // 坐标轴文字样式,默认取全局样式
  29502. nameTextStyle: {},
  29503. // 文字与轴线距离
  29504. nameGap: 15,
  29505. silent: false, // Default false to support tooltip.
  29506. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  29507. tooltip: {
  29508. show: false
  29509. },
  29510. axisPointer: {},
  29511. // 坐标轴线
  29512. axisLine: {
  29513. // 默认显示,属性show控制显示与否
  29514. show: true,
  29515. onZero: true,
  29516. onZeroAxisIndex: null,
  29517. // 属性lineStyle控制线条样式
  29518. lineStyle: {
  29519. color: '#333',
  29520. width: 1,
  29521. type: 'solid'
  29522. },
  29523. // 坐标轴两端的箭头
  29524. symbol: ['none', 'none'],
  29525. symbolSize: [10, 15]
  29526. },
  29527. // 坐标轴小标记
  29528. axisTick: {
  29529. // 属性show控制显示与否,默认显示
  29530. show: true,
  29531. // 控制小标记是否在grid里
  29532. inside: false,
  29533. // 属性length控制线长
  29534. length: 5,
  29535. // 属性lineStyle控制线条样式
  29536. lineStyle: {
  29537. width: 1
  29538. }
  29539. },
  29540. // 坐标轴文本标签,详见axis.axisLabel
  29541. axisLabel: {
  29542. show: true,
  29543. // 控制文本标签是否在grid里
  29544. inside: false,
  29545. rotate: 0,
  29546. showMinLabel: null, // true | false | null (auto)
  29547. showMaxLabel: null, // true | false | null (auto)
  29548. margin: 8,
  29549. // formatter: null,
  29550. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  29551. fontSize: 12
  29552. },
  29553. // 分隔线
  29554. splitLine: {
  29555. // 默认显示,属性show控制显示与否
  29556. show: true,
  29557. // 属性lineStyle(详见lineStyle)控制线条样式
  29558. lineStyle: {
  29559. color: ['#ccc'],
  29560. width: 1,
  29561. type: 'solid'
  29562. }
  29563. },
  29564. // 分隔区域
  29565. splitArea: {
  29566. // 默认不显示,属性show控制显示与否
  29567. show: false,
  29568. // 属性areaStyle(详见areaStyle)控制区域样式
  29569. areaStyle: {
  29570. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  29571. }
  29572. }
  29573. };
  29574. var axisDefault = {};
  29575. axisDefault.categoryAxis = merge({
  29576. // 类目起始和结束两端空白策略
  29577. boundaryGap: true,
  29578. // Set false to faster category collection.
  29579. // Only usefull in the case like: category is
  29580. // ['2012-01-01', '2012-01-02', ...], where the input
  29581. // data has been ensured not duplicate and is large data.
  29582. // null means "auto":
  29583. // if axis.data provided, do not deduplication,
  29584. // else do deduplication.
  29585. deduplication: null,
  29586. // splitArea: {
  29587. // show: false
  29588. // },
  29589. splitLine: {
  29590. show: false
  29591. },
  29592. // 坐标轴小标记
  29593. axisTick: {
  29594. // If tick is align with label when boundaryGap is true
  29595. alignWithLabel: false,
  29596. interval: 'auto'
  29597. },
  29598. // 坐标轴文本标签,详见axis.axisLabel
  29599. axisLabel: {
  29600. interval: 'auto'
  29601. }
  29602. }, defaultOption);
  29603. axisDefault.valueAxis = merge({
  29604. // 数值起始和结束两端空白策略
  29605. boundaryGap: [0, 0],
  29606. // TODO
  29607. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  29608. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  29609. // min: null,
  29610. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  29611. // max: null,
  29612. // Readonly prop, specifies start value of the range when using data zoom.
  29613. // rangeStart: null
  29614. // Readonly prop, specifies end value of the range when using data zoom.
  29615. // rangeEnd: null
  29616. // 脱离0值比例,放大聚焦到最终_min,_max区间
  29617. // scale: false,
  29618. // 分割段数,默认为5
  29619. splitNumber: 5
  29620. // Minimum interval
  29621. // minInterval: null
  29622. // maxInterval: null
  29623. }, defaultOption);
  29624. // FIXME
  29625. axisDefault.timeAxis = defaults({
  29626. scale: true,
  29627. min: 'dataMin',
  29628. max: 'dataMax'
  29629. }, axisDefault.valueAxis);
  29630. axisDefault.logAxis = defaults({
  29631. scale: true,
  29632. logBase: 10
  29633. }, axisDefault.valueAxis);
  29634. // FIXME axisType is fixed ?
  29635. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  29636. /**
  29637. * Generate sub axis model class
  29638. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  29639. * @param {module:echarts/model/Component} BaseAxisModelClass
  29640. * @param {Function} axisTypeDefaulter
  29641. * @param {Object} [extraDefaultOption]
  29642. */
  29643. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  29644. each$1(AXIS_TYPES, function (axisType) {
  29645. BaseAxisModelClass.extend({
  29646. /**
  29647. * @readOnly
  29648. */
  29649. type: axisName + 'Axis.' + axisType,
  29650. mergeDefaultAndTheme: function (option, ecModel) {
  29651. var layoutMode = this.layoutMode;
  29652. var inputPositionParams = layoutMode
  29653. ? getLayoutParams(option) : {};
  29654. var themeModel = ecModel.getTheme();
  29655. merge(option, themeModel.get(axisType + 'Axis'));
  29656. merge(option, this.getDefaultOption());
  29657. option.type = axisTypeDefaulter(axisName, option);
  29658. if (layoutMode) {
  29659. mergeLayoutParam(option, inputPositionParams, layoutMode);
  29660. }
  29661. },
  29662. /**
  29663. * @override
  29664. */
  29665. optionUpdated: function () {
  29666. var thisOption = this.option;
  29667. if (thisOption.type === 'category') {
  29668. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  29669. }
  29670. },
  29671. /**
  29672. * Should not be called before all of 'getInitailData' finished.
  29673. * Because categories are collected during initializing data.
  29674. */
  29675. getCategories: function () {
  29676. // FIXME
  29677. // warning if called before all of 'getInitailData' finished.
  29678. if (this.option.type === 'category') {
  29679. return this.__ordinalMeta.categories;
  29680. }
  29681. },
  29682. getOrdinalMeta: function () {
  29683. return this.__ordinalMeta;
  29684. },
  29685. defaultOption: mergeAll(
  29686. [
  29687. {},
  29688. axisDefault[axisType + 'Axis'],
  29689. extraDefaultOption
  29690. ],
  29691. true
  29692. )
  29693. });
  29694. });
  29695. ComponentModel.registerSubTypeDefaulter(
  29696. axisName + 'Axis',
  29697. curry(axisTypeDefaulter, axisName)
  29698. );
  29699. };
  29700. var AxisModel = ComponentModel.extend({
  29701. type: 'cartesian2dAxis',
  29702. /**
  29703. * @type {module:echarts/coord/cartesian/Axis2D}
  29704. */
  29705. axis: null,
  29706. /**
  29707. * @override
  29708. */
  29709. init: function () {
  29710. AxisModel.superApply(this, 'init', arguments);
  29711. this.resetRange();
  29712. },
  29713. /**
  29714. * @override
  29715. */
  29716. mergeOption: function () {
  29717. AxisModel.superApply(this, 'mergeOption', arguments);
  29718. this.resetRange();
  29719. },
  29720. /**
  29721. * @override
  29722. */
  29723. restoreData: function () {
  29724. AxisModel.superApply(this, 'restoreData', arguments);
  29725. this.resetRange();
  29726. },
  29727. /**
  29728. * @override
  29729. * @return {module:echarts/model/Component}
  29730. */
  29731. getCoordSysModel: function () {
  29732. return this.ecModel.queryComponents({
  29733. mainType: 'grid',
  29734. index: this.option.gridIndex,
  29735. id: this.option.gridId
  29736. })[0];
  29737. }
  29738. });
  29739. function getAxisType(axisDim, option) {
  29740. // Default axis with data is category axis
  29741. return option.type || (option.data ? 'category' : 'value');
  29742. }
  29743. merge(AxisModel.prototype, axisModelCommonMixin);
  29744. var extraOption = {
  29745. // gridIndex: 0,
  29746. // gridId: '',
  29747. // Offset is for multiple axis on the same position
  29748. offset: 0
  29749. };
  29750. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  29751. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  29752. // Grid 是在有直角坐标系的时候必须要存在的
  29753. // 所以这里也要被 Cartesian2D 依赖
  29754. ComponentModel.extend({
  29755. type: 'grid',
  29756. dependencies: ['xAxis', 'yAxis'],
  29757. layoutMode: 'box',
  29758. /**
  29759. * @type {module:echarts/coord/cartesian/Grid}
  29760. */
  29761. coordinateSystem: null,
  29762. defaultOption: {
  29763. show: false,
  29764. zlevel: 0,
  29765. z: 0,
  29766. left: '10%',
  29767. top: 60,
  29768. right: '10%',
  29769. bottom: 60,
  29770. // If grid size contain label
  29771. containLabel: false,
  29772. // width: {totalWidth} - left - right,
  29773. // height: {totalHeight} - top - bottom,
  29774. backgroundColor: 'rgba(0,0,0,0)',
  29775. borderWidth: 1,
  29776. borderColor: '#ccc'
  29777. }
  29778. });
  29779. /**
  29780. * Grid is a region which contains at most 4 cartesian systems
  29781. *
  29782. * TODO Default cartesian
  29783. */
  29784. // Depends on GridModel, AxisModel, which performs preprocess.
  29785. var each$6 = each$1;
  29786. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29787. var niceScaleExtent$1 = niceScaleExtent;
  29788. /**
  29789. * Check if the axis is used in the specified grid
  29790. * @inner
  29791. */
  29792. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29793. return axisModel.getCoordSysModel() === gridModel;
  29794. }
  29795. function rotateTextRect(textRect, rotate) {
  29796. var rotateRadians = rotate * Math.PI / 180;
  29797. var boundingBox = textRect.plain();
  29798. var beforeWidth = boundingBox.width;
  29799. var beforeHeight = boundingBox.height;
  29800. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29801. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29802. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29803. return rotatedRect;
  29804. }
  29805. function getLabelUnionRect(axis) {
  29806. var axisModel = axis.model;
  29807. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29808. var axisLabelModel = axisModel.getModel('axisLabel');
  29809. var rect;
  29810. var step = 1;
  29811. var labelCount = labels.length;
  29812. if (labelCount > 40) {
  29813. // Simple optimization for large amount of labels
  29814. step = Math.ceil(labelCount / 40);
  29815. }
  29816. for (var i = 0; i < labelCount; i += step) {
  29817. if (!axis.isLabelIgnored(i)) {
  29818. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29819. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29820. rect ? rect.union(singleRect) : (rect = singleRect);
  29821. }
  29822. }
  29823. return rect;
  29824. }
  29825. function Grid(gridModel, ecModel, api) {
  29826. /**
  29827. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29828. * @private
  29829. */
  29830. this._coordsMap = {};
  29831. /**
  29832. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29833. * @private
  29834. */
  29835. this._coordsList = [];
  29836. /**
  29837. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29838. * @private
  29839. */
  29840. this._axesMap = {};
  29841. /**
  29842. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29843. * @private
  29844. */
  29845. this._axesList = [];
  29846. this._initCartesian(gridModel, ecModel, api);
  29847. this.model = gridModel;
  29848. }
  29849. var gridProto = Grid.prototype;
  29850. gridProto.type = 'grid';
  29851. gridProto.axisPointerEnabled = true;
  29852. gridProto.getRect = function () {
  29853. return this._rect;
  29854. };
  29855. gridProto.update = function (ecModel, api) {
  29856. var axesMap = this._axesMap;
  29857. this._updateScale(ecModel, this.model);
  29858. each$6(axesMap.x, function (xAxis) {
  29859. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29860. });
  29861. each$6(axesMap.y, function (yAxis) {
  29862. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29863. });
  29864. each$6(axesMap.x, function (xAxis) {
  29865. fixAxisOnZero(axesMap, 'y', xAxis);
  29866. });
  29867. each$6(axesMap.y, function (yAxis) {
  29868. fixAxisOnZero(axesMap, 'x', yAxis);
  29869. });
  29870. // Resize again if containLabel is enabled
  29871. // FIXME It may cause getting wrong grid size in data processing stage
  29872. this.resize(this.model, api);
  29873. };
  29874. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29875. // onZero can not be enabled in these two situations:
  29876. // 1. When any other axis is a category axis.
  29877. // 2. When no axis is cross 0 point.
  29878. var axes = axesMap[otherAxisDim];
  29879. if (!axis.onZero) {
  29880. return;
  29881. }
  29882. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29883. // If target axis is specified.
  29884. if (onZeroAxisIndex != null) {
  29885. var otherAxis = axes[onZeroAxisIndex];
  29886. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29887. axis.onZero = false;
  29888. }
  29889. return;
  29890. }
  29891. for (var idx in axes) {
  29892. if (axes.hasOwnProperty(idx)) {
  29893. var otherAxis = axes[idx];
  29894. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29895. onZeroAxisIndex = +idx;
  29896. break;
  29897. }
  29898. }
  29899. }
  29900. if (onZeroAxisIndex == null) {
  29901. axis.onZero = false;
  29902. }
  29903. axis.onZeroAxisIndex = onZeroAxisIndex;
  29904. }
  29905. function canNotOnZeroToAxis(axis) {
  29906. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29907. }
  29908. /**
  29909. * Resize the grid
  29910. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29911. * @param {module:echarts/ExtensionAPI} api
  29912. */
  29913. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29914. var gridRect = getLayoutRect(
  29915. gridModel.getBoxLayoutParams(), {
  29916. width: api.getWidth(),
  29917. height: api.getHeight()
  29918. });
  29919. this._rect = gridRect;
  29920. var axesList = this._axesList;
  29921. adjustAxes();
  29922. // Minus label size
  29923. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29924. each$6(axesList, function (axis) {
  29925. if (!axis.model.get('axisLabel.inside')) {
  29926. var labelUnionRect = getLabelUnionRect(axis);
  29927. if (labelUnionRect) {
  29928. var dim = axis.isHorizontal() ? 'height' : 'width';
  29929. var margin = axis.model.get('axisLabel.margin');
  29930. gridRect[dim] -= labelUnionRect[dim] + margin;
  29931. if (axis.position === 'top') {
  29932. gridRect.y += labelUnionRect.height + margin;
  29933. }
  29934. else if (axis.position === 'left') {
  29935. gridRect.x += labelUnionRect.width + margin;
  29936. }
  29937. }
  29938. }
  29939. });
  29940. adjustAxes();
  29941. }
  29942. function adjustAxes() {
  29943. each$6(axesList, function (axis) {
  29944. var isHorizontal = axis.isHorizontal();
  29945. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29946. var idx = axis.inverse ? 1 : 0;
  29947. axis.setExtent(extent[idx], extent[1 - idx]);
  29948. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29949. });
  29950. }
  29951. };
  29952. /**
  29953. * @param {string} axisType
  29954. * @param {number} [axisIndex]
  29955. */
  29956. gridProto.getAxis = function (axisType, axisIndex) {
  29957. var axesMapOnDim = this._axesMap[axisType];
  29958. if (axesMapOnDim != null) {
  29959. if (axisIndex == null) {
  29960. // Find first axis
  29961. for (var name in axesMapOnDim) {
  29962. if (axesMapOnDim.hasOwnProperty(name)) {
  29963. return axesMapOnDim[name];
  29964. }
  29965. }
  29966. }
  29967. return axesMapOnDim[axisIndex];
  29968. }
  29969. };
  29970. /**
  29971. * @return {Array.<module:echarts/coord/Axis>}
  29972. */
  29973. gridProto.getAxes = function () {
  29974. return this._axesList.slice();
  29975. };
  29976. /**
  29977. * Usage:
  29978. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29979. * grid.getCartesian(xAxisIndex);
  29980. * grid.getCartesian(null, yAxisIndex);
  29981. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29982. *
  29983. * @param {number|Object} [xAxisIndex]
  29984. * @param {number} [yAxisIndex]
  29985. */
  29986. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29987. if (xAxisIndex != null && yAxisIndex != null) {
  29988. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29989. return this._coordsMap[key];
  29990. }
  29991. if (isObject$1(xAxisIndex)) {
  29992. yAxisIndex = xAxisIndex.yAxisIndex;
  29993. xAxisIndex = xAxisIndex.xAxisIndex;
  29994. }
  29995. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29996. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29997. if (coordList[i].getAxis('x').index === xAxisIndex
  29998. || coordList[i].getAxis('y').index === yAxisIndex
  29999. ) {
  30000. return coordList[i];
  30001. }
  30002. }
  30003. };
  30004. gridProto.getCartesians = function () {
  30005. return this._coordsList.slice();
  30006. };
  30007. /**
  30008. * @implements
  30009. * see {module:echarts/CoodinateSystem}
  30010. */
  30011. gridProto.convertToPixel = function (ecModel, finder, value) {
  30012. var target = this._findConvertTarget(ecModel, finder);
  30013. return target.cartesian
  30014. ? target.cartesian.dataToPoint(value)
  30015. : target.axis
  30016. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  30017. : null;
  30018. };
  30019. /**
  30020. * @implements
  30021. * see {module:echarts/CoodinateSystem}
  30022. */
  30023. gridProto.convertFromPixel = function (ecModel, finder, value) {
  30024. var target = this._findConvertTarget(ecModel, finder);
  30025. return target.cartesian
  30026. ? target.cartesian.pointToData(value)
  30027. : target.axis
  30028. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  30029. : null;
  30030. };
  30031. /**
  30032. * @inner
  30033. */
  30034. gridProto._findConvertTarget = function (ecModel, finder) {
  30035. var seriesModel = finder.seriesModel;
  30036. var xAxisModel = finder.xAxisModel
  30037. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  30038. var yAxisModel = finder.yAxisModel
  30039. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  30040. var gridModel = finder.gridModel;
  30041. var coordsList = this._coordsList;
  30042. var cartesian;
  30043. var axis;
  30044. if (seriesModel) {
  30045. cartesian = seriesModel.coordinateSystem;
  30046. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  30047. }
  30048. else if (xAxisModel && yAxisModel) {
  30049. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  30050. }
  30051. else if (xAxisModel) {
  30052. axis = this.getAxis('x', xAxisModel.componentIndex);
  30053. }
  30054. else if (yAxisModel) {
  30055. axis = this.getAxis('y', yAxisModel.componentIndex);
  30056. }
  30057. // Lowest priority.
  30058. else if (gridModel) {
  30059. var grid = gridModel.coordinateSystem;
  30060. if (grid === this) {
  30061. cartesian = this._coordsList[0];
  30062. }
  30063. }
  30064. return {cartesian: cartesian, axis: axis};
  30065. };
  30066. /**
  30067. * @implements
  30068. * see {module:echarts/CoodinateSystem}
  30069. */
  30070. gridProto.containPoint = function (point) {
  30071. var coord = this._coordsList[0];
  30072. if (coord) {
  30073. return coord.containPoint(point);
  30074. }
  30075. };
  30076. /**
  30077. * Initialize cartesian coordinate systems
  30078. * @private
  30079. */
  30080. gridProto._initCartesian = function (gridModel, ecModel, api) {
  30081. var axisPositionUsed = {
  30082. left: false,
  30083. right: false,
  30084. top: false,
  30085. bottom: false
  30086. };
  30087. var axesMap = {
  30088. x: {},
  30089. y: {}
  30090. };
  30091. var axesCount = {
  30092. x: 0,
  30093. y: 0
  30094. };
  30095. /// Create axis
  30096. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  30097. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  30098. if (!axesCount.x || !axesCount.y) {
  30099. // Roll back when there no either x or y axis
  30100. this._axesMap = {};
  30101. this._axesList = [];
  30102. return;
  30103. }
  30104. this._axesMap = axesMap;
  30105. /// Create cartesian2d
  30106. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  30107. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  30108. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30109. var cartesian = new Cartesian2D(key);
  30110. cartesian.grid = this;
  30111. cartesian.model = gridModel;
  30112. this._coordsMap[key] = cartesian;
  30113. this._coordsList.push(cartesian);
  30114. cartesian.addAxis(xAxis);
  30115. cartesian.addAxis(yAxis);
  30116. }, this);
  30117. }, this);
  30118. function createAxisCreator(axisType) {
  30119. return function (axisModel, idx) {
  30120. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  30121. return;
  30122. }
  30123. var axisPosition = axisModel.get('position');
  30124. if (axisType === 'x') {
  30125. // Fix position
  30126. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  30127. // Default bottom of X
  30128. axisPosition = 'bottom';
  30129. if (axisPositionUsed[axisPosition]) {
  30130. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  30131. }
  30132. }
  30133. }
  30134. else {
  30135. // Fix position
  30136. if (axisPosition !== 'left' && axisPosition !== 'right') {
  30137. // Default left of Y
  30138. axisPosition = 'left';
  30139. if (axisPositionUsed[axisPosition]) {
  30140. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  30141. }
  30142. }
  30143. }
  30144. axisPositionUsed[axisPosition] = true;
  30145. var axis = new Axis2D(
  30146. axisType, createScaleByModel(axisModel),
  30147. [0, 0],
  30148. axisModel.get('type'),
  30149. axisPosition
  30150. );
  30151. var isCategory = axis.type === 'category';
  30152. axis.onBand = isCategory && axisModel.get('boundaryGap');
  30153. axis.inverse = axisModel.get('inverse');
  30154. axis.onZero = axisModel.get('axisLine.onZero');
  30155. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30156. // Inject axis into axisModel
  30157. axisModel.axis = axis;
  30158. // Inject axisModel into axis
  30159. axis.model = axisModel;
  30160. // Inject grid info axis
  30161. axis.grid = this;
  30162. // Index of axis, can be used as key
  30163. axis.index = idx;
  30164. this._axesList.push(axis);
  30165. axesMap[axisType][idx] = axis;
  30166. axesCount[axisType]++;
  30167. };
  30168. }
  30169. };
  30170. /**
  30171. * Update cartesian properties from series
  30172. * @param {module:echarts/model/Option} option
  30173. * @private
  30174. */
  30175. gridProto._updateScale = function (ecModel, gridModel) {
  30176. // Reset scale
  30177. each$1(this._axesList, function (axis) {
  30178. axis.scale.setExtent(Infinity, -Infinity);
  30179. });
  30180. ecModel.eachSeries(function (seriesModel) {
  30181. if (isCartesian2D(seriesModel)) {
  30182. var axesModels = findAxesModels(seriesModel, ecModel);
  30183. var xAxisModel = axesModels[0];
  30184. var yAxisModel = axesModels[1];
  30185. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  30186. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  30187. ) {
  30188. return;
  30189. }
  30190. var cartesian = this.getCartesian(
  30191. xAxisModel.componentIndex, yAxisModel.componentIndex
  30192. );
  30193. var data = seriesModel.getData();
  30194. var xAxis = cartesian.getAxis('x');
  30195. var yAxis = cartesian.getAxis('y');
  30196. if (data.type === 'list') {
  30197. unionExtent(data, xAxis, seriesModel);
  30198. unionExtent(data, yAxis, seriesModel);
  30199. }
  30200. }
  30201. }, this);
  30202. function unionExtent(data, axis, seriesModel) {
  30203. each$6(data.mapDimension(axis.dim, true), function (dim) {
  30204. axis.scale.unionExtentFromData(data, dim);
  30205. });
  30206. }
  30207. };
  30208. /**
  30209. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  30210. * @return {Object} {baseAxes: [], otherAxes: []}
  30211. */
  30212. gridProto.getTooltipAxes = function (dim) {
  30213. var baseAxes = [];
  30214. var otherAxes = [];
  30215. each$6(this.getCartesians(), function (cartesian) {
  30216. var baseAxis = (dim != null && dim !== 'auto')
  30217. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  30218. var otherAxis = cartesian.getOtherAxis(baseAxis);
  30219. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  30220. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  30221. });
  30222. return {baseAxes: baseAxes, otherAxes: otherAxes};
  30223. };
  30224. /**
  30225. * @inner
  30226. */
  30227. function updateAxisTransform(axis, coordBase) {
  30228. var axisExtent = axis.getExtent();
  30229. var axisExtentSum = axisExtent[0] + axisExtent[1];
  30230. // Fast transform
  30231. axis.toGlobalCoord = axis.dim === 'x'
  30232. ? function (coord) {
  30233. return coord + coordBase;
  30234. }
  30235. : function (coord) {
  30236. return axisExtentSum - coord + coordBase;
  30237. };
  30238. axis.toLocalCoord = axis.dim === 'x'
  30239. ? function (coord) {
  30240. return coord - coordBase;
  30241. }
  30242. : function (coord) {
  30243. return axisExtentSum - coord + coordBase;
  30244. };
  30245. }
  30246. var axesTypes = ['xAxis', 'yAxis'];
  30247. /**
  30248. * @inner
  30249. */
  30250. function findAxesModels(seriesModel, ecModel) {
  30251. return map(axesTypes, function (axisType) {
  30252. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  30253. if (__DEV__) {
  30254. if (!axisModel) {
  30255. throw new Error(axisType + ' "' + retrieve(
  30256. seriesModel.get(axisType + 'Index'),
  30257. seriesModel.get(axisType + 'Id'),
  30258. 0
  30259. ) + '" not found');
  30260. }
  30261. }
  30262. return axisModel;
  30263. });
  30264. }
  30265. /**
  30266. * @inner
  30267. */
  30268. function isCartesian2D(seriesModel) {
  30269. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  30270. }
  30271. Grid.create = function (ecModel, api) {
  30272. var grids = [];
  30273. ecModel.eachComponent('grid', function (gridModel, idx) {
  30274. var grid = new Grid(gridModel, ecModel, api);
  30275. grid.name = 'grid_' + idx;
  30276. // dataSampling requires axis extent, so resize
  30277. // should be performed in create stage.
  30278. grid.resize(gridModel, api, true);
  30279. gridModel.coordinateSystem = grid;
  30280. grids.push(grid);
  30281. });
  30282. // Inject the coordinateSystems into seriesModel
  30283. ecModel.eachSeries(function (seriesModel) {
  30284. if (!isCartesian2D(seriesModel)) {
  30285. return;
  30286. }
  30287. var axesModels = findAxesModels(seriesModel, ecModel);
  30288. var xAxisModel = axesModels[0];
  30289. var yAxisModel = axesModels[1];
  30290. var gridModel = xAxisModel.getCoordSysModel();
  30291. if (__DEV__) {
  30292. if (!gridModel) {
  30293. throw new Error(
  30294. 'Grid "' + retrieve(
  30295. xAxisModel.get('gridIndex'),
  30296. xAxisModel.get('gridId'),
  30297. 0
  30298. ) + '" not found'
  30299. );
  30300. }
  30301. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  30302. throw new Error('xAxis and yAxis must use the same grid');
  30303. }
  30304. }
  30305. var grid = gridModel.coordinateSystem;
  30306. seriesModel.coordinateSystem = grid.getCartesian(
  30307. xAxisModel.componentIndex, yAxisModel.componentIndex
  30308. );
  30309. });
  30310. return grids;
  30311. };
  30312. // For deciding which dimensions to use when creating list data
  30313. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  30314. CoordinateSystemManager.register('cartesian2d', Grid);
  30315. var PI$2 = Math.PI;
  30316. function makeAxisEventDataBase(axisModel) {
  30317. var eventData = {
  30318. componentType: axisModel.mainType
  30319. };
  30320. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  30321. return eventData;
  30322. }
  30323. /**
  30324. * A final axis is translated and rotated from a "standard axis".
  30325. * So opt.position and opt.rotation is required.
  30326. *
  30327. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  30328. * for example: (0, 0) ------------> (0, 50)
  30329. *
  30330. * nameDirection or tickDirection or labelDirection is 1 means tick
  30331. * or label is below the standard axis, whereas is -1 means above
  30332. * the standard axis. labelOffset means offset between label and axis,
  30333. * which is useful when 'onZero', where axisLabel is in the grid and
  30334. * label in outside grid.
  30335. *
  30336. * Tips: like always,
  30337. * positive rotation represents anticlockwise, and negative rotation
  30338. * represents clockwise.
  30339. * The direction of position coordinate is the same as the direction
  30340. * of screen coordinate.
  30341. *
  30342. * Do not need to consider axis 'inverse', which is auto processed by
  30343. * axis extent.
  30344. *
  30345. * @param {module:zrender/container/Group} group
  30346. * @param {Object} axisModel
  30347. * @param {Object} opt Standard axis parameters.
  30348. * @param {Array.<number>} opt.position [x, y]
  30349. * @param {number} opt.rotation by radian
  30350. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  30351. * @param {number} [opt.tickDirection=1] 1 or -1
  30352. * @param {number} [opt.labelDirection=1] 1 or -1
  30353. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  30354. * @param {string} [opt.axisLabelShow] default get from axisModel.
  30355. * @param {string} [opt.axisName] default get from axisModel.
  30356. * @param {number} [opt.axisNameAvailableWidth]
  30357. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  30358. * @param {number} [opt.labelInterval] Default label interval when label
  30359. * interval from model is null or 'auto'.
  30360. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  30361. * @param {number} [opt.nameTruncateMaxWidth]
  30362. */
  30363. var AxisBuilder = function (axisModel, opt) {
  30364. /**
  30365. * @readOnly
  30366. */
  30367. this.opt = opt;
  30368. /**
  30369. * @readOnly
  30370. */
  30371. this.axisModel = axisModel;
  30372. // Default value
  30373. defaults(
  30374. opt,
  30375. {
  30376. labelOffset: 0,
  30377. nameDirection: 1,
  30378. tickDirection: 1,
  30379. labelDirection: 1,
  30380. silent: true
  30381. }
  30382. );
  30383. /**
  30384. * @readOnly
  30385. */
  30386. this.group = new Group();
  30387. // FIXME Not use a seperate text group?
  30388. var dumbGroup = new Group({
  30389. position: opt.position.slice(),
  30390. rotation: opt.rotation
  30391. });
  30392. // this.group.add(dumbGroup);
  30393. // this._dumbGroup = dumbGroup;
  30394. dumbGroup.updateTransform();
  30395. this._transform = dumbGroup.transform;
  30396. this._dumbGroup = dumbGroup;
  30397. };
  30398. AxisBuilder.prototype = {
  30399. constructor: AxisBuilder,
  30400. hasBuilder: function (name) {
  30401. return !!builders[name];
  30402. },
  30403. add: function (name) {
  30404. builders[name].call(this);
  30405. },
  30406. getGroup: function () {
  30407. return this.group;
  30408. }
  30409. };
  30410. var builders = {
  30411. /**
  30412. * @private
  30413. */
  30414. axisLine: function () {
  30415. var opt = this.opt;
  30416. var axisModel = this.axisModel;
  30417. if (!axisModel.get('axisLine.show')) {
  30418. return;
  30419. }
  30420. var extent = this.axisModel.axis.getExtent();
  30421. var matrix = this._transform;
  30422. var pt1 = [extent[0], 0];
  30423. var pt2 = [extent[1], 0];
  30424. if (matrix) {
  30425. applyTransform(pt1, pt1, matrix);
  30426. applyTransform(pt2, pt2, matrix);
  30427. }
  30428. var lineStyle = extend(
  30429. {
  30430. lineCap: 'round'
  30431. },
  30432. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  30433. );
  30434. this.group.add(new Line(subPixelOptimizeLine({
  30435. // Id for animation
  30436. anid: 'line',
  30437. shape: {
  30438. x1: pt1[0],
  30439. y1: pt1[1],
  30440. x2: pt2[0],
  30441. y2: pt2[1]
  30442. },
  30443. style: lineStyle,
  30444. strokeContainThreshold: opt.strokeContainThreshold || 5,
  30445. silent: true,
  30446. z2: 1
  30447. })));
  30448. var arrows = axisModel.get('axisLine.symbol');
  30449. var arrowSize = axisModel.get('axisLine.symbolSize');
  30450. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  30451. if (typeof arrowOffset === 'number') {
  30452. arrowOffset = [arrowOffset, arrowOffset];
  30453. }
  30454. if (arrows != null) {
  30455. if (typeof arrows === 'string') {
  30456. // Use the same arrow for start and end point
  30457. arrows = [arrows, arrows];
  30458. }
  30459. if (typeof arrowSize === 'string'
  30460. || typeof arrowSize === 'number'
  30461. ) {
  30462. // Use the same size for width and height
  30463. arrowSize = [arrowSize, arrowSize];
  30464. }
  30465. var symbolWidth = arrowSize[0];
  30466. var symbolHeight = arrowSize[1];
  30467. each$1([{
  30468. rotate: opt.rotation + Math.PI / 2,
  30469. offset: arrowOffset[0],
  30470. r: 0
  30471. }, {
  30472. rotate: opt.rotation - Math.PI / 2,
  30473. offset: arrowOffset[1],
  30474. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  30475. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  30476. }], function (point, index) {
  30477. if (arrows[index] !== 'none' && arrows[index] != null) {
  30478. var symbol = createSymbol(
  30479. arrows[index],
  30480. -symbolWidth / 2,
  30481. -symbolHeight / 2,
  30482. symbolWidth,
  30483. symbolHeight,
  30484. lineStyle.stroke,
  30485. true
  30486. );
  30487. // Calculate arrow position with offset
  30488. var r = point.r + point.offset;
  30489. var pos = [
  30490. pt1[0] + r * Math.cos(opt.rotation),
  30491. pt1[1] - r * Math.sin(opt.rotation)
  30492. ];
  30493. symbol.attr({
  30494. rotation: point.rotate,
  30495. position: pos,
  30496. silent: true
  30497. });
  30498. this.group.add(symbol);
  30499. }
  30500. }, this);
  30501. }
  30502. },
  30503. /**
  30504. * @private
  30505. */
  30506. axisTickLabel: function () {
  30507. var axisModel = this.axisModel;
  30508. var opt = this.opt;
  30509. var tickEls = buildAxisTick(this, axisModel, opt);
  30510. var labelEls = buildAxisLabel(this, axisModel, opt);
  30511. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  30512. },
  30513. /**
  30514. * @private
  30515. */
  30516. axisName: function () {
  30517. var opt = this.opt;
  30518. var axisModel = this.axisModel;
  30519. var name = retrieve(opt.axisName, axisModel.get('name'));
  30520. if (!name) {
  30521. return;
  30522. }
  30523. var nameLocation = axisModel.get('nameLocation');
  30524. var nameDirection = opt.nameDirection;
  30525. var textStyleModel = axisModel.getModel('nameTextStyle');
  30526. var gap = axisModel.get('nameGap') || 0;
  30527. var extent = this.axisModel.axis.getExtent();
  30528. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  30529. var pos = [
  30530. nameLocation === 'start'
  30531. ? extent[0] - gapSignal * gap
  30532. : nameLocation === 'end'
  30533. ? extent[1] + gapSignal * gap
  30534. : (extent[0] + extent[1]) / 2, // 'middle'
  30535. // Reuse labelOffset.
  30536. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  30537. ];
  30538. var labelLayout;
  30539. var nameRotation = axisModel.get('nameRotate');
  30540. if (nameRotation != null) {
  30541. nameRotation = nameRotation * PI$2 / 180; // To radian.
  30542. }
  30543. var axisNameAvailableWidth;
  30544. if (isNameLocationCenter(nameLocation)) {
  30545. labelLayout = innerTextLayout(
  30546. opt.rotation,
  30547. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  30548. nameDirection
  30549. );
  30550. }
  30551. else {
  30552. labelLayout = endTextLayout(
  30553. opt, nameLocation, nameRotation || 0, extent
  30554. );
  30555. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  30556. if (axisNameAvailableWidth != null) {
  30557. axisNameAvailableWidth = Math.abs(
  30558. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  30559. );
  30560. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  30561. }
  30562. }
  30563. var textFont = textStyleModel.getFont();
  30564. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  30565. var ellipsis = truncateOpt.ellipsis;
  30566. var maxWidth = retrieve(
  30567. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  30568. );
  30569. // FIXME
  30570. // truncate rich text? (consider performance)
  30571. var truncatedText = (ellipsis != null && maxWidth != null)
  30572. ? truncateText$1(
  30573. name, maxWidth, textFont, ellipsis,
  30574. {minChar: 2, placeholder: truncateOpt.placeholder}
  30575. )
  30576. : name;
  30577. var tooltipOpt = axisModel.get('tooltip', true);
  30578. var mainType = axisModel.mainType;
  30579. var formatterParams = {
  30580. componentType: mainType,
  30581. name: name,
  30582. $vars: ['name']
  30583. };
  30584. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  30585. var textEl = new Text({
  30586. // Id for animation
  30587. anid: 'name',
  30588. __fullText: name,
  30589. __truncatedText: truncatedText,
  30590. position: pos,
  30591. rotation: labelLayout.rotation,
  30592. silent: isSilent(axisModel),
  30593. z2: 1,
  30594. tooltip: (tooltipOpt && tooltipOpt.show)
  30595. ? extend({
  30596. content: name,
  30597. formatter: function () {
  30598. return name;
  30599. },
  30600. formatterParams: formatterParams
  30601. }, tooltipOpt)
  30602. : null
  30603. });
  30604. setTextStyle(textEl.style, textStyleModel, {
  30605. text: truncatedText,
  30606. textFont: textFont,
  30607. textFill: textStyleModel.getTextColor()
  30608. || axisModel.get('axisLine.lineStyle.color'),
  30609. textAlign: labelLayout.textAlign,
  30610. textVerticalAlign: labelLayout.textVerticalAlign
  30611. });
  30612. if (axisModel.get('triggerEvent')) {
  30613. textEl.eventData = makeAxisEventDataBase(axisModel);
  30614. textEl.eventData.targetType = 'axisName';
  30615. textEl.eventData.name = name;
  30616. }
  30617. // FIXME
  30618. this._dumbGroup.add(textEl);
  30619. textEl.updateTransform();
  30620. this.group.add(textEl);
  30621. textEl.decomposeTransform();
  30622. }
  30623. };
  30624. /**
  30625. * @public
  30626. * @static
  30627. * @param {Object} opt
  30628. * @param {number} axisRotation in radian
  30629. * @param {number} textRotation in radian
  30630. * @param {number} direction
  30631. * @return {Object} {
  30632. * rotation, // according to axis
  30633. * textAlign,
  30634. * textVerticalAlign
  30635. * }
  30636. */
  30637. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  30638. var rotationDiff = remRadian(textRotation - axisRotation);
  30639. var textAlign;
  30640. var textVerticalAlign;
  30641. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  30642. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  30643. textAlign = 'center';
  30644. }
  30645. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  30646. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  30647. textAlign = 'center';
  30648. }
  30649. else {
  30650. textVerticalAlign = 'middle';
  30651. if (rotationDiff > 0 && rotationDiff < PI$2) {
  30652. textAlign = direction > 0 ? 'right' : 'left';
  30653. }
  30654. else {
  30655. textAlign = direction > 0 ? 'left' : 'right';
  30656. }
  30657. }
  30658. return {
  30659. rotation: rotationDiff,
  30660. textAlign: textAlign,
  30661. textVerticalAlign: textVerticalAlign
  30662. };
  30663. };
  30664. function endTextLayout(opt, textPosition, textRotate, extent) {
  30665. var rotationDiff = remRadian(textRotate - opt.rotation);
  30666. var textAlign;
  30667. var textVerticalAlign;
  30668. var inverse = extent[0] > extent[1];
  30669. var onLeft = (textPosition === 'start' && !inverse)
  30670. || (textPosition !== 'start' && inverse);
  30671. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  30672. textVerticalAlign = onLeft ? 'bottom' : 'top';
  30673. textAlign = 'center';
  30674. }
  30675. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  30676. textVerticalAlign = onLeft ? 'top' : 'bottom';
  30677. textAlign = 'center';
  30678. }
  30679. else {
  30680. textVerticalAlign = 'middle';
  30681. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  30682. textAlign = onLeft ? 'left' : 'right';
  30683. }
  30684. else {
  30685. textAlign = onLeft ? 'right' : 'left';
  30686. }
  30687. }
  30688. return {
  30689. rotation: rotationDiff,
  30690. textAlign: textAlign,
  30691. textVerticalAlign: textVerticalAlign
  30692. };
  30693. }
  30694. function isSilent(axisModel) {
  30695. var tooltipOpt = axisModel.get('tooltip');
  30696. return axisModel.get('silent')
  30697. // Consider mouse cursor, add these restrictions.
  30698. || !(
  30699. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  30700. );
  30701. }
  30702. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  30703. // If min or max are user set, we need to check
  30704. // If the tick on min(max) are overlap on their neighbour tick
  30705. // If they are overlapped, we need to hide the min(max) tick label
  30706. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30707. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30708. // FIXME
  30709. // Have not consider onBand yet, where tick els is more than label els.
  30710. labelEls = labelEls || [];
  30711. tickEls = tickEls || [];
  30712. var firstLabel = labelEls[0];
  30713. var nextLabel = labelEls[1];
  30714. var lastLabel = labelEls[labelEls.length - 1];
  30715. var prevLabel = labelEls[labelEls.length - 2];
  30716. var firstTick = tickEls[0];
  30717. var nextTick = tickEls[1];
  30718. var lastTick = tickEls[tickEls.length - 1];
  30719. var prevTick = tickEls[tickEls.length - 2];
  30720. if (showMinLabel === false) {
  30721. ignoreEl(firstLabel);
  30722. ignoreEl(firstTick);
  30723. }
  30724. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  30725. if (showMinLabel) {
  30726. ignoreEl(nextLabel);
  30727. ignoreEl(nextTick);
  30728. }
  30729. else {
  30730. ignoreEl(firstLabel);
  30731. ignoreEl(firstTick);
  30732. }
  30733. }
  30734. if (showMaxLabel === false) {
  30735. ignoreEl(lastLabel);
  30736. ignoreEl(lastTick);
  30737. }
  30738. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  30739. if (showMaxLabel) {
  30740. ignoreEl(prevLabel);
  30741. ignoreEl(prevTick);
  30742. }
  30743. else {
  30744. ignoreEl(lastLabel);
  30745. ignoreEl(lastTick);
  30746. }
  30747. }
  30748. }
  30749. function ignoreEl(el) {
  30750. el && (el.ignore = true);
  30751. }
  30752. function isTwoLabelOverlapped(current, next, labelLayout) {
  30753. // current and next has the same rotation.
  30754. var firstRect = current && current.getBoundingRect().clone();
  30755. var nextRect = next && next.getBoundingRect().clone();
  30756. if (!firstRect || !nextRect) {
  30757. return;
  30758. }
  30759. // When checking intersect of two rotated labels, we use mRotationBack
  30760. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  30761. var mRotationBack = identity([]);
  30762. rotate(mRotationBack, mRotationBack, -current.rotation);
  30763. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  30764. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  30765. return firstRect.intersect(nextRect);
  30766. }
  30767. function isNameLocationCenter(nameLocation) {
  30768. return nameLocation === 'middle' || nameLocation === 'center';
  30769. }
  30770. /**
  30771. * @static
  30772. */
  30773. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  30774. axis,
  30775. i,
  30776. interval,
  30777. ticksCnt,
  30778. showMinLabel,
  30779. showMaxLabel
  30780. ) {
  30781. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  30782. return false;
  30783. }
  30784. // FIXME
  30785. // Have not consider label overlap (if label is too long) yet.
  30786. var rawTick;
  30787. var scale$$1 = axis.scale;
  30788. return scale$$1.type === 'ordinal'
  30789. && (
  30790. typeof interval === 'function'
  30791. ? (
  30792. rawTick = scale$$1.getTicks()[i],
  30793. !interval(rawTick, scale$$1.getLabel(rawTick))
  30794. )
  30795. : i % (interval + 1)
  30796. );
  30797. };
  30798. /**
  30799. * @static
  30800. */
  30801. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30802. var interval = model.get('interval');
  30803. if (interval == null || interval == 'auto') {
  30804. interval = labelInterval;
  30805. }
  30806. return interval;
  30807. };
  30808. function buildAxisTick(axisBuilder, axisModel, opt) {
  30809. var axis = axisModel.axis;
  30810. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30811. return;
  30812. }
  30813. var tickModel = axisModel.getModel('axisTick');
  30814. var lineStyleModel = tickModel.getModel('lineStyle');
  30815. var tickLen = tickModel.get('length');
  30816. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30817. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30818. // FIXME
  30819. // Corresponds to ticksCoords ?
  30820. var ticks = axis.scale.getTicks();
  30821. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30822. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30823. var pt1 = [];
  30824. var pt2 = [];
  30825. var matrix = axisBuilder._transform;
  30826. var tickEls = [];
  30827. var ticksCnt = ticksCoords.length;
  30828. for (var i = 0; i < ticksCnt; i++) {
  30829. // Only ordinal scale support tick interval
  30830. if (ifIgnoreOnTick$1(
  30831. axis, i, tickInterval, ticksCnt,
  30832. showMinLabel, showMaxLabel
  30833. )) {
  30834. continue;
  30835. }
  30836. var tickCoord = ticksCoords[i];
  30837. pt1[0] = tickCoord;
  30838. pt1[1] = 0;
  30839. pt2[0] = tickCoord;
  30840. pt2[1] = opt.tickDirection * tickLen;
  30841. if (matrix) {
  30842. applyTransform(pt1, pt1, matrix);
  30843. applyTransform(pt2, pt2, matrix);
  30844. }
  30845. // Tick line, Not use group transform to have better line draw
  30846. var tickEl = new Line(subPixelOptimizeLine({
  30847. // Id for animation
  30848. anid: 'tick_' + ticks[i],
  30849. shape: {
  30850. x1: pt1[0],
  30851. y1: pt1[1],
  30852. x2: pt2[0],
  30853. y2: pt2[1]
  30854. },
  30855. style: defaults(
  30856. lineStyleModel.getLineStyle(),
  30857. {
  30858. stroke: axisModel.get('axisLine.lineStyle.color')
  30859. }
  30860. ),
  30861. z2: 2,
  30862. silent: true
  30863. }));
  30864. axisBuilder.group.add(tickEl);
  30865. tickEls.push(tickEl);
  30866. }
  30867. return tickEls;
  30868. }
  30869. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30870. var axis = axisModel.axis;
  30871. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30872. if (!show || axis.scale.isBlank()) {
  30873. return;
  30874. }
  30875. var labelModel = axisModel.getModel('axisLabel');
  30876. var labelMargin = labelModel.get('margin');
  30877. var ticks = axis.scale.getTicks();
  30878. var labels = axisModel.getFormattedLabels();
  30879. // Special label rotate.
  30880. var labelRotation = (
  30881. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30882. ) * PI$2 / 180;
  30883. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30884. var categoryData = axisModel.getCategories();
  30885. var labelEls = [];
  30886. var silent = isSilent(axisModel);
  30887. var triggerEvent = axisModel.get('triggerEvent');
  30888. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30889. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30890. each$1(ticks, function (tickVal, index) {
  30891. if (ifIgnoreOnTick$1(
  30892. axis, index, opt.labelInterval, ticks.length,
  30893. showMinLabel, showMaxLabel
  30894. )) {
  30895. return;
  30896. }
  30897. var itemLabelModel = labelModel;
  30898. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30899. itemLabelModel = new Model(
  30900. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30901. );
  30902. }
  30903. var textColor = itemLabelModel.getTextColor()
  30904. || axisModel.get('axisLine.lineStyle.color');
  30905. var tickCoord = axis.dataToCoord(tickVal);
  30906. var pos = [
  30907. tickCoord,
  30908. opt.labelOffset + opt.labelDirection * labelMargin
  30909. ];
  30910. var labelStr = axis.scale.getLabel(tickVal);
  30911. var textEl = new Text({
  30912. // Id for animation
  30913. anid: 'label_' + tickVal,
  30914. position: pos,
  30915. rotation: labelLayout.rotation,
  30916. silent: silent,
  30917. z2: 10
  30918. });
  30919. setTextStyle(textEl.style, itemLabelModel, {
  30920. text: labels[index],
  30921. textAlign: itemLabelModel.getShallow('align', true)
  30922. || labelLayout.textAlign,
  30923. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30924. || itemLabelModel.getShallow('baseline', true)
  30925. || labelLayout.textVerticalAlign,
  30926. textFill: typeof textColor === 'function'
  30927. ? textColor(
  30928. // (1) In category axis with data zoom, tick is not the original
  30929. // index of axis.data. So tick should not be exposed to user
  30930. // in category axis.
  30931. // (2) Compatible with previous version, which always returns labelStr.
  30932. // But in interval scale labelStr is like '223,445', which maked
  30933. // user repalce ','. So we modify it to return original val but remain
  30934. // it as 'string' to avoid error in replacing.
  30935. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30936. index
  30937. )
  30938. : textColor
  30939. });
  30940. // Pack data for mouse event
  30941. if (triggerEvent) {
  30942. textEl.eventData = makeAxisEventDataBase(axisModel);
  30943. textEl.eventData.targetType = 'axisLabel';
  30944. textEl.eventData.value = labelStr;
  30945. }
  30946. // FIXME
  30947. axisBuilder._dumbGroup.add(textEl);
  30948. textEl.updateTransform();
  30949. labelEls.push(textEl);
  30950. axisBuilder.group.add(textEl);
  30951. textEl.decomposeTransform();
  30952. });
  30953. return labelEls;
  30954. }
  30955. var each$7 = each$1;
  30956. var curry$1 = curry;
  30957. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30958. // allAxesInfo should be updated when setOption performed.
  30959. function collect(ecModel, api) {
  30960. var result = {
  30961. /**
  30962. * key: makeKey(axis.model)
  30963. * value: {
  30964. * axis,
  30965. * coordSys,
  30966. * axisPointerModel,
  30967. * triggerTooltip,
  30968. * involveSeries,
  30969. * snap,
  30970. * seriesModels,
  30971. * seriesDataCount
  30972. * }
  30973. */
  30974. axesInfo: {},
  30975. seriesInvolved: false,
  30976. /**
  30977. * key: makeKey(coordSys.model)
  30978. * value: Object: key makeKey(axis.model), value: axisInfo
  30979. */
  30980. coordSysAxesInfo: {},
  30981. coordSysMap: {}
  30982. };
  30983. collectAxesInfo(result, ecModel, api);
  30984. // Check seriesInvolved for performance, in case too many series in some chart.
  30985. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30986. return result;
  30987. }
  30988. function collectAxesInfo(result, ecModel, api) {
  30989. var globalTooltipModel = ecModel.getComponent('tooltip');
  30990. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30991. // links can only be set on global.
  30992. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30993. var linkGroups = [];
  30994. // Collect axes info.
  30995. each$7(api.getCoordinateSystems(), function (coordSys) {
  30996. // Some coordinate system do not support axes, like geo.
  30997. if (!coordSys.axisPointerEnabled) {
  30998. return;
  30999. }
  31000. var coordSysKey = makeKey(coordSys.model);
  31001. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  31002. result.coordSysMap[coordSysKey] = coordSys;
  31003. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  31004. // for user. So we enable seting tooltip on coordSys model.
  31005. var coordSysModel = coordSys.model;
  31006. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  31007. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  31008. // If axis tooltip used, choose tooltip axis for each coordSys.
  31009. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  31010. if (coordSys.getTooltipAxes
  31011. && globalTooltipModel
  31012. // If tooltip.showContent is set as false, tooltip will not
  31013. // show but axisPointer will show as normal.
  31014. && baseTooltipModel.get('show')
  31015. ) {
  31016. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  31017. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  31018. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  31019. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  31020. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  31021. if (triggerAxis || cross) {
  31022. each$7(tooltipAxes.baseAxes, curry$1(
  31023. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  31024. ));
  31025. }
  31026. if (cross) {
  31027. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  31028. }
  31029. }
  31030. // fromTooltip: true | false | 'cross'
  31031. // triggerTooltip: true | false | null
  31032. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  31033. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  31034. var axisPointerShow = axisPointerModel.get('show');
  31035. if (!axisPointerShow || (
  31036. axisPointerShow === 'auto'
  31037. && !fromTooltip
  31038. && !isHandleTrigger(axisPointerModel)
  31039. )) {
  31040. return;
  31041. }
  31042. if (triggerTooltip == null) {
  31043. triggerTooltip = axisPointerModel.get('triggerTooltip');
  31044. }
  31045. axisPointerModel = fromTooltip
  31046. ? makeAxisPointerModel(
  31047. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  31048. fromTooltip, triggerTooltip
  31049. )
  31050. : axisPointerModel;
  31051. var snap = axisPointerModel.get('snap');
  31052. var key = makeKey(axis.model);
  31053. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  31054. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  31055. var axisInfo = result.axesInfo[key] = {
  31056. key: key,
  31057. axis: axis,
  31058. coordSys: coordSys,
  31059. axisPointerModel: axisPointerModel,
  31060. triggerTooltip: triggerTooltip,
  31061. involveSeries: involveSeries,
  31062. snap: snap,
  31063. useHandle: isHandleTrigger(axisPointerModel),
  31064. seriesModels: []
  31065. };
  31066. axesInfoInCoordSys[key] = axisInfo;
  31067. result.seriesInvolved |= involveSeries;
  31068. var groupIndex = getLinkGroupIndex(linksOption, axis);
  31069. if (groupIndex != null) {
  31070. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  31071. linkGroup.axesInfo[key] = axisInfo;
  31072. linkGroup.mapper = linksOption[groupIndex].mapper;
  31073. axisInfo.linkGroup = linkGroup;
  31074. }
  31075. }
  31076. });
  31077. }
  31078. function makeAxisPointerModel(
  31079. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  31080. ) {
  31081. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  31082. var volatileOption = {};
  31083. each$7(
  31084. [
  31085. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  31086. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  31087. ],
  31088. function (field) {
  31089. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  31090. }
  31091. );
  31092. // category axis do not auto snap, otherwise some tick that do not
  31093. // has value can not be hovered. value/time/log axis default snap if
  31094. // triggered from tooltip and trigger tooltip.
  31095. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  31096. // Compatibel with previous behavior, tooltip axis do not show label by default.
  31097. // Only these properties can be overrided from tooltip to axisPointer.
  31098. if (tooltipAxisPointerModel.get('type') === 'cross') {
  31099. volatileOption.type = 'line';
  31100. }
  31101. var labelOption = volatileOption.label || (volatileOption.label = {});
  31102. // Follow the convention, do not show label when triggered by tooltip by default.
  31103. labelOption.show == null && (labelOption.show = false);
  31104. if (fromTooltip === 'cross') {
  31105. // When 'cross', both axes show labels.
  31106. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  31107. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  31108. // If triggerTooltip, this is a base axis, which should better not use cross style
  31109. // (cross style is dashed by default)
  31110. if (!triggerTooltip) {
  31111. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  31112. crossStyle && defaults(labelOption, crossStyle.textStyle);
  31113. }
  31114. }
  31115. return axis.model.getModel(
  31116. 'axisPointer',
  31117. new Model(volatileOption, globalAxisPointerModel, ecModel)
  31118. );
  31119. }
  31120. function collectSeriesInfo(result, ecModel) {
  31121. // Prepare data for axis trigger
  31122. ecModel.eachSeries(function (seriesModel) {
  31123. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  31124. var coordSys = seriesModel.coordinateSystem;
  31125. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  31126. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  31127. if (!coordSys
  31128. || seriesTooltipTrigger === 'none'
  31129. || seriesTooltipTrigger === false
  31130. || seriesTooltipTrigger === 'item'
  31131. || seriesTooltipShow === false
  31132. || seriesModel.get('axisPointer.show', true) === false
  31133. ) {
  31134. return;
  31135. }
  31136. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  31137. var axis = axisInfo.axis;
  31138. if (coordSys.getAxis(axis.dim) === axis) {
  31139. axisInfo.seriesModels.push(seriesModel);
  31140. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  31141. axisInfo.seriesDataCount += seriesModel.getData().count();
  31142. }
  31143. });
  31144. }, this);
  31145. }
  31146. /**
  31147. * For example:
  31148. * {
  31149. * axisPointer: {
  31150. * links: [{
  31151. * xAxisIndex: [2, 4],
  31152. * yAxisIndex: 'all'
  31153. * }, {
  31154. * xAxisId: ['a5', 'a7'],
  31155. * xAxisName: 'xxx'
  31156. * }]
  31157. * }
  31158. * }
  31159. */
  31160. function getLinkGroupIndex(linksOption, axis) {
  31161. var axisModel = axis.model;
  31162. var dim = axis.dim;
  31163. for (var i = 0; i < linksOption.length; i++) {
  31164. var linkOption = linksOption[i] || {};
  31165. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  31166. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  31167. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  31168. ) {
  31169. return i;
  31170. }
  31171. }
  31172. }
  31173. function checkPropInLink(linkPropValue, axisPropValue) {
  31174. return linkPropValue === 'all'
  31175. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  31176. || linkPropValue === axisPropValue;
  31177. }
  31178. function fixValue(axisModel) {
  31179. var axisInfo = getAxisInfo(axisModel);
  31180. if (!axisInfo) {
  31181. return;
  31182. }
  31183. var axisPointerModel = axisInfo.axisPointerModel;
  31184. var scale = axisInfo.axis.scale;
  31185. var option = axisPointerModel.option;
  31186. var status = axisPointerModel.get('status');
  31187. var value = axisPointerModel.get('value');
  31188. // Parse init value for category and time axis.
  31189. if (value != null) {
  31190. value = scale.parse(value);
  31191. }
  31192. var useHandle = isHandleTrigger(axisPointerModel);
  31193. // If `handle` used, `axisPointer` will always be displayed, so value
  31194. // and status should be initialized.
  31195. if (status == null) {
  31196. option.status = useHandle ? 'show' : 'hide';
  31197. }
  31198. var extent = scale.getExtent().slice();
  31199. extent[0] > extent[1] && extent.reverse();
  31200. if (// Pick a value on axis when initializing.
  31201. value == null
  31202. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  31203. // where we should re-pick a value to keep `handle` displaying normally.
  31204. || value > extent[1]
  31205. ) {
  31206. // Make handle displayed on the end of the axis when init, which looks better.
  31207. value = extent[1];
  31208. }
  31209. if (value < extent[0]) {
  31210. value = extent[0];
  31211. }
  31212. option.value = value;
  31213. if (useHandle) {
  31214. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  31215. }
  31216. }
  31217. function getAxisInfo(axisModel) {
  31218. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  31219. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  31220. }
  31221. function getAxisPointerModel(axisModel) {
  31222. var axisInfo = getAxisInfo(axisModel);
  31223. return axisInfo && axisInfo.axisPointerModel;
  31224. }
  31225. function isHandleTrigger(axisPointerModel) {
  31226. return !!axisPointerModel.get('handle.show');
  31227. }
  31228. /**
  31229. * @param {module:echarts/model/Model} model
  31230. * @return {string} unique key
  31231. */
  31232. function makeKey(model) {
  31233. return model.type + '||' + model.id;
  31234. }
  31235. /**
  31236. * Base class of AxisView.
  31237. */
  31238. var AxisView = extendComponentView({
  31239. type: 'axis',
  31240. /**
  31241. * @private
  31242. */
  31243. _axisPointer: null,
  31244. /**
  31245. * @protected
  31246. * @type {string}
  31247. */
  31248. axisPointerClass: null,
  31249. /**
  31250. * @override
  31251. */
  31252. render: function (axisModel, ecModel, api, payload) {
  31253. // FIXME
  31254. // This process should proformed after coordinate systems updated
  31255. // (axis scale updated), and should be performed each time update.
  31256. // So put it here temporarily, although it is not appropriate to
  31257. // put a model-writing procedure in `view`.
  31258. this.axisPointerClass && fixValue(axisModel);
  31259. AxisView.superApply(this, 'render', arguments);
  31260. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  31261. },
  31262. /**
  31263. * Action handler.
  31264. * @public
  31265. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31266. * @param {module:echarts/model/Global} ecModel
  31267. * @param {module:echarts/ExtensionAPI} api
  31268. * @param {Object} payload
  31269. */
  31270. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  31271. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  31272. },
  31273. /**
  31274. * @override
  31275. */
  31276. remove: function (ecModel, api) {
  31277. var axisPointer = this._axisPointer;
  31278. axisPointer && axisPointer.remove(api);
  31279. AxisView.superApply(this, 'remove', arguments);
  31280. },
  31281. /**
  31282. * @override
  31283. */
  31284. dispose: function (ecModel, api) {
  31285. disposeAxisPointer(this, api);
  31286. AxisView.superApply(this, 'dispose', arguments);
  31287. }
  31288. });
  31289. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  31290. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  31291. if (!Clazz) {
  31292. return;
  31293. }
  31294. var axisPointerModel = getAxisPointerModel(axisModel);
  31295. axisPointerModel
  31296. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  31297. .render(axisModel, axisPointerModel, api, forceRender)
  31298. : disposeAxisPointer(axisView, api);
  31299. }
  31300. function disposeAxisPointer(axisView, ecModel, api) {
  31301. var axisPointer = axisView._axisPointer;
  31302. axisPointer && axisPointer.dispose(ecModel, api);
  31303. axisView._axisPointer = null;
  31304. }
  31305. var axisPointerClazz = [];
  31306. AxisView.registerAxisPointerClass = function (type, clazz) {
  31307. if (__DEV__) {
  31308. if (axisPointerClazz[type]) {
  31309. throw new Error('axisPointer ' + type + ' exists');
  31310. }
  31311. }
  31312. axisPointerClazz[type] = clazz;
  31313. };
  31314. AxisView.getAxisPointerClass = function (type) {
  31315. return type && axisPointerClazz[type];
  31316. };
  31317. /**
  31318. * @param {Object} opt {labelInside}
  31319. * @return {Object} {
  31320. * position, rotation, labelDirection, labelOffset,
  31321. * tickDirection, labelRotate, labelInterval, z2
  31322. * }
  31323. */
  31324. function layout$1(gridModel, axisModel, opt) {
  31325. opt = opt || {};
  31326. var grid = gridModel.coordinateSystem;
  31327. var axis = axisModel.axis;
  31328. var layout = {};
  31329. var rawAxisPosition = axis.position;
  31330. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  31331. var axisDim = axis.dim;
  31332. var rect = grid.getRect();
  31333. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  31334. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  31335. var axisOffset = axisModel.get('offset') || 0;
  31336. var posBound = axisDim === 'x'
  31337. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  31338. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  31339. if (axis.onZero) {
  31340. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  31341. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  31342. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  31343. }
  31344. // Axis position
  31345. layout.position = [
  31346. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  31347. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  31348. ];
  31349. // Axis rotation
  31350. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  31351. // Tick and label direction, x y is axisDim
  31352. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  31353. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  31354. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  31355. if (axisModel.get('axisTick.inside')) {
  31356. layout.tickDirection = -layout.tickDirection;
  31357. }
  31358. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  31359. layout.labelDirection = -layout.labelDirection;
  31360. }
  31361. // Special label rotation
  31362. var labelRotate = axisModel.get('axisLabel.rotate');
  31363. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  31364. // label interval when auto mode.
  31365. layout.labelInterval = axis.getLabelInterval();
  31366. // Over splitLine and splitArea
  31367. layout.z2 = 1;
  31368. return layout;
  31369. }
  31370. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  31371. var getInterval = AxisBuilder.getInterval;
  31372. var axisBuilderAttrs = [
  31373. 'axisLine', 'axisTickLabel', 'axisName'
  31374. ];
  31375. var selfBuilderAttrs = [
  31376. 'splitArea', 'splitLine'
  31377. ];
  31378. // function getAlignWithLabel(model, axisModel) {
  31379. // var alignWithLabel = model.get('alignWithLabel');
  31380. // if (alignWithLabel === 'auto') {
  31381. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  31382. // }
  31383. // return alignWithLabel;
  31384. // }
  31385. var CartesianAxisView = AxisView.extend({
  31386. type: 'cartesianAxis',
  31387. axisPointerClass: 'CartesianAxisPointer',
  31388. /**
  31389. * @override
  31390. */
  31391. render: function (axisModel, ecModel, api, payload) {
  31392. this.group.removeAll();
  31393. var oldAxisGroup = this._axisGroup;
  31394. this._axisGroup = new Group();
  31395. this.group.add(this._axisGroup);
  31396. if (!axisModel.get('show')) {
  31397. return;
  31398. }
  31399. var gridModel = axisModel.getCoordSysModel();
  31400. var layout = layout$1(gridModel, axisModel);
  31401. var axisBuilder = new AxisBuilder(axisModel, layout);
  31402. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  31403. this._axisGroup.add(axisBuilder.getGroup());
  31404. each$1(selfBuilderAttrs, function (name) {
  31405. if (axisModel.get(name + '.show')) {
  31406. this['_' + name](axisModel, gridModel, layout.labelInterval);
  31407. }
  31408. }, this);
  31409. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  31410. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  31411. },
  31412. /**
  31413. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31414. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31415. * @param {number|Function} labelInterval
  31416. * @private
  31417. */
  31418. _splitLine: function (axisModel, gridModel, labelInterval) {
  31419. var axis = axisModel.axis;
  31420. if (axis.scale.isBlank()) {
  31421. return;
  31422. }
  31423. var splitLineModel = axisModel.getModel('splitLine');
  31424. var lineStyleModel = splitLineModel.getModel('lineStyle');
  31425. var lineColors = lineStyleModel.get('color');
  31426. var lineInterval = getInterval(splitLineModel, labelInterval);
  31427. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  31428. var gridRect = gridModel.coordinateSystem.getRect();
  31429. var isHorizontal = axis.isHorizontal();
  31430. var lineCount = 0;
  31431. var ticksCoords = axis.getTicksCoords(
  31432. // splitLineModel.get('alignWithLabel')
  31433. );
  31434. var ticks = axis.scale.getTicks();
  31435. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31436. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31437. var p1 = [];
  31438. var p2 = [];
  31439. // Simple optimization
  31440. // Batching the lines if color are the same
  31441. var lineStyle = lineStyleModel.getLineStyle();
  31442. for (var i = 0; i < ticksCoords.length; i++) {
  31443. if (ifIgnoreOnTick(
  31444. axis, i, lineInterval, ticksCoords.length,
  31445. showMinLabel, showMaxLabel
  31446. )) {
  31447. continue;
  31448. }
  31449. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31450. if (isHorizontal) {
  31451. p1[0] = tickCoord;
  31452. p1[1] = gridRect.y;
  31453. p2[0] = tickCoord;
  31454. p2[1] = gridRect.y + gridRect.height;
  31455. }
  31456. else {
  31457. p1[0] = gridRect.x;
  31458. p1[1] = tickCoord;
  31459. p2[0] = gridRect.x + gridRect.width;
  31460. p2[1] = tickCoord;
  31461. }
  31462. var colorIndex = (lineCount++) % lineColors.length;
  31463. this._axisGroup.add(new Line(subPixelOptimizeLine({
  31464. anid: 'line_' + ticks[i],
  31465. shape: {
  31466. x1: p1[0],
  31467. y1: p1[1],
  31468. x2: p2[0],
  31469. y2: p2[1]
  31470. },
  31471. style: defaults({
  31472. stroke: lineColors[colorIndex]
  31473. }, lineStyle),
  31474. silent: true
  31475. })));
  31476. }
  31477. },
  31478. /**
  31479. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31480. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31481. * @param {number|Function} labelInterval
  31482. * @private
  31483. */
  31484. _splitArea: function (axisModel, gridModel, labelInterval) {
  31485. var axis = axisModel.axis;
  31486. if (axis.scale.isBlank()) {
  31487. return;
  31488. }
  31489. var splitAreaModel = axisModel.getModel('splitArea');
  31490. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  31491. var areaColors = areaStyleModel.get('color');
  31492. var gridRect = gridModel.coordinateSystem.getRect();
  31493. var ticksCoords = axis.getTicksCoords(
  31494. // splitAreaModel.get('alignWithLabel')
  31495. );
  31496. var ticks = axis.scale.getTicks();
  31497. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  31498. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  31499. var count = 0;
  31500. var areaInterval = getInterval(splitAreaModel, labelInterval);
  31501. var areaStyle = areaStyleModel.getAreaStyle();
  31502. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  31503. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31504. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31505. for (var i = 1; i < ticksCoords.length; i++) {
  31506. if (ifIgnoreOnTick(
  31507. axis, i, areaInterval, ticksCoords.length,
  31508. showMinLabel, showMaxLabel
  31509. ) && (i < ticksCoords.length - 1)) {
  31510. continue;
  31511. }
  31512. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31513. var x;
  31514. var y;
  31515. var width;
  31516. var height;
  31517. if (axis.isHorizontal()) {
  31518. x = prevX;
  31519. y = gridRect.y;
  31520. width = tickCoord - x;
  31521. height = gridRect.height;
  31522. }
  31523. else {
  31524. x = gridRect.x;
  31525. y = prevY;
  31526. width = gridRect.width;
  31527. height = tickCoord - y;
  31528. }
  31529. var colorIndex = (count++) % areaColors.length;
  31530. this._axisGroup.add(new Rect({
  31531. anid: 'area_' + ticks[i],
  31532. shape: {
  31533. x: x,
  31534. y: y,
  31535. width: width,
  31536. height: height
  31537. },
  31538. style: defaults({
  31539. fill: areaColors[colorIndex]
  31540. }, areaStyle),
  31541. silent: true
  31542. }));
  31543. prevX = x + width;
  31544. prevY = y + height;
  31545. }
  31546. }
  31547. });
  31548. CartesianAxisView.extend({
  31549. type: 'xAxis'
  31550. });
  31551. CartesianAxisView.extend({
  31552. type: 'yAxis'
  31553. });
  31554. // Grid view
  31555. extendComponentView({
  31556. type: 'grid',
  31557. render: function (gridModel, ecModel) {
  31558. this.group.removeAll();
  31559. if (gridModel.get('show')) {
  31560. this.group.add(new Rect({
  31561. shape: gridModel.coordinateSystem.getRect(),
  31562. style: defaults({
  31563. fill: gridModel.get('backgroundColor')
  31564. }, gridModel.getItemStyle()),
  31565. silent: true,
  31566. z2: -1
  31567. }));
  31568. }
  31569. }
  31570. });
  31571. registerPreprocessor(function (option) {
  31572. // Only create grid when need
  31573. if (option.xAxis && option.yAxis && !option.grid) {
  31574. option.grid = {};
  31575. }
  31576. });
  31577. // In case developer forget to include grid component
  31578. registerVisual(visualSymbol('line', 'circle', 'line'));
  31579. registerLayout(pointsLayout('line'));
  31580. // Down sample after filter
  31581. registerProcessor(
  31582. PRIORITY.PROCESSOR.STATISTIC,
  31583. dataSample('line')
  31584. );
  31585. var BaseBarSeries = SeriesModel.extend({
  31586. type: 'series.__base_bar__',
  31587. getInitialData: function (option, ecModel) {
  31588. return createListFromArray(this.getSource(), this);
  31589. },
  31590. getMarkerPosition: function (value) {
  31591. var coordSys = this.coordinateSystem;
  31592. if (coordSys) {
  31593. // PENDING if clamp ?
  31594. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31595. var data = this.getData();
  31596. var offset = data.getLayout('offset');
  31597. var size = data.getLayout('size');
  31598. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31599. pt[offsetIndex] += offset + size / 2;
  31600. return pt;
  31601. }
  31602. return [NaN, NaN];
  31603. },
  31604. defaultOption: {
  31605. zlevel: 0, // 一级层叠
  31606. z: 2, // 二级层叠
  31607. coordinateSystem: 'cartesian2d',
  31608. legendHoverLink: true,
  31609. // stack: null
  31610. // Cartesian coordinate system
  31611. // xAxisIndex: 0,
  31612. // yAxisIndex: 0,
  31613. // 最小高度改为0
  31614. barMinHeight: 0,
  31615. // 最小角度为0,仅对极坐标系下的柱状图有效
  31616. barMinAngle: 0,
  31617. // cursor: null,
  31618. // barMaxWidth: null,
  31619. // 默认自适应
  31620. // barWidth: null,
  31621. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31622. // barGap: '30%',
  31623. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31624. // barCategoryGap: '20%',
  31625. // label: {
  31626. // show: false
  31627. // },
  31628. itemStyle: {},
  31629. emphasis: {}
  31630. }
  31631. });
  31632. BaseBarSeries.extend({
  31633. type: 'series.bar',
  31634. dependencies: ['grid', 'polar'],
  31635. brushSelector: 'rect'
  31636. });
  31637. function setLabel(
  31638. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  31639. ) {
  31640. var labelModel = itemModel.getModel('label');
  31641. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31642. setLabelStyle(
  31643. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  31644. {
  31645. labelFetcher: seriesModel,
  31646. labelDataIndex: dataIndex,
  31647. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31648. isRectText: true,
  31649. autoColor: color
  31650. }
  31651. );
  31652. fixPosition(normalStyle);
  31653. fixPosition(hoverStyle);
  31654. }
  31655. function fixPosition(style, labelPositionOutside) {
  31656. if (style.textPosition === 'outside') {
  31657. style.textPosition = labelPositionOutside;
  31658. }
  31659. }
  31660. var getBarItemStyle = makeStyleMapper(
  31661. [
  31662. ['fill', 'color'],
  31663. ['stroke', 'borderColor'],
  31664. ['lineWidth', 'borderWidth'],
  31665. // Compatitable with 2
  31666. ['stroke', 'barBorderColor'],
  31667. ['lineWidth', 'barBorderWidth'],
  31668. ['opacity'],
  31669. ['shadowBlur'],
  31670. ['shadowOffsetX'],
  31671. ['shadowOffsetY'],
  31672. ['shadowColor']
  31673. ]
  31674. );
  31675. var barItemStyle = {
  31676. getBarItemStyle: function (excludes) {
  31677. var style = getBarItemStyle(this, excludes);
  31678. if (this.getBorderLineDash) {
  31679. var lineDash = this.getBorderLineDash();
  31680. lineDash && (style.lineDash = lineDash);
  31681. }
  31682. return style;
  31683. }
  31684. };
  31685. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31686. // FIXME
  31687. // Just for compatible with ec2.
  31688. extend(Model.prototype, barItemStyle);
  31689. extendChartView({
  31690. type: 'bar',
  31691. render: function (seriesModel, ecModel, api) {
  31692. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31693. if (coordinateSystemType === 'cartesian2d'
  31694. || coordinateSystemType === 'polar'
  31695. ) {
  31696. this._render(seriesModel, ecModel, api);
  31697. }
  31698. else if (__DEV__) {
  31699. console.warn('Only cartesian2d and polar supported for bar.');
  31700. }
  31701. return this.group;
  31702. },
  31703. dispose: noop,
  31704. _render: function (seriesModel, ecModel, api) {
  31705. var group = this.group;
  31706. var data = seriesModel.getData();
  31707. var oldData = this._data;
  31708. var coord = seriesModel.coordinateSystem;
  31709. var baseAxis = coord.getBaseAxis();
  31710. var isHorizontalOrRadial;
  31711. if (coord.type === 'cartesian2d') {
  31712. isHorizontalOrRadial = baseAxis.isHorizontal();
  31713. }
  31714. else if (coord.type === 'polar') {
  31715. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31716. }
  31717. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31718. data.diff(oldData)
  31719. .add(function (dataIndex) {
  31720. if (!data.hasValue(dataIndex)) {
  31721. return;
  31722. }
  31723. var itemModel = data.getItemModel(dataIndex);
  31724. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31725. var el = elementCreator[coord.type](
  31726. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  31727. );
  31728. data.setItemGraphicEl(dataIndex, el);
  31729. group.add(el);
  31730. updateStyle(
  31731. el, data, dataIndex, itemModel, layout,
  31732. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31733. );
  31734. })
  31735. .update(function (newIndex, oldIndex) {
  31736. var el = oldData.getItemGraphicEl(oldIndex);
  31737. if (!data.hasValue(newIndex)) {
  31738. group.remove(el);
  31739. return;
  31740. }
  31741. var itemModel = data.getItemModel(newIndex);
  31742. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31743. if (el) {
  31744. updateProps(el, {shape: layout}, animationModel, newIndex);
  31745. }
  31746. else {
  31747. el = elementCreator[coord.type](
  31748. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  31749. );
  31750. }
  31751. data.setItemGraphicEl(newIndex, el);
  31752. // Add back
  31753. group.add(el);
  31754. updateStyle(
  31755. el, data, newIndex, itemModel, layout,
  31756. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31757. );
  31758. })
  31759. .remove(function (dataIndex) {
  31760. var el = oldData.getItemGraphicEl(dataIndex);
  31761. if (coord.type === 'cartesian2d') {
  31762. el && removeRect(dataIndex, animationModel, el);
  31763. }
  31764. else {
  31765. el && removeSector(dataIndex, animationModel, el);
  31766. }
  31767. })
  31768. .execute();
  31769. this._data = data;
  31770. },
  31771. remove: function (ecModel, api) {
  31772. var group = this.group;
  31773. var data = this._data;
  31774. if (ecModel.get('animation')) {
  31775. if (data) {
  31776. data.eachItemGraphicEl(function (el) {
  31777. if (el.type === 'sector') {
  31778. removeSector(el.dataIndex, ecModel, el);
  31779. }
  31780. else {
  31781. removeRect(el.dataIndex, ecModel, el);
  31782. }
  31783. });
  31784. }
  31785. }
  31786. else {
  31787. group.removeAll();
  31788. }
  31789. }
  31790. });
  31791. var elementCreator = {
  31792. cartesian2d: function (
  31793. data, dataIndex, itemModel, layout, isHorizontal,
  31794. animationModel, isUpdate
  31795. ) {
  31796. var rect = new Rect({shape: extend({}, layout)});
  31797. // Animation
  31798. if (animationModel) {
  31799. var rectShape = rect.shape;
  31800. var animateProperty = isHorizontal ? 'height' : 'width';
  31801. var animateTarget = {};
  31802. rectShape[animateProperty] = 0;
  31803. animateTarget[animateProperty] = layout[animateProperty];
  31804. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31805. shape: animateTarget
  31806. }, animationModel, dataIndex);
  31807. }
  31808. return rect;
  31809. },
  31810. polar: function (
  31811. data, dataIndex, itemModel, layout, isRadial,
  31812. animationModel, isUpdate
  31813. ) {
  31814. // Keep the same logic with bar in catesion: use end value to control
  31815. // direction. Notice that if clockwise is true (by default), the sector
  31816. // will always draw clockwisely, no matter whether endAngle is greater
  31817. // or less than startAngle.
  31818. var clockwise = layout.startAngle < layout.endAngle;
  31819. var sector = new Sector({
  31820. shape: defaults({clockwise: clockwise}, layout)
  31821. });
  31822. // Animation
  31823. if (animationModel) {
  31824. var sectorShape = sector.shape;
  31825. var animateProperty = isRadial ? 'r' : 'endAngle';
  31826. var animateTarget = {};
  31827. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31828. animateTarget[animateProperty] = layout[animateProperty];
  31829. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31830. shape: animateTarget
  31831. }, animationModel, dataIndex);
  31832. }
  31833. return sector;
  31834. }
  31835. };
  31836. function removeRect(dataIndex, animationModel, el) {
  31837. // Not show text when animating
  31838. el.style.text = null;
  31839. updateProps(el, {
  31840. shape: {
  31841. width: 0
  31842. }
  31843. }, animationModel, dataIndex, function () {
  31844. el.parent && el.parent.remove(el);
  31845. });
  31846. }
  31847. function removeSector(dataIndex, animationModel, el) {
  31848. // Not show text when animating
  31849. el.style.text = null;
  31850. updateProps(el, {
  31851. shape: {
  31852. r: el.shape.r0
  31853. }
  31854. }, animationModel, dataIndex, function () {
  31855. el.parent && el.parent.remove(el);
  31856. });
  31857. }
  31858. var getLayout = {
  31859. cartesian2d: function (data, dataIndex, itemModel) {
  31860. var layout = data.getItemLayout(dataIndex);
  31861. var fixedLineWidth = getLineWidth(itemModel, layout);
  31862. // fix layout with lineWidth
  31863. var signX = layout.width > 0 ? 1 : -1;
  31864. var signY = layout.height > 0 ? 1 : -1;
  31865. return {
  31866. x: layout.x + signX * fixedLineWidth / 2,
  31867. y: layout.y + signY * fixedLineWidth / 2,
  31868. width: layout.width - signX * fixedLineWidth,
  31869. height: layout.height - signY * fixedLineWidth
  31870. };
  31871. },
  31872. polar: function (data, dataIndex, itemModel) {
  31873. var layout = data.getItemLayout(dataIndex);
  31874. return {
  31875. cx: layout.cx,
  31876. cy: layout.cy,
  31877. r0: layout.r0,
  31878. r: layout.r,
  31879. startAngle: layout.startAngle,
  31880. endAngle: layout.endAngle
  31881. };
  31882. }
  31883. };
  31884. function updateStyle(
  31885. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31886. ) {
  31887. var color = data.getItemVisual(dataIndex, 'color');
  31888. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31889. var itemStyleModel = itemModel.getModel('itemStyle');
  31890. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31891. if (!isPolar) {
  31892. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31893. }
  31894. el.useStyle(defaults(
  31895. {
  31896. fill: color,
  31897. opacity: opacity
  31898. },
  31899. itemStyleModel.getBarItemStyle()
  31900. ));
  31901. var cursorStyle = itemModel.getShallow('cursor');
  31902. cursorStyle && el.attr('cursor', cursorStyle);
  31903. var labelPositionOutside = isHorizontal
  31904. ? (layout.height > 0 ? 'bottom' : 'top')
  31905. : (layout.width > 0 ? 'left' : 'right');
  31906. if (!isPolar) {
  31907. setLabel(
  31908. el.style, hoverStyle, itemModel, color,
  31909. seriesModel, dataIndex, labelPositionOutside
  31910. );
  31911. }
  31912. setHoverStyle(el, hoverStyle);
  31913. }
  31914. // In case width or height are too small.
  31915. function getLineWidth(itemModel, rawLayout) {
  31916. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31917. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31918. }
  31919. // In case developer forget to include grid component
  31920. registerLayout(curry(layout, 'bar'));
  31921. // Visual coding for legend
  31922. registerVisual(function (ecModel) {
  31923. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31924. var data = seriesModel.getData();
  31925. data.setVisual('legendSymbol', 'roundRect');
  31926. });
  31927. });
  31928. /**
  31929. * [Usage]:
  31930. * (1)
  31931. * createListSimply(seriesModel, ['value']);
  31932. * (2)
  31933. * createListSimply(seriesModel, {
  31934. * coordDimensions: ['value'],
  31935. * dimensionsCount: 5
  31936. * });
  31937. *
  31938. * @param {module:echarts/model/Series} seriesModel
  31939. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31940. * The options in opt, see `echarts/data/helper/createDimensions`
  31941. * @param {Array.<string>} [nameList]
  31942. * @return {module:echarts/data/List}
  31943. */
  31944. var createListSimply = function (seriesModel, opt, nameList) {
  31945. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31946. var source = seriesModel.getSource();
  31947. var dimensionsInfo = createDimensions(source, opt);
  31948. var list = new List(dimensionsInfo, seriesModel);
  31949. list.initData(source, nameList);
  31950. return list;
  31951. };
  31952. /**
  31953. * Data selectable mixin for chart series.
  31954. * To eanble data select, option of series must have `selectedMode`.
  31955. * And each data item will use `selected` to toggle itself selected status
  31956. */
  31957. var selectableMixin = {
  31958. /**
  31959. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  31960. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31961. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31962. */
  31963. updateSelectedMap: function (targetList) {
  31964. this._targetList = isArray(targetList) ? targetList.slice() : [];
  31965. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31966. targetMap.set(target.name, target);
  31967. return targetMap;
  31968. }, createHashMap());
  31969. },
  31970. /**
  31971. * Either name or id should be passed as input here.
  31972. * If both of them are defined, id is used.
  31973. *
  31974. * @param {string|undefined} name name of data
  31975. * @param {number|undefined} id dataIndex of data
  31976. */
  31977. // PENGING If selectedMode is null ?
  31978. select: function (name, id) {
  31979. var target = id != null
  31980. ? this._targetList[id]
  31981. : this._selectTargetMap.get(name);
  31982. var selectedMode = this.get('selectedMode');
  31983. if (selectedMode === 'single') {
  31984. this._selectTargetMap.each(function (target) {
  31985. target.selected = false;
  31986. });
  31987. }
  31988. target && (target.selected = true);
  31989. },
  31990. /**
  31991. * Either name or id should be passed as input here.
  31992. * If both of them are defined, id is used.
  31993. *
  31994. * @param {string|undefined} name name of data
  31995. * @param {number|undefined} id dataIndex of data
  31996. */
  31997. unSelect: function (name, id) {
  31998. var target = id != null
  31999. ? this._targetList[id]
  32000. : this._selectTargetMap.get(name);
  32001. // var selectedMode = this.get('selectedMode');
  32002. // selectedMode !== 'single' && target && (target.selected = false);
  32003. target && (target.selected = false);
  32004. },
  32005. /**
  32006. * Either name or id should be passed as input here.
  32007. * If both of them are defined, id is used.
  32008. *
  32009. * @param {string|undefined} name name of data
  32010. * @param {number|undefined} id dataIndex of data
  32011. */
  32012. toggleSelected: function (name, id) {
  32013. var target = id != null
  32014. ? this._targetList[id]
  32015. : this._selectTargetMap.get(name);
  32016. if (target != null) {
  32017. this[target.selected ? 'unSelect' : 'select'](name, id);
  32018. return target.selected;
  32019. }
  32020. },
  32021. /**
  32022. * Either name or id should be passed as input here.
  32023. * If both of them are defined, id is used.
  32024. *
  32025. * @param {string|undefined} name name of data
  32026. * @param {number|undefined} id dataIndex of data
  32027. */
  32028. isSelected: function (name, id) {
  32029. var target = id != null
  32030. ? this._targetList[id]
  32031. : this._selectTargetMap.get(name);
  32032. return target && target.selected;
  32033. }
  32034. };
  32035. var PieSeries = extendSeriesModel({
  32036. type: 'series.pie',
  32037. // Overwrite
  32038. init: function (option) {
  32039. PieSeries.superApply(this, 'init', arguments);
  32040. // Enable legend selection for each data item
  32041. // Use a function instead of direct access because data reference may changed
  32042. this.legendDataProvider = function () {
  32043. return this.getRawData();
  32044. };
  32045. this.updateSelectedMap(this._createSelectableList());
  32046. this._defaultLabelLine(option);
  32047. },
  32048. // Overwrite
  32049. mergeOption: function (newOption) {
  32050. PieSeries.superCall(this, 'mergeOption', newOption);
  32051. this.updateSelectedMap(this._createSelectableList());
  32052. },
  32053. getInitialData: function (option, ecModel) {
  32054. return createListSimply(this, ['value']);
  32055. },
  32056. _createSelectableList: function () {
  32057. var data = this.getRawData();
  32058. var valueDim = data.mapDimension('value');
  32059. var targetList = [];
  32060. for (var i = 0, len = data.count(); i < len; i++) {
  32061. targetList.push({
  32062. name: data.getName(i),
  32063. value: data.get(valueDim, i),
  32064. selected: retrieveRawAttr(data, i, 'selected')
  32065. });
  32066. }
  32067. return targetList;
  32068. },
  32069. // Overwrite
  32070. getDataParams: function (dataIndex) {
  32071. var data = this.getData();
  32072. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  32073. // FIXME toFixed?
  32074. var valueList = [];
  32075. data.each(data.mapDimension('value'), function (value) {
  32076. valueList.push(value);
  32077. });
  32078. params.percent = getPercentWithPrecision(
  32079. valueList,
  32080. dataIndex,
  32081. data.hostModel.get('percentPrecision')
  32082. );
  32083. params.$vars.push('percent');
  32084. return params;
  32085. },
  32086. _defaultLabelLine: function (option) {
  32087. // Extend labelLine emphasis
  32088. defaultEmphasis(option, 'labelLine', ['show']);
  32089. var labelLineNormalOpt = option.labelLine;
  32090. var labelLineEmphasisOpt = option.emphasis.labelLine;
  32091. // Not show label line if `label.normal.show = false`
  32092. labelLineNormalOpt.show = labelLineNormalOpt.show
  32093. && option.label.show;
  32094. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  32095. && option.emphasis.label.show;
  32096. },
  32097. defaultOption: {
  32098. zlevel: 0,
  32099. z: 2,
  32100. legendHoverLink: true,
  32101. hoverAnimation: true,
  32102. // 默认全局居中
  32103. center: ['50%', '50%'],
  32104. radius: [0, '75%'],
  32105. // 默认顺时针
  32106. clockwise: true,
  32107. startAngle: 90,
  32108. // 最小角度改为0
  32109. minAngle: 0,
  32110. // 选中时扇区偏移量
  32111. selectedOffset: 10,
  32112. // 高亮扇区偏移量
  32113. hoverOffset: 10,
  32114. // If use strategy to avoid label overlapping
  32115. avoidLabelOverlap: true,
  32116. // 选择模式,默认关闭,可选single,multiple
  32117. // selectedMode: false,
  32118. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  32119. // roseType: null,
  32120. percentPrecision: 2,
  32121. // If still show when all data zero.
  32122. stillShowZeroSum: true,
  32123. // cursor: null,
  32124. label: {
  32125. // If rotate around circle
  32126. rotate: false,
  32127. show: true,
  32128. // 'outer', 'inside', 'center'
  32129. position: 'outer'
  32130. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32131. // 默认使用全局文本样式,详见TEXTSTYLE
  32132. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  32133. },
  32134. // Enabled when label.normal.position is 'outer'
  32135. labelLine: {
  32136. show: true,
  32137. // 引导线两段中的第一段长度
  32138. length: 15,
  32139. // 引导线两段中的第二段长度
  32140. length2: 15,
  32141. smooth: false,
  32142. lineStyle: {
  32143. // color: 各异,
  32144. width: 1,
  32145. type: 'solid'
  32146. }
  32147. },
  32148. itemStyle: {
  32149. borderWidth: 1
  32150. },
  32151. // Animation type canbe expansion, scale
  32152. animationType: 'expansion',
  32153. animationEasing: 'cubicOut'
  32154. }
  32155. });
  32156. mixin(PieSeries, selectableMixin);
  32157. /**
  32158. * @param {module:echarts/model/Series} seriesModel
  32159. * @param {boolean} hasAnimation
  32160. * @inner
  32161. */
  32162. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  32163. var data = seriesModel.getData();
  32164. var dataIndex = this.dataIndex;
  32165. var name = data.getName(dataIndex);
  32166. var selectedOffset = seriesModel.get('selectedOffset');
  32167. api.dispatchAction({
  32168. type: 'pieToggleSelect',
  32169. from: uid,
  32170. name: name,
  32171. seriesId: seriesModel.id
  32172. });
  32173. data.each(function (idx) {
  32174. toggleItemSelected(
  32175. data.getItemGraphicEl(idx),
  32176. data.getItemLayout(idx),
  32177. seriesModel.isSelected(data.getName(idx)),
  32178. selectedOffset,
  32179. hasAnimation
  32180. );
  32181. });
  32182. }
  32183. /**
  32184. * @param {module:zrender/graphic/Sector} el
  32185. * @param {Object} layout
  32186. * @param {boolean} isSelected
  32187. * @param {number} selectedOffset
  32188. * @param {boolean} hasAnimation
  32189. * @inner
  32190. */
  32191. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  32192. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32193. var dx = Math.cos(midAngle);
  32194. var dy = Math.sin(midAngle);
  32195. var offset = isSelected ? selectedOffset : 0;
  32196. var position = [dx * offset, dy * offset];
  32197. hasAnimation
  32198. // animateTo will stop revious animation like update transition
  32199. ? el.animate()
  32200. .when(200, {
  32201. position: position
  32202. })
  32203. .start('bounceOut')
  32204. : el.attr('position', position);
  32205. }
  32206. /**
  32207. * Piece of pie including Sector, Label, LabelLine
  32208. * @constructor
  32209. * @extends {module:zrender/graphic/Group}
  32210. */
  32211. function PiePiece(data, idx) {
  32212. Group.call(this);
  32213. var sector = new Sector({
  32214. z2: 2
  32215. });
  32216. var polyline = new Polyline();
  32217. var text = new Text();
  32218. this.add(sector);
  32219. this.add(polyline);
  32220. this.add(text);
  32221. this.updateData(data, idx, true);
  32222. // Hover to change label and labelLine
  32223. function onEmphasis() {
  32224. polyline.ignore = polyline.hoverIgnore;
  32225. text.ignore = text.hoverIgnore;
  32226. }
  32227. function onNormal() {
  32228. polyline.ignore = polyline.normalIgnore;
  32229. text.ignore = text.normalIgnore;
  32230. }
  32231. this.on('emphasis', onEmphasis)
  32232. .on('normal', onNormal)
  32233. .on('mouseover', onEmphasis)
  32234. .on('mouseout', onNormal);
  32235. }
  32236. var piePieceProto = PiePiece.prototype;
  32237. piePieceProto.updateData = function (data, idx, firstCreate) {
  32238. var sector = this.childAt(0);
  32239. var seriesModel = data.hostModel;
  32240. var itemModel = data.getItemModel(idx);
  32241. var layout = data.getItemLayout(idx);
  32242. var sectorShape = extend({}, layout);
  32243. sectorShape.label = null;
  32244. if (firstCreate) {
  32245. sector.setShape(sectorShape);
  32246. var animationType = seriesModel.getShallow('animationType');
  32247. if (animationType === 'scale') {
  32248. sector.shape.r = layout.r0;
  32249. initProps(sector, {
  32250. shape: {
  32251. r: layout.r
  32252. }
  32253. }, seriesModel, idx);
  32254. }
  32255. // Expansion
  32256. else {
  32257. sector.shape.endAngle = layout.startAngle;
  32258. updateProps(sector, {
  32259. shape: {
  32260. endAngle: layout.endAngle
  32261. }
  32262. }, seriesModel, idx);
  32263. }
  32264. }
  32265. else {
  32266. updateProps(sector, {
  32267. shape: sectorShape
  32268. }, seriesModel, idx);
  32269. }
  32270. // Update common style
  32271. var visualColor = data.getItemVisual(idx, 'color');
  32272. sector.useStyle(
  32273. defaults(
  32274. {
  32275. lineJoin: 'bevel',
  32276. fill: visualColor
  32277. },
  32278. itemModel.getModel('itemStyle').getItemStyle()
  32279. )
  32280. );
  32281. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  32282. var cursorStyle = itemModel.getShallow('cursor');
  32283. cursorStyle && sector.attr('cursor', cursorStyle);
  32284. // Toggle selected
  32285. toggleItemSelected(
  32286. this,
  32287. data.getItemLayout(idx),
  32288. seriesModel.isSelected(null, idx),
  32289. seriesModel.get('selectedOffset'),
  32290. seriesModel.get('animation')
  32291. );
  32292. function onEmphasis() {
  32293. // Sector may has animation of updating data. Force to move to the last frame
  32294. // Or it may stopped on the wrong shape
  32295. sector.stopAnimation(true);
  32296. sector.animateTo({
  32297. shape: {
  32298. r: layout.r + seriesModel.get('hoverOffset')
  32299. }
  32300. }, 300, 'elasticOut');
  32301. }
  32302. function onNormal() {
  32303. sector.stopAnimation(true);
  32304. sector.animateTo({
  32305. shape: {
  32306. r: layout.r
  32307. }
  32308. }, 300, 'elasticOut');
  32309. }
  32310. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  32311. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  32312. sector
  32313. .on('mouseover', onEmphasis)
  32314. .on('mouseout', onNormal)
  32315. .on('emphasis', onEmphasis)
  32316. .on('normal', onNormal);
  32317. }
  32318. this._updateLabel(data, idx);
  32319. setHoverStyle(this);
  32320. };
  32321. piePieceProto._updateLabel = function (data, idx) {
  32322. var labelLine = this.childAt(1);
  32323. var labelText = this.childAt(2);
  32324. var seriesModel = data.hostModel;
  32325. var itemModel = data.getItemModel(idx);
  32326. var layout = data.getItemLayout(idx);
  32327. var labelLayout = layout.label;
  32328. var visualColor = data.getItemVisual(idx, 'color');
  32329. updateProps(labelLine, {
  32330. shape: {
  32331. points: labelLayout.linePoints || [
  32332. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  32333. ]
  32334. }
  32335. }, seriesModel, idx);
  32336. updateProps(labelText, {
  32337. style: {
  32338. x: labelLayout.x,
  32339. y: labelLayout.y
  32340. }
  32341. }, seriesModel, idx);
  32342. labelText.attr({
  32343. rotation: labelLayout.rotation,
  32344. origin: [labelLayout.x, labelLayout.y],
  32345. z2: 10
  32346. });
  32347. var labelModel = itemModel.getModel('label');
  32348. var labelHoverModel = itemModel.getModel('emphasis.label');
  32349. var labelLineModel = itemModel.getModel('labelLine');
  32350. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  32351. var visualColor = data.getItemVisual(idx, 'color');
  32352. setLabelStyle(
  32353. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  32354. {
  32355. labelFetcher: data.hostModel,
  32356. labelDataIndex: idx,
  32357. defaultText: data.getName(idx),
  32358. autoColor: visualColor,
  32359. useInsideStyle: !!labelLayout.inside
  32360. },
  32361. {
  32362. textAlign: labelLayout.textAlign,
  32363. textVerticalAlign: labelLayout.verticalAlign,
  32364. opacity: data.getItemVisual(idx, 'opacity')
  32365. }
  32366. );
  32367. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  32368. labelText.hoverIgnore = !labelHoverModel.get('show');
  32369. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  32370. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  32371. // Default use item visual color
  32372. labelLine.setStyle({
  32373. stroke: visualColor,
  32374. opacity: data.getItemVisual(idx, 'opacity')
  32375. });
  32376. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  32377. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  32378. var smooth = labelLineModel.get('smooth');
  32379. if (smooth && smooth === true) {
  32380. smooth = 0.4;
  32381. }
  32382. labelLine.setShape({
  32383. smooth: smooth
  32384. });
  32385. };
  32386. inherits(PiePiece, Group);
  32387. // Pie view
  32388. var PieView = Chart.extend({
  32389. type: 'pie',
  32390. init: function () {
  32391. var sectorGroup = new Group();
  32392. this._sectorGroup = sectorGroup;
  32393. },
  32394. render: function (seriesModel, ecModel, api, payload) {
  32395. if (payload && (payload.from === this.uid)) {
  32396. return;
  32397. }
  32398. var data = seriesModel.getData();
  32399. var oldData = this._data;
  32400. var group = this.group;
  32401. var hasAnimation = ecModel.get('animation');
  32402. var isFirstRender = !oldData;
  32403. var animationType = seriesModel.get('animationType');
  32404. var onSectorClick = curry(
  32405. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  32406. );
  32407. var selectedMode = seriesModel.get('selectedMode');
  32408. data.diff(oldData)
  32409. .add(function (idx) {
  32410. var piePiece = new PiePiece(data, idx);
  32411. // Default expansion animation
  32412. if (isFirstRender && animationType !== 'scale') {
  32413. piePiece.eachChild(function (child) {
  32414. child.stopAnimation(true);
  32415. });
  32416. }
  32417. selectedMode && piePiece.on('click', onSectorClick);
  32418. data.setItemGraphicEl(idx, piePiece);
  32419. group.add(piePiece);
  32420. })
  32421. .update(function (newIdx, oldIdx) {
  32422. var piePiece = oldData.getItemGraphicEl(oldIdx);
  32423. piePiece.updateData(data, newIdx);
  32424. piePiece.off('click');
  32425. selectedMode && piePiece.on('click', onSectorClick);
  32426. group.add(piePiece);
  32427. data.setItemGraphicEl(newIdx, piePiece);
  32428. })
  32429. .remove(function (idx) {
  32430. var piePiece = oldData.getItemGraphicEl(idx);
  32431. group.remove(piePiece);
  32432. })
  32433. .execute();
  32434. if (
  32435. hasAnimation && isFirstRender && data.count() > 0
  32436. // Default expansion animation
  32437. && animationType !== 'scale'
  32438. ) {
  32439. var shape = data.getItemLayout(0);
  32440. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  32441. var removeClipPath = bind(group.removeClipPath, group);
  32442. group.setClipPath(this._createClipPath(
  32443. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  32444. ));
  32445. }
  32446. this._data = data;
  32447. },
  32448. dispose: function () {},
  32449. _createClipPath: function (
  32450. cx, cy, r, startAngle, clockwise, cb, seriesModel
  32451. ) {
  32452. var clipPath = new Sector({
  32453. shape: {
  32454. cx: cx,
  32455. cy: cy,
  32456. r0: 0,
  32457. r: r,
  32458. startAngle: startAngle,
  32459. endAngle: startAngle,
  32460. clockwise: clockwise
  32461. }
  32462. });
  32463. initProps(clipPath, {
  32464. shape: {
  32465. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  32466. }
  32467. }, seriesModel, cb);
  32468. return clipPath;
  32469. },
  32470. /**
  32471. * @implement
  32472. */
  32473. containPoint: function (point, seriesModel) {
  32474. var data = seriesModel.getData();
  32475. var itemLayout = data.getItemLayout(0);
  32476. if (itemLayout) {
  32477. var dx = point[0] - itemLayout.cx;
  32478. var dy = point[1] - itemLayout.cy;
  32479. var radius = Math.sqrt(dx * dx + dy * dy);
  32480. return radius <= itemLayout.r && radius >= itemLayout.r0;
  32481. }
  32482. }
  32483. });
  32484. var createDataSelectAction = function (seriesType, actionInfos) {
  32485. each$1(actionInfos, function (actionInfo) {
  32486. actionInfo.update = 'updateView';
  32487. /**
  32488. * @payload
  32489. * @property {string} seriesName
  32490. * @property {string} name
  32491. */
  32492. registerAction(actionInfo, function (payload, ecModel) {
  32493. var selected = {};
  32494. ecModel.eachComponent(
  32495. {mainType: 'series', subType: seriesType, query: payload},
  32496. function (seriesModel) {
  32497. if (seriesModel[actionInfo.method]) {
  32498. seriesModel[actionInfo.method](
  32499. payload.name,
  32500. payload.dataIndex
  32501. );
  32502. }
  32503. var data = seriesModel.getData();
  32504. // Create selected map
  32505. data.each(function (idx) {
  32506. var name = data.getName(idx);
  32507. selected[name] = seriesModel.isSelected(name)
  32508. || false;
  32509. });
  32510. }
  32511. );
  32512. return {
  32513. name: payload.name,
  32514. selected: selected
  32515. };
  32516. });
  32517. });
  32518. };
  32519. // Pick color from palette for each data item.
  32520. // Applicable for charts that require applying color palette
  32521. // in data level (like pie, funnel, chord).
  32522. var dataColor = function (seriesType) {
  32523. return {
  32524. getTargetSeries: function (ecModel) {
  32525. // Pie and funnel may use diferrent scope
  32526. var paletteScope = {};
  32527. var seiresModelMap = createHashMap();
  32528. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32529. seriesModel.__paletteScope = paletteScope;
  32530. seiresModelMap.set(seriesModel.uid, seriesModel);
  32531. });
  32532. return seiresModelMap;
  32533. },
  32534. reset: function (seriesModel, ecModel) {
  32535. var dataAll = seriesModel.getRawData();
  32536. var idxMap = {};
  32537. var data = seriesModel.getData();
  32538. data.each(function (idx) {
  32539. var rawIdx = data.getRawIndex(idx);
  32540. idxMap[rawIdx] = idx;
  32541. });
  32542. dataAll.each(function (rawIdx) {
  32543. var filteredIdx = idxMap[rawIdx];
  32544. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  32545. var singleDataColor = filteredIdx != null
  32546. && data.getItemVisual(filteredIdx, 'color', true);
  32547. if (!singleDataColor) {
  32548. // FIXME Performance
  32549. var itemModel = dataAll.getItemModel(rawIdx);
  32550. var color = itemModel.get('itemStyle.color')
  32551. || seriesModel.getColorFromPalette(
  32552. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  32553. dataAll.count()
  32554. );
  32555. // Legend may use the visual info in data before processed
  32556. dataAll.setItemVisual(rawIdx, 'color', color);
  32557. // Data is not filtered
  32558. if (filteredIdx != null) {
  32559. data.setItemVisual(filteredIdx, 'color', color);
  32560. }
  32561. }
  32562. else {
  32563. // Set data all color for legend
  32564. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  32565. }
  32566. });
  32567. }
  32568. };
  32569. };
  32570. // FIXME emphasis label position is not same with normal label position
  32571. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  32572. list.sort(function (a, b) {
  32573. return a.y - b.y;
  32574. });
  32575. // 压
  32576. function shiftDown(start, end, delta, dir) {
  32577. for (var j = start; j < end; j++) {
  32578. list[j].y += delta;
  32579. if (j > start
  32580. && j + 1 < end
  32581. && list[j + 1].y > list[j].y + list[j].height
  32582. ) {
  32583. shiftUp(j, delta / 2);
  32584. return;
  32585. }
  32586. }
  32587. shiftUp(end - 1, delta / 2);
  32588. }
  32589. // 弹
  32590. function shiftUp(end, delta) {
  32591. for (var j = end; j >= 0; j--) {
  32592. list[j].y -= delta;
  32593. if (j > 0
  32594. && list[j].y > list[j - 1].y + list[j - 1].height
  32595. ) {
  32596. break;
  32597. }
  32598. }
  32599. }
  32600. function changeX(list, isDownList, cx, cy, r, dir) {
  32601. var lastDeltaX = dir > 0
  32602. ? isDownList // 右侧
  32603. ? Number.MAX_VALUE // 下
  32604. : 0 // 上
  32605. : isDownList // 左侧
  32606. ? Number.MAX_VALUE // 下
  32607. : 0; // 上
  32608. for (var i = 0, l = list.length; i < l; i++) {
  32609. // Not change x for center label
  32610. if (list[i].position === 'center') {
  32611. continue;
  32612. }
  32613. var deltaY = Math.abs(list[i].y - cy);
  32614. var length = list[i].len;
  32615. var length2 = list[i].len2;
  32616. var deltaX = (deltaY < r + length)
  32617. ? Math.sqrt(
  32618. (r + length + length2) * (r + length + length2)
  32619. - deltaY * deltaY
  32620. )
  32621. : Math.abs(list[i].x - cx);
  32622. if (isDownList && deltaX >= lastDeltaX) {
  32623. // 右下,左下
  32624. deltaX = lastDeltaX - 10;
  32625. }
  32626. if (!isDownList && deltaX <= lastDeltaX) {
  32627. // 右上,左上
  32628. deltaX = lastDeltaX + 10;
  32629. }
  32630. list[i].x = cx + deltaX * dir;
  32631. lastDeltaX = deltaX;
  32632. }
  32633. }
  32634. var lastY = 0;
  32635. var delta;
  32636. var len = list.length;
  32637. var upList = [];
  32638. var downList = [];
  32639. for (var i = 0; i < len; i++) {
  32640. delta = list[i].y - lastY;
  32641. if (delta < 0) {
  32642. shiftDown(i, len, -delta, dir);
  32643. }
  32644. lastY = list[i].y + list[i].height;
  32645. }
  32646. if (viewHeight - lastY < 0) {
  32647. shiftUp(len - 1, lastY - viewHeight);
  32648. }
  32649. for (var i = 0; i < len; i++) {
  32650. if (list[i].y >= cy) {
  32651. downList.push(list[i]);
  32652. }
  32653. else {
  32654. upList.push(list[i]);
  32655. }
  32656. }
  32657. changeX(upList, false, cx, cy, r, dir);
  32658. changeX(downList, true, cx, cy, r, dir);
  32659. }
  32660. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  32661. var leftList = [];
  32662. var rightList = [];
  32663. for (var i = 0; i < labelLayoutList.length; i++) {
  32664. if (labelLayoutList[i].x < cx) {
  32665. leftList.push(labelLayoutList[i]);
  32666. }
  32667. else {
  32668. rightList.push(labelLayoutList[i]);
  32669. }
  32670. }
  32671. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  32672. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  32673. for (var i = 0; i < labelLayoutList.length; i++) {
  32674. var linePoints = labelLayoutList[i].linePoints;
  32675. if (linePoints) {
  32676. var dist = linePoints[1][0] - linePoints[2][0];
  32677. if (labelLayoutList[i].x < cx) {
  32678. linePoints[2][0] = labelLayoutList[i].x + 3;
  32679. }
  32680. else {
  32681. linePoints[2][0] = labelLayoutList[i].x - 3;
  32682. }
  32683. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  32684. linePoints[1][0] = linePoints[2][0] + dist;
  32685. }
  32686. }
  32687. }
  32688. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  32689. var data = seriesModel.getData();
  32690. var labelLayoutList = [];
  32691. var cx;
  32692. var cy;
  32693. var hasLabelRotate = false;
  32694. data.each(function (idx) {
  32695. var layout = data.getItemLayout(idx);
  32696. var itemModel = data.getItemModel(idx);
  32697. var labelModel = itemModel.getModel('label');
  32698. // Use position in normal or emphasis
  32699. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  32700. var labelLineModel = itemModel.getModel('labelLine');
  32701. var labelLineLen = labelLineModel.get('length');
  32702. var labelLineLen2 = labelLineModel.get('length2');
  32703. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32704. var dx = Math.cos(midAngle);
  32705. var dy = Math.sin(midAngle);
  32706. var textX;
  32707. var textY;
  32708. var linePoints;
  32709. var textAlign;
  32710. cx = layout.cx;
  32711. cy = layout.cy;
  32712. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  32713. if (labelPosition === 'center') {
  32714. textX = layout.cx;
  32715. textY = layout.cy;
  32716. textAlign = 'center';
  32717. }
  32718. else {
  32719. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  32720. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  32721. textX = x1 + dx * 3;
  32722. textY = y1 + dy * 3;
  32723. if (!isLabelInside) {
  32724. // For roseType
  32725. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  32726. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  32727. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  32728. var y3 = y2;
  32729. textX = x3 + (dx < 0 ? -5 : 5);
  32730. textY = y3;
  32731. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  32732. }
  32733. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  32734. }
  32735. var font = labelModel.getFont();
  32736. var labelRotate = labelModel.get('rotate')
  32737. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  32738. var text = seriesModel.getFormattedLabel(idx, 'normal')
  32739. || data.getName(idx);
  32740. var textRect = getBoundingRect(
  32741. text, font, textAlign, 'top'
  32742. );
  32743. hasLabelRotate = !!labelRotate;
  32744. layout.label = {
  32745. x: textX,
  32746. y: textY,
  32747. position: labelPosition,
  32748. height: textRect.height,
  32749. len: labelLineLen,
  32750. len2: labelLineLen2,
  32751. linePoints: linePoints,
  32752. textAlign: textAlign,
  32753. verticalAlign: 'middle',
  32754. rotation: labelRotate,
  32755. inside: isLabelInside
  32756. };
  32757. // Not layout the inside label
  32758. if (!isLabelInside) {
  32759. labelLayoutList.push(layout.label);
  32760. }
  32761. });
  32762. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  32763. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  32764. }
  32765. };
  32766. var PI2$4 = Math.PI * 2;
  32767. var RADIAN = Math.PI / 180;
  32768. var pieLayout = function (seriesType, ecModel, api, payload) {
  32769. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32770. var data = seriesModel.getData();
  32771. var valueDim = data.mapDimension('value');
  32772. var center = seriesModel.get('center');
  32773. var radius = seriesModel.get('radius');
  32774. if (!isArray(radius)) {
  32775. radius = [0, radius];
  32776. }
  32777. if (!isArray(center)) {
  32778. center = [center, center];
  32779. }
  32780. var width = api.getWidth();
  32781. var height = api.getHeight();
  32782. var size = Math.min(width, height);
  32783. var cx = parsePercent$1(center[0], width);
  32784. var cy = parsePercent$1(center[1], height);
  32785. var r0 = parsePercent$1(radius[0], size / 2);
  32786. var r = parsePercent$1(radius[1], size / 2);
  32787. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  32788. var minAngle = seriesModel.get('minAngle') * RADIAN;
  32789. var validDataCount = 0;
  32790. data.each(valueDim, function (value) {
  32791. !isNaN(value) && validDataCount++;
  32792. });
  32793. var sum = data.getSum(valueDim);
  32794. // Sum may be 0
  32795. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  32796. var clockwise = seriesModel.get('clockwise');
  32797. var roseType = seriesModel.get('roseType');
  32798. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32799. // [0...max]
  32800. var extent = data.getDataExtent(valueDim);
  32801. extent[0] = 0;
  32802. // In the case some sector angle is smaller than minAngle
  32803. var restAngle = PI2$4;
  32804. var valueSumLargerThanMinAngle = 0;
  32805. var currentAngle = startAngle;
  32806. var dir = clockwise ? 1 : -1;
  32807. data.each(valueDim, function (value, idx) {
  32808. var angle;
  32809. if (isNaN(value)) {
  32810. data.setItemLayout(idx, {
  32811. angle: NaN,
  32812. startAngle: NaN,
  32813. endAngle: NaN,
  32814. clockwise: clockwise,
  32815. cx: cx,
  32816. cy: cy,
  32817. r0: r0,
  32818. r: roseType
  32819. ? NaN
  32820. : r
  32821. });
  32822. return;
  32823. }
  32824. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32825. if (roseType !== 'area') {
  32826. angle = (sum === 0 && stillShowZeroSum)
  32827. ? unitRadian : (value * unitRadian);
  32828. }
  32829. else {
  32830. angle = PI2$4 / validDataCount;
  32831. }
  32832. if (angle < minAngle) {
  32833. angle = minAngle;
  32834. restAngle -= minAngle;
  32835. }
  32836. else {
  32837. valueSumLargerThanMinAngle += value;
  32838. }
  32839. var endAngle = currentAngle + dir * angle;
  32840. data.setItemLayout(idx, {
  32841. angle: angle,
  32842. startAngle: currentAngle,
  32843. endAngle: endAngle,
  32844. clockwise: clockwise,
  32845. cx: cx,
  32846. cy: cy,
  32847. r0: r0,
  32848. r: roseType
  32849. ? linearMap(value, extent, [r0, r])
  32850. : r
  32851. });
  32852. currentAngle = endAngle;
  32853. });
  32854. // Some sector is constrained by minAngle
  32855. // Rest sectors needs recalculate angle
  32856. if (restAngle < PI2$4 && validDataCount) {
  32857. // Average the angle if rest angle is not enough after all angles is
  32858. // Constrained by minAngle
  32859. if (restAngle <= 1e-3) {
  32860. var angle = PI2$4 / validDataCount;
  32861. data.each(valueDim, function (value, idx) {
  32862. if (!isNaN(value)) {
  32863. var layout = data.getItemLayout(idx);
  32864. layout.angle = angle;
  32865. layout.startAngle = startAngle + dir * idx * angle;
  32866. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32867. }
  32868. });
  32869. }
  32870. else {
  32871. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32872. currentAngle = startAngle;
  32873. data.each(valueDim, function (value, idx) {
  32874. if (!isNaN(value)) {
  32875. var layout = data.getItemLayout(idx);
  32876. var angle = layout.angle === minAngle
  32877. ? minAngle : value * unitRadian;
  32878. layout.startAngle = currentAngle;
  32879. layout.endAngle = currentAngle + dir * angle;
  32880. currentAngle += dir * angle;
  32881. }
  32882. });
  32883. }
  32884. }
  32885. labelLayout(seriesModel, r, width, height);
  32886. });
  32887. };
  32888. var dataFilter = function (seriesType) {
  32889. return {
  32890. seriesType: seriesType,
  32891. reset: function (seriesModel, ecModel) {
  32892. var legendModels = ecModel.findComponents({
  32893. mainType: 'legend'
  32894. });
  32895. if (!legendModels || !legendModels.length) {
  32896. return;
  32897. }
  32898. var data = seriesModel.getData();
  32899. data.filterSelf(function (idx) {
  32900. var name = data.getName(idx);
  32901. // If in any legend component the status is not selected.
  32902. for (var i = 0; i < legendModels.length; i++) {
  32903. if (!legendModels[i].isSelected(name)) {
  32904. return false;
  32905. }
  32906. }
  32907. return true;
  32908. });
  32909. }
  32910. };
  32911. };
  32912. createDataSelectAction('pie', [{
  32913. type: 'pieToggleSelect',
  32914. event: 'pieselectchanged',
  32915. method: 'toggleSelected'
  32916. }, {
  32917. type: 'pieSelect',
  32918. event: 'pieselected',
  32919. method: 'select'
  32920. }, {
  32921. type: 'pieUnSelect',
  32922. event: 'pieunselected',
  32923. method: 'unSelect'
  32924. }]);
  32925. registerVisual(dataColor('pie'));
  32926. registerLayout(curry(pieLayout, 'pie'));
  32927. registerProcessor(dataFilter('pie'));
  32928. SeriesModel.extend({
  32929. type: 'series.scatter',
  32930. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32931. getInitialData: function (option, ecModel) {
  32932. return createListFromArray(this.getSource(), this);
  32933. },
  32934. brushSelector: 'point',
  32935. getProgressive: function () {
  32936. var progressive = this.option.progressive;
  32937. if (progressive == null) {
  32938. // PENDING
  32939. return this.option.large ? 5e3 : this.get('progressive');
  32940. }
  32941. return progressive;
  32942. },
  32943. getProgressiveThreshold: function () {
  32944. var progressiveThreshold = this.option.progressiveThreshold;
  32945. if (progressiveThreshold == null) {
  32946. // PENDING
  32947. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32948. }
  32949. return progressiveThreshold;
  32950. },
  32951. defaultOption: {
  32952. coordinateSystem: 'cartesian2d',
  32953. zlevel: 0,
  32954. z: 2,
  32955. legendHoverLink: true,
  32956. hoverAnimation: true,
  32957. // Cartesian coordinate system
  32958. // xAxisIndex: 0,
  32959. // yAxisIndex: 0,
  32960. // Polar coordinate system
  32961. // polarIndex: 0,
  32962. // Geo coordinate system
  32963. // geoIndex: 0,
  32964. // symbol: null, // 图形类型
  32965. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32966. // symbolRotate: null, // 图形旋转控制
  32967. large: false,
  32968. // Available when large is true
  32969. largeThreshold: 2000,
  32970. // cursor: null,
  32971. // label: {
  32972. // show: false
  32973. // distance: 5,
  32974. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32975. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32976. // 'inside'|'left'|'right'|'top'|'bottom'
  32977. // 默认使用全局文本样式,详见TEXTSTYLE
  32978. // },
  32979. itemStyle: {
  32980. opacity: 0.8
  32981. // color: 各异
  32982. },
  32983. progressive: null
  32984. }
  32985. });
  32986. // TODO Batch by color
  32987. var BOOST_SIZE_THRESHOLD = 4;
  32988. var LargeSymbolPath = extendShape({
  32989. shape: {
  32990. points: null
  32991. },
  32992. symbolProxy: null,
  32993. buildPath: function (path, shape) {
  32994. var points = shape.points;
  32995. var size = shape.size;
  32996. var symbolProxy = this.symbolProxy;
  32997. var symbolProxyShape = symbolProxy.shape;
  32998. var ctx = path.getContext ? path.getContext() : path;
  32999. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  33000. // Do draw in afterBrush.
  33001. if (canBoost) {
  33002. return;
  33003. }
  33004. for (var i = 0; i < points.length;) {
  33005. var x = points[i++];
  33006. var y = points[i++];
  33007. if (isNaN(x) || isNaN(y)) {
  33008. continue;
  33009. }
  33010. symbolProxyShape.x = x - size[0] / 2;
  33011. symbolProxyShape.y = y - size[1] / 2;
  33012. symbolProxyShape.width = size[0];
  33013. symbolProxyShape.height = size[1];
  33014. symbolProxy.buildPath(path, symbolProxyShape, true);
  33015. }
  33016. },
  33017. afterBrush: function (ctx) {
  33018. var shape = this.shape;
  33019. var points = shape.points;
  33020. var size = shape.size;
  33021. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  33022. if (!canBoost) {
  33023. return;
  33024. }
  33025. this.setTransform(ctx);
  33026. // PENDING If style or other canvas status changed?
  33027. for (var i = 0; i < points.length;) {
  33028. var x = points[i++];
  33029. var y = points[i++];
  33030. if (isNaN(x) || isNaN(y)) {
  33031. continue;
  33032. }
  33033. // fillRect is faster than building a rect path and draw.
  33034. // And it support light globalCompositeOperation.
  33035. ctx.fillRect(
  33036. x - size[0] / 2, y - size[1] / 2,
  33037. size[0], size[1]
  33038. );
  33039. }
  33040. this.restoreTransform(ctx);
  33041. },
  33042. findDataIndex: function (x, y) {
  33043. // TODO ???
  33044. // Consider transform
  33045. var shape = this.shape;
  33046. var points = shape.points;
  33047. var size = shape.size;
  33048. var w = Math.max(size[0], 4);
  33049. var h = Math.max(size[1], 4);
  33050. // Not consider transform
  33051. // Treat each element as a rect
  33052. // top down traverse
  33053. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  33054. var i = idx * 2;
  33055. var x0 = points[i] - w / 2;
  33056. var y0 = points[i + 1] - h / 2;
  33057. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  33058. return idx;
  33059. }
  33060. }
  33061. return -1;
  33062. }
  33063. });
  33064. function LargeSymbolDraw() {
  33065. this.group = new Group();
  33066. }
  33067. var largeSymbolProto = LargeSymbolDraw.prototype;
  33068. largeSymbolProto.isPersistent = function () {
  33069. return !this._incremental;
  33070. };
  33071. /**
  33072. * Update symbols draw by new data
  33073. * @param {module:echarts/data/List} data
  33074. */
  33075. largeSymbolProto.updateData = function (data) {
  33076. this.group.removeAll();
  33077. var symbolEl = new LargeSymbolPath({
  33078. rectHover: true,
  33079. cursor: 'default'
  33080. });
  33081. symbolEl.setShape({
  33082. points: data.getLayout('symbolPoints')
  33083. });
  33084. this._setCommon(symbolEl, data);
  33085. this.group.add(symbolEl);
  33086. this._incremental = null;
  33087. };
  33088. largeSymbolProto.updateLayout = function (data) {
  33089. if (this._incremental) {
  33090. return;
  33091. }
  33092. var points = data.getLayout('symbolPoints');
  33093. this.group.eachChild(function (child) {
  33094. if (child.startIndex != null) {
  33095. var len = (child.endIndex - child.startIndex) * 2;
  33096. var byteOffset = child.startIndex * 4 * 2;
  33097. points = new Float32Array(points.buffer, byteOffset, len);
  33098. }
  33099. child.setShape('points', points);
  33100. });
  33101. };
  33102. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  33103. this.group.removeAll();
  33104. this._clearIncremental();
  33105. // Only use incremental displayables when data amount is larger than 2 million.
  33106. // PENDING Incremental data?
  33107. if (data.count() > 2e6) {
  33108. if (!this._incremental) {
  33109. this._incremental = new IncrementalDisplayble({
  33110. silent: true
  33111. });
  33112. }
  33113. this.group.add(this._incremental);
  33114. }
  33115. else {
  33116. this._incremental = null;
  33117. }
  33118. };
  33119. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  33120. var symbolEl;
  33121. if (this._incremental) {
  33122. symbolEl = new LargeSymbolPath();
  33123. this._incremental.addDisplayable(symbolEl, true);
  33124. }
  33125. else {
  33126. symbolEl = new LargeSymbolPath({
  33127. rectHover: true,
  33128. cursor: 'default',
  33129. startIndex: taskParams.start,
  33130. endIndex: taskParams.end
  33131. });
  33132. symbolEl.incremental = true;
  33133. this.group.add(symbolEl);
  33134. }
  33135. symbolEl.setShape({
  33136. points: data.getLayout('symbolPoints')
  33137. });
  33138. this._setCommon(symbolEl, data, !!this._incremental);
  33139. };
  33140. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  33141. var hostModel = data.hostModel;
  33142. // TODO
  33143. // if (data.hasItemVisual.symbolSize) {
  33144. // // TODO typed array?
  33145. // symbolEl.setShape('sizes', data.mapArray(
  33146. // function (idx) {
  33147. // var size = data.getItemVisual(idx, 'symbolSize');
  33148. // return (size instanceof Array) ? size : [size, size];
  33149. // }
  33150. // ));
  33151. // }
  33152. // else {
  33153. var size = data.getVisual('symbolSize');
  33154. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  33155. // }
  33156. // Create symbolProxy to build path for each data
  33157. symbolEl.symbolProxy = createSymbol(
  33158. data.getVisual('symbol'), 0, 0, 0, 0
  33159. );
  33160. // Use symbolProxy setColor method
  33161. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  33162. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  33163. symbolEl.useStyle(
  33164. // Draw shadow when doing fillRect is extremely slow.
  33165. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  33166. );
  33167. var visualColor = data.getVisual('color');
  33168. if (visualColor) {
  33169. symbolEl.setColor(visualColor);
  33170. }
  33171. if (!isIncremental) {
  33172. // Enable tooltip
  33173. // PENDING May have performance issue when path is extremely large
  33174. symbolEl.seriesIndex = hostModel.seriesIndex;
  33175. symbolEl.on('mousemove', function (e) {
  33176. symbolEl.dataIndex = null;
  33177. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  33178. if (dataIndex >= 0) {
  33179. // Provide dataIndex for tooltip
  33180. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  33181. }
  33182. });
  33183. }
  33184. };
  33185. largeSymbolProto.remove = function () {
  33186. this._clearIncremental();
  33187. this._incremental = null;
  33188. this.group.removeAll();
  33189. };
  33190. largeSymbolProto._clearIncremental = function () {
  33191. var incremental = this._incremental;
  33192. if (incremental) {
  33193. incremental.clearDisplaybles();
  33194. }
  33195. };
  33196. extendChartView({
  33197. type: 'scatter',
  33198. render: function (seriesModel, ecModel, api) {
  33199. var data = seriesModel.getData();
  33200. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33201. symbolDraw.updateData(data);
  33202. this._finished = true;
  33203. },
  33204. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  33205. var data = seriesModel.getData();
  33206. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33207. symbolDraw.incrementalPrepareUpdate(data);
  33208. this._finished = false;
  33209. },
  33210. incrementalRender: function (taskParams, seriesModel, ecModel) {
  33211. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  33212. this._finished = taskParams.end === seriesModel.getData().count();
  33213. },
  33214. updateTransform: function (seriesModel, ecModel, api) {
  33215. var data = seriesModel.getData();
  33216. // Must mark group dirty and make sure the incremental layer will be cleared
  33217. // PENDING
  33218. this.group.dirty();
  33219. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  33220. return {
  33221. update: true
  33222. };
  33223. }
  33224. else {
  33225. var res = pointsLayout().reset(seriesModel);
  33226. if (res.progress) {
  33227. res.progress({ start: 0, end: data.count() }, data);
  33228. }
  33229. this._symbolDraw.updateLayout(data);
  33230. }
  33231. },
  33232. _updateSymbolDraw: function (data, seriesModel) {
  33233. var symbolDraw = this._symbolDraw;
  33234. var pipelineContext = seriesModel.pipelineContext;
  33235. var isLargeDraw = pipelineContext.large;
  33236. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  33237. symbolDraw && symbolDraw.remove();
  33238. symbolDraw = this._symbolDraw = isLargeDraw
  33239. ? new LargeSymbolDraw()
  33240. : new SymbolDraw();
  33241. this._isLargeDraw = isLargeDraw;
  33242. this.group.removeAll();
  33243. }
  33244. this.group.add(symbolDraw.group);
  33245. return symbolDraw;
  33246. },
  33247. remove: function (ecModel, api) {
  33248. this._symbolDraw && this._symbolDraw.remove(true);
  33249. this._symbolDraw = null;
  33250. },
  33251. dispose: function () {}
  33252. });
  33253. // import * as zrUtil from 'zrender/src/core/util';
  33254. // In case developer forget to include grid component
  33255. registerVisual(visualSymbol('scatter', 'circle'));
  33256. registerLayout(pointsLayout('scatter'));
  33257. // echarts.registerProcessor(function (ecModel, api) {
  33258. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  33259. // var data = seriesModel.getData();
  33260. // var coordSys = seriesModel.coordinateSystem;
  33261. // if (coordSys.type !== 'geo') {
  33262. // return;
  33263. // }
  33264. // var startPt = coordSys.pointToData([0, 0]);
  33265. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  33266. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  33267. // return data.mapDimension(dim);
  33268. // });
  33269. // var range = {};
  33270. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  33271. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  33272. // data.selectRange(range);
  33273. // });
  33274. // });
  33275. function IndicatorAxis(dim, scale, radiusExtent) {
  33276. Axis.call(this, dim, scale, radiusExtent);
  33277. /**
  33278. * Axis type
  33279. * - 'category'
  33280. * - 'value'
  33281. * - 'time'
  33282. * - 'log'
  33283. * @type {string}
  33284. */
  33285. this.type = 'value';
  33286. this.angle = 0;
  33287. /**
  33288. * Indicator name
  33289. * @type {string}
  33290. */
  33291. this.name = '';
  33292. /**
  33293. * @type {module:echarts/model/Model}
  33294. */
  33295. this.model;
  33296. }
  33297. inherits(IndicatorAxis, Axis);
  33298. // TODO clockwise
  33299. function Radar(radarModel, ecModel, api) {
  33300. this._model = radarModel;
  33301. /**
  33302. * Radar dimensions
  33303. * @type {Array.<string>}
  33304. */
  33305. this.dimensions = [];
  33306. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  33307. var dim = 'indicator_' + idx;
  33308. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  33309. indicatorAxis.name = indicatorModel.get('name');
  33310. // Inject model and axis
  33311. indicatorAxis.model = indicatorModel;
  33312. indicatorModel.axis = indicatorAxis;
  33313. this.dimensions.push(dim);
  33314. return indicatorAxis;
  33315. }, this);
  33316. this.resize(radarModel, api);
  33317. /**
  33318. * @type {number}
  33319. * @readOnly
  33320. */
  33321. this.cx;
  33322. /**
  33323. * @type {number}
  33324. * @readOnly
  33325. */
  33326. this.cy;
  33327. /**
  33328. * @type {number}
  33329. * @readOnly
  33330. */
  33331. this.r;
  33332. /**
  33333. * @type {number}
  33334. * @readOnly
  33335. */
  33336. this.startAngle;
  33337. }
  33338. Radar.prototype.getIndicatorAxes = function () {
  33339. return this._indicatorAxes;
  33340. };
  33341. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  33342. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  33343. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  33344. };
  33345. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  33346. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  33347. var angle = indicatorAxis.angle;
  33348. var x = this.cx + coord * Math.cos(angle);
  33349. var y = this.cy - coord * Math.sin(angle);
  33350. return [x, y];
  33351. };
  33352. Radar.prototype.pointToData = function (pt) {
  33353. var dx = pt[0] - this.cx;
  33354. var dy = pt[1] - this.cy;
  33355. var radius = Math.sqrt(dx * dx + dy * dy);
  33356. dx /= radius;
  33357. dy /= radius;
  33358. var radian = Math.atan2(-dy, dx);
  33359. // Find the closest angle
  33360. // FIXME index can calculated directly
  33361. var minRadianDiff = Infinity;
  33362. var closestAxis;
  33363. var closestAxisIdx = -1;
  33364. for (var i = 0; i < this._indicatorAxes.length; i++) {
  33365. var indicatorAxis = this._indicatorAxes[i];
  33366. var diff = Math.abs(radian - indicatorAxis.angle);
  33367. if (diff < minRadianDiff) {
  33368. closestAxis = indicatorAxis;
  33369. closestAxisIdx = i;
  33370. minRadianDiff = diff;
  33371. }
  33372. }
  33373. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  33374. };
  33375. Radar.prototype.resize = function (radarModel, api) {
  33376. var center = radarModel.get('center');
  33377. var viewWidth = api.getWidth();
  33378. var viewHeight = api.getHeight();
  33379. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  33380. this.cx = parsePercent$1(center[0], viewWidth);
  33381. this.cy = parsePercent$1(center[1], viewHeight);
  33382. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  33383. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  33384. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  33385. indicatorAxis.setExtent(0, this.r);
  33386. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  33387. // Normalize to [-PI, PI]
  33388. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  33389. indicatorAxis.angle = angle;
  33390. }, this);
  33391. };
  33392. Radar.prototype.update = function (ecModel, api) {
  33393. var indicatorAxes = this._indicatorAxes;
  33394. var radarModel = this._model;
  33395. each$1(indicatorAxes, function (indicatorAxis) {
  33396. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  33397. });
  33398. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  33399. if (radarSeries.get('coordinateSystem') !== 'radar'
  33400. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  33401. ) {
  33402. return;
  33403. }
  33404. var data = radarSeries.getData();
  33405. each$1(indicatorAxes, function (indicatorAxis) {
  33406. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  33407. });
  33408. }, this);
  33409. var splitNumber = radarModel.get('splitNumber');
  33410. function increaseInterval(interval) {
  33411. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  33412. // Increase interval
  33413. var f = interval / exp10;
  33414. if (f === 2) {
  33415. f = 5;
  33416. }
  33417. else { // f is 2 or 5
  33418. f *= 2;
  33419. }
  33420. return f * exp10;
  33421. }
  33422. // Force all the axis fixing the maxSplitNumber.
  33423. each$1(indicatorAxes, function (indicatorAxis, idx) {
  33424. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  33425. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  33426. var axisModel = indicatorAxis.model;
  33427. var scale = indicatorAxis.scale;
  33428. var fixedMin = axisModel.getMin();
  33429. var fixedMax = axisModel.getMax();
  33430. var interval = scale.getInterval();
  33431. if (fixedMin != null && fixedMax != null) {
  33432. // User set min, max, divide to get new interval
  33433. scale.setExtent(+fixedMin, +fixedMax);
  33434. scale.setInterval(
  33435. (fixedMax - fixedMin) / splitNumber
  33436. );
  33437. }
  33438. else if (fixedMin != null) {
  33439. var max;
  33440. // User set min, expand extent on the other side
  33441. do {
  33442. max = fixedMin + interval * splitNumber;
  33443. scale.setExtent(+fixedMin, max);
  33444. // Interval must been set after extent
  33445. // FIXME
  33446. scale.setInterval(interval);
  33447. interval = increaseInterval(interval);
  33448. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  33449. }
  33450. else if (fixedMax != null) {
  33451. var min;
  33452. // User set min, expand extent on the other side
  33453. do {
  33454. min = fixedMax - interval * splitNumber;
  33455. scale.setExtent(min, +fixedMax);
  33456. scale.setInterval(interval);
  33457. interval = increaseInterval(interval);
  33458. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  33459. }
  33460. else {
  33461. var nicedSplitNumber = scale.getTicks().length - 1;
  33462. if (nicedSplitNumber > splitNumber) {
  33463. interval = increaseInterval(interval);
  33464. }
  33465. // PENDING
  33466. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  33467. var halfSplitNumber = Math.round(splitNumber / 2);
  33468. scale.setExtent(
  33469. round$1(center - halfSplitNumber * interval),
  33470. round$1(center + (splitNumber - halfSplitNumber) * interval)
  33471. );
  33472. scale.setInterval(interval);
  33473. }
  33474. });
  33475. };
  33476. /**
  33477. * Radar dimensions is based on the data
  33478. * @type {Array}
  33479. */
  33480. Radar.dimensions = [];
  33481. Radar.create = function (ecModel, api) {
  33482. var radarList = [];
  33483. ecModel.eachComponent('radar', function (radarModel) {
  33484. var radar = new Radar(radarModel, ecModel, api);
  33485. radarList.push(radar);
  33486. radarModel.coordinateSystem = radar;
  33487. });
  33488. ecModel.eachSeriesByType('radar', function (radarSeries) {
  33489. if (radarSeries.get('coordinateSystem') === 'radar') {
  33490. // Inject coordinate system
  33491. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  33492. }
  33493. });
  33494. return radarList;
  33495. };
  33496. CoordinateSystemManager.register('radar', Radar);
  33497. var valueAxisDefault = axisDefault.valueAxis;
  33498. function defaultsShow(opt, show) {
  33499. return defaults({
  33500. show: show
  33501. }, opt);
  33502. }
  33503. var RadarModel = extendComponentModel({
  33504. type: 'radar',
  33505. optionUpdated: function () {
  33506. var boundaryGap = this.get('boundaryGap');
  33507. var splitNumber = this.get('splitNumber');
  33508. var scale = this.get('scale');
  33509. var axisLine = this.get('axisLine');
  33510. var axisTick = this.get('axisTick');
  33511. var axisLabel = this.get('axisLabel');
  33512. var nameTextStyle = this.get('name');
  33513. var showName = this.get('name.show');
  33514. var nameFormatter = this.get('name.formatter');
  33515. var nameGap = this.get('nameGap');
  33516. var triggerEvent = this.get('triggerEvent');
  33517. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  33518. // PENDING
  33519. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  33520. indicatorOpt.min = 0;
  33521. }
  33522. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  33523. indicatorOpt.max = 0;
  33524. }
  33525. var iNameTextStyle = nameTextStyle;
  33526. if(indicatorOpt.color != null) {
  33527. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  33528. }
  33529. // Use same configuration
  33530. indicatorOpt = merge(clone(indicatorOpt), {
  33531. boundaryGap: boundaryGap,
  33532. splitNumber: splitNumber,
  33533. scale: scale,
  33534. axisLine: axisLine,
  33535. axisTick: axisTick,
  33536. axisLabel: axisLabel,
  33537. // Competitable with 2 and use text
  33538. name: indicatorOpt.text,
  33539. nameLocation: 'end',
  33540. nameGap: nameGap,
  33541. // min: 0,
  33542. nameTextStyle: iNameTextStyle,
  33543. triggerEvent: triggerEvent
  33544. }, false);
  33545. if (!showName) {
  33546. indicatorOpt.name = '';
  33547. }
  33548. if (typeof nameFormatter === 'string') {
  33549. var indName = indicatorOpt.name;
  33550. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  33551. }
  33552. else if (typeof nameFormatter === 'function') {
  33553. indicatorOpt.name = nameFormatter(
  33554. indicatorOpt.name, indicatorOpt
  33555. );
  33556. }
  33557. var model = extend(
  33558. new Model(indicatorOpt, null, this.ecModel),
  33559. axisModelCommonMixin
  33560. );
  33561. // For triggerEvent.
  33562. model.mainType = 'radar';
  33563. model.componentIndex = this.componentIndex;
  33564. return model;
  33565. }, this);
  33566. this.getIndicatorModels = function () {
  33567. return indicatorModels;
  33568. };
  33569. },
  33570. defaultOption: {
  33571. zlevel: 0,
  33572. z: 0,
  33573. center: ['50%', '50%'],
  33574. radius: '75%',
  33575. startAngle: 90,
  33576. name: {
  33577. show: true
  33578. // formatter: null
  33579. // textStyle: {}
  33580. },
  33581. boundaryGap: [0, 0],
  33582. splitNumber: 5,
  33583. nameGap: 15,
  33584. scale: false,
  33585. // Polygon or circle
  33586. shape: 'polygon',
  33587. axisLine: merge(
  33588. {
  33589. lineStyle: {
  33590. color: '#bbb'
  33591. }
  33592. },
  33593. valueAxisDefault.axisLine
  33594. ),
  33595. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  33596. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  33597. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  33598. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  33599. // {text, min, max}
  33600. indicator: []
  33601. }
  33602. });
  33603. var axisBuilderAttrs$1 = [
  33604. 'axisLine', 'axisTickLabel', 'axisName'
  33605. ];
  33606. extendComponentView({
  33607. type: 'radar',
  33608. render: function (radarModel, ecModel, api) {
  33609. var group = this.group;
  33610. group.removeAll();
  33611. this._buildAxes(radarModel);
  33612. this._buildSplitLineAndArea(radarModel);
  33613. },
  33614. _buildAxes: function (radarModel) {
  33615. var radar = radarModel.coordinateSystem;
  33616. var indicatorAxes = radar.getIndicatorAxes();
  33617. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  33618. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  33619. position: [radar.cx, radar.cy],
  33620. rotation: indicatorAxis.angle,
  33621. labelDirection: -1,
  33622. tickDirection: -1,
  33623. nameDirection: 1
  33624. });
  33625. return axisBuilder;
  33626. });
  33627. each$1(axisBuilders, function (axisBuilder) {
  33628. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  33629. this.group.add(axisBuilder.getGroup());
  33630. }, this);
  33631. },
  33632. _buildSplitLineAndArea: function (radarModel) {
  33633. var radar = radarModel.coordinateSystem;
  33634. var indicatorAxes = radar.getIndicatorAxes();
  33635. if (!indicatorAxes.length) {
  33636. return;
  33637. }
  33638. var shape = radarModel.get('shape');
  33639. var splitLineModel = radarModel.getModel('splitLine');
  33640. var splitAreaModel = radarModel.getModel('splitArea');
  33641. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33642. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33643. var showSplitLine = splitLineModel.get('show');
  33644. var showSplitArea = splitAreaModel.get('show');
  33645. var splitLineColors = lineStyleModel.get('color');
  33646. var splitAreaColors = areaStyleModel.get('color');
  33647. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  33648. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  33649. var splitLines = [];
  33650. var splitAreas = [];
  33651. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  33652. var colorIndex = idx % areaOrLineColorList.length;
  33653. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  33654. return colorIndex;
  33655. }
  33656. if (shape === 'circle') {
  33657. var ticksRadius = indicatorAxes[0].getTicksCoords();
  33658. var cx = radar.cx;
  33659. var cy = radar.cy;
  33660. for (var i = 0; i < ticksRadius.length; i++) {
  33661. if (showSplitLine) {
  33662. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  33663. splitLines[colorIndex].push(new Circle({
  33664. shape: {
  33665. cx: cx,
  33666. cy: cy,
  33667. r: ticksRadius[i]
  33668. }
  33669. }));
  33670. }
  33671. if (showSplitArea && i < ticksRadius.length - 1) {
  33672. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  33673. splitAreas[colorIndex].push(new Ring({
  33674. shape: {
  33675. cx: cx,
  33676. cy: cy,
  33677. r0: ticksRadius[i],
  33678. r: ticksRadius[i + 1]
  33679. }
  33680. }));
  33681. }
  33682. }
  33683. }
  33684. // Polyyon
  33685. else {
  33686. var realSplitNumber;
  33687. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  33688. var ticksCoords = indicatorAxis.getTicksCoords();
  33689. realSplitNumber = realSplitNumber == null
  33690. ? ticksCoords.length - 1
  33691. : Math.min(ticksCoords.length - 1, realSplitNumber);
  33692. return map(ticksCoords, function (tickCoord) {
  33693. return radar.coordToPoint(tickCoord, idx);
  33694. });
  33695. });
  33696. var prevPoints = [];
  33697. for (var i = 0; i <= realSplitNumber; i++) {
  33698. var points = [];
  33699. for (var j = 0; j < indicatorAxes.length; j++) {
  33700. points.push(axesTicksPoints[j][i]);
  33701. }
  33702. // Close
  33703. if (points[0]) {
  33704. points.push(points[0].slice());
  33705. }
  33706. else {
  33707. if (__DEV__) {
  33708. console.error('Can\'t draw value axis ' + i);
  33709. }
  33710. }
  33711. if (showSplitLine) {
  33712. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  33713. splitLines[colorIndex].push(new Polyline({
  33714. shape: {
  33715. points: points
  33716. }
  33717. }));
  33718. }
  33719. if (showSplitArea && prevPoints) {
  33720. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  33721. splitAreas[colorIndex].push(new Polygon({
  33722. shape: {
  33723. points: points.concat(prevPoints)
  33724. }
  33725. }));
  33726. }
  33727. prevPoints = points.slice().reverse();
  33728. }
  33729. }
  33730. var lineStyle = lineStyleModel.getLineStyle();
  33731. var areaStyle = areaStyleModel.getAreaStyle();
  33732. // Add splitArea before splitLine
  33733. each$1(splitAreas, function (splitAreas, idx) {
  33734. this.group.add(mergePath(
  33735. splitAreas, {
  33736. style: defaults({
  33737. stroke: 'none',
  33738. fill: splitAreaColors[idx % splitAreaColors.length]
  33739. }, areaStyle),
  33740. silent: true
  33741. }
  33742. ));
  33743. }, this);
  33744. each$1(splitLines, function (splitLines, idx) {
  33745. this.group.add(mergePath(
  33746. splitLines, {
  33747. style: defaults({
  33748. fill: 'none',
  33749. stroke: splitLineColors[idx % splitLineColors.length]
  33750. }, lineStyle),
  33751. silent: true
  33752. }
  33753. ));
  33754. }, this);
  33755. }
  33756. });
  33757. var RadarSeries = SeriesModel.extend({
  33758. type: 'series.radar',
  33759. dependencies: ['radar'],
  33760. // Overwrite
  33761. init: function (option) {
  33762. RadarSeries.superApply(this, 'init', arguments);
  33763. // Enable legend selection for each data item
  33764. // Use a function instead of direct access because data reference may changed
  33765. this.legendDataProvider = function () {
  33766. return this.getRawData();
  33767. };
  33768. },
  33769. getInitialData: function (option, ecModel) {
  33770. return createListSimply(this, {
  33771. generateCoord: 'indicator_',
  33772. generateCoordCount: Infinity
  33773. });
  33774. },
  33775. formatTooltip: function (dataIndex) {
  33776. var data = this.getData();
  33777. var coordSys = this.coordinateSystem;
  33778. var indicatorAxes = coordSys.getIndicatorAxes();
  33779. var name = this.getData().getName(dataIndex);
  33780. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  33781. + map(indicatorAxes, function (axis, idx) {
  33782. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  33783. return encodeHTML(axis.name + ' : ' + val);
  33784. }).join('<br />');
  33785. },
  33786. defaultOption: {
  33787. zlevel: 0,
  33788. z: 2,
  33789. coordinateSystem: 'radar',
  33790. legendHoverLink: true,
  33791. radarIndex: 0,
  33792. lineStyle: {
  33793. width: 2,
  33794. type: 'solid'
  33795. },
  33796. label: {
  33797. position: 'top'
  33798. },
  33799. // areaStyle: {
  33800. // },
  33801. // itemStyle: {}
  33802. symbol: 'emptyCircle',
  33803. symbolSize: 4
  33804. // symbolRotate: null
  33805. }
  33806. });
  33807. function normalizeSymbolSize(symbolSize) {
  33808. if (!isArray(symbolSize)) {
  33809. symbolSize = [+symbolSize, +symbolSize];
  33810. }
  33811. return symbolSize;
  33812. }
  33813. extendChartView({
  33814. type: 'radar',
  33815. render: function (seriesModel, ecModel, api) {
  33816. var polar = seriesModel.coordinateSystem;
  33817. var group = this.group;
  33818. var data = seriesModel.getData();
  33819. var oldData = this._data;
  33820. function createSymbol$$1(data, idx) {
  33821. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33822. var color = data.getItemVisual(idx, 'color');
  33823. if (symbolType === 'none') {
  33824. return;
  33825. }
  33826. var symbolSize = normalizeSymbolSize(
  33827. data.getItemVisual(idx, 'symbolSize')
  33828. );
  33829. var symbolPath = createSymbol(
  33830. symbolType, -1, -1, 2, 2, color
  33831. );
  33832. symbolPath.attr({
  33833. style: {
  33834. strokeNoScale: true
  33835. },
  33836. z2: 100,
  33837. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  33838. });
  33839. return symbolPath;
  33840. }
  33841. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  33842. // Simply rerender all
  33843. symbolGroup.removeAll();
  33844. for (var i = 0; i < newPoints.length - 1; i++) {
  33845. var symbolPath = createSymbol$$1(data, idx);
  33846. if (symbolPath) {
  33847. symbolPath.__dimIdx = i;
  33848. if (oldPoints[i]) {
  33849. symbolPath.attr('position', oldPoints[i]);
  33850. graphic[isInit ? 'initProps' : 'updateProps'](
  33851. symbolPath, {
  33852. position: newPoints[i]
  33853. }, seriesModel, idx
  33854. );
  33855. }
  33856. else {
  33857. symbolPath.attr('position', newPoints[i]);
  33858. }
  33859. symbolGroup.add(symbolPath);
  33860. }
  33861. }
  33862. }
  33863. function getInitialPoints(points) {
  33864. return map(points, function (pt) {
  33865. return [polar.cx, polar.cy];
  33866. });
  33867. }
  33868. data.diff(oldData)
  33869. .add(function (idx) {
  33870. var points = data.getItemLayout(idx);
  33871. if (!points) {
  33872. return;
  33873. }
  33874. var polygon = new Polygon();
  33875. var polyline = new Polyline();
  33876. var target = {
  33877. shape: {
  33878. points: points
  33879. }
  33880. };
  33881. polygon.shape.points = getInitialPoints(points);
  33882. polyline.shape.points = getInitialPoints(points);
  33883. initProps(polygon, target, seriesModel, idx);
  33884. initProps(polyline, target, seriesModel, idx);
  33885. var itemGroup = new Group();
  33886. var symbolGroup = new Group();
  33887. itemGroup.add(polyline);
  33888. itemGroup.add(polygon);
  33889. itemGroup.add(symbolGroup);
  33890. updateSymbols(
  33891. polyline.shape.points, points, symbolGroup, data, idx, true
  33892. );
  33893. data.setItemGraphicEl(idx, itemGroup);
  33894. })
  33895. .update(function (newIdx, oldIdx) {
  33896. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  33897. var polyline = itemGroup.childAt(0);
  33898. var polygon = itemGroup.childAt(1);
  33899. var symbolGroup = itemGroup.childAt(2);
  33900. var target = {
  33901. shape: {
  33902. points: data.getItemLayout(newIdx)
  33903. }
  33904. };
  33905. if (!target.shape.points) {
  33906. return;
  33907. }
  33908. updateSymbols(
  33909. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  33910. );
  33911. updateProps(polyline, target, seriesModel);
  33912. updateProps(polygon, target, seriesModel);
  33913. data.setItemGraphicEl(newIdx, itemGroup);
  33914. })
  33915. .remove(function (idx) {
  33916. group.remove(oldData.getItemGraphicEl(idx));
  33917. })
  33918. .execute();
  33919. data.eachItemGraphicEl(function (itemGroup, idx) {
  33920. var itemModel = data.getItemModel(idx);
  33921. var polyline = itemGroup.childAt(0);
  33922. var polygon = itemGroup.childAt(1);
  33923. var symbolGroup = itemGroup.childAt(2);
  33924. var color = data.getItemVisual(idx, 'color');
  33925. group.add(itemGroup);
  33926. polyline.useStyle(
  33927. defaults(
  33928. itemModel.getModel('lineStyle').getLineStyle(),
  33929. {
  33930. fill: 'none',
  33931. stroke: color
  33932. }
  33933. )
  33934. );
  33935. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  33936. var areaStyleModel = itemModel.getModel('areaStyle');
  33937. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  33938. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  33939. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  33940. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  33941. polygon.ignore = polygonIgnore;
  33942. polygon.useStyle(
  33943. defaults(
  33944. areaStyleModel.getAreaStyle(),
  33945. {
  33946. fill: color,
  33947. opacity: 0.7
  33948. }
  33949. )
  33950. );
  33951. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  33952. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  33953. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  33954. var labelModel = itemModel.getModel('label');
  33955. var labelHoverModel = itemModel.getModel('emphasis.label');
  33956. symbolGroup.eachChild(function (symbolPath) {
  33957. symbolPath.setStyle(itemStyle);
  33958. symbolPath.hoverStyle = clone(itemHoverStyle);
  33959. setLabelStyle(
  33960. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  33961. {
  33962. labelFetcher: data.hostModel,
  33963. labelDataIndex: idx,
  33964. labelDimIndex: symbolPath.__dimIdx,
  33965. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  33966. autoColor: color,
  33967. isRectText: true
  33968. }
  33969. );
  33970. });
  33971. function onEmphasis() {
  33972. polygon.attr('ignore', hoverPolygonIgnore);
  33973. }
  33974. function onNormal() {
  33975. polygon.attr('ignore', polygonIgnore);
  33976. }
  33977. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  33978. itemGroup.on('emphasis', onEmphasis)
  33979. .on('mouseover', onEmphasis)
  33980. .on('normal', onNormal)
  33981. .on('mouseout', onNormal);
  33982. setHoverStyle(itemGroup);
  33983. });
  33984. this._data = data;
  33985. },
  33986. remove: function () {
  33987. this.group.removeAll();
  33988. this._data = null;
  33989. },
  33990. dispose: function () {}
  33991. });
  33992. var radarLayout = function (ecModel) {
  33993. ecModel.eachSeriesByType('radar', function (seriesModel) {
  33994. var data = seriesModel.getData();
  33995. var points = [];
  33996. var coordSys = seriesModel.coordinateSystem;
  33997. if (!coordSys) {
  33998. return;
  33999. }
  34000. function pointsConverter(val, idx) {
  34001. points[idx] = points[idx] || [];
  34002. points[idx][i] = coordSys.dataToPoint(val, i);
  34003. }
  34004. var axes = coordSys.getIndicatorAxes();
  34005. for (var i = 0; i < coordSys.getIndicatorAxes().length; i++) {
  34006. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  34007. }
  34008. data.each(function (idx) {
  34009. // Close polygon
  34010. points[idx][0] && points[idx].push(points[idx][0].slice());
  34011. data.setItemLayout(idx, points[idx]);
  34012. });
  34013. });
  34014. };
  34015. // Backward compat for radar chart in 2
  34016. var backwardCompat$1 = function (option) {
  34017. var polarOptArr = option.polar;
  34018. if (polarOptArr) {
  34019. if (!isArray(polarOptArr)) {
  34020. polarOptArr = [polarOptArr];
  34021. }
  34022. var polarNotRadar = [];
  34023. each$1(polarOptArr, function (polarOpt, idx) {
  34024. if (polarOpt.indicator) {
  34025. if (polarOpt.type && !polarOpt.shape) {
  34026. polarOpt.shape = polarOpt.type;
  34027. }
  34028. option.radar = option.radar || [];
  34029. if (!isArray(option.radar)) {
  34030. option.radar = [option.radar];
  34031. }
  34032. option.radar.push(polarOpt);
  34033. }
  34034. else {
  34035. polarNotRadar.push(polarOpt);
  34036. }
  34037. });
  34038. option.polar = polarNotRadar;
  34039. }
  34040. each$1(option.series, function (seriesOpt) {
  34041. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  34042. seriesOpt.radarIndex = seriesOpt.polarIndex;
  34043. }
  34044. });
  34045. };
  34046. // Must use radar component
  34047. registerVisual(dataColor('radar'));
  34048. registerVisual(visualSymbol('radar', 'circle'));
  34049. registerLayout(radarLayout);
  34050. registerProcessor(dataFilter('radar'));
  34051. registerPreprocessor(backwardCompat$1);
  34052. /**
  34053. * Simple view coordinate system
  34054. * Mapping given x, y to transformd view x, y
  34055. */
  34056. var v2ApplyTransform$1 = applyTransform;
  34057. // Dummy transform node
  34058. function TransformDummy() {
  34059. Transformable.call(this);
  34060. }
  34061. mixin(TransformDummy, Transformable);
  34062. function View(name) {
  34063. /**
  34064. * @type {string}
  34065. */
  34066. this.name = name;
  34067. /**
  34068. * @type {Object}
  34069. */
  34070. this.zoomLimit;
  34071. Transformable.call(this);
  34072. this._roamTransformable = new TransformDummy();
  34073. this._rawTransformable = new TransformDummy();
  34074. this._center;
  34075. this._zoom;
  34076. }
  34077. View.prototype = {
  34078. constructor: View,
  34079. type: 'view',
  34080. /**
  34081. * @param {Array.<string>}
  34082. * @readOnly
  34083. */
  34084. dimensions: ['x', 'y'],
  34085. /**
  34086. * Set bounding rect
  34087. * @param {number} x
  34088. * @param {number} y
  34089. * @param {number} width
  34090. * @param {number} height
  34091. */
  34092. // PENDING to getRect
  34093. setBoundingRect: function (x, y, width, height) {
  34094. this._rect = new BoundingRect(x, y, width, height);
  34095. return this._rect;
  34096. },
  34097. /**
  34098. * @return {module:zrender/core/BoundingRect}
  34099. */
  34100. // PENDING to getRect
  34101. getBoundingRect: function () {
  34102. return this._rect;
  34103. },
  34104. /**
  34105. * @param {number} x
  34106. * @param {number} y
  34107. * @param {number} width
  34108. * @param {number} height
  34109. */
  34110. setViewRect: function (x, y, width, height) {
  34111. this.transformTo(x, y, width, height);
  34112. this._viewRect = new BoundingRect(x, y, width, height);
  34113. },
  34114. /**
  34115. * Transformed to particular position and size
  34116. * @param {number} x
  34117. * @param {number} y
  34118. * @param {number} width
  34119. * @param {number} height
  34120. */
  34121. transformTo: function (x, y, width, height) {
  34122. var rect = this.getBoundingRect();
  34123. var rawTransform = this._rawTransformable;
  34124. rawTransform.transform = rect.calculateTransform(
  34125. new BoundingRect(x, y, width, height)
  34126. );
  34127. rawTransform.decomposeTransform();
  34128. this._updateTransform();
  34129. },
  34130. /**
  34131. * Set center of view
  34132. * @param {Array.<number>} [centerCoord]
  34133. */
  34134. setCenter: function (centerCoord) {
  34135. if (!centerCoord) {
  34136. return;
  34137. }
  34138. this._center = centerCoord;
  34139. this._updateCenterAndZoom();
  34140. },
  34141. /**
  34142. * @param {number} zoom
  34143. */
  34144. setZoom: function (zoom) {
  34145. zoom = zoom || 1;
  34146. var zoomLimit = this.zoomLimit;
  34147. if (zoomLimit) {
  34148. if (zoomLimit.max != null) {
  34149. zoom = Math.min(zoomLimit.max, zoom);
  34150. }
  34151. if (zoomLimit.min != null) {
  34152. zoom = Math.max(zoomLimit.min, zoom);
  34153. }
  34154. }
  34155. this._zoom = zoom;
  34156. this._updateCenterAndZoom();
  34157. },
  34158. /**
  34159. * Get default center without roam
  34160. */
  34161. getDefaultCenter: function () {
  34162. // Rect before any transform
  34163. var rawRect = this.getBoundingRect();
  34164. var cx = rawRect.x + rawRect.width / 2;
  34165. var cy = rawRect.y + rawRect.height / 2;
  34166. return [cx, cy];
  34167. },
  34168. getCenter: function () {
  34169. return this._center || this.getDefaultCenter();
  34170. },
  34171. getZoom: function () {
  34172. return this._zoom || 1;
  34173. },
  34174. /**
  34175. * @return {Array.<number}
  34176. */
  34177. getRoamTransform: function () {
  34178. return this._roamTransformable.getLocalTransform();
  34179. },
  34180. /**
  34181. * Remove roam
  34182. */
  34183. _updateCenterAndZoom: function () {
  34184. // Must update after view transform updated
  34185. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  34186. var roamTransform = this._roamTransformable;
  34187. var defaultCenter = this.getDefaultCenter();
  34188. var center = this.getCenter();
  34189. var zoom = this.getZoom();
  34190. center = applyTransform([], center, rawTransformMatrix);
  34191. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  34192. roamTransform.origin = center;
  34193. roamTransform.position = [
  34194. defaultCenter[0] - center[0],
  34195. defaultCenter[1] - center[1]
  34196. ];
  34197. roamTransform.scale = [zoom, zoom];
  34198. this._updateTransform();
  34199. },
  34200. /**
  34201. * Update transform from roam and mapLocation
  34202. * @private
  34203. */
  34204. _updateTransform: function () {
  34205. var roamTransformable = this._roamTransformable;
  34206. var rawTransformable = this._rawTransformable;
  34207. rawTransformable.parent = roamTransformable;
  34208. roamTransformable.updateTransform();
  34209. rawTransformable.updateTransform();
  34210. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  34211. this._rawTransform = rawTransformable.getLocalTransform();
  34212. this.invTransform = this.invTransform || [];
  34213. invert(this.invTransform, this.transform);
  34214. this.decomposeTransform();
  34215. },
  34216. /**
  34217. * @return {module:zrender/core/BoundingRect}
  34218. */
  34219. getViewRect: function () {
  34220. return this._viewRect;
  34221. },
  34222. /**
  34223. * Get view rect after roam transform
  34224. * @return {module:zrender/core/BoundingRect}
  34225. */
  34226. getViewRectAfterRoam: function () {
  34227. var rect = this.getBoundingRect().clone();
  34228. rect.applyTransform(this.transform);
  34229. return rect;
  34230. },
  34231. /**
  34232. * Convert a single (lon, lat) data item to (x, y) point.
  34233. * @param {Array.<number>} data
  34234. * @param {boolean} noRoam
  34235. * @param {Array.<number>} [out]
  34236. * @return {Array.<number>}
  34237. */
  34238. dataToPoint: function (data, noRoam, out) {
  34239. var transform = noRoam ? this._rawTransform : this.transform;
  34240. out = out || [];
  34241. return transform
  34242. ? v2ApplyTransform$1(out, data, transform)
  34243. : copy(out, data);
  34244. },
  34245. /**
  34246. * Convert a (x, y) point to (lon, lat) data
  34247. * @param {Array.<number>} point
  34248. * @return {Array.<number>}
  34249. */
  34250. pointToData: function (point) {
  34251. var invTransform = this.invTransform;
  34252. return invTransform
  34253. ? v2ApplyTransform$1([], point, invTransform)
  34254. : [point[0], point[1]];
  34255. },
  34256. /**
  34257. * @implements
  34258. * see {module:echarts/CoodinateSystem}
  34259. */
  34260. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  34261. /**
  34262. * @implements
  34263. * see {module:echarts/CoodinateSystem}
  34264. */
  34265. convertFromPixel: curry(doConvert$1, 'pointToData'),
  34266. /**
  34267. * @implements
  34268. * see {module:echarts/CoodinateSystem}
  34269. */
  34270. containPoint: function (point) {
  34271. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  34272. }
  34273. /**
  34274. * @return {number}
  34275. */
  34276. // getScalarScale: function () {
  34277. // // Use determinant square root of transform to mutiply scalar
  34278. // var m = this.transform;
  34279. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  34280. // return det;
  34281. // }
  34282. };
  34283. mixin(View, Transformable);
  34284. function doConvert$1(methodName, ecModel, finder, value) {
  34285. var seriesModel = finder.seriesModel;
  34286. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  34287. return coordSys === this ? coordSys[methodName](value) : null;
  34288. }
  34289. // Fix for 南海诸岛
  34290. var geoCoord = [126, 25];
  34291. var points$1 = [
  34292. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  34293. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  34294. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  34295. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  34296. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  34297. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  34298. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  34299. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  34300. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  34301. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  34302. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  34303. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  34304. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  34305. [1,92.4],[1,3.5],[0,3.5]]
  34306. ];
  34307. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  34308. for (var k = 0; k < points$1[i$1].length; k++) {
  34309. points$1[i$1][k][0] /= 10.5;
  34310. points$1[i$1][k][1] /= -10.5 / 0.75;
  34311. points$1[i$1][k][0] += geoCoord[0];
  34312. points$1[i$1][k][1] += geoCoord[1];
  34313. }
  34314. }
  34315. var fixNanhai = function (geo) {
  34316. if (geo.map === 'china') {
  34317. geo.regions.push(new Region(
  34318. '南海诸岛',
  34319. map(points$1, function (exterior) {
  34320. return {
  34321. type: 'polygon',
  34322. exterior: exterior
  34323. };
  34324. }), geoCoord
  34325. ));
  34326. }
  34327. };
  34328. var coordsOffsetMap = {
  34329. '南海诸岛' : [32, 80],
  34330. // 全国
  34331. '广东': [0, -10],
  34332. '香港': [10, 5],
  34333. '澳门': [-10, 10],
  34334. //'北京': [-10, 0],
  34335. '天津': [5, 5]
  34336. };
  34337. var fixTextCoord = function (geo) {
  34338. each$1(geo.regions, function (region) {
  34339. var coordFix = coordsOffsetMap[region.name];
  34340. if (coordFix) {
  34341. var cp = region.center;
  34342. cp[0] += coordFix[0] / 10.5;
  34343. cp[1] += -coordFix[1] / (10.5 / 0.75);
  34344. }
  34345. });
  34346. };
  34347. var geoCoordMap = {
  34348. 'Russia': [100, 60],
  34349. 'United States': [-99, 38],
  34350. 'United States of America': [-99, 38]
  34351. };
  34352. var fixGeoCoord = function (geo) {
  34353. each$1(geo.regions, function (region) {
  34354. var geoCoord = geoCoordMap[region.name];
  34355. if (geoCoord) {
  34356. var cp = region.center;
  34357. cp[0] = geoCoord[0];
  34358. cp[1] = geoCoord[1];
  34359. }
  34360. });
  34361. };
  34362. // Fix for 钓鱼岛
  34363. // var Region = require('../Region');
  34364. // var zrUtil = require('zrender/src/core/util');
  34365. // var geoCoord = [126, 25];
  34366. var points$2 = [
  34367. [
  34368. [123.45165252685547, 25.73527164402261],
  34369. [123.49731445312499, 25.73527164402261],
  34370. [123.49731445312499, 25.750734064600884],
  34371. [123.45165252685547, 25.750734064600884],
  34372. [123.45165252685547, 25.73527164402261]
  34373. ]
  34374. ];
  34375. var fixDiaoyuIsland = function (geo) {
  34376. if (geo.map === 'china') {
  34377. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  34378. if (geo.regions[i].name === '台湾') {
  34379. geo.regions[i].geometries.push({
  34380. type: 'polygon',
  34381. exterior: points$2[0]
  34382. });
  34383. }
  34384. }
  34385. }
  34386. };
  34387. // Geo fix functions
  34388. var geoFixFuncs = [
  34389. fixNanhai,
  34390. fixTextCoord,
  34391. fixGeoCoord,
  34392. fixDiaoyuIsland
  34393. ];
  34394. /**
  34395. * [Geo description]
  34396. * @param {string} name Geo name
  34397. * @param {string} map Map type
  34398. * @param {Object} geoJson
  34399. * @param {Object} [specialAreas]
  34400. * Specify the positioned areas by left, top, width, height
  34401. * @param {Object.<string, string>} [nameMap]
  34402. * Specify name alias
  34403. */
  34404. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  34405. View.call(this, name);
  34406. /**
  34407. * Map type
  34408. * @type {string}
  34409. */
  34410. this.map = map$$1;
  34411. this._nameCoordMap = createHashMap();
  34412. this.loadGeoJson(geoJson, specialAreas, nameMap);
  34413. }
  34414. Geo.prototype = {
  34415. constructor: Geo,
  34416. type: 'geo',
  34417. /**
  34418. * @param {Array.<string>}
  34419. * @readOnly
  34420. */
  34421. dimensions: ['lng', 'lat'],
  34422. /**
  34423. * If contain given lng,lat coord
  34424. * @param {Array.<number>}
  34425. * @readOnly
  34426. */
  34427. containCoord: function (coord) {
  34428. var regions = this.regions;
  34429. for (var i = 0; i < regions.length; i++) {
  34430. if (regions[i].contain(coord)) {
  34431. return true;
  34432. }
  34433. }
  34434. return false;
  34435. },
  34436. /**
  34437. * @param {Object} geoJson
  34438. * @param {Object} [specialAreas]
  34439. * Specify the positioned areas by left, top, width, height
  34440. * @param {Object.<string, string>} [nameMap]
  34441. * Specify name alias
  34442. */
  34443. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  34444. // https://jsperf.com/try-catch-performance-overhead
  34445. try {
  34446. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  34447. }
  34448. catch (e) {
  34449. throw 'Invalid geoJson format\n' + e.message;
  34450. }
  34451. specialAreas = specialAreas || {};
  34452. nameMap = nameMap || {};
  34453. var regions = this.regions;
  34454. var regionsMap = createHashMap();
  34455. for (var i = 0; i < regions.length; i++) {
  34456. var regionName = regions[i].name;
  34457. // Try use the alias in nameMap
  34458. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  34459. regions[i].name = regionName;
  34460. regionsMap.set(regionName, regions[i]);
  34461. // Add geoJson
  34462. this.addGeoCoord(regionName, regions[i].center);
  34463. // Some area like Alaska in USA map needs to be tansformed
  34464. // to look better
  34465. var specialArea = specialAreas[regionName];
  34466. if (specialArea) {
  34467. regions[i].transformTo(
  34468. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  34469. );
  34470. }
  34471. }
  34472. this._regionsMap = regionsMap;
  34473. this._rect = null;
  34474. each$1(geoFixFuncs, function (fixFunc) {
  34475. fixFunc(this);
  34476. }, this);
  34477. },
  34478. // Overwrite
  34479. transformTo: function (x, y, width, height) {
  34480. var rect = this.getBoundingRect();
  34481. rect = rect.clone();
  34482. // Longitute is inverted
  34483. rect.y = -rect.y - rect.height;
  34484. var rawTransformable = this._rawTransformable;
  34485. rawTransformable.transform = rect.calculateTransform(
  34486. new BoundingRect(x, y, width, height)
  34487. );
  34488. rawTransformable.decomposeTransform();
  34489. var scale = rawTransformable.scale;
  34490. scale[1] = -scale[1];
  34491. rawTransformable.updateTransform();
  34492. this._updateTransform();
  34493. },
  34494. /**
  34495. * @param {string} name
  34496. * @return {module:echarts/coord/geo/Region}
  34497. */
  34498. getRegion: function (name) {
  34499. return this._regionsMap.get(name);
  34500. },
  34501. getRegionByCoord: function (coord) {
  34502. var regions = this.regions;
  34503. for (var i = 0; i < regions.length; i++) {
  34504. if (regions[i].contain(coord)) {
  34505. return regions[i];
  34506. }
  34507. }
  34508. },
  34509. /**
  34510. * Add geoCoord for indexing by name
  34511. * @param {string} name
  34512. * @param {Array.<number>} geoCoord
  34513. */
  34514. addGeoCoord: function (name, geoCoord) {
  34515. this._nameCoordMap.set(name, geoCoord);
  34516. },
  34517. /**
  34518. * Get geoCoord by name
  34519. * @param {string} name
  34520. * @return {Array.<number>}
  34521. */
  34522. getGeoCoord: function (name) {
  34523. return this._nameCoordMap.get(name);
  34524. },
  34525. // Overwrite
  34526. getBoundingRect: function () {
  34527. if (this._rect) {
  34528. return this._rect;
  34529. }
  34530. var rect;
  34531. var regions = this.regions;
  34532. for (var i = 0; i < regions.length; i++) {
  34533. var regionRect = regions[i].getBoundingRect();
  34534. rect = rect || regionRect.clone();
  34535. rect.union(regionRect);
  34536. }
  34537. // FIXME Always return new ?
  34538. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  34539. },
  34540. /**
  34541. * @param {string|Array.<number>} data
  34542. * @param {boolean} noRoam
  34543. * @param {Array.<number>} [out]
  34544. * @return {Array.<number>}
  34545. */
  34546. dataToPoint: function (data, noRoam, out) {
  34547. if (typeof data === 'string') {
  34548. // Map area name to geoCoord
  34549. data = this.getGeoCoord(data);
  34550. }
  34551. if (data) {
  34552. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  34553. }
  34554. },
  34555. /**
  34556. * @inheritDoc
  34557. */
  34558. convertToPixel: curry(doConvert, 'dataToPoint'),
  34559. /**
  34560. * @inheritDoc
  34561. */
  34562. convertFromPixel: curry(doConvert, 'pointToData')
  34563. };
  34564. mixin(Geo, View);
  34565. function doConvert(methodName, ecModel, finder, value) {
  34566. var geoModel = finder.geoModel;
  34567. var seriesModel = finder.seriesModel;
  34568. var coordSys = geoModel
  34569. ? geoModel.coordinateSystem
  34570. : seriesModel
  34571. ? (
  34572. seriesModel.coordinateSystem // For map.
  34573. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  34574. )
  34575. : null;
  34576. return coordSys === this ? coordSys[methodName](value) : null;
  34577. }
  34578. /**
  34579. * Resize method bound to the geo
  34580. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  34581. * @param {module:echarts/ExtensionAPI} api
  34582. */
  34583. function resizeGeo(geoModel, api) {
  34584. var boundingCoords = geoModel.get('boundingCoords');
  34585. if (boundingCoords != null) {
  34586. var leftTop = boundingCoords[0];
  34587. var rightBottom = boundingCoords[1];
  34588. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  34589. if (__DEV__) {
  34590. console.error('Invalid boundingCoords');
  34591. }
  34592. }
  34593. else {
  34594. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  34595. }
  34596. }
  34597. var rect = this.getBoundingRect();
  34598. var boxLayoutOption;
  34599. var center = geoModel.get('layoutCenter');
  34600. var size = geoModel.get('layoutSize');
  34601. var viewWidth = api.getWidth();
  34602. var viewHeight = api.getHeight();
  34603. var aspectScale = geoModel.get('aspectScale') || 0.75;
  34604. var aspect = rect.width / rect.height * aspectScale;
  34605. var useCenterAndSize = false;
  34606. if (center && size) {
  34607. center = [
  34608. parsePercent$1(center[0], viewWidth),
  34609. parsePercent$1(center[1], viewHeight)
  34610. ];
  34611. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  34612. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  34613. useCenterAndSize = true;
  34614. }
  34615. else {
  34616. if (__DEV__) {
  34617. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  34618. }
  34619. }
  34620. }
  34621. var viewRect;
  34622. if (useCenterAndSize) {
  34623. var viewRect = {};
  34624. if (aspect > 1) {
  34625. // Width is same with size
  34626. viewRect.width = size;
  34627. viewRect.height = size / aspect;
  34628. }
  34629. else {
  34630. viewRect.height = size;
  34631. viewRect.width = size * aspect;
  34632. }
  34633. viewRect.y = center[1] - viewRect.height / 2;
  34634. viewRect.x = center[0] - viewRect.width / 2;
  34635. }
  34636. else {
  34637. // Use left/top/width/height
  34638. boxLayoutOption = geoModel.getBoxLayoutParams();
  34639. // 0.75 rate
  34640. boxLayoutOption.aspect = aspect;
  34641. viewRect = getLayoutRect(boxLayoutOption, {
  34642. width: viewWidth,
  34643. height: viewHeight
  34644. });
  34645. }
  34646. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  34647. this.setCenter(geoModel.get('center'));
  34648. this.setZoom(geoModel.get('zoom'));
  34649. }
  34650. /**
  34651. * @param {module:echarts/coord/Geo} geo
  34652. * @param {module:echarts/model/Model} model
  34653. * @inner
  34654. */
  34655. function setGeoCoords(geo, model) {
  34656. each$1(model.get('geoCoord'), function (geoCoord, name) {
  34657. geo.addGeoCoord(name, geoCoord);
  34658. });
  34659. }
  34660. if (__DEV__) {
  34661. var mapNotExistsError = function (name) {
  34662. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  34663. };
  34664. }
  34665. var geoCreator = {
  34666. // For deciding which dimensions to use when creating list data
  34667. dimensions: Geo.prototype.dimensions,
  34668. create: function (ecModel, api) {
  34669. var geoList = [];
  34670. // FIXME Create each time may be slow
  34671. ecModel.eachComponent('geo', function (geoModel, idx) {
  34672. var name = geoModel.get('map');
  34673. var mapData = getMap(name);
  34674. if (__DEV__) {
  34675. if (!mapData) {
  34676. mapNotExistsError(name);
  34677. }
  34678. }
  34679. var geo = new Geo(
  34680. name + idx, name,
  34681. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34682. geoModel.get('nameMap')
  34683. );
  34684. geo.zoomLimit = geoModel.get('scaleLimit');
  34685. geoList.push(geo);
  34686. setGeoCoords(geo, geoModel);
  34687. geoModel.coordinateSystem = geo;
  34688. geo.model = geoModel;
  34689. // Inject resize method
  34690. geo.resize = resizeGeo;
  34691. geo.resize(geoModel, api);
  34692. });
  34693. ecModel.eachSeries(function (seriesModel) {
  34694. var coordSys = seriesModel.get('coordinateSystem');
  34695. if (coordSys === 'geo') {
  34696. var geoIndex = seriesModel.get('geoIndex') || 0;
  34697. seriesModel.coordinateSystem = geoList[geoIndex];
  34698. }
  34699. });
  34700. // If has map series
  34701. var mapModelGroupBySeries = {};
  34702. ecModel.eachSeriesByType('map', function (seriesModel) {
  34703. if (!seriesModel.getHostGeoModel()) {
  34704. var mapType = seriesModel.getMapType();
  34705. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  34706. mapModelGroupBySeries[mapType].push(seriesModel);
  34707. }
  34708. });
  34709. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  34710. var mapData = getMap(mapType);
  34711. if (__DEV__) {
  34712. if (!mapData) {
  34713. mapNotExistsError(mapSeries[0].get('map'));
  34714. }
  34715. }
  34716. var nameMapList = map(mapSeries, function (singleMapSeries) {
  34717. return singleMapSeries.get('nameMap');
  34718. });
  34719. var geo = new Geo(
  34720. mapType, mapType,
  34721. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34722. mergeAll(nameMapList)
  34723. );
  34724. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  34725. return singleMapSeries.get('scaleLimit');
  34726. }));
  34727. geoList.push(geo);
  34728. // Inject resize method
  34729. geo.resize = resizeGeo;
  34730. geo.resize(mapSeries[0], api);
  34731. each$1(mapSeries, function (singleMapSeries) {
  34732. singleMapSeries.coordinateSystem = geo;
  34733. setGeoCoords(geo, singleMapSeries);
  34734. });
  34735. });
  34736. return geoList;
  34737. },
  34738. /**
  34739. * Fill given regions array
  34740. * @param {Array.<Object>} originRegionArr
  34741. * @param {string} mapName
  34742. * @param {Object} [nameMap]
  34743. * @return {Array}
  34744. */
  34745. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  34746. // Not use the original
  34747. var regionsArr = (originRegionArr || []).slice();
  34748. nameMap = nameMap || {};
  34749. var map$$1 = getMap(mapName);
  34750. var geoJson = map$$1 && map$$1.geoJson;
  34751. if (!geoJson) {
  34752. if (__DEV__) {
  34753. mapNotExistsError(mapName);
  34754. }
  34755. return originRegionArr;
  34756. }
  34757. var dataNameMap = createHashMap();
  34758. var features = geoJson.features;
  34759. for (var i = 0; i < regionsArr.length; i++) {
  34760. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  34761. }
  34762. for (var i = 0; i < features.length; i++) {
  34763. var name = features[i].properties.name;
  34764. if (!dataNameMap.get(name)) {
  34765. if (nameMap.hasOwnProperty(name)) {
  34766. name = nameMap[name];
  34767. }
  34768. regionsArr.push({
  34769. name: name
  34770. });
  34771. }
  34772. }
  34773. return regionsArr;
  34774. }
  34775. };
  34776. registerCoordinateSystem('geo', geoCreator);
  34777. var MapSeries = SeriesModel.extend({
  34778. type: 'series.map',
  34779. dependencies: ['geo'],
  34780. layoutMode: 'box',
  34781. /**
  34782. * Only first map series of same mapType will drawMap
  34783. * @type {boolean}
  34784. */
  34785. needsDrawMap: false,
  34786. /**
  34787. * Group of all map series with same mapType
  34788. * @type {boolean}
  34789. */
  34790. seriesGroup: [],
  34791. init: function (option) {
  34792. // this._fillOption(option, this.getMapType());
  34793. // this.option = option;
  34794. MapSeries.superApply(this, 'init', arguments);
  34795. this.updateSelectedMap(this._createSelectableList());
  34796. },
  34797. getInitialData: function (option) {
  34798. return createListSimply(this, ['value']);
  34799. },
  34800. mergeOption: function (newOption) {
  34801. // this._fillOption(newOption, this.getMapType());
  34802. MapSeries.superApply(this, 'mergeOption', arguments);
  34803. this.updateSelectedMap(this._createSelectableList());
  34804. },
  34805. _createSelectableList: function () {
  34806. var data = this.getRawData();
  34807. var valueDim = data.mapDimension('value');
  34808. var targetList = [];
  34809. for (var i = 0, len = data.count(); i < len; i++) {
  34810. targetList.push({
  34811. name: data.getName(i),
  34812. value: data.get(valueDim, i),
  34813. selected: retrieveRawAttr(data, i, 'selected')
  34814. });
  34815. }
  34816. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  34817. return targetList;
  34818. },
  34819. /**
  34820. * If no host geo model, return null, which means using a
  34821. * inner exclusive geo model.
  34822. */
  34823. getHostGeoModel: function () {
  34824. var geoIndex = this.option.geoIndex;
  34825. return geoIndex != null
  34826. ? this.dependentModels.geo[geoIndex]
  34827. : null;
  34828. },
  34829. getMapType: function () {
  34830. return (this.getHostGeoModel() || this).option.map;
  34831. },
  34832. _fillOption: function (option, mapName) {
  34833. // Shallow clone
  34834. // option = zrUtil.extend({}, option);
  34835. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  34836. // return option;
  34837. },
  34838. getRawValue: function (dataIndex) {
  34839. // Use value stored in data instead because it is calculated from multiple series
  34840. // FIXME Provide all value of multiple series ?
  34841. var data = this.getData();
  34842. return data.get(data.mapDimension('value'), dataIndex);
  34843. },
  34844. /**
  34845. * Get model of region
  34846. * @param {string} name
  34847. * @return {module:echarts/model/Model}
  34848. */
  34849. getRegionModel: function (regionName) {
  34850. var data = this.getData();
  34851. return data.getItemModel(data.indexOfName(regionName));
  34852. },
  34853. /**
  34854. * Map tooltip formatter
  34855. *
  34856. * @param {number} dataIndex
  34857. */
  34858. formatTooltip: function (dataIndex) {
  34859. // FIXME orignalData and data is a bit confusing
  34860. var data = this.getData();
  34861. var formattedValue = addCommas(this.getRawValue(dataIndex));
  34862. var name = data.getName(dataIndex);
  34863. var seriesGroup = this.seriesGroup;
  34864. var seriesNames = [];
  34865. for (var i = 0; i < seriesGroup.length; i++) {
  34866. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  34867. var valueDim = data.mapDimension('value');
  34868. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  34869. seriesNames.push(
  34870. encodeHTML(seriesGroup[i].name)
  34871. );
  34872. }
  34873. }
  34874. return seriesNames.join(', ') + '<br />'
  34875. + encodeHTML(name + ' : ' + formattedValue);
  34876. },
  34877. /**
  34878. * @implement
  34879. */
  34880. getTooltipPosition: function (dataIndex) {
  34881. if (dataIndex != null) {
  34882. var name = this.getData().getName(dataIndex);
  34883. var geo = this.coordinateSystem;
  34884. var region = geo.getRegion(name);
  34885. return region && geo.dataToPoint(region.center);
  34886. }
  34887. },
  34888. setZoom: function (zoom) {
  34889. this.option.zoom = zoom;
  34890. },
  34891. setCenter: function (center) {
  34892. this.option.center = center;
  34893. },
  34894. defaultOption: {
  34895. // 一级层叠
  34896. zlevel: 0,
  34897. // 二级层叠
  34898. z: 2,
  34899. coordinateSystem: 'geo',
  34900. // map should be explicitly specified since ec3.
  34901. map: '',
  34902. // If `geoIndex` is not specified, a exclusive geo will be
  34903. // created. Otherwise use the specified geo component, and
  34904. // `map` and `mapType` are ignored.
  34905. // geoIndex: 0,
  34906. // 'center' | 'left' | 'right' | 'x%' | {number}
  34907. left: 'center',
  34908. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  34909. top: 'center',
  34910. // right
  34911. // bottom
  34912. // width:
  34913. // height
  34914. // Aspect is width / height. Inited to be geoJson bbox aspect
  34915. // This parameter is used for scale this aspect
  34916. aspectScale: 0.75,
  34917. ///// Layout with center and size
  34918. // If you wan't to put map in a fixed size box with right aspect ratio
  34919. // This two properties may more conveninet
  34920. // layoutCenter: [50%, 50%]
  34921. // layoutSize: 100
  34922. // 数值合并方式,默认加和,可选为:
  34923. // 'sum' | 'average' | 'max' | 'min'
  34924. // mapValueCalculation: 'sum',
  34925. // 地图数值计算结果小数精度
  34926. // mapValuePrecision: 0,
  34927. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  34928. showLegendSymbol: true,
  34929. // 选择模式,默认关闭,可选single,multiple
  34930. // selectedMode: false,
  34931. dataRangeHoverLink: true,
  34932. // 是否开启缩放及漫游模式
  34933. // roam: false,
  34934. // Define left-top, right-bottom coords to control view
  34935. // For example, [ [180, 90], [-180, -90] ],
  34936. // higher priority than center and zoom
  34937. boundingCoords: null,
  34938. // Default on center of map
  34939. center: null,
  34940. zoom: 1,
  34941. scaleLimit: null,
  34942. label: {
  34943. show: false,
  34944. color: '#000'
  34945. },
  34946. // scaleLimit: null,
  34947. itemStyle: {
  34948. borderWidth: 0.5,
  34949. borderColor: '#444',
  34950. areaColor: '#eee'
  34951. },
  34952. emphasis: {
  34953. label: {
  34954. show: true,
  34955. color: 'rgb(100,0,0)'
  34956. },
  34957. itemStyle: {
  34958. areaColor: 'rgba(255,215,0,0.8)'
  34959. }
  34960. }
  34961. }
  34962. });
  34963. mixin(MapSeries, selectableMixin);
  34964. var ATTR = '\0_ec_interaction_mutex';
  34965. function take(zr, resourceKey, userKey) {
  34966. var store = getStore(zr);
  34967. store[resourceKey] = userKey;
  34968. }
  34969. function release(zr, resourceKey, userKey) {
  34970. var store = getStore(zr);
  34971. var uKey = store[resourceKey];
  34972. if (uKey === userKey) {
  34973. store[resourceKey] = null;
  34974. }
  34975. }
  34976. function isTaken(zr, resourceKey) {
  34977. return !!getStore(zr)[resourceKey];
  34978. }
  34979. function getStore(zr) {
  34980. return zr[ATTR] || (zr[ATTR] = {});
  34981. }
  34982. /**
  34983. * payload: {
  34984. * type: 'takeGlobalCursor',
  34985. * key: 'dataZoomSelect', or 'brush', or ...,
  34986. * If no userKey, release global cursor.
  34987. * }
  34988. */
  34989. registerAction(
  34990. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  34991. function () {}
  34992. );
  34993. /**
  34994. * @alias module:echarts/component/helper/RoamController
  34995. * @constructor
  34996. * @mixin {module:zrender/mixin/Eventful}
  34997. *
  34998. * @param {module:zrender/zrender~ZRender} zr
  34999. */
  35000. function RoamController(zr) {
  35001. /**
  35002. * @type {Function}
  35003. */
  35004. this.pointerChecker;
  35005. /**
  35006. * @type {module:zrender}
  35007. */
  35008. this._zr = zr;
  35009. /**
  35010. * @type {Object}
  35011. */
  35012. this._opt = {};
  35013. // Avoid two roamController bind the same handler
  35014. var bind$$1 = bind;
  35015. var mousedownHandler = bind$$1(mousedown, this);
  35016. var mousemoveHandler = bind$$1(mousemove, this);
  35017. var mouseupHandler = bind$$1(mouseup, this);
  35018. var mousewheelHandler = bind$$1(mousewheel, this);
  35019. var pinchHandler = bind$$1(pinch, this);
  35020. Eventful.call(this);
  35021. /**
  35022. * @param {Function} pointerChecker
  35023. * input: x, y
  35024. * output: boolean
  35025. */
  35026. this.setPointerChecker = function (pointerChecker) {
  35027. this.pointerChecker = pointerChecker;
  35028. };
  35029. /**
  35030. * Notice: only enable needed types. For example, if 'zoom'
  35031. * is not needed, 'zoom' should not be enabled, otherwise
  35032. * default mousewheel behaviour (scroll page) will be disabled.
  35033. *
  35034. * @param {boolean|string} [controlType=true] Specify the control type,
  35035. * which can be null/undefined or true/false
  35036. * or 'pan/move' or 'zoom'/'scale'
  35037. * @param {Object} [opt]
  35038. * @param {Object} [opt.zoomOnMouseWheel=true]
  35039. * @param {Object} [opt.moveOnMouseMove=true]
  35040. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  35041. */
  35042. this.enable = function (controlType, opt) {
  35043. // Disable previous first
  35044. this.disable();
  35045. this._opt = defaults(clone(opt) || {}, {
  35046. zoomOnMouseWheel: true,
  35047. moveOnMouseMove: true,
  35048. preventDefaultMouseMove: true
  35049. });
  35050. if (controlType == null) {
  35051. controlType = true;
  35052. }
  35053. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  35054. zr.on('mousedown', mousedownHandler);
  35055. zr.on('mousemove', mousemoveHandler);
  35056. zr.on('mouseup', mouseupHandler);
  35057. }
  35058. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  35059. zr.on('mousewheel', mousewheelHandler);
  35060. zr.on('pinch', pinchHandler);
  35061. }
  35062. };
  35063. this.disable = function () {
  35064. zr.off('mousedown', mousedownHandler);
  35065. zr.off('mousemove', mousemoveHandler);
  35066. zr.off('mouseup', mouseupHandler);
  35067. zr.off('mousewheel', mousewheelHandler);
  35068. zr.off('pinch', pinchHandler);
  35069. };
  35070. this.dispose = this.disable;
  35071. this.isDragging = function () {
  35072. return this._dragging;
  35073. };
  35074. this.isPinching = function () {
  35075. return this._pinching;
  35076. };
  35077. }
  35078. mixin(RoamController, Eventful);
  35079. function mousedown(e) {
  35080. if (notLeftMouse(e)
  35081. || (e.target && e.target.draggable)
  35082. ) {
  35083. return;
  35084. }
  35085. var x = e.offsetX;
  35086. var y = e.offsetY;
  35087. // Only check on mosedown, but not mousemove.
  35088. // Mouse can be out of target when mouse moving.
  35089. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  35090. this._x = x;
  35091. this._y = y;
  35092. this._dragging = true;
  35093. }
  35094. }
  35095. function mousemove(e) {
  35096. if (notLeftMouse(e)
  35097. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  35098. || !this._dragging
  35099. || e.gestureEvent === 'pinch'
  35100. || isTaken(this._zr, 'globalPan')
  35101. ) {
  35102. return;
  35103. }
  35104. var x = e.offsetX;
  35105. var y = e.offsetY;
  35106. var oldX = this._x;
  35107. var oldY = this._y;
  35108. var dx = x - oldX;
  35109. var dy = y - oldY;
  35110. this._x = x;
  35111. this._y = y;
  35112. this._opt.preventDefaultMouseMove && stop(e.event);
  35113. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  35114. }
  35115. function mouseup(e) {
  35116. if (!notLeftMouse(e)) {
  35117. this._dragging = false;
  35118. }
  35119. }
  35120. function mousewheel(e) {
  35121. // wheelDelta maybe -0 in chrome mac.
  35122. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  35123. return;
  35124. }
  35125. // Convenience:
  35126. // Mac and VM Windows on Mac: scroll up: zoom out.
  35127. // Windows: scroll up: zoom in.
  35128. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  35129. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  35130. }
  35131. function pinch(e) {
  35132. if (isTaken(this._zr, 'globalPan')) {
  35133. return;
  35134. }
  35135. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  35136. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  35137. }
  35138. function zoom(e, zoomDelta, zoomX, zoomY) {
  35139. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  35140. // When mouse is out of roamController rect,
  35141. // default befavoius should not be be disabled, otherwise
  35142. // page sliding is disabled, contrary to expectation.
  35143. stop(e.event);
  35144. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  35145. }
  35146. }
  35147. function checkKeyBinding(roamController, prop, e) {
  35148. var setting = roamController._opt[prop];
  35149. return setting
  35150. && (!isString(setting) || e.event[setting + 'Key']);
  35151. }
  35152. /**
  35153. * For geo and graph.
  35154. *
  35155. * @param {Object} controllerHost
  35156. * @param {module:zrender/Element} controllerHost.target
  35157. */
  35158. function updateViewOnPan(controllerHost, dx, dy) {
  35159. var target = controllerHost.target;
  35160. var pos = target.position;
  35161. pos[0] += dx;
  35162. pos[1] += dy;
  35163. target.dirty();
  35164. }
  35165. /**
  35166. * For geo and graph.
  35167. *
  35168. * @param {Object} controllerHost
  35169. * @param {module:zrender/Element} controllerHost.target
  35170. * @param {number} controllerHost.zoom
  35171. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  35172. */
  35173. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  35174. var target = controllerHost.target;
  35175. var zoomLimit = controllerHost.zoomLimit;
  35176. var pos = target.position;
  35177. var scale = target.scale;
  35178. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  35179. newZoom *= zoomDelta;
  35180. if (zoomLimit) {
  35181. var zoomMin = zoomLimit.min || 0;
  35182. var zoomMax = zoomLimit.max || Infinity;
  35183. newZoom = Math.max(
  35184. Math.min(zoomMax, newZoom),
  35185. zoomMin
  35186. );
  35187. }
  35188. var zoomScale = newZoom / controllerHost.zoom;
  35189. controllerHost.zoom = newZoom;
  35190. // Keep the mouse center when scaling
  35191. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  35192. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  35193. scale[0] *= zoomScale;
  35194. scale[1] *= zoomScale;
  35195. target.dirty();
  35196. }
  35197. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  35198. /**
  35199. * Avoid that: mouse click on a elements that is over geo or graph,
  35200. * but roam is triggered.
  35201. */
  35202. function onIrrelevantElement(e, api, targetCoordSysModel) {
  35203. var model = api.getComponentByElement(e.topTarget);
  35204. // If model is axisModel, it works only if it is injected with coordinateSystem.
  35205. var coordSys = model && model.coordinateSystem;
  35206. return model
  35207. && model !== targetCoordSysModel
  35208. && !IRRELEVANT_EXCLUDES[model.mainType]
  35209. && (coordSys && coordSys.model !== targetCoordSysModel);
  35210. }
  35211. function getFixedItemStyle(model, scale) {
  35212. var itemStyle = model.getItemStyle();
  35213. var areaColor = model.get('areaColor');
  35214. // If user want the color not to be changed when hover,
  35215. // they should both set areaColor and color to be null.
  35216. if (areaColor != null) {
  35217. itemStyle.fill = areaColor;
  35218. }
  35219. return itemStyle;
  35220. }
  35221. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  35222. group.off('click');
  35223. group.off('mousedown');
  35224. if (mapOrGeoModel.get('selectedMode')) {
  35225. group.on('mousedown', function () {
  35226. mapDraw._mouseDownFlag = true;
  35227. });
  35228. group.on('click', function (e) {
  35229. if (!mapDraw._mouseDownFlag) {
  35230. return;
  35231. }
  35232. mapDraw._mouseDownFlag = false;
  35233. var el = e.target;
  35234. while (!el.__regions) {
  35235. el = el.parent;
  35236. }
  35237. if (!el) {
  35238. return;
  35239. }
  35240. var action = {
  35241. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  35242. batch: map(el.__regions, function (region) {
  35243. return {
  35244. name: region.name,
  35245. from: fromView.uid
  35246. };
  35247. })
  35248. };
  35249. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  35250. api.dispatchAction(action);
  35251. updateMapSelected(mapOrGeoModel, group);
  35252. });
  35253. }
  35254. }
  35255. function updateMapSelected(mapOrGeoModel, group) {
  35256. // FIXME
  35257. group.eachChild(function (otherRegionEl) {
  35258. each$1(otherRegionEl.__regions, function (region) {
  35259. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  35260. });
  35261. });
  35262. }
  35263. /**
  35264. * @alias module:echarts/component/helper/MapDraw
  35265. * @param {module:echarts/ExtensionAPI} api
  35266. * @param {boolean} updateGroup
  35267. */
  35268. function MapDraw(api, updateGroup) {
  35269. var group = new Group();
  35270. /**
  35271. * @type {module:echarts/component/helper/RoamController}
  35272. * @private
  35273. */
  35274. this._controller = new RoamController(api.getZr());
  35275. /**
  35276. * @type {Object} {target, zoom, zoomLimit}
  35277. * @private
  35278. */
  35279. this._controllerHost = {target: updateGroup ? group : null};
  35280. /**
  35281. * @type {module:zrender/container/Group}
  35282. * @readOnly
  35283. */
  35284. this.group = group;
  35285. /**
  35286. * @type {boolean}
  35287. * @private
  35288. */
  35289. this._updateGroup = updateGroup;
  35290. /**
  35291. * This flag is used to make sure that only one among
  35292. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  35293. * action may be triggered when `pan`, which is unexpected.
  35294. * @type {booelan}
  35295. */
  35296. this._mouseDownFlag;
  35297. }
  35298. MapDraw.prototype = {
  35299. constructor: MapDraw,
  35300. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  35301. var isGeo = mapOrGeoModel.mainType === 'geo';
  35302. // Map series has data. GEO model that controlled by map series
  35303. // will be assigned with map data. Other GEO model has no data.
  35304. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  35305. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  35306. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  35307. data = mapSeries.getData();
  35308. }
  35309. });
  35310. var geo = mapOrGeoModel.coordinateSystem;
  35311. var group = this.group;
  35312. var scale = geo.scale;
  35313. var groupNewProp = {
  35314. position: geo.position,
  35315. scale: scale
  35316. };
  35317. // No animation when first draw or in action
  35318. if (!group.childAt(0) || payload) {
  35319. group.attr(groupNewProp);
  35320. }
  35321. else {
  35322. updateProps(group, groupNewProp, mapOrGeoModel);
  35323. }
  35324. group.removeAll();
  35325. var itemStyleAccessPath = ['itemStyle'];
  35326. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  35327. var labelAccessPath = ['label'];
  35328. var hoverLabelAccessPath = ['emphasis', 'label'];
  35329. var nameMap = createHashMap();
  35330. each$1(geo.regions, function (region) {
  35331. // Consider in GeoJson properties.name may be duplicated, for example,
  35332. // there is multiple region named "United Kindom" or "France" (so many
  35333. // colonies). And it is not appropriate to merge them in geo, which
  35334. // will make them share the same label and bring trouble in label
  35335. // location calculation.
  35336. var regionGroup = nameMap.get(region.name)
  35337. || nameMap.set(region.name, new Group());
  35338. var compoundPath = new CompoundPath({
  35339. shape: {
  35340. paths: []
  35341. }
  35342. });
  35343. regionGroup.add(compoundPath);
  35344. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  35345. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  35346. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  35347. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  35348. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  35349. var labelModel = regionModel.getModel(labelAccessPath);
  35350. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  35351. var dataIdx;
  35352. // Use the itemStyle in data if has data
  35353. if (data) {
  35354. dataIdx = data.indexOfName(region.name);
  35355. // Only visual color of each item will be used. It can be encoded by dataRange
  35356. // But visual color of series is used in symbol drawing
  35357. //
  35358. // Visual color for each series is for the symbol draw
  35359. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  35360. if (visualColor) {
  35361. itemStyle.fill = visualColor;
  35362. }
  35363. }
  35364. each$1(region.geometries, function (geometry) {
  35365. if (geometry.type !== 'polygon') {
  35366. return;
  35367. }
  35368. compoundPath.shape.paths.push(new Polygon({
  35369. shape: {
  35370. points: geometry.exterior
  35371. }
  35372. }));
  35373. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  35374. compoundPath.shape.paths.push(new Polygon({
  35375. shape: {
  35376. points: geometry.interiors[i]
  35377. }
  35378. }));
  35379. }
  35380. });
  35381. compoundPath.setStyle(itemStyle);
  35382. compoundPath.style.strokeNoScale = true;
  35383. compoundPath.culling = true;
  35384. // Label
  35385. var showLabel = labelModel.get('show');
  35386. var hoverShowLabel = hoverLabelModel.get('show');
  35387. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  35388. var itemLayout = data && data.getItemLayout(dataIdx);
  35389. // In the following cases label will be drawn
  35390. // 1. In map series and data value is NaN
  35391. // 2. In geo component
  35392. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  35393. if (
  35394. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  35395. || (itemLayout && itemLayout.showLabel)
  35396. ) {
  35397. var query = !isGeo ? dataIdx : region.name;
  35398. var labelFetcher;
  35399. // Consider dataIdx not found.
  35400. if (!data || dataIdx >= 0) {
  35401. labelFetcher = mapOrGeoModel;
  35402. }
  35403. var textEl = new Text({
  35404. position: region.center.slice(),
  35405. scale: [1 / scale[0], 1 / scale[1]],
  35406. z2: 10,
  35407. silent: true
  35408. });
  35409. setLabelStyle(
  35410. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  35411. {
  35412. labelFetcher: labelFetcher,
  35413. labelDataIndex: query,
  35414. defaultText: region.name,
  35415. useInsideStyle: false
  35416. },
  35417. {
  35418. textAlign: 'center',
  35419. textVerticalAlign: 'middle'
  35420. }
  35421. );
  35422. regionGroup.add(textEl);
  35423. }
  35424. // setItemGraphicEl, setHoverStyle after all polygons and labels
  35425. // are added to the rigionGroup
  35426. if (data) {
  35427. data.setItemGraphicEl(dataIdx, regionGroup);
  35428. }
  35429. else {
  35430. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  35431. // Package custom mouse event for geo component
  35432. compoundPath.eventData = {
  35433. componentType: 'geo',
  35434. geoIndex: mapOrGeoModel.componentIndex,
  35435. name: region.name,
  35436. region: (regionModel && regionModel.option) || {}
  35437. };
  35438. }
  35439. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  35440. groupRegions.push(region);
  35441. setHoverStyle(
  35442. regionGroup,
  35443. hoverItemStyle,
  35444. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  35445. );
  35446. group.add(regionGroup);
  35447. });
  35448. this._updateController(mapOrGeoModel, ecModel, api);
  35449. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  35450. updateMapSelected(mapOrGeoModel, group);
  35451. },
  35452. remove: function () {
  35453. this.group.removeAll();
  35454. this._controller.dispose();
  35455. this._controllerHost = {};
  35456. },
  35457. _updateController: function (mapOrGeoModel, ecModel, api) {
  35458. var geo = mapOrGeoModel.coordinateSystem;
  35459. var controller = this._controller;
  35460. var controllerHost = this._controllerHost;
  35461. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  35462. controllerHost.zoom = geo.getZoom();
  35463. // roamType is will be set default true if it is null
  35464. controller.enable(mapOrGeoModel.get('roam') || false);
  35465. var mainType = mapOrGeoModel.mainType;
  35466. function makeActionBase() {
  35467. var action = {
  35468. type: 'geoRoam',
  35469. componentType: mainType
  35470. };
  35471. action[mainType + 'Id'] = mapOrGeoModel.id;
  35472. return action;
  35473. }
  35474. controller.off('pan').on('pan', function (dx, dy) {
  35475. this._mouseDownFlag = false;
  35476. updateViewOnPan(controllerHost, dx, dy);
  35477. api.dispatchAction(extend(makeActionBase(), {
  35478. dx: dx,
  35479. dy: dy
  35480. }));
  35481. }, this);
  35482. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  35483. this._mouseDownFlag = false;
  35484. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  35485. api.dispatchAction(extend(makeActionBase(), {
  35486. zoom: zoom,
  35487. originX: mouseX,
  35488. originY: mouseY
  35489. }));
  35490. if (this._updateGroup) {
  35491. var group = this.group;
  35492. var scale = group.scale;
  35493. group.traverse(function (el) {
  35494. if (el.type === 'text') {
  35495. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  35496. }
  35497. });
  35498. }
  35499. }, this);
  35500. controller.setPointerChecker(function (e, x, y) {
  35501. return geo.getViewRectAfterRoam().contain(x, y)
  35502. && !onIrrelevantElement(e, api, mapOrGeoModel);
  35503. });
  35504. }
  35505. };
  35506. extendChartView({
  35507. type: 'map',
  35508. render: function (mapModel, ecModel, api, payload) {
  35509. // Not render if it is an toggleSelect action from self
  35510. if (payload && payload.type === 'mapToggleSelect'
  35511. && payload.from === this.uid
  35512. ) {
  35513. return;
  35514. }
  35515. var group = this.group;
  35516. group.removeAll();
  35517. if (mapModel.getHostGeoModel()) {
  35518. return;
  35519. }
  35520. // Not update map if it is an roam action from self
  35521. if (!(payload && payload.type === 'geoRoam'
  35522. && payload.componentType === 'series'
  35523. && payload.seriesId === mapModel.id
  35524. )
  35525. ) {
  35526. if (mapModel.needsDrawMap) {
  35527. var mapDraw = this._mapDraw || new MapDraw(api, true);
  35528. group.add(mapDraw.group);
  35529. mapDraw.draw(mapModel, ecModel, api, this, payload);
  35530. this._mapDraw = mapDraw;
  35531. }
  35532. else {
  35533. // Remove drawed map
  35534. this._mapDraw && this._mapDraw.remove();
  35535. this._mapDraw = null;
  35536. }
  35537. }
  35538. else {
  35539. var mapDraw = this._mapDraw;
  35540. mapDraw && group.add(mapDraw.group);
  35541. }
  35542. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  35543. && this._renderSymbols(mapModel, ecModel, api);
  35544. },
  35545. remove: function () {
  35546. this._mapDraw && this._mapDraw.remove();
  35547. this._mapDraw = null;
  35548. this.group.removeAll();
  35549. },
  35550. dispose: function () {
  35551. this._mapDraw && this._mapDraw.remove();
  35552. this._mapDraw = null;
  35553. },
  35554. _renderSymbols: function (mapModel, ecModel, api) {
  35555. var originalData = mapModel.originalData;
  35556. var group = this.group;
  35557. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  35558. if (isNaN(value)) {
  35559. return;
  35560. }
  35561. var layout = originalData.getItemLayout(idx);
  35562. if (!layout || !layout.point) {
  35563. // Not exists in map
  35564. return;
  35565. }
  35566. var point = layout.point;
  35567. var offset = layout.offset;
  35568. var circle = new Circle({
  35569. style: {
  35570. // Because the special of map draw.
  35571. // Which needs statistic of multiple series and draw on one map.
  35572. // And each series also need a symbol with legend color
  35573. //
  35574. // Layout and visual are put one the different data
  35575. fill: mapModel.getData().getVisual('color')
  35576. },
  35577. shape: {
  35578. cx: point[0] + offset * 9,
  35579. cy: point[1],
  35580. r: 3
  35581. },
  35582. silent: true,
  35583. // Do not overlap the first series, on which labels are displayed.
  35584. z2: !offset ? 10 : 8
  35585. });
  35586. // First data on the same region
  35587. if (!offset) {
  35588. var fullData = mapModel.mainSeries.getData();
  35589. var name = originalData.getName(idx);
  35590. var fullIndex = fullData.indexOfName(name);
  35591. var itemModel = originalData.getItemModel(idx);
  35592. var labelModel = itemModel.getModel('label');
  35593. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35594. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  35595. var normalText = retrieve2(
  35596. mapModel.getFormattedLabel(idx, 'normal'),
  35597. name
  35598. );
  35599. var emphasisText = retrieve2(
  35600. mapModel.getFormattedLabel(idx, 'emphasis'),
  35601. normalText
  35602. );
  35603. var onEmphasis = function () {
  35604. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  35605. text: hoverLabelModel.get('show') ? emphasisText : null
  35606. }, {isRectText: true, useInsideStyle: false}, true);
  35607. circle.style.extendFrom(hoverStyle);
  35608. // Make label upper than others if overlaps.
  35609. circle.__mapOriginalZ2 = circle.z2;
  35610. circle.z2 += 1;
  35611. };
  35612. var onNormal = function () {
  35613. setTextStyle(circle.style, labelModel, {
  35614. text: labelModel.get('show') ? normalText : null,
  35615. textPosition: labelModel.getShallow('position') || 'bottom'
  35616. }, {isRectText: true, useInsideStyle: false});
  35617. if (circle.__mapOriginalZ2 != null) {
  35618. circle.z2 = circle.__mapOriginalZ2;
  35619. circle.__mapOriginalZ2 = null;
  35620. }
  35621. };
  35622. polygonGroups.on('mouseover', onEmphasis)
  35623. .on('mouseout', onNormal)
  35624. .on('emphasis', onEmphasis)
  35625. .on('normal', onNormal);
  35626. onNormal();
  35627. }
  35628. group.add(circle);
  35629. });
  35630. }
  35631. });
  35632. /**
  35633. * @param {module:echarts/coord/View} view
  35634. * @param {Object} payload
  35635. * @param {Object} [zoomLimit]
  35636. */
  35637. function updateCenterAndZoom(
  35638. view, payload, zoomLimit
  35639. ) {
  35640. var previousZoom = view.getZoom();
  35641. var center = view.getCenter();
  35642. var zoom = payload.zoom;
  35643. var point = view.dataToPoint(center);
  35644. if (payload.dx != null && payload.dy != null) {
  35645. point[0] -= payload.dx;
  35646. point[1] -= payload.dy;
  35647. var center = view.pointToData(point);
  35648. view.setCenter(center);
  35649. }
  35650. if (zoom != null) {
  35651. if (zoomLimit) {
  35652. var zoomMin = zoomLimit.min || 0;
  35653. var zoomMax = zoomLimit.max || Infinity;
  35654. zoom = Math.max(
  35655. Math.min(previousZoom * zoom, zoomMax),
  35656. zoomMin
  35657. ) / previousZoom;
  35658. }
  35659. // Zoom on given point(originX, originY)
  35660. view.scale[0] *= zoom;
  35661. view.scale[1] *= zoom;
  35662. var position = view.position;
  35663. var fixX = (payload.originX - position[0]) * (zoom - 1);
  35664. var fixY = (payload.originY - position[1]) * (zoom - 1);
  35665. position[0] -= fixX;
  35666. position[1] -= fixY;
  35667. view.updateTransform();
  35668. // Get the new center
  35669. var center = view.pointToData(point);
  35670. view.setCenter(center);
  35671. view.setZoom(zoom * previousZoom);
  35672. }
  35673. return {
  35674. center: view.getCenter(),
  35675. zoom: view.getZoom()
  35676. };
  35677. }
  35678. /**
  35679. * @payload
  35680. * @property {string} [componentType=series]
  35681. * @property {number} [dx]
  35682. * @property {number} [dy]
  35683. * @property {number} [zoom]
  35684. * @property {number} [originX]
  35685. * @property {number} [originY]
  35686. */
  35687. registerAction({
  35688. type: 'geoRoam',
  35689. event: 'geoRoam',
  35690. update: 'updateTransform'
  35691. }, function (payload, ecModel) {
  35692. var componentType = payload.componentType || 'series';
  35693. ecModel.eachComponent(
  35694. { mainType: componentType, query: payload },
  35695. function (componentModel) {
  35696. var geo = componentModel.coordinateSystem;
  35697. if (geo.type !== 'geo') {
  35698. return;
  35699. }
  35700. var res = updateCenterAndZoom(
  35701. geo, payload, componentModel.get('scaleLimit')
  35702. );
  35703. componentModel.setCenter
  35704. && componentModel.setCenter(res.center);
  35705. componentModel.setZoom
  35706. && componentModel.setZoom(res.zoom);
  35707. // All map series with same `map` use the same geo coordinate system
  35708. // So the center and zoom must be in sync. Include the series not selected by legend
  35709. if (componentType === 'series') {
  35710. each$1(componentModel.seriesGroup, function (seriesModel) {
  35711. seriesModel.setCenter(res.center);
  35712. seriesModel.setZoom(res.zoom);
  35713. });
  35714. }
  35715. }
  35716. );
  35717. });
  35718. var mapSymbolLayout = function (ecModel) {
  35719. var processedMapType = {};
  35720. ecModel.eachSeriesByType('map', function (mapSeries) {
  35721. var mapType = mapSeries.getMapType();
  35722. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  35723. return;
  35724. }
  35725. var mapSymbolOffsets = {};
  35726. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  35727. var geo = subMapSeries.coordinateSystem;
  35728. var data = subMapSeries.originalData;
  35729. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  35730. data.each(data.mapDimension('value'), function (value, idx) {
  35731. var name = data.getName(idx);
  35732. var region = geo.getRegion(name);
  35733. // If input series.data is [11, 22, '-'/null/undefined, 44],
  35734. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  35735. // not be drawn. So here must validate if value is NaN.
  35736. if (!region || isNaN(value)) {
  35737. return;
  35738. }
  35739. var offset = mapSymbolOffsets[name] || 0;
  35740. var point = geo.dataToPoint(region.center);
  35741. mapSymbolOffsets[name] = offset + 1;
  35742. data.setItemLayout(idx, {
  35743. point: point,
  35744. offset: offset
  35745. });
  35746. });
  35747. }
  35748. });
  35749. // Show label of those region not has legendSymbol(which is offset 0)
  35750. var data = mapSeries.getData();
  35751. data.each(function (idx) {
  35752. var name = data.getName(idx);
  35753. var layout = data.getItemLayout(idx) || {};
  35754. layout.showLabel = !mapSymbolOffsets[name];
  35755. data.setItemLayout(idx, layout);
  35756. });
  35757. processedMapType[mapType] = true;
  35758. });
  35759. };
  35760. var mapVisual = function (ecModel) {
  35761. ecModel.eachSeriesByType('map', function (seriesModel) {
  35762. var colorList = seriesModel.get('color');
  35763. var itemStyleModel = seriesModel.getModel('itemStyle');
  35764. var areaColor = itemStyleModel.get('areaColor');
  35765. var color = itemStyleModel.get('color')
  35766. || colorList[seriesModel.seriesIndex % colorList.length];
  35767. seriesModel.getData().setVisual({
  35768. 'areaColor': areaColor,
  35769. 'color': color
  35770. });
  35771. });
  35772. };
  35773. // FIXME 公用?
  35774. /**
  35775. * @param {Array.<module:echarts/data/List>} datas
  35776. * @param {string} statisticType 'average' 'sum'
  35777. * @inner
  35778. */
  35779. function dataStatistics(datas, statisticType) {
  35780. var dataNameMap = {};
  35781. each$1(datas, function (data) {
  35782. data.each(data.mapDimension('value'), function (value, idx) {
  35783. // Add prefix to avoid conflict with Object.prototype.
  35784. var mapKey = 'ec-' + data.getName(idx);
  35785. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  35786. if (!isNaN(value)) {
  35787. dataNameMap[mapKey].push(value);
  35788. }
  35789. });
  35790. });
  35791. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  35792. var mapKey = 'ec-' + datas[0].getName(idx);
  35793. var sum = 0;
  35794. var min = Infinity;
  35795. var max = -Infinity;
  35796. var len = dataNameMap[mapKey].length;
  35797. for (var i = 0; i < len; i++) {
  35798. min = Math.min(min, dataNameMap[mapKey][i]);
  35799. max = Math.max(max, dataNameMap[mapKey][i]);
  35800. sum += dataNameMap[mapKey][i];
  35801. }
  35802. var result;
  35803. if (statisticType === 'min') {
  35804. result = min;
  35805. }
  35806. else if (statisticType === 'max') {
  35807. result = max;
  35808. }
  35809. else if (statisticType === 'average') {
  35810. result = sum / len;
  35811. }
  35812. else {
  35813. result = sum;
  35814. }
  35815. return len === 0 ? NaN : result;
  35816. });
  35817. }
  35818. var mapDataStatistic = function (ecModel) {
  35819. var seriesGroups = {};
  35820. ecModel.eachSeriesByType('map', function (seriesModel) {
  35821. var hostGeoModel = seriesModel.getHostGeoModel();
  35822. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  35823. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  35824. });
  35825. each$1(seriesGroups, function (seriesList, key) {
  35826. var data = dataStatistics(
  35827. map(seriesList, function (seriesModel) {
  35828. return seriesModel.getData();
  35829. }),
  35830. seriesList[0].get('mapValueCalculation')
  35831. );
  35832. for (var i = 0; i < seriesList.length; i++) {
  35833. seriesList[i].originalData = seriesList[i].getData();
  35834. }
  35835. // FIXME Put where?
  35836. for (var i = 0; i < seriesList.length; i++) {
  35837. seriesList[i].seriesGroup = seriesList;
  35838. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  35839. seriesList[i].setData(data.cloneShallow());
  35840. seriesList[i].mainSeries = seriesList[0];
  35841. }
  35842. });
  35843. };
  35844. var backwardCompat$2 = function (option) {
  35845. // Save geoCoord
  35846. var mapSeries = [];
  35847. each$1(option.series, function (seriesOpt) {
  35848. if (seriesOpt && seriesOpt.type === 'map') {
  35849. mapSeries.push(seriesOpt);
  35850. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  35851. // Put x, y, width, height, x2, y2 in the top level
  35852. defaults(seriesOpt, seriesOpt.mapLocation);
  35853. }
  35854. });
  35855. };
  35856. registerLayout(mapSymbolLayout);
  35857. registerVisual(mapVisual);
  35858. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  35859. registerPreprocessor(backwardCompat$2);
  35860. createDataSelectAction('map', [{
  35861. type: 'mapToggleSelect',
  35862. event: 'mapselectchanged',
  35863. method: 'toggleSelected'
  35864. }, {
  35865. type: 'mapSelect',
  35866. event: 'mapselected',
  35867. method: 'select'
  35868. }, {
  35869. type: 'mapUnSelect',
  35870. event: 'mapunselected',
  35871. method: 'unSelect'
  35872. }]);
  35873. /**
  35874. * Link lists and struct (graph or tree)
  35875. */
  35876. var each$8 = each$1;
  35877. var DATAS = '\0__link_datas';
  35878. var MAIN_DATA = '\0__link_mainData';
  35879. // Caution:
  35880. // In most case, either list or its shallow clones (see list.cloneShallow)
  35881. // is active in echarts process. So considering heap memory consumption,
  35882. // we do not clone tree or graph, but share them among list and its shallow clones.
  35883. // But in some rare case, we have to keep old list (like do animation in chart). So
  35884. // please take care that both the old list and the new list share the same tree/graph.
  35885. /**
  35886. * @param {Object} opt
  35887. * @param {module:echarts/data/List} opt.mainData
  35888. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  35889. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  35890. * @param {Object} [opt.datas] {dataType: data},
  35891. * like: {node: nodeList, edge: edgeList}.
  35892. * Should contain mainData.
  35893. * @param {Object} [opt.datasAttr] {dataType: attr},
  35894. * designation: struct[datasAttr[dataType]] = list;
  35895. */
  35896. function linkList(opt) {
  35897. var mainData = opt.mainData;
  35898. var datas = opt.datas;
  35899. if (!datas) {
  35900. datas = {main: mainData};
  35901. opt.datasAttr = {main: 'data'};
  35902. }
  35903. opt.datas = opt.mainData = null;
  35904. linkAll(mainData, datas, opt);
  35905. // Porxy data original methods.
  35906. each$8(datas, function (data) {
  35907. each$8(mainData.TRANSFERABLE_METHODS, function (methodName) {
  35908. data.wrapMethod(methodName, curry(transferInjection, opt));
  35909. });
  35910. });
  35911. // Beyond transfer, additional features should be added to `cloneShallow`.
  35912. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  35913. // Only mainData trigger change, because struct.update may trigger
  35914. // another changable methods, which may bring about dead lock.
  35915. each$8(mainData.CHANGABLE_METHODS, function (methodName) {
  35916. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  35917. });
  35918. // Make sure datas contains mainData.
  35919. assert$1(datas[mainData.dataType] === mainData);
  35920. }
  35921. function transferInjection(opt, res) {
  35922. if (isMainData(this)) {
  35923. // Transfer datas to new main data.
  35924. var datas = extend({}, this[DATAS]);
  35925. datas[this.dataType] = res;
  35926. linkAll(res, datas, opt);
  35927. }
  35928. else {
  35929. // Modify the reference in main data to point newData.
  35930. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  35931. }
  35932. return res;
  35933. }
  35934. function changeInjection(opt, res) {
  35935. opt.struct && opt.struct.update(this);
  35936. return res;
  35937. }
  35938. function cloneShallowInjection(opt, res) {
  35939. // cloneShallow, which brings about some fragilities, may be inappropriate
  35940. // to be exposed as an API. So for implementation simplicity we can make
  35941. // the restriction that cloneShallow of not-mainData should not be invoked
  35942. // outside, but only be invoked here.
  35943. each$8(res[DATAS], function (data, dataType) {
  35944. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  35945. });
  35946. return res;
  35947. }
  35948. /**
  35949. * Supplement method to List.
  35950. *
  35951. * @public
  35952. * @param {string} [dataType] If not specified, return mainData.
  35953. * @return {module:echarts/data/List}
  35954. */
  35955. function getLinkedData(dataType) {
  35956. var mainData = this[MAIN_DATA];
  35957. return (dataType == null || mainData == null)
  35958. ? mainData
  35959. : mainData[DATAS][dataType];
  35960. }
  35961. function isMainData(data) {
  35962. return data[MAIN_DATA] === data;
  35963. }
  35964. function linkAll(mainData, datas, opt) {
  35965. mainData[DATAS] = {};
  35966. each$8(datas, function (data, dataType) {
  35967. linkSingle(data, dataType, mainData, opt);
  35968. });
  35969. }
  35970. function linkSingle(data, dataType, mainData, opt) {
  35971. mainData[DATAS][dataType] = data;
  35972. data[MAIN_DATA] = mainData;
  35973. data.dataType = dataType;
  35974. if (opt.struct) {
  35975. data[opt.structAttr] = opt.struct;
  35976. opt.struct[opt.datasAttr[dataType]] = data;
  35977. }
  35978. // Supplement method.
  35979. data.getLinkedData = getLinkedData;
  35980. }
  35981. /**
  35982. * Tree data structure
  35983. *
  35984. * @module echarts/data/Tree
  35985. */
  35986. /**
  35987. * @constructor module:echarts/data/Tree~TreeNode
  35988. * @param {string} name
  35989. * @param {module:echarts/data/Tree} hostTree
  35990. */
  35991. var TreeNode = function (name, hostTree) {
  35992. /**
  35993. * @type {string}
  35994. */
  35995. this.name = name || '';
  35996. /**
  35997. * Depth of node
  35998. *
  35999. * @type {number}
  36000. * @readOnly
  36001. */
  36002. this.depth = 0;
  36003. /**
  36004. * Height of the subtree rooted at this node.
  36005. * @type {number}
  36006. * @readOnly
  36007. */
  36008. this.height = 0;
  36009. /**
  36010. * @type {module:echarts/data/Tree~TreeNode}
  36011. * @readOnly
  36012. */
  36013. this.parentNode = null;
  36014. /**
  36015. * Reference to list item.
  36016. * Do not persistent dataIndex outside,
  36017. * besause it may be changed by list.
  36018. * If dataIndex -1,
  36019. * this node is logical deleted (filtered) in list.
  36020. *
  36021. * @type {Object}
  36022. * @readOnly
  36023. */
  36024. this.dataIndex = -1;
  36025. /**
  36026. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  36027. * @readOnly
  36028. */
  36029. this.children = [];
  36030. /**
  36031. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  36032. * @pubilc
  36033. */
  36034. this.viewChildren = [];
  36035. /**
  36036. * @type {moduel:echarts/data/Tree}
  36037. * @readOnly
  36038. */
  36039. this.hostTree = hostTree;
  36040. };
  36041. TreeNode.prototype = {
  36042. constructor: TreeNode,
  36043. /**
  36044. * The node is removed.
  36045. * @return {boolean} is removed.
  36046. */
  36047. isRemoved: function () {
  36048. return this.dataIndex < 0;
  36049. },
  36050. /**
  36051. * Travel this subtree (include this node).
  36052. * Usage:
  36053. * node.eachNode(function () { ... }); // preorder
  36054. * node.eachNode('preorder', function () { ... }); // preorder
  36055. * node.eachNode('postorder', function () { ... }); // postorder
  36056. * node.eachNode(
  36057. * {order: 'postorder', attr: 'viewChildren'},
  36058. * function () { ... }
  36059. * ); // postorder
  36060. *
  36061. * @param {(Object|string)} options If string, means order.
  36062. * @param {string=} options.order 'preorder' or 'postorder'
  36063. * @param {string=} options.attr 'children' or 'viewChildren'
  36064. * @param {Function} cb If in preorder and return false,
  36065. * its subtree will not be visited.
  36066. * @param {Object} [context]
  36067. */
  36068. eachNode: function (options, cb, context) {
  36069. if (typeof options === 'function') {
  36070. context = cb;
  36071. cb = options;
  36072. options = null;
  36073. }
  36074. options = options || {};
  36075. if (isString(options)) {
  36076. options = {order: options};
  36077. }
  36078. var order = options.order || 'preorder';
  36079. var children = this[options.attr || 'children'];
  36080. var suppressVisitSub;
  36081. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  36082. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  36083. children[i].eachNode(options, cb, context);
  36084. }
  36085. order === 'postorder' && cb.call(context, this);
  36086. },
  36087. /**
  36088. * Update depth and height of this subtree.
  36089. *
  36090. * @param {number} depth
  36091. */
  36092. updateDepthAndHeight: function (depth) {
  36093. var height = 0;
  36094. this.depth = depth;
  36095. for (var i = 0; i < this.children.length; i++) {
  36096. var child = this.children[i];
  36097. child.updateDepthAndHeight(depth + 1);
  36098. if (child.height > height) {
  36099. height = child.height;
  36100. }
  36101. }
  36102. this.height = height + 1;
  36103. },
  36104. /**
  36105. * @param {string} id
  36106. * @return {module:echarts/data/Tree~TreeNode}
  36107. */
  36108. getNodeById: function (id) {
  36109. if (this.getId() === id) {
  36110. return this;
  36111. }
  36112. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  36113. var res = children[i].getNodeById(id);
  36114. if (res) {
  36115. return res;
  36116. }
  36117. }
  36118. },
  36119. /**
  36120. * @param {module:echarts/data/Tree~TreeNode} node
  36121. * @return {boolean}
  36122. */
  36123. contains: function (node) {
  36124. if (node === this) {
  36125. return true;
  36126. }
  36127. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  36128. var res = children[i].contains(node);
  36129. if (res) {
  36130. return res;
  36131. }
  36132. }
  36133. },
  36134. /**
  36135. * @param {boolean} includeSelf Default false.
  36136. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  36137. */
  36138. getAncestors: function (includeSelf) {
  36139. var ancestors = [];
  36140. var node = includeSelf ? this : this.parentNode;
  36141. while (node) {
  36142. ancestors.push(node);
  36143. node = node.parentNode;
  36144. }
  36145. ancestors.reverse();
  36146. return ancestors;
  36147. },
  36148. /**
  36149. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  36150. * @return {number} Value.
  36151. */
  36152. getValue: function (dimension) {
  36153. var data = this.hostTree.data;
  36154. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  36155. },
  36156. /**
  36157. * @param {Object} layout
  36158. * @param {boolean=} [merge=false]
  36159. */
  36160. setLayout: function (layout, merge$$1) {
  36161. this.dataIndex >= 0
  36162. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  36163. },
  36164. /**
  36165. * @return {Object} layout
  36166. */
  36167. getLayout: function () {
  36168. return this.hostTree.data.getItemLayout(this.dataIndex);
  36169. },
  36170. /**
  36171. * @param {string} [path]
  36172. * @return {module:echarts/model/Model}
  36173. */
  36174. getModel: function (path) {
  36175. if (this.dataIndex < 0) {
  36176. return;
  36177. }
  36178. var hostTree = this.hostTree;
  36179. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  36180. var levelModel = this.getLevelModel();
  36181. var leavesModel;
  36182. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  36183. leavesModel = this.getLeavesModel();
  36184. }
  36185. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  36186. },
  36187. /**
  36188. * @return {module:echarts/model/Model}
  36189. */
  36190. getLevelModel: function () {
  36191. return (this.hostTree.levelModels || [])[this.depth];
  36192. },
  36193. /**
  36194. * @return {module:echarts/model/Model}
  36195. */
  36196. getLeavesModel: function () {
  36197. return this.hostTree.leavesModel;
  36198. },
  36199. /**
  36200. * @example
  36201. * setItemVisual('color', color);
  36202. * setItemVisual({
  36203. * 'color': color
  36204. * });
  36205. */
  36206. setVisual: function (key, value) {
  36207. this.dataIndex >= 0
  36208. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  36209. },
  36210. /**
  36211. * Get item visual
  36212. */
  36213. getVisual: function (key, ignoreParent) {
  36214. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  36215. },
  36216. /**
  36217. * @public
  36218. * @return {number}
  36219. */
  36220. getRawIndex: function () {
  36221. return this.hostTree.data.getRawIndex(this.dataIndex);
  36222. },
  36223. /**
  36224. * @public
  36225. * @return {string}
  36226. */
  36227. getId: function () {
  36228. return this.hostTree.data.getId(this.dataIndex);
  36229. },
  36230. /**
  36231. * if this is an ancestor of another node
  36232. *
  36233. * @public
  36234. * @param {TreeNode} node another node
  36235. * @return {boolean} if is ancestor
  36236. */
  36237. isAncestorOf: function (node) {
  36238. var parent = node.parentNode;
  36239. while (parent) {
  36240. if (parent === this) {
  36241. return true;
  36242. }
  36243. parent = parent.parentNode;
  36244. }
  36245. return false;
  36246. },
  36247. /**
  36248. * if this is an descendant of another node
  36249. *
  36250. * @public
  36251. * @param {TreeNode} node another node
  36252. * @return {boolean} if is descendant
  36253. */
  36254. isDescendantOf: function (node) {
  36255. return node !== this && node.isAncestorOf(this);
  36256. }
  36257. };
  36258. /**
  36259. * @constructor
  36260. * @alias module:echarts/data/Tree
  36261. * @param {module:echarts/model/Model} hostModel
  36262. * @param {Array.<Object>} levelOptions
  36263. * @param {Object} leavesOption
  36264. */
  36265. function Tree(hostModel, levelOptions, leavesOption) {
  36266. /**
  36267. * @type {module:echarts/data/Tree~TreeNode}
  36268. * @readOnly
  36269. */
  36270. this.root;
  36271. /**
  36272. * @type {module:echarts/data/List}
  36273. * @readOnly
  36274. */
  36275. this.data;
  36276. /**
  36277. * Index of each item is the same as the raw index of coresponding list item.
  36278. * @private
  36279. * @type {Array.<module:echarts/data/Tree~TreeNode}
  36280. */
  36281. this._nodes = [];
  36282. /**
  36283. * @private
  36284. * @readOnly
  36285. * @type {module:echarts/model/Model}
  36286. */
  36287. this.hostModel = hostModel;
  36288. /**
  36289. * @private
  36290. * @readOnly
  36291. * @type {Array.<module:echarts/model/Model}
  36292. */
  36293. this.levelModels = map(levelOptions || [], function (levelDefine) {
  36294. return new Model(levelDefine, hostModel, hostModel.ecModel);
  36295. });
  36296. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  36297. }
  36298. Tree.prototype = {
  36299. constructor: Tree,
  36300. type: 'tree',
  36301. /**
  36302. * Travel this subtree (include this node).
  36303. * Usage:
  36304. * node.eachNode(function () { ... }); // preorder
  36305. * node.eachNode('preorder', function () { ... }); // preorder
  36306. * node.eachNode('postorder', function () { ... }); // postorder
  36307. * node.eachNode(
  36308. * {order: 'postorder', attr: 'viewChildren'},
  36309. * function () { ... }
  36310. * ); // postorder
  36311. *
  36312. * @param {(Object|string)} options If string, means order.
  36313. * @param {string=} options.order 'preorder' or 'postorder'
  36314. * @param {string=} options.attr 'children' or 'viewChildren'
  36315. * @param {Function} cb
  36316. * @param {Object} [context]
  36317. */
  36318. eachNode: function(options, cb, context) {
  36319. this.root.eachNode(options, cb, context);
  36320. },
  36321. /**
  36322. * @param {number} dataIndex
  36323. * @return {module:echarts/data/Tree~TreeNode}
  36324. */
  36325. getNodeByDataIndex: function (dataIndex) {
  36326. var rawIndex = this.data.getRawIndex(dataIndex);
  36327. return this._nodes[rawIndex];
  36328. },
  36329. /**
  36330. * @param {string} name
  36331. * @return {module:echarts/data/Tree~TreeNode}
  36332. */
  36333. getNodeByName: function (name) {
  36334. return this.root.getNodeByName(name);
  36335. },
  36336. /**
  36337. * Update item available by list,
  36338. * when list has been performed options like 'filterSelf' or 'map'.
  36339. */
  36340. update: function () {
  36341. var data = this.data;
  36342. var nodes = this._nodes;
  36343. for (var i = 0, len = nodes.length; i < len; i++) {
  36344. nodes[i].dataIndex = -1;
  36345. }
  36346. for (var i = 0, len = data.count(); i < len; i++) {
  36347. nodes[data.getRawIndex(i)].dataIndex = i;
  36348. }
  36349. },
  36350. /**
  36351. * Clear all layouts
  36352. */
  36353. clearLayouts: function () {
  36354. this.data.clearItemLayouts();
  36355. }
  36356. };
  36357. /**
  36358. * data node format:
  36359. * {
  36360. * name: ...
  36361. * value: ...
  36362. * children: [
  36363. * {
  36364. * name: ...
  36365. * value: ...
  36366. * children: ...
  36367. * },
  36368. * ...
  36369. * ]
  36370. * }
  36371. *
  36372. * @static
  36373. * @param {Object} dataRoot Root node.
  36374. * @param {module:echarts/model/Model} hostModel
  36375. * @param {Object} treeOptions
  36376. * @param {Array.<Object>} treeOptions.levels
  36377. * @param {Array.<Object>} treeOptions.leaves
  36378. * @return module:echarts/data/Tree
  36379. */
  36380. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  36381. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  36382. var listData = [];
  36383. var dimMax = 1;
  36384. buildHierarchy(dataRoot);
  36385. function buildHierarchy(dataNode, parentNode) {
  36386. var value = dataNode.value;
  36387. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  36388. listData.push(dataNode);
  36389. var node = new TreeNode(dataNode.name, tree);
  36390. parentNode
  36391. ? addChild(node, parentNode)
  36392. : (tree.root = node);
  36393. tree._nodes.push(node);
  36394. var children = dataNode.children;
  36395. if (children) {
  36396. for (var i = 0; i < children.length; i++) {
  36397. buildHierarchy(children[i], node);
  36398. }
  36399. }
  36400. }
  36401. tree.root.updateDepthAndHeight(0);
  36402. var dimensionsInfo = createDimensions(listData, {
  36403. coordDimensions: ['value'],
  36404. dimensionsCount: dimMax
  36405. });
  36406. var list = new List(dimensionsInfo, hostModel);
  36407. list.initData(listData);
  36408. linkList({
  36409. mainData: list,
  36410. struct: tree,
  36411. structAttr: 'tree'
  36412. });
  36413. tree.update();
  36414. return tree;
  36415. };
  36416. /**
  36417. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  36418. * so this function is not ready and not necessary to be public.
  36419. *
  36420. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  36421. */
  36422. function addChild(child, node) {
  36423. var children = node.children;
  36424. if (child.parentNode === node) {
  36425. return;
  36426. }
  36427. children.push(child);
  36428. child.parentNode = node;
  36429. }
  36430. /**
  36431. * @file Create data struct and define tree view's series model
  36432. */
  36433. SeriesModel.extend({
  36434. type: 'series.tree',
  36435. layoutInfo: null,
  36436. // can support the position parameters 'left', 'top','right','bottom', 'width',
  36437. // 'height' in the setOption() with 'merge' mode normal.
  36438. layoutMode: 'box',
  36439. /**
  36440. * Init a tree data structure from data in option series
  36441. * @param {Object} option the object used to config echarts view
  36442. * @return {module:echarts/data/List} storage initial data
  36443. */
  36444. getInitialData: function (option) {
  36445. //create an virtual root
  36446. var root = {name: option.name, children: option.data};
  36447. var leaves = option.leaves || {};
  36448. var treeOption = {};
  36449. treeOption.leaves = leaves;
  36450. var tree = Tree.createTree(root, this, treeOption);
  36451. var treeDepth = 0;
  36452. tree.eachNode('preorder', function (node) {
  36453. if (node.depth > treeDepth) {
  36454. treeDepth = node.depth;
  36455. }
  36456. });
  36457. var expandAndCollapse = option.expandAndCollapse;
  36458. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  36459. ? option.initialTreeDepth : treeDepth;
  36460. tree.root.eachNode('preorder', function (node) {
  36461. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  36462. node.isExpand = (item && item.collapsed != null)
  36463. ? !item.collapsed
  36464. : node.depth <= expandTreeDepth;
  36465. });
  36466. return tree.data;
  36467. },
  36468. /**
  36469. * @override
  36470. * @param {number} dataIndex
  36471. */
  36472. formatTooltip: function (dataIndex) {
  36473. var tree = this.getData().tree;
  36474. var realRoot = tree.root.children[0];
  36475. var node = tree.getNodeByDataIndex(dataIndex);
  36476. var value = node.getValue();
  36477. var name = node.name;
  36478. while (node && (node !== realRoot)) {
  36479. name = node.parentNode.name + '.' + name;
  36480. node = node.parentNode;
  36481. }
  36482. return encodeHTML(name + (
  36483. (isNaN(value) || value == null) ? '' : ' : ' + value
  36484. ));
  36485. },
  36486. defaultOption: {
  36487. zlevel: 0,
  36488. z: 2,
  36489. // the position of the whole view
  36490. left: '12%',
  36491. top: '12%',
  36492. right: '12%',
  36493. bottom: '12%',
  36494. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  36495. layout: 'orthogonal',
  36496. // the orient of orthoginal layout, can be setted to 'horizontal' or 'vertical'
  36497. orient: 'horizontal',
  36498. symbol: 'emptyCircle',
  36499. symbolSize: 7,
  36500. expandAndCollapse: true,
  36501. initialTreeDepth: 2,
  36502. lineStyle: {
  36503. color: '#ccc',
  36504. width: 1.5,
  36505. curveness: 0.5
  36506. },
  36507. itemStyle: {
  36508. color: 'lightsteelblue',
  36509. borderColor: '#c23531',
  36510. borderWidth: 1.5
  36511. },
  36512. label: {
  36513. show: true,
  36514. color: '#555'
  36515. },
  36516. leaves: {
  36517. label: {
  36518. show: true
  36519. }
  36520. },
  36521. animationEasing: 'linear',
  36522. animationDuration: 700,
  36523. animationDurationUpdate: 1000
  36524. }
  36525. });
  36526. /**
  36527. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  36528. * the tree.
  36529. * @see https://github.com/d3/d3-hierarchy
  36530. */
  36531. /**
  36532. * Initialize all computational message for following algorithm
  36533. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  36534. */
  36535. function init$2(root) {
  36536. root.hierNode = {
  36537. defaultAncestor: null,
  36538. ancestor: root,
  36539. prelim: 0,
  36540. modifier: 0,
  36541. change: 0,
  36542. shift: 0,
  36543. i: 0,
  36544. thread: null
  36545. };
  36546. var nodes = [root];
  36547. var node;
  36548. var children;
  36549. while (node = nodes.pop()) { // jshint ignore:line
  36550. children = node.children;
  36551. if (node.isExpand && children.length) {
  36552. var n = children.length;
  36553. for (var i = n - 1; i >= 0; i--) {
  36554. var child = children[i];
  36555. child.hierNode = {
  36556. defaultAncestor: null,
  36557. ancestor: child,
  36558. prelim: 0,
  36559. modifier: 0,
  36560. change: 0,
  36561. shift: 0,
  36562. i: i,
  36563. thread: null
  36564. };
  36565. nodes.push(child);
  36566. }
  36567. }
  36568. }
  36569. }
  36570. /**
  36571. * Computes a preliminary x coordinate for node. Before that, this function is
  36572. * applied recursively to the children of node, as well as the function
  36573. * apportion(). After spacing out the children by calling executeShifts(), the
  36574. * node is placed to the midpoint of its outermost children.
  36575. * @param {module:echarts/data/Tree~TreeNode} node
  36576. * @param {Function} separation
  36577. */
  36578. function firstWalk(node, separation) {
  36579. var children = node.isExpand ? node.children : [];
  36580. var siblings = node.parentNode.children;
  36581. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  36582. if (children.length) {
  36583. executeShifts(node);
  36584. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  36585. if (subtreeW) {
  36586. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  36587. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  36588. }
  36589. else {
  36590. node.hierNode.prelim = midPoint;
  36591. }
  36592. }
  36593. else if (subtreeW) {
  36594. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  36595. }
  36596. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  36597. }
  36598. /**
  36599. * Computes all real x-coordinates by summing up the modifiers recursively.
  36600. * @param {module:echarts/data/Tree~TreeNode} node
  36601. */
  36602. function secondWalk(node) {
  36603. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  36604. node.setLayout({x: nodeX}, true);
  36605. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  36606. }
  36607. function separation(cb) {
  36608. return arguments.length ? cb : defaultSeparation;
  36609. }
  36610. /**
  36611. * Transform the common coordinate to radial coordinate
  36612. * @param {number} x
  36613. * @param {number} y
  36614. * @return {Object}
  36615. */
  36616. function radialCoordinate(x, y) {
  36617. var radialCoor = {};
  36618. x -= Math.PI / 2;
  36619. radialCoor.x = y * Math.cos(x);
  36620. radialCoor.y = y * Math.sin(x);
  36621. return radialCoor;
  36622. }
  36623. /**
  36624. * Get the layout position of the whole view
  36625. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  36626. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  36627. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  36628. */
  36629. function getViewRect(seriesModel, api) {
  36630. return getLayoutRect(
  36631. seriesModel.getBoxLayoutParams(), {
  36632. width: api.getWidth(),
  36633. height: api.getHeight()
  36634. }
  36635. );
  36636. }
  36637. /**
  36638. * All other shifts, applied to the smaller subtrees between w- and w+, are
  36639. * performed by this function.
  36640. * @param {module:echarts/data/Tree~TreeNode} node
  36641. */
  36642. function executeShifts(node) {
  36643. var children = node.children;
  36644. var n = children.length;
  36645. var shift = 0;
  36646. var change = 0;
  36647. while (--n >= 0) {
  36648. var child = children[n];
  36649. child.hierNode.prelim += shift;
  36650. child.hierNode.modifier += shift;
  36651. change += child.hierNode.change;
  36652. shift += child.hierNode.shift + change;
  36653. }
  36654. }
  36655. /**
  36656. * The core of the algorithm. Here, a new subtree is combined with the
  36657. * previous subtrees. Threads are used to traverse the inside and outside
  36658. * contours of the left and right subtree up to the highest common level.
  36659. * Whenever two nodes of the inside contours conflict, we compute the left
  36660. * one of the greatest uncommon ancestors using the function nextAncestor()
  36661. * and call moveSubtree() to shift the subtree and prepare the shifts of
  36662. * smaller subtrees. Finally, we add a new thread (if necessary).
  36663. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  36664. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  36665. * @param {module:echarts/data/Tree~TreeNode} ancestor
  36666. * @param {Function} separation
  36667. * @return {module:echarts/data/Tree~TreeNode}
  36668. */
  36669. function apportion(subtreeV, subtreeW, ancestor, separation) {
  36670. if (subtreeW) {
  36671. var nodeOutRight = subtreeV;
  36672. var nodeInRight = subtreeV;
  36673. var nodeOutLeft = nodeInRight.parentNode.children[0];
  36674. var nodeInLeft = subtreeW;
  36675. var sumOutRight = nodeOutRight.hierNode.modifier;
  36676. var sumInRight = nodeInRight.hierNode.modifier;
  36677. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  36678. var sumInLeft = nodeInLeft.hierNode.modifier;
  36679. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  36680. nodeOutRight = nextRight(nodeOutRight);
  36681. nodeOutLeft = nextLeft(nodeOutLeft);
  36682. nodeOutRight.hierNode.ancestor = subtreeV;
  36683. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  36684. - sumInRight + separation(nodeInLeft, nodeInRight);
  36685. if (shift > 0) {
  36686. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  36687. sumInRight += shift;
  36688. sumOutRight += shift;
  36689. }
  36690. sumInLeft += nodeInLeft.hierNode.modifier;
  36691. sumInRight += nodeInRight.hierNode.modifier;
  36692. sumOutRight += nodeOutRight.hierNode.modifier;
  36693. sumOutLeft += nodeOutLeft.hierNode.modifier;
  36694. }
  36695. if (nodeInLeft && !nextRight(nodeOutRight)) {
  36696. nodeOutRight.hierNode.thread = nodeInLeft;
  36697. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  36698. }
  36699. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  36700. nodeOutLeft.hierNode.thread = nodeInRight;
  36701. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  36702. ancestor = subtreeV;
  36703. }
  36704. }
  36705. return ancestor;
  36706. }
  36707. /**
  36708. * This function is used to traverse the right contour of a subtree.
  36709. * It returns the rightmost child of node or the thread of node. The function
  36710. * returns null if and only if node is on the highest depth of its subtree.
  36711. * @param {module:echarts/data/Tree~TreeNode} node
  36712. * @return {module:echarts/data/Tree~TreeNode}
  36713. */
  36714. function nextRight(node) {
  36715. var children = node.children;
  36716. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  36717. }
  36718. /**
  36719. * This function is used to traverse the left contour of a subtree (or a subforest).
  36720. * It returns the leftmost child of node or the thread of node. The function
  36721. * returns null if and only if node is on the highest depth of its subtree.
  36722. * @param {module:echarts/data/Tree~TreeNode} node
  36723. * @return {module:echarts/data/Tree~TreeNode}
  36724. */
  36725. function nextLeft(node) {
  36726. var children = node.children;
  36727. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  36728. }
  36729. /**
  36730. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  36731. * Otherwise, returns the specified ancestor.
  36732. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  36733. * @param {module:echarts/data/Tree~TreeNode} node
  36734. * @param {module:echarts/data/Tree~TreeNode} ancestor
  36735. * @return {module:echarts/data/Tree~TreeNode}
  36736. */
  36737. function nextAncestor(nodeInLeft, node, ancestor) {
  36738. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  36739. ? nodeInLeft.hierNode.ancestor : ancestor;
  36740. }
  36741. /**
  36742. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  36743. * @param {module:echarts/data/Tree~TreeNode} wl
  36744. * @param {module:echarts/data/Tree~TreeNode} wr
  36745. * @param {number} shift [description]
  36746. */
  36747. function moveSubtree(wl, wr,shift) {
  36748. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  36749. wr.hierNode.change -= change;
  36750. wr.hierNode.shift += shift;
  36751. wr.hierNode.modifier += shift;
  36752. wr.hierNode.prelim += shift;
  36753. wl.hierNode.change += change;
  36754. }
  36755. function defaultSeparation(node1, node2) {
  36756. return node1.parentNode === node2.parentNode ? 1 : 2;
  36757. }
  36758. /**
  36759. * @file This file used to draw tree view
  36760. */
  36761. extendChartView({
  36762. type: 'tree',
  36763. /**
  36764. * Init the chart
  36765. * @override
  36766. * @param {module:echarts/model/Global} ecModel
  36767. * @param {module:echarts/ExtensionAPI} api
  36768. */
  36769. init: function (ecModel, api) {
  36770. /**
  36771. * @private
  36772. * @type {module:echarts/data/Tree}
  36773. */
  36774. this._oldTree;
  36775. /**
  36776. * @private
  36777. * @type {module:zrender/container/Group}
  36778. */
  36779. this._mainGroup = new Group();
  36780. this.group.add(this._mainGroup);
  36781. },
  36782. render: function (seriesModel, ecModel, api, payload) {
  36783. var data = seriesModel.getData();
  36784. var layoutInfo = seriesModel.layoutInfo;
  36785. var group = this._mainGroup;
  36786. var layout = seriesModel.get('layout');
  36787. if (layout === 'radial') {
  36788. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  36789. }
  36790. else {
  36791. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  36792. }
  36793. var oldData = this._data;
  36794. var seriesScope = {
  36795. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  36796. layout: layout,
  36797. orient: seriesModel.get('orient'),
  36798. curvature: seriesModel.get('lineStyle.curveness'),
  36799. symbolRotate: seriesModel.get('symbolRotate'),
  36800. symbolOffset: seriesModel.get('symbolOffset'),
  36801. hoverAnimation: seriesModel.get('hoverAnimation'),
  36802. useNameLabel: true,
  36803. fadeIn: true
  36804. };
  36805. data.diff(oldData)
  36806. .add(function (newIdx) {
  36807. if (symbolNeedsDraw$1(data, newIdx)) {
  36808. // create node and edge
  36809. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  36810. }
  36811. })
  36812. .update(function (newIdx, oldIdx) {
  36813. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36814. if (!symbolNeedsDraw$1(data, newIdx)) {
  36815. symbolEl && removeNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36816. return;
  36817. }
  36818. // update node and edge
  36819. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36820. })
  36821. .remove(function (oldIdx) {
  36822. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36823. removeNode(data, oldIdx, symbolEl, group, seriesModel, seriesScope);
  36824. })
  36825. .execute();
  36826. if (seriesScope.expandAndCollapse === true) {
  36827. data.eachItemGraphicEl(function (el, dataIndex) {
  36828. el.off('click').on('click', function () {
  36829. api.dispatchAction({
  36830. type: 'treeExpandAndCollapse',
  36831. seriesId: seriesModel.id,
  36832. dataIndex: dataIndex
  36833. });
  36834. });
  36835. });
  36836. }
  36837. this._data = data;
  36838. },
  36839. dispose: function () {},
  36840. remove: function () {
  36841. this._mainGroup.removeAll();
  36842. this._data = null;
  36843. }
  36844. });
  36845. function symbolNeedsDraw$1(data, dataIndex) {
  36846. var layout = data.getItemLayout(dataIndex);
  36847. return layout
  36848. && !isNaN(layout.x) && !isNaN(layout.y)
  36849. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  36850. }
  36851. function getTreeNodeStyle(node, itemModel, seriesScope) {
  36852. seriesScope.itemModel = itemModel;
  36853. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  36854. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36855. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  36856. seriesScope.labelModel = itemModel.getModel('label');
  36857. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  36858. if (node.isExpand === false && node.children.length !== 0) {
  36859. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  36860. }
  36861. else {
  36862. seriesScope.symbolInnerColor = '#fff';
  36863. }
  36864. return seriesScope;
  36865. }
  36866. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36867. var isInit = !symbolEl;
  36868. var node = data.tree.getNodeByDataIndex(dataIndex);
  36869. var itemModel = node.getModel();
  36870. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36871. var virtualRoot = data.tree.root;
  36872. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36873. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  36874. var sourceLayout = source.getLayout();
  36875. var sourceOldLayout = sourceSymbolEl
  36876. ? {
  36877. x: sourceSymbolEl.position[0],
  36878. y: sourceSymbolEl.position[1],
  36879. rawX: sourceSymbolEl.__radialOldRawX,
  36880. rawY: sourceSymbolEl.__radialOldRawY
  36881. }
  36882. : sourceLayout;
  36883. var targetLayout = node.getLayout();
  36884. if (isInit) {
  36885. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  36886. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  36887. }
  36888. else {
  36889. symbolEl.updateData(data, dataIndex, seriesScope);
  36890. }
  36891. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  36892. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  36893. symbolEl.__radialRawX = targetLayout.rawX;
  36894. symbolEl.__radialRawY = targetLayout.rawY;
  36895. group.add(symbolEl);
  36896. data.setItemGraphicEl(dataIndex, symbolEl);
  36897. updateProps(symbolEl, {
  36898. position: [targetLayout.x, targetLayout.y]
  36899. }, seriesModel);
  36900. var symbolPath = symbolEl.getSymbolPath();
  36901. if (seriesScope.layout === 'radial') {
  36902. var realRoot = virtualRoot.children[0];
  36903. var rootLayout = realRoot.getLayout();
  36904. var length = realRoot.children.length;
  36905. var rad;
  36906. var isLeft;
  36907. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  36908. var center = {};
  36909. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  36910. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  36911. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  36912. if (rad < 0) {
  36913. rad = Math.PI * 2 + rad;
  36914. }
  36915. isLeft = center.x < rootLayout.x;
  36916. if (isLeft) {
  36917. rad = rad - Math.PI;
  36918. }
  36919. }
  36920. else {
  36921. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  36922. if (rad < 0) {
  36923. rad = Math.PI * 2 + rad;
  36924. }
  36925. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  36926. isLeft = targetLayout.x < rootLayout.x;
  36927. if (isLeft) {
  36928. rad = rad - Math.PI;
  36929. }
  36930. }
  36931. else {
  36932. isLeft = targetLayout.x > rootLayout.x;
  36933. if (!isLeft) {
  36934. rad = rad - Math.PI;
  36935. }
  36936. }
  36937. }
  36938. var textPosition = isLeft ? 'left' : 'right';
  36939. symbolPath.setStyle({
  36940. textPosition: textPosition,
  36941. textRotation: -rad,
  36942. textOrigin: 'center',
  36943. verticalAlign: 'middle'
  36944. });
  36945. }
  36946. if (node.parentNode && node.parentNode !== virtualRoot) {
  36947. var edge = symbolEl.__edge;
  36948. if (!edge) {
  36949. edge = symbolEl.__edge = new BezierCurve({
  36950. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  36951. style: defaults({opacity: 0}, seriesScope.lineStyle)
  36952. });
  36953. }
  36954. updateProps(edge, {
  36955. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  36956. style: {opacity: 1}
  36957. }, seriesModel);
  36958. group.add(edge);
  36959. }
  36960. }
  36961. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36962. var node = data.tree.getNodeByDataIndex(dataIndex);
  36963. var virtualRoot = data.tree.root;
  36964. var itemModel = node.getModel();
  36965. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36966. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36967. var sourceLayout;
  36968. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  36969. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  36970. }
  36971. updateProps(symbolEl, {
  36972. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  36973. }, seriesModel, function () {
  36974. group.remove(symbolEl);
  36975. data.setItemGraphicEl(dataIndex, null);
  36976. });
  36977. symbolEl.fadeOut(null, {keepLabel: true});
  36978. var edge = symbolEl.__edge;
  36979. if (edge) {
  36980. updateProps(edge, {
  36981. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  36982. style: {
  36983. opacity: 0
  36984. }
  36985. }, seriesModel, function () {
  36986. group.remove(edge);
  36987. });
  36988. }
  36989. }
  36990. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  36991. var cpx1;
  36992. var cpy1;
  36993. var cpx2;
  36994. var cpy2;
  36995. var orient = seriesScope.orient;
  36996. if (seriesScope.layout === 'radial') {
  36997. var x1 = sourceLayout.rawX;
  36998. var y1 = sourceLayout.rawY;
  36999. var x2 = targetLayout.rawX;
  37000. var y2 = targetLayout.rawY;
  37001. var radialCoor1 = radialCoordinate(x1, y1);
  37002. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  37003. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  37004. var radialCoor4 = radialCoordinate(x2, y2);
  37005. return {
  37006. x1: radialCoor1.x,
  37007. y1: radialCoor1.y,
  37008. x2: radialCoor4.x,
  37009. y2: radialCoor4.y,
  37010. cpx1: radialCoor2.x,
  37011. cpy1: radialCoor2.y,
  37012. cpx2: radialCoor3.x,
  37013. cpy2: radialCoor3.y
  37014. };
  37015. }
  37016. else {
  37017. var x1 = sourceLayout.x;
  37018. var y1 = sourceLayout.y;
  37019. var x2 = targetLayout.x;
  37020. var y2 = targetLayout.y;
  37021. if (orient === 'horizontal') {
  37022. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  37023. cpy1 = y1;
  37024. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  37025. cpy2 = y2;
  37026. }
  37027. if (orient === 'vertical') {
  37028. cpx1 = x1;
  37029. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  37030. cpx2 = x2;
  37031. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  37032. }
  37033. return {
  37034. x1: x1,
  37035. y1: y1,
  37036. x2: x2,
  37037. y2: y2,
  37038. cpx1: cpx1,
  37039. cpy1: cpy1,
  37040. cpx2: cpx2,
  37041. cpy2: cpy2
  37042. };
  37043. }
  37044. }
  37045. registerAction({
  37046. type: 'treeExpandAndCollapse',
  37047. event: 'treeExpandAndCollapse',
  37048. update: 'update'
  37049. }, function (payload, ecModel) {
  37050. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  37051. var dataIndex = payload.dataIndex;
  37052. var tree = seriesModel.getData().tree;
  37053. var node = tree.getNodeByDataIndex(dataIndex);
  37054. node.isExpand = !node.isExpand;
  37055. });
  37056. });
  37057. /**
  37058. * Traverse the tree from bottom to top and do something
  37059. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  37060. * @param {Function} callback
  37061. */
  37062. function eachAfter (root, callback, separation) {
  37063. var nodes = [root];
  37064. var next = [];
  37065. var node;
  37066. while (node = nodes.pop()) { // jshint ignore:line
  37067. next.push(node);
  37068. if (node.isExpand) {
  37069. var children = node.children;
  37070. if (children.length) {
  37071. for (var i = 0; i < children.length; i++) {
  37072. nodes.push(children[i]);
  37073. }
  37074. }
  37075. }
  37076. }
  37077. while (node = next.pop()) { // jshint ignore:line
  37078. callback(node, separation);
  37079. }
  37080. }
  37081. /**
  37082. * Traverse the tree from top to bottom and do something
  37083. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  37084. * @param {Function} callback
  37085. */
  37086. function eachBefore (root, callback) {
  37087. var nodes = [root];
  37088. var node;
  37089. while (node = nodes.pop()) { // jshint ignore:line
  37090. callback(node);
  37091. if (node.isExpand) {
  37092. var children = node.children;
  37093. if (children.length) {
  37094. for (var i = children.length - 1; i >= 0; i--) {
  37095. nodes.push(children[i]);
  37096. }
  37097. }
  37098. }
  37099. }
  37100. }
  37101. var commonLayout = function (seriesModel, api) {
  37102. var layoutInfo = getViewRect(seriesModel, api);
  37103. seriesModel.layoutInfo = layoutInfo;
  37104. var layout = seriesModel.get('layout');
  37105. var width = 0;
  37106. var height = 0;
  37107. var separation$$1 = null;
  37108. if (layout === 'radial') {
  37109. width = 2 * Math.PI;
  37110. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  37111. separation$$1 = separation(function (node1, node2) {
  37112. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  37113. });
  37114. }
  37115. else {
  37116. width = layoutInfo.width;
  37117. height = layoutInfo.height;
  37118. separation$$1 = separation();
  37119. }
  37120. var virtualRoot = seriesModel.getData().tree.root;
  37121. var realRoot = virtualRoot.children[0];
  37122. init$2(virtualRoot);
  37123. eachAfter(realRoot, firstWalk, separation$$1);
  37124. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  37125. eachBefore(realRoot, secondWalk);
  37126. var left = realRoot;
  37127. var right = realRoot;
  37128. var bottom = realRoot;
  37129. eachBefore(realRoot, function (node) {
  37130. var x = node.getLayout().x;
  37131. if (x < left.getLayout().x) {
  37132. left = node;
  37133. }
  37134. if (x > right.getLayout().x) {
  37135. right = node;
  37136. }
  37137. if (node.depth > bottom.depth) {
  37138. bottom = node;
  37139. }
  37140. });
  37141. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  37142. var tx = delta - left.getLayout().x;
  37143. var kx = 0;
  37144. var ky = 0;
  37145. var coorX = 0;
  37146. var coorY = 0;
  37147. if (layout === 'radial') {
  37148. kx = width / (right.getLayout().x + delta + tx);
  37149. // here we use (node.depth - 1), bucause the real root's depth is 1
  37150. ky = height/ ((bottom.depth - 1) || 1);
  37151. eachBefore(realRoot, function (node) {
  37152. coorX = (node.getLayout().x + tx) * kx;
  37153. coorY = (node.depth - 1) * ky;
  37154. var finalCoor = radialCoordinate(coorX, coorY);
  37155. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  37156. });
  37157. }
  37158. else {
  37159. if (seriesModel.get('orient') === 'horizontal') {
  37160. ky = height / (right.getLayout().x + delta + tx);
  37161. kx = width / ((bottom.depth - 1) || 1);
  37162. eachBefore(realRoot, function (node) {
  37163. coorY = (node.getLayout().x + tx) * ky;
  37164. coorX = (node.depth - 1) * kx;
  37165. node.setLayout({x: coorX, y: coorY}, true);
  37166. });
  37167. }
  37168. else {
  37169. kx = width / (right.getLayout().x + delta + tx);
  37170. ky = height / ((bottom.depth - 1) || 1);
  37171. eachBefore(realRoot, function (node) {
  37172. coorX = (node.getLayout().x + tx) * kx;
  37173. coorY = (node.depth - 1) * ky;
  37174. node.setLayout({x: coorX, y: coorY}, true);
  37175. });
  37176. }
  37177. }
  37178. };
  37179. var orthogonalLayout = function (ecModel, api) {
  37180. ecModel.eachSeriesByType('tree', function (seriesModel) {
  37181. commonLayout(seriesModel, api);
  37182. });
  37183. };
  37184. var radialLayout = function (ecModel, api) {
  37185. ecModel.eachSeriesByType('tree', function (seriesModel) {
  37186. commonLayout(seriesModel, api);
  37187. });
  37188. };
  37189. registerVisual(visualSymbol('tree', 'circle'));
  37190. registerLayout(orthogonalLayout);
  37191. registerLayout(radialLayout);
  37192. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  37193. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  37194. var root = seriesModel.getData().tree.root;
  37195. var targetNode = payload.targetNode;
  37196. if (targetNode && root.contains(targetNode)) {
  37197. return {node: targetNode};
  37198. }
  37199. var targetNodeId = payload.targetNodeId;
  37200. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  37201. return {node: targetNode};
  37202. }
  37203. }
  37204. }
  37205. // Not includes the given node at the last item.
  37206. function getPathToRoot(node) {
  37207. var path = [];
  37208. while (node) {
  37209. node = node.parentNode;
  37210. node && path.push(node);
  37211. }
  37212. return path.reverse();
  37213. }
  37214. function aboveViewRoot(viewRoot, node) {
  37215. var viewPath = getPathToRoot(viewRoot);
  37216. return indexOf(viewPath, node) >= 0;
  37217. }
  37218. // From root to the input node (the input node will be included).
  37219. function wrapTreePathInfo(node, seriesModel) {
  37220. var treePathInfo = [];
  37221. while (node) {
  37222. var nodeDataIndex = node.dataIndex;
  37223. treePathInfo.push({
  37224. name: node.name,
  37225. dataIndex: nodeDataIndex,
  37226. value: seriesModel.getRawValue(nodeDataIndex)
  37227. });
  37228. node = node.parentNode;
  37229. }
  37230. treePathInfo.reverse();
  37231. return treePathInfo;
  37232. }
  37233. SeriesModel.extend({
  37234. type: 'series.treemap',
  37235. layoutMode: 'box',
  37236. dependencies: ['grid', 'polar'],
  37237. /**
  37238. * @type {module:echarts/data/Tree~Node}
  37239. */
  37240. _viewRoot: null,
  37241. defaultOption: {
  37242. // Disable progressive rendering
  37243. progressive: 0,
  37244. hoverLayerThreshold: Infinity,
  37245. // center: ['50%', '50%'], // not supported in ec3.
  37246. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  37247. left: 'center',
  37248. top: 'middle',
  37249. right: null,
  37250. bottom: null,
  37251. width: '80%',
  37252. height: '80%',
  37253. sort: true, // Can be null or false or true
  37254. // (order by desc default, asc not supported yet (strange effect))
  37255. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  37256. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  37257. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  37258. // Count from zero (zero represents only view root).
  37259. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  37260. // to align specialized icon. ▷▶❒❐▼✚
  37261. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  37262. // target node area in the view area.
  37263. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  37264. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  37265. // If leafDepth is set and clicking a node which has children but
  37266. // be on left depth, the behaviour would be changing root. Otherwise
  37267. // use behavious defined above.
  37268. animation: true,
  37269. animationDurationUpdate: 900,
  37270. animationEasing: 'quinticInOut',
  37271. breadcrumb: {
  37272. show: true,
  37273. height: 22,
  37274. left: 'center',
  37275. top: 'bottom',
  37276. // right
  37277. // bottom
  37278. emptyItemWidth: 25, // Width of empty node.
  37279. itemStyle: {
  37280. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  37281. borderColor: 'rgba(255,255,255,0.7)',
  37282. borderWidth: 1,
  37283. shadowColor: 'rgba(150,150,150,1)',
  37284. shadowBlur: 3,
  37285. shadowOffsetX: 0,
  37286. shadowOffsetY: 0,
  37287. textStyle: {
  37288. color: '#fff'
  37289. }
  37290. },
  37291. emphasis: {
  37292. textStyle: {}
  37293. }
  37294. },
  37295. label: {
  37296. show: true,
  37297. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  37298. distance: 0,
  37299. padding: 5,
  37300. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  37301. // formatter: null,
  37302. color: '#fff',
  37303. ellipsis: true
  37304. // align
  37305. // verticalAlign
  37306. },
  37307. upperLabel: { // Label when node is parent.
  37308. show: false,
  37309. position: [0, '50%'],
  37310. height: 20,
  37311. // formatter: null,
  37312. color: '#fff',
  37313. ellipsis: true,
  37314. // align: null,
  37315. verticalAlign: 'middle'
  37316. },
  37317. itemStyle: {
  37318. color: null, // Can be 'none' if not necessary.
  37319. colorAlpha: null, // Can be 'none' if not necessary.
  37320. colorSaturation: null, // Can be 'none' if not necessary.
  37321. borderWidth: 0,
  37322. gapWidth: 0,
  37323. borderColor: '#fff',
  37324. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  37325. // border color is evaluated by color of current node and
  37326. // borderColorSaturation.
  37327. },
  37328. emphasis: {
  37329. upperLabel: {
  37330. show: true,
  37331. position: [0, '50%'],
  37332. color: '#fff',
  37333. ellipsis: true,
  37334. verticalAlign: 'middle'
  37335. }
  37336. },
  37337. visualDimension: 0, // Can be 0, 1, 2, 3.
  37338. visualMin: null,
  37339. visualMax: null,
  37340. color: [], // + treemapSeries.color should not be modified. Please only modified
  37341. // level[n].color (if necessary).
  37342. // + Specify color list of each level. level[0].color would be global
  37343. // color list if not specified. (see method `setDefault`).
  37344. // + But set as a empty array to forbid fetch color from global palette
  37345. // when using nodeModel.get('color'), otherwise nodes on deep level
  37346. // will always has color palette set and are not able to inherit color
  37347. // from parent node.
  37348. // + TreemapSeries.color can not be set as 'none', otherwise effect
  37349. // legend color fetching (see seriesColor.js).
  37350. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  37351. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  37352. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  37353. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  37354. // be rendered. Only works when sort is 'asc' or 'desc'.
  37355. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  37356. // grandchildren will not show.
  37357. // Why grandchildren? If not grandchildren but children,
  37358. // some siblings show children and some not,
  37359. // the appearance may be mess and not consistent,
  37360. levels: [] // Each item: {
  37361. // visibleMin, itemStyle, visualDimension, label
  37362. // }
  37363. // data: {
  37364. // value: [],
  37365. // children: [],
  37366. // link: 'http://xxx.xxx.xxx',
  37367. // target: 'blank' or 'self'
  37368. // }
  37369. },
  37370. /**
  37371. * @override
  37372. */
  37373. getInitialData: function (option, ecModel) {
  37374. // Create a virtual root.
  37375. var root = {name: option.name, children: option.data};
  37376. completeTreeValue(root);
  37377. var levels = option.levels || [];
  37378. levels = option.levels = setDefault(levels, ecModel);
  37379. var treeOption = {};
  37380. treeOption.levels = levels;
  37381. // Make sure always a new tree is created when setOption,
  37382. // in TreemapView, we check whether oldTree === newTree
  37383. // to choose mappings approach among old shapes and new shapes.
  37384. return Tree.createTree(root, this, treeOption).data;
  37385. },
  37386. optionUpdated: function () {
  37387. this.resetViewRoot();
  37388. },
  37389. /**
  37390. * @override
  37391. * @param {number} dataIndex
  37392. * @param {boolean} [mutipleSeries=false]
  37393. */
  37394. formatTooltip: function (dataIndex) {
  37395. var data = this.getData();
  37396. var value = this.getRawValue(dataIndex);
  37397. var formattedValue = isArray(value)
  37398. ? addCommas(value[0]) : addCommas(value);
  37399. var name = data.getName(dataIndex);
  37400. return encodeHTML(name + ': ' + formattedValue);
  37401. },
  37402. /**
  37403. * Add tree path to tooltip param
  37404. *
  37405. * @override
  37406. * @param {number} dataIndex
  37407. * @return {Object}
  37408. */
  37409. getDataParams: function (dataIndex) {
  37410. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  37411. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  37412. params.treePathInfo = wrapTreePathInfo(node, this);
  37413. return params;
  37414. },
  37415. /**
  37416. * @public
  37417. * @param {Object} layoutInfo {
  37418. * x: containerGroup x
  37419. * y: containerGroup y
  37420. * width: containerGroup width
  37421. * height: containerGroup height
  37422. * }
  37423. */
  37424. setLayoutInfo: function (layoutInfo) {
  37425. /**
  37426. * @readOnly
  37427. * @type {Object}
  37428. */
  37429. this.layoutInfo = this.layoutInfo || {};
  37430. extend(this.layoutInfo, layoutInfo);
  37431. },
  37432. /**
  37433. * @param {string} id
  37434. * @return {number} index
  37435. */
  37436. mapIdToIndex: function (id) {
  37437. // A feature is implemented:
  37438. // index is monotone increasing with the sequence of
  37439. // input id at the first time.
  37440. // This feature can make sure that each data item and its
  37441. // mapped color have the same index between data list and
  37442. // color list at the beginning, which is useful for user
  37443. // to adjust data-color mapping.
  37444. /**
  37445. * @private
  37446. * @type {Object}
  37447. */
  37448. var idIndexMap = this._idIndexMap;
  37449. if (!idIndexMap) {
  37450. idIndexMap = this._idIndexMap = createHashMap();
  37451. /**
  37452. * @private
  37453. * @type {number}
  37454. */
  37455. this._idIndexMapCount = 0;
  37456. }
  37457. var index = idIndexMap.get(id);
  37458. if (index == null) {
  37459. idIndexMap.set(id, index = this._idIndexMapCount++);
  37460. }
  37461. return index;
  37462. },
  37463. getViewRoot: function () {
  37464. return this._viewRoot;
  37465. },
  37466. /**
  37467. * @param {module:echarts/data/Tree~Node} [viewRoot]
  37468. */
  37469. resetViewRoot: function (viewRoot) {
  37470. viewRoot
  37471. ? (this._viewRoot = viewRoot)
  37472. : (viewRoot = this._viewRoot);
  37473. var root = this.getRawData().tree.root;
  37474. if (!viewRoot
  37475. || (viewRoot !== root && !root.contains(viewRoot))
  37476. ) {
  37477. this._viewRoot = root;
  37478. }
  37479. }
  37480. });
  37481. /**
  37482. * @param {Object} dataNode
  37483. */
  37484. function completeTreeValue(dataNode) {
  37485. // Postorder travel tree.
  37486. // If value of none-leaf node is not set,
  37487. // calculate it by suming up the value of all children.
  37488. var sum = 0;
  37489. each$1(dataNode.children, function (child) {
  37490. completeTreeValue(child);
  37491. var childValue = child.value;
  37492. isArray(childValue) && (childValue = childValue[0]);
  37493. sum += childValue;
  37494. });
  37495. var thisValue = dataNode.value;
  37496. if (isArray(thisValue)) {
  37497. thisValue = thisValue[0];
  37498. }
  37499. if (thisValue == null || isNaN(thisValue)) {
  37500. thisValue = sum;
  37501. }
  37502. // Value should not less than 0.
  37503. if (thisValue < 0) {
  37504. thisValue = 0;
  37505. }
  37506. isArray(dataNode.value)
  37507. ? (dataNode.value[0] = thisValue)
  37508. : (dataNode.value = thisValue);
  37509. }
  37510. /**
  37511. * set default to level configuration
  37512. */
  37513. function setDefault(levels, ecModel) {
  37514. var globalColorList = ecModel.get('color');
  37515. if (!globalColorList) {
  37516. return;
  37517. }
  37518. levels = levels || [];
  37519. var hasColorDefine;
  37520. each$1(levels, function (levelDefine) {
  37521. var model = new Model(levelDefine);
  37522. var modelColor = model.get('color');
  37523. if (model.get('itemStyle.color')
  37524. || (modelColor && modelColor !== 'none')
  37525. ) {
  37526. hasColorDefine = true;
  37527. }
  37528. });
  37529. if (!hasColorDefine) {
  37530. var level0 = levels[0] || (levels[0] = {});
  37531. level0.color = globalColorList.slice();
  37532. }
  37533. return levels;
  37534. }
  37535. var TEXT_PADDING = 8;
  37536. var ITEM_GAP = 8;
  37537. var ARRAY_LENGTH = 5;
  37538. function Breadcrumb(containerGroup) {
  37539. /**
  37540. * @private
  37541. * @type {module:zrender/container/Group}
  37542. */
  37543. this.group = new Group();
  37544. containerGroup.add(this.group);
  37545. }
  37546. Breadcrumb.prototype = {
  37547. constructor: Breadcrumb,
  37548. render: function (seriesModel, api, targetNode, onSelect) {
  37549. var model = seriesModel.getModel('breadcrumb');
  37550. var thisGroup = this.group;
  37551. thisGroup.removeAll();
  37552. if (!model.get('show') || !targetNode) {
  37553. return;
  37554. }
  37555. var normalStyleModel = model.getModel('itemStyle');
  37556. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  37557. var textStyleModel = normalStyleModel.getModel('textStyle');
  37558. var layoutParam = {
  37559. pos: {
  37560. left: model.get('left'),
  37561. right: model.get('right'),
  37562. top: model.get('top'),
  37563. bottom: model.get('bottom')
  37564. },
  37565. box: {
  37566. width: api.getWidth(),
  37567. height: api.getHeight()
  37568. },
  37569. emptyItemWidth: model.get('emptyItemWidth'),
  37570. totalWidth: 0,
  37571. renderList: []
  37572. };
  37573. this._prepare(targetNode, layoutParam, textStyleModel);
  37574. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  37575. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  37576. },
  37577. /**
  37578. * Prepare render list and total width
  37579. * @private
  37580. */
  37581. _prepare: function (targetNode, layoutParam, textStyleModel) {
  37582. for (var node = targetNode; node; node = node.parentNode) {
  37583. var text = node.getModel().get('name');
  37584. var textRect = textStyleModel.getTextRect(text);
  37585. var itemWidth = Math.max(
  37586. textRect.width + TEXT_PADDING * 2,
  37587. layoutParam.emptyItemWidth
  37588. );
  37589. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  37590. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  37591. }
  37592. },
  37593. /**
  37594. * @private
  37595. */
  37596. _renderContent: function (
  37597. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  37598. ) {
  37599. // Start rendering.
  37600. var lastX = 0;
  37601. var emptyItemWidth = layoutParam.emptyItemWidth;
  37602. var height = seriesModel.get('breadcrumb.height');
  37603. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  37604. var totalWidth = layoutParam.totalWidth;
  37605. var renderList = layoutParam.renderList;
  37606. for (var i = renderList.length - 1; i >= 0; i--) {
  37607. var item = renderList[i];
  37608. var itemNode = item.node;
  37609. var itemWidth = item.width;
  37610. var text = item.text;
  37611. // Hdie text and shorten width if necessary.
  37612. if (totalWidth > availableSize.width) {
  37613. totalWidth -= itemWidth - emptyItemWidth;
  37614. itemWidth = emptyItemWidth;
  37615. text = null;
  37616. }
  37617. var el = new Polygon({
  37618. shape: {
  37619. points: makeItemPoints(
  37620. lastX, 0, itemWidth, height,
  37621. i === renderList.length - 1, i === 0
  37622. )
  37623. },
  37624. style: defaults(
  37625. normalStyleModel.getItemStyle(),
  37626. {
  37627. lineJoin: 'bevel',
  37628. text: text,
  37629. textFill: textStyleModel.getTextColor(),
  37630. textFont: textStyleModel.getFont()
  37631. }
  37632. ),
  37633. z: 10,
  37634. onclick: curry(onSelect, itemNode)
  37635. });
  37636. this.group.add(el);
  37637. packEventData(el, seriesModel, itemNode);
  37638. lastX += itemWidth + ITEM_GAP;
  37639. }
  37640. },
  37641. /**
  37642. * @override
  37643. */
  37644. remove: function () {
  37645. this.group.removeAll();
  37646. }
  37647. };
  37648. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  37649. var points = [
  37650. [head ? x : x - ARRAY_LENGTH, y],
  37651. [x + itemWidth, y],
  37652. [x + itemWidth, y + itemHeight],
  37653. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  37654. ];
  37655. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  37656. !head && points.push([x, y + itemHeight / 2]);
  37657. return points;
  37658. }
  37659. // Package custom mouse event.
  37660. function packEventData(el, seriesModel, itemNode) {
  37661. el.eventData = {
  37662. componentType: 'series',
  37663. componentSubType: 'treemap',
  37664. seriesIndex: seriesModel.componentIndex,
  37665. seriesName: seriesModel.name,
  37666. seriesType: 'treemap',
  37667. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  37668. nodeData: {
  37669. dataIndex: itemNode && itemNode.dataIndex,
  37670. name: itemNode && itemNode.name
  37671. },
  37672. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  37673. };
  37674. }
  37675. /**
  37676. * @param {number} [time=500] Time in ms
  37677. * @param {string} [easing='linear']
  37678. * @param {number} [delay=0]
  37679. * @param {Function} [callback]
  37680. *
  37681. * @example
  37682. * // Animate position
  37683. * animation
  37684. * .createWrap()
  37685. * .add(el1, {position: [10, 10]})
  37686. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  37687. * .done(function () { // done })
  37688. * .start('cubicOut');
  37689. */
  37690. function createWrap() {
  37691. var storage = [];
  37692. var elExistsMap = {};
  37693. var doneCallback;
  37694. return {
  37695. /**
  37696. * Caution: a el can only be added once, otherwise 'done'
  37697. * might not be called. This method checks this (by el.id),
  37698. * suppresses adding and returns false when existing el found.
  37699. *
  37700. * @param {modele:zrender/Element} el
  37701. * @param {Object} target
  37702. * @param {number} [time=500]
  37703. * @param {number} [delay=0]
  37704. * @param {string} [easing='linear']
  37705. * @return {boolean} Whether adding succeeded.
  37706. *
  37707. * @example
  37708. * add(el, target, time, delay, easing);
  37709. * add(el, target, time, easing);
  37710. * add(el, target, time);
  37711. * add(el, target);
  37712. */
  37713. add: function (el, target, time, delay, easing) {
  37714. if (isString(delay)) {
  37715. easing = delay;
  37716. delay = 0;
  37717. }
  37718. if (elExistsMap[el.id]) {
  37719. return false;
  37720. }
  37721. elExistsMap[el.id] = 1;
  37722. storage.push(
  37723. {el: el, target: target, time: time, delay: delay, easing: easing}
  37724. );
  37725. return true;
  37726. },
  37727. /**
  37728. * Only execute when animation finished. Will not execute when any
  37729. * of 'stop' or 'stopAnimation' called.
  37730. *
  37731. * @param {Function} callback
  37732. */
  37733. done: function (callback) {
  37734. doneCallback = callback;
  37735. return this;
  37736. },
  37737. /**
  37738. * Will stop exist animation firstly.
  37739. */
  37740. start: function () {
  37741. var count = storage.length;
  37742. for (var i = 0, len = storage.length; i < len; i++) {
  37743. var item = storage[i];
  37744. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  37745. }
  37746. return this;
  37747. function done() {
  37748. count--;
  37749. if (!count) {
  37750. storage.length = 0;
  37751. elExistsMap = {};
  37752. doneCallback && doneCallback();
  37753. }
  37754. }
  37755. }
  37756. };
  37757. }
  37758. var bind$1 = bind;
  37759. var Group$2 = Group;
  37760. var Rect$1 = Rect;
  37761. var each$9 = each$1;
  37762. var DRAG_THRESHOLD = 3;
  37763. var PATH_LABEL_NOAMAL = ['label'];
  37764. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  37765. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  37766. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  37767. var Z_BASE = 10; // Should bigger than every z.
  37768. var Z_BG = 1;
  37769. var Z_CONTENT = 2;
  37770. var getItemStyleEmphasis = makeStyleMapper([
  37771. ['fill', 'color'],
  37772. // `borderColor` and `borderWidth` has been occupied,
  37773. // so use `stroke` to indicate the stroke of the rect.
  37774. ['stroke', 'strokeColor'],
  37775. ['lineWidth', 'strokeWidth'],
  37776. ['shadowBlur'],
  37777. ['shadowOffsetX'],
  37778. ['shadowOffsetY'],
  37779. ['shadowColor']
  37780. ]);
  37781. var getItemStyleNormal = function (model) {
  37782. // Normal style props should include emphasis style props.
  37783. var itemStyle = getItemStyleEmphasis(model);
  37784. // Clear styles set by emphasis.
  37785. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  37786. return itemStyle;
  37787. };
  37788. extendChartView({
  37789. type: 'treemap',
  37790. /**
  37791. * @override
  37792. */
  37793. init: function (o, api) {
  37794. /**
  37795. * @private
  37796. * @type {module:zrender/container/Group}
  37797. */
  37798. this._containerGroup;
  37799. /**
  37800. * @private
  37801. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  37802. */
  37803. this._storage = createStorage();
  37804. /**
  37805. * @private
  37806. * @type {module:echarts/data/Tree}
  37807. */
  37808. this._oldTree;
  37809. /**
  37810. * @private
  37811. * @type {module:echarts/chart/treemap/Breadcrumb}
  37812. */
  37813. this._breadcrumb;
  37814. /**
  37815. * @private
  37816. * @type {module:echarts/component/helper/RoamController}
  37817. */
  37818. this._controller;
  37819. /**
  37820. * 'ready', 'animating'
  37821. * @private
  37822. */
  37823. this._state = 'ready';
  37824. },
  37825. /**
  37826. * @override
  37827. */
  37828. render: function (seriesModel, ecModel, api, payload) {
  37829. var models = ecModel.findComponents({
  37830. mainType: 'series', subType: 'treemap', query: payload
  37831. });
  37832. if (indexOf(models, seriesModel) < 0) {
  37833. return;
  37834. }
  37835. this.seriesModel = seriesModel;
  37836. this.api = api;
  37837. this.ecModel = ecModel;
  37838. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  37839. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  37840. var payloadType = payload && payload.type;
  37841. var layoutInfo = seriesModel.layoutInfo;
  37842. var isInit = !this._oldTree;
  37843. var thisStorage = this._storage;
  37844. // Mark new root when action is treemapRootToNode.
  37845. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  37846. ? {
  37847. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  37848. direction: payload.direction
  37849. }
  37850. : null;
  37851. var containerGroup = this._giveContainerGroup(layoutInfo);
  37852. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  37853. (
  37854. !isInit && (
  37855. !payloadType
  37856. || payloadType === 'treemapZoomToNode'
  37857. || payloadType === 'treemapRootToNode'
  37858. )
  37859. )
  37860. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  37861. : renderResult.renderFinally();
  37862. this._resetController(api);
  37863. this._renderBreadcrumb(seriesModel, api, targetInfo);
  37864. },
  37865. /**
  37866. * @private
  37867. */
  37868. _giveContainerGroup: function (layoutInfo) {
  37869. var containerGroup = this._containerGroup;
  37870. if (!containerGroup) {
  37871. // FIXME
  37872. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  37873. containerGroup = this._containerGroup = new Group$2();
  37874. this._initEvents(containerGroup);
  37875. this.group.add(containerGroup);
  37876. }
  37877. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  37878. return containerGroup;
  37879. },
  37880. /**
  37881. * @private
  37882. */
  37883. _doRender: function (containerGroup, seriesModel, reRoot) {
  37884. var thisTree = seriesModel.getData().tree;
  37885. var oldTree = this._oldTree;
  37886. // Clear last shape records.
  37887. var lastsForAnimation = createStorage();
  37888. var thisStorage = createStorage();
  37889. var oldStorage = this._storage;
  37890. var willInvisibleEls = [];
  37891. var doRenderNode = curry(
  37892. renderNode, seriesModel,
  37893. thisStorage, oldStorage, reRoot,
  37894. lastsForAnimation, willInvisibleEls
  37895. );
  37896. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  37897. // the oldTree is actually losted, so we can not find all of the old graphic
  37898. // elements from tree. So we use this stragegy: make element storage, move
  37899. // from old storage to new storage, clear old storage.
  37900. dualTravel(
  37901. thisTree.root ? [thisTree.root] : [],
  37902. (oldTree && oldTree.root) ? [oldTree.root] : [],
  37903. containerGroup,
  37904. thisTree === oldTree || !oldTree,
  37905. 0
  37906. );
  37907. // Process all removing.
  37908. var willDeleteEls = clearStorage(oldStorage);
  37909. this._oldTree = thisTree;
  37910. this._storage = thisStorage;
  37911. return {
  37912. lastsForAnimation: lastsForAnimation,
  37913. willDeleteEls: willDeleteEls,
  37914. renderFinally: renderFinally
  37915. };
  37916. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  37917. // When 'render' is triggered by action,
  37918. // 'this' and 'old' may be the same tree,
  37919. // we use rawIndex in that case.
  37920. if (sameTree) {
  37921. oldViewChildren = thisViewChildren;
  37922. each$9(thisViewChildren, function (child, index) {
  37923. !child.isRemoved() && processNode(index, index);
  37924. });
  37925. }
  37926. // Diff hierarchically (diff only in each subtree, but not whole).
  37927. // because, consistency of view is important.
  37928. else {
  37929. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  37930. .add(processNode)
  37931. .update(processNode)
  37932. .remove(curry(processNode, null))
  37933. .execute();
  37934. }
  37935. function getKey(node) {
  37936. // Identify by name or raw index.
  37937. return node.getId();
  37938. }
  37939. function processNode(newIndex, oldIndex) {
  37940. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  37941. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  37942. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  37943. group && dualTravel(
  37944. thisNode && thisNode.viewChildren || [],
  37945. oldNode && oldNode.viewChildren || [],
  37946. group,
  37947. sameTree,
  37948. depth + 1
  37949. );
  37950. }
  37951. }
  37952. function clearStorage(storage) {
  37953. var willDeleteEls = createStorage();
  37954. storage && each$9(storage, function (store, storageName) {
  37955. var delEls = willDeleteEls[storageName];
  37956. each$9(store, function (el) {
  37957. el && (delEls.push(el), el.__tmWillDelete = 1);
  37958. });
  37959. });
  37960. return willDeleteEls;
  37961. }
  37962. function renderFinally() {
  37963. each$9(willDeleteEls, function (els) {
  37964. each$9(els, function (el) {
  37965. el.parent && el.parent.remove(el);
  37966. });
  37967. });
  37968. each$9(willInvisibleEls, function (el) {
  37969. el.invisible = true;
  37970. // Setting invisible is for optimizing, so no need to set dirty,
  37971. // just mark as invisible.
  37972. el.dirty();
  37973. });
  37974. }
  37975. },
  37976. /**
  37977. * @private
  37978. */
  37979. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  37980. if (!seriesModel.get('animation')) {
  37981. return;
  37982. }
  37983. var duration = seriesModel.get('animationDurationUpdate');
  37984. var easing = seriesModel.get('animationEasing');
  37985. var animationWrap = createWrap();
  37986. // Make delete animations.
  37987. each$9(renderResult.willDeleteEls, function (store, storageName) {
  37988. each$9(store, function (el, rawIndex) {
  37989. if (el.invisible) {
  37990. return;
  37991. }
  37992. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  37993. var target;
  37994. if (reRoot && reRoot.direction === 'drillDown') {
  37995. target = parent === reRoot.rootNodeGroup
  37996. // This is the content element of view root.
  37997. // Only `content` will enter this branch, because
  37998. // `background` and `nodeGroup` will not be deleted.
  37999. ? {
  38000. shape: {
  38001. x: 0,
  38002. y: 0,
  38003. width: parent.__tmNodeWidth,
  38004. height: parent.__tmNodeHeight
  38005. },
  38006. style: {
  38007. opacity: 0
  38008. }
  38009. }
  38010. // Others.
  38011. : {style: {opacity: 0}};
  38012. }
  38013. else {
  38014. var targetX = 0;
  38015. var targetY = 0;
  38016. if (!parent.__tmWillDelete) {
  38017. // Let node animate to right-bottom corner, cooperating with fadeout,
  38018. // which is appropriate for user understanding.
  38019. // Divided by 2 for reRoot rolling up effect.
  38020. targetX = parent.__tmNodeWidth / 2;
  38021. targetY = parent.__tmNodeHeight / 2;
  38022. }
  38023. target = storageName === 'nodeGroup'
  38024. ? {position: [targetX, targetY], style: {opacity: 0}}
  38025. : {
  38026. shape: {x: targetX, y: targetY, width: 0, height: 0},
  38027. style: {opacity: 0}
  38028. };
  38029. }
  38030. target && animationWrap.add(el, target, duration, easing);
  38031. });
  38032. });
  38033. // Make other animations
  38034. each$9(this._storage, function (store, storageName) {
  38035. each$9(store, function (el, rawIndex) {
  38036. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  38037. var target = {};
  38038. if (!last) {
  38039. return;
  38040. }
  38041. if (storageName === 'nodeGroup') {
  38042. if (last.old) {
  38043. target.position = el.position.slice();
  38044. el.attr('position', last.old);
  38045. }
  38046. }
  38047. else {
  38048. if (last.old) {
  38049. target.shape = extend({}, el.shape);
  38050. el.setShape(last.old);
  38051. }
  38052. if (last.fadein) {
  38053. el.setStyle('opacity', 0);
  38054. target.style = {opacity: 1};
  38055. }
  38056. // When animation is stopped for succedent animation starting,
  38057. // el.style.opacity might not be 1
  38058. else if (el.style.opacity !== 1) {
  38059. target.style = {opacity: 1};
  38060. }
  38061. }
  38062. animationWrap.add(el, target, duration, easing);
  38063. });
  38064. }, this);
  38065. this._state = 'animating';
  38066. animationWrap
  38067. .done(bind$1(function () {
  38068. this._state = 'ready';
  38069. renderResult.renderFinally();
  38070. }, this))
  38071. .start();
  38072. },
  38073. /**
  38074. * @private
  38075. */
  38076. _resetController: function (api) {
  38077. var controller = this._controller;
  38078. // Init controller.
  38079. if (!controller) {
  38080. controller = this._controller = new RoamController(api.getZr());
  38081. controller.enable(this.seriesModel.get('roam'));
  38082. controller.on('pan', bind$1(this._onPan, this));
  38083. controller.on('zoom', bind$1(this._onZoom, this));
  38084. }
  38085. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  38086. controller.setPointerChecker(function (e, x, y) {
  38087. return rect.contain(x, y);
  38088. });
  38089. },
  38090. /**
  38091. * @private
  38092. */
  38093. _clearController: function () {
  38094. var controller = this._controller;
  38095. if (controller) {
  38096. controller.dispose();
  38097. controller = null;
  38098. }
  38099. },
  38100. /**
  38101. * @private
  38102. */
  38103. _onPan: function (dx, dy) {
  38104. if (this._state !== 'animating'
  38105. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  38106. ) {
  38107. // These param must not be cached.
  38108. var root = this.seriesModel.getData().tree.root;
  38109. if (!root) {
  38110. return;
  38111. }
  38112. var rootLayout = root.getLayout();
  38113. if (!rootLayout) {
  38114. return;
  38115. }
  38116. this.api.dispatchAction({
  38117. type: 'treemapMove',
  38118. from: this.uid,
  38119. seriesId: this.seriesModel.id,
  38120. rootRect: {
  38121. x: rootLayout.x + dx, y: rootLayout.y + dy,
  38122. width: rootLayout.width, height: rootLayout.height
  38123. }
  38124. });
  38125. }
  38126. },
  38127. /**
  38128. * @private
  38129. */
  38130. _onZoom: function (scale, mouseX, mouseY) {
  38131. if (this._state !== 'animating') {
  38132. // These param must not be cached.
  38133. var root = this.seriesModel.getData().tree.root;
  38134. if (!root) {
  38135. return;
  38136. }
  38137. var rootLayout = root.getLayout();
  38138. if (!rootLayout) {
  38139. return;
  38140. }
  38141. var rect = new BoundingRect(
  38142. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  38143. );
  38144. var layoutInfo = this.seriesModel.layoutInfo;
  38145. // Transform mouse coord from global to containerGroup.
  38146. mouseX -= layoutInfo.x;
  38147. mouseY -= layoutInfo.y;
  38148. // Scale root bounding rect.
  38149. var m = create$1();
  38150. translate(m, m, [-mouseX, -mouseY]);
  38151. scale$1(m, m, [scale, scale]);
  38152. translate(m, m, [mouseX, mouseY]);
  38153. rect.applyTransform(m);
  38154. this.api.dispatchAction({
  38155. type: 'treemapRender',
  38156. from: this.uid,
  38157. seriesId: this.seriesModel.id,
  38158. rootRect: {
  38159. x: rect.x, y: rect.y,
  38160. width: rect.width, height: rect.height
  38161. }
  38162. });
  38163. }
  38164. },
  38165. /**
  38166. * @private
  38167. */
  38168. _initEvents: function (containerGroup) {
  38169. containerGroup.on('click', function (e) {
  38170. if (this._state !== 'ready') {
  38171. return;
  38172. }
  38173. var nodeClick = this.seriesModel.get('nodeClick', true);
  38174. if (!nodeClick) {
  38175. return;
  38176. }
  38177. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  38178. if (!targetInfo) {
  38179. return;
  38180. }
  38181. var node = targetInfo.node;
  38182. if (node.getLayout().isLeafRoot) {
  38183. this._rootToNode(targetInfo);
  38184. }
  38185. else {
  38186. if (nodeClick === 'zoomToNode') {
  38187. this._zoomToNode(targetInfo);
  38188. }
  38189. else if (nodeClick === 'link') {
  38190. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  38191. var link = itemModel.get('link', true);
  38192. var linkTarget = itemModel.get('target', true) || 'blank';
  38193. link && window.open(link, linkTarget);
  38194. }
  38195. }
  38196. }, this);
  38197. },
  38198. /**
  38199. * @private
  38200. */
  38201. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  38202. if (!targetInfo) {
  38203. targetInfo = seriesModel.get('leafDepth', true) != null
  38204. ? {node: seriesModel.getViewRoot()}
  38205. // FIXME
  38206. // better way?
  38207. // Find breadcrumb tail on center of containerGroup.
  38208. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  38209. if (!targetInfo) {
  38210. targetInfo = {node: seriesModel.getData().tree.root};
  38211. }
  38212. }
  38213. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  38214. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  38215. function onSelect(node) {
  38216. if (this._state !== 'animating') {
  38217. aboveViewRoot(seriesModel.getViewRoot(), node)
  38218. ? this._rootToNode({node: node})
  38219. : this._zoomToNode({node: node});
  38220. }
  38221. }
  38222. },
  38223. /**
  38224. * @override
  38225. */
  38226. remove: function () {
  38227. this._clearController();
  38228. this._containerGroup && this._containerGroup.removeAll();
  38229. this._storage = createStorage();
  38230. this._state = 'ready';
  38231. this._breadcrumb && this._breadcrumb.remove();
  38232. },
  38233. dispose: function () {
  38234. this._clearController();
  38235. },
  38236. /**
  38237. * @private
  38238. */
  38239. _zoomToNode: function (targetInfo) {
  38240. this.api.dispatchAction({
  38241. type: 'treemapZoomToNode',
  38242. from: this.uid,
  38243. seriesId: this.seriesModel.id,
  38244. targetNode: targetInfo.node
  38245. });
  38246. },
  38247. /**
  38248. * @private
  38249. */
  38250. _rootToNode: function (targetInfo) {
  38251. this.api.dispatchAction({
  38252. type: 'treemapRootToNode',
  38253. from: this.uid,
  38254. seriesId: this.seriesModel.id,
  38255. targetNode: targetInfo.node
  38256. });
  38257. },
  38258. /**
  38259. * @public
  38260. * @param {number} x Global coord x.
  38261. * @param {number} y Global coord y.
  38262. * @return {Object} info If not found, return undefined;
  38263. * @return {number} info.node Target node.
  38264. * @return {number} info.offsetX x refer to target node.
  38265. * @return {number} info.offsetY y refer to target node.
  38266. */
  38267. findTarget: function (x, y) {
  38268. var targetInfo;
  38269. var viewRoot = this.seriesModel.getViewRoot();
  38270. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  38271. var bgEl = this._storage.background[node.getRawIndex()];
  38272. // If invisible, there might be no element.
  38273. if (bgEl) {
  38274. var point = bgEl.transformCoordToLocal(x, y);
  38275. var shape = bgEl.shape;
  38276. // For performance consideration, dont use 'getBoundingRect'.
  38277. if (shape.x <= point[0]
  38278. && point[0] <= shape.x + shape.width
  38279. && shape.y <= point[1]
  38280. && point[1] <= shape.y + shape.height
  38281. ) {
  38282. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  38283. }
  38284. else {
  38285. return false; // Suppress visit subtree.
  38286. }
  38287. }
  38288. }, this);
  38289. return targetInfo;
  38290. }
  38291. });
  38292. /**
  38293. * @inner
  38294. */
  38295. function createStorage() {
  38296. return {nodeGroup: [], background: [], content: []};
  38297. }
  38298. /**
  38299. * @inner
  38300. * @return Return undefined means do not travel further.
  38301. */
  38302. function renderNode(
  38303. seriesModel, thisStorage, oldStorage, reRoot,
  38304. lastsForAnimation, willInvisibleEls,
  38305. thisNode, oldNode, parentGroup, depth
  38306. ) {
  38307. // Whether under viewRoot.
  38308. if (!thisNode) {
  38309. // Deleting nodes will be performed finally. This method just find
  38310. // element from old storage, or create new element, set them to new
  38311. // storage, and set styles.
  38312. return;
  38313. }
  38314. // -------------------------------------------------------------------
  38315. // Start of closure variables available in "Procedures in renderNode".
  38316. var thisLayout = thisNode.getLayout();
  38317. if (!thisLayout || !thisLayout.isInView) {
  38318. return;
  38319. }
  38320. var thisWidth = thisLayout.width;
  38321. var thisHeight = thisLayout.height;
  38322. var borderWidth = thisLayout.borderWidth;
  38323. var thisInvisible = thisLayout.invisible;
  38324. var thisRawIndex = thisNode.getRawIndex();
  38325. var oldRawIndex = oldNode && oldNode.getRawIndex();
  38326. var thisViewChildren = thisNode.viewChildren;
  38327. var upperHeight = thisLayout.upperHeight;
  38328. var isParent = thisViewChildren && thisViewChildren.length;
  38329. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  38330. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  38331. // End of closure ariables available in "Procedures in renderNode".
  38332. // -----------------------------------------------------------------
  38333. // Node group
  38334. var group = giveGraphic('nodeGroup', Group$2);
  38335. if (!group) {
  38336. return;
  38337. }
  38338. parentGroup.add(group);
  38339. // x,y are not set when el is above view root.
  38340. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  38341. group.__tmNodeWidth = thisWidth;
  38342. group.__tmNodeHeight = thisHeight;
  38343. if (thisLayout.isAboveViewRoot) {
  38344. return group;
  38345. }
  38346. // Background
  38347. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  38348. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  38349. // No children, render content.
  38350. if (!isParent) {
  38351. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  38352. content && renderContent(group, content);
  38353. }
  38354. return group;
  38355. // ----------------------------
  38356. // | Procedures in renderNode |
  38357. // ----------------------------
  38358. function renderBackground(group, bg, useUpperLabel) {
  38359. // For tooltip.
  38360. bg.dataIndex = thisNode.dataIndex;
  38361. bg.seriesIndex = seriesModel.seriesIndex;
  38362. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  38363. var visualBorderColor = thisNode.getVisual('borderColor', true);
  38364. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  38365. updateStyle(bg, function () {
  38366. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  38367. normalStyle.fill = visualBorderColor;
  38368. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  38369. emphasisStyle.fill = emphasisBorderColor;
  38370. if (useUpperLabel) {
  38371. var upperLabelWidth = thisWidth - 2 * borderWidth;
  38372. prepareText(
  38373. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  38374. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  38375. );
  38376. }
  38377. // For old bg.
  38378. else {
  38379. normalStyle.text = emphasisStyle.text = null;
  38380. }
  38381. bg.setStyle(normalStyle);
  38382. setHoverStyle(bg, emphasisStyle);
  38383. });
  38384. group.add(bg);
  38385. }
  38386. function renderContent(group, content) {
  38387. // For tooltip.
  38388. content.dataIndex = thisNode.dataIndex;
  38389. content.seriesIndex = seriesModel.seriesIndex;
  38390. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  38391. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  38392. content.culling = true;
  38393. content.setShape({
  38394. x: borderWidth,
  38395. y: borderWidth,
  38396. width: contentWidth,
  38397. height: contentHeight
  38398. });
  38399. var visualColor = thisNode.getVisual('color', true);
  38400. updateStyle(content, function () {
  38401. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  38402. normalStyle.fill = visualColor;
  38403. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  38404. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  38405. content.setStyle(normalStyle);
  38406. setHoverStyle(content, emphasisStyle);
  38407. });
  38408. group.add(content);
  38409. }
  38410. function updateStyle(element, cb) {
  38411. if (!thisInvisible) {
  38412. // If invisible, do not set visual, otherwise the element will
  38413. // change immediately before animation. We think it is OK to
  38414. // remain its origin color when moving out of the view window.
  38415. cb();
  38416. if (!element.__tmWillVisible) {
  38417. element.invisible = false;
  38418. }
  38419. }
  38420. else {
  38421. // Delay invisible setting utill animation finished,
  38422. // avoid element vanish suddenly before animation.
  38423. !element.invisible && willInvisibleEls.push(element);
  38424. }
  38425. }
  38426. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  38427. var nodeModel = thisNode.getModel();
  38428. var text = retrieve(
  38429. seriesModel.getFormattedLabel(
  38430. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  38431. ),
  38432. nodeModel.get('name')
  38433. );
  38434. if (!upperLabelRect && thisLayout.isLeafRoot) {
  38435. var iconChar = seriesModel.get('drillDownIcon', true);
  38436. text = iconChar ? iconChar + ' ' + text : text;
  38437. }
  38438. var normalLabelModel = nodeModel.getModel(
  38439. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  38440. );
  38441. var emphasisLabelModel = nodeModel.getModel(
  38442. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  38443. );
  38444. var isShow = normalLabelModel.getShallow('show');
  38445. setLabelStyle(
  38446. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  38447. {
  38448. defaultText: isShow ? text : null,
  38449. autoColor: visualColor,
  38450. isRectText: true
  38451. }
  38452. );
  38453. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  38454. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  38455. ? {
  38456. outerWidth: width,
  38457. outerHeight: height,
  38458. minChar: 2
  38459. }
  38460. : null;
  38461. }
  38462. function giveGraphic(storageName, Ctor, depth, z) {
  38463. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  38464. var lasts = lastsForAnimation[storageName];
  38465. if (element) {
  38466. // Remove from oldStorage
  38467. oldStorage[storageName][oldRawIndex] = null;
  38468. prepareAnimationWhenHasOld(lasts, element, storageName);
  38469. }
  38470. // If invisible and no old element, do not create new element (for optimizing).
  38471. else if (!thisInvisible) {
  38472. element = new Ctor({z: calculateZ(depth, z)});
  38473. element.__tmDepth = depth;
  38474. element.__tmStorageName = storageName;
  38475. prepareAnimationWhenNoOld(lasts, element, storageName);
  38476. }
  38477. // Set to thisStorage
  38478. return (thisStorage[storageName][thisRawIndex] = element);
  38479. }
  38480. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  38481. var lastCfg = lasts[thisRawIndex] = {};
  38482. lastCfg.old = storageName === 'nodeGroup'
  38483. ? element.position.slice()
  38484. : extend({}, element.shape);
  38485. }
  38486. // If a element is new, we need to find the animation start point carefully,
  38487. // otherwise it will looks strange when 'zoomToNode'.
  38488. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  38489. var lastCfg = lasts[thisRawIndex] = {};
  38490. var parentNode = thisNode.parentNode;
  38491. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  38492. var parentOldX = 0;
  38493. var parentOldY = 0;
  38494. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  38495. // For convenience, get old bounding rect from background.
  38496. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  38497. if (!reRoot && parentOldBg && parentOldBg.old) {
  38498. parentOldX = parentOldBg.old.width;
  38499. parentOldY = parentOldBg.old.height;
  38500. }
  38501. // When no parent old shape found, its parent is new too,
  38502. // so we can just use {x:0, y:0}.
  38503. lastCfg.old = storageName === 'nodeGroup'
  38504. ? [0, parentOldY]
  38505. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  38506. }
  38507. // Fade in, user can be aware that these nodes are new.
  38508. lastCfg.fadein = storageName !== 'nodeGroup';
  38509. }
  38510. }
  38511. // We can not set all backgroud with the same z, Because the behaviour of
  38512. // drill down and roll up differ background creation sequence from tree
  38513. // hierarchy sequence, which cause that lowser background element overlap
  38514. // upper ones. So we calculate z based on depth.
  38515. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  38516. // treemap with large z overlaps other components.
  38517. function calculateZ(depth, zInLevel) {
  38518. var zb = depth * Z_BASE + zInLevel;
  38519. return (zb - 1) / zb;
  38520. }
  38521. /**
  38522. * @file Treemap action
  38523. */
  38524. var noop$1 = function () {};
  38525. var actionTypes = [
  38526. 'treemapZoomToNode',
  38527. 'treemapRender',
  38528. 'treemapMove'
  38529. ];
  38530. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  38531. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  38532. }
  38533. registerAction(
  38534. {type: 'treemapRootToNode', update: 'updateView'},
  38535. function (payload, ecModel) {
  38536. ecModel.eachComponent(
  38537. {mainType: 'series', subType: 'treemap', query: payload},
  38538. handleRootToNode
  38539. );
  38540. function handleRootToNode(model, index) {
  38541. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  38542. var targetInfo = retrieveTargetInfo(payload, types, model);
  38543. if (targetInfo) {
  38544. var originViewRoot = model.getViewRoot();
  38545. if (originViewRoot) {
  38546. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  38547. ? 'rollUp' : 'drillDown';
  38548. }
  38549. model.resetViewRoot(targetInfo.node);
  38550. }
  38551. }
  38552. }
  38553. );
  38554. var each$10 = each$1;
  38555. var isObject$5 = isObject$1;
  38556. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  38557. /**
  38558. * @param {Object} option
  38559. * @param {string} [option.type] See visualHandlers.
  38560. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  38561. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  38562. * required when mappingMethod is 'linear'
  38563. * @param {Array.<Object>=} [option.pieceList] [
  38564. * {value: someValue},
  38565. * {interval: [min1, max1], visual: {...}},
  38566. * {interval: [min2, max2]}
  38567. * ],
  38568. * required when mappingMethod is 'piecewise'.
  38569. * Visual for only each piece can be specified.
  38570. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  38571. * required when mappingMethod is 'category'.
  38572. * If no option.categories, categories is set
  38573. * as [0, 1, 2, ...].
  38574. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  38575. * @param {(Array|Object|*)} [option.visual] Visual data.
  38576. * when mappingMethod is 'category',
  38577. * visual data can be array or object
  38578. * (like: {cate1: '#222', none: '#fff'})
  38579. * or primary types (which represents
  38580. * defualt category visual), otherwise visual
  38581. * can be array or primary (which will be
  38582. * normalized to array).
  38583. *
  38584. */
  38585. var VisualMapping = function (option) {
  38586. var mappingMethod = option.mappingMethod;
  38587. var visualType = option.type;
  38588. /**
  38589. * @readOnly
  38590. * @type {Object}
  38591. */
  38592. var thisOption = this.option = clone(option);
  38593. /**
  38594. * @readOnly
  38595. * @type {string}
  38596. */
  38597. this.type = visualType;
  38598. /**
  38599. * @readOnly
  38600. * @type {string}
  38601. */
  38602. this.mappingMethod = mappingMethod;
  38603. /**
  38604. * @private
  38605. * @type {Function}
  38606. */
  38607. this._normalizeData = normalizers[mappingMethod];
  38608. var visualHandler = visualHandlers[visualType];
  38609. /**
  38610. * @public
  38611. * @type {Function}
  38612. */
  38613. this.applyVisual = visualHandler.applyVisual;
  38614. /**
  38615. * @public
  38616. * @type {Function}
  38617. */
  38618. this.getColorMapper = visualHandler.getColorMapper;
  38619. /**
  38620. * @private
  38621. * @type {Function}
  38622. */
  38623. this._doMap = visualHandler._doMap[mappingMethod];
  38624. if (mappingMethod === 'piecewise') {
  38625. normalizeVisualRange(thisOption);
  38626. preprocessForPiecewise(thisOption);
  38627. }
  38628. else if (mappingMethod === 'category') {
  38629. thisOption.categories
  38630. ? preprocessForSpecifiedCategory(thisOption)
  38631. // categories is ordinal when thisOption.categories not specified,
  38632. // which need no more preprocess except normalize visual.
  38633. : normalizeVisualRange(thisOption, true);
  38634. }
  38635. else { // mappingMethod === 'linear' or 'fixed'
  38636. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  38637. normalizeVisualRange(thisOption);
  38638. }
  38639. };
  38640. VisualMapping.prototype = {
  38641. constructor: VisualMapping,
  38642. mapValueToVisual: function (value) {
  38643. var normalized = this._normalizeData(value);
  38644. return this._doMap(normalized, value);
  38645. },
  38646. getNormalizer: function () {
  38647. return bind(this._normalizeData, this);
  38648. }
  38649. };
  38650. var visualHandlers = VisualMapping.visualHandlers = {
  38651. color: {
  38652. applyVisual: makeApplyVisual('color'),
  38653. /**
  38654. * Create a mapper function
  38655. * @return {Function}
  38656. */
  38657. getColorMapper: function () {
  38658. var thisOption = this.option;
  38659. return bind(
  38660. thisOption.mappingMethod === 'category'
  38661. ? function (value, isNormalized) {
  38662. !isNormalized && (value = this._normalizeData(value));
  38663. return doMapCategory.call(this, value);
  38664. }
  38665. : function (value, isNormalized, out) {
  38666. // If output rgb array
  38667. // which will be much faster and useful in pixel manipulation
  38668. var returnRGBArray = !!out;
  38669. !isNormalized && (value = this._normalizeData(value));
  38670. out = fastLerp(value, thisOption.parsedVisual, out);
  38671. return returnRGBArray ? out : stringify(out, 'rgba');
  38672. },
  38673. this
  38674. );
  38675. },
  38676. _doMap: {
  38677. linear: function (normalized) {
  38678. return stringify(
  38679. fastLerp(normalized, this.option.parsedVisual),
  38680. 'rgba'
  38681. );
  38682. },
  38683. category: doMapCategory,
  38684. piecewise: function (normalized, value) {
  38685. var result = getSpecifiedVisual.call(this, value);
  38686. if (result == null) {
  38687. result = stringify(
  38688. fastLerp(normalized, this.option.parsedVisual),
  38689. 'rgba'
  38690. );
  38691. }
  38692. return result;
  38693. },
  38694. fixed: doMapFixed
  38695. }
  38696. },
  38697. colorHue: makePartialColorVisualHandler(function (color, value) {
  38698. return modifyHSL(color, value);
  38699. }),
  38700. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  38701. return modifyHSL(color, null, value);
  38702. }),
  38703. colorLightness: makePartialColorVisualHandler(function (color, value) {
  38704. return modifyHSL(color, null, null, value);
  38705. }),
  38706. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  38707. return modifyAlpha(color, value);
  38708. }),
  38709. opacity: {
  38710. applyVisual: makeApplyVisual('opacity'),
  38711. _doMap: makeDoMap([0, 1])
  38712. },
  38713. symbol: {
  38714. applyVisual: function (value, getter, setter) {
  38715. var symbolCfg = this.mapValueToVisual(value);
  38716. if (isString(symbolCfg)) {
  38717. setter('symbol', symbolCfg);
  38718. }
  38719. else if (isObject$5(symbolCfg)) {
  38720. for (var name in symbolCfg) {
  38721. if (symbolCfg.hasOwnProperty(name)) {
  38722. setter(name, symbolCfg[name]);
  38723. }
  38724. }
  38725. }
  38726. },
  38727. _doMap: {
  38728. linear: doMapToArray,
  38729. category: doMapCategory,
  38730. piecewise: function (normalized, value) {
  38731. var result = getSpecifiedVisual.call(this, value);
  38732. if (result == null) {
  38733. result = doMapToArray.call(this, normalized);
  38734. }
  38735. return result;
  38736. },
  38737. fixed: doMapFixed
  38738. }
  38739. },
  38740. symbolSize: {
  38741. applyVisual: makeApplyVisual('symbolSize'),
  38742. _doMap: makeDoMap([0, 1])
  38743. }
  38744. };
  38745. function preprocessForPiecewise(thisOption) {
  38746. var pieceList = thisOption.pieceList;
  38747. thisOption.hasSpecialVisual = false;
  38748. each$1(pieceList, function (piece, index) {
  38749. piece.originIndex = index;
  38750. // piece.visual is "result visual value" but not
  38751. // a visual range, so it does not need to be normalized.
  38752. if (piece.visual != null) {
  38753. thisOption.hasSpecialVisual = true;
  38754. }
  38755. });
  38756. }
  38757. function preprocessForSpecifiedCategory(thisOption) {
  38758. // Hash categories.
  38759. var categories = thisOption.categories;
  38760. var visual = thisOption.visual;
  38761. var categoryMap = thisOption.categoryMap = {};
  38762. each$10(categories, function (cate, index) {
  38763. categoryMap[cate] = index;
  38764. });
  38765. // Process visual map input.
  38766. if (!isArray(visual)) {
  38767. var visualArr = [];
  38768. if (isObject$1(visual)) {
  38769. each$10(visual, function (v, cate) {
  38770. var index = categoryMap[cate];
  38771. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  38772. });
  38773. }
  38774. else { // Is primary type, represents default visual.
  38775. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  38776. }
  38777. visual = setVisualToOption(thisOption, visualArr);
  38778. }
  38779. // Remove categories that has no visual,
  38780. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  38781. for (var i = categories.length - 1; i >= 0; i--) {
  38782. if (visual[i] == null) {
  38783. delete categoryMap[categories[i]];
  38784. categories.pop();
  38785. }
  38786. }
  38787. }
  38788. function normalizeVisualRange(thisOption, isCategory) {
  38789. var visual = thisOption.visual;
  38790. var visualArr = [];
  38791. if (isObject$1(visual)) {
  38792. each$10(visual, function (v) {
  38793. visualArr.push(v);
  38794. });
  38795. }
  38796. else if (visual != null) {
  38797. visualArr.push(visual);
  38798. }
  38799. var doNotNeedPair = {color: 1, symbol: 1};
  38800. if (!isCategory
  38801. && visualArr.length === 1
  38802. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  38803. ) {
  38804. // Do not care visualArr.length === 0, which is illegal.
  38805. visualArr[1] = visualArr[0];
  38806. }
  38807. setVisualToOption(thisOption, visualArr);
  38808. }
  38809. function makePartialColorVisualHandler(applyValue) {
  38810. return {
  38811. applyVisual: function (value, getter, setter) {
  38812. value = this.mapValueToVisual(value);
  38813. // Must not be array value
  38814. setter('color', applyValue(getter('color'), value));
  38815. },
  38816. _doMap: makeDoMap([0, 1])
  38817. };
  38818. }
  38819. function doMapToArray(normalized) {
  38820. var visual = this.option.visual;
  38821. return visual[
  38822. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  38823. ] || {};
  38824. }
  38825. function makeApplyVisual(visualType) {
  38826. return function (value, getter, setter) {
  38827. setter(visualType, this.mapValueToVisual(value));
  38828. };
  38829. }
  38830. function doMapCategory(normalized) {
  38831. var visual = this.option.visual;
  38832. return visual[
  38833. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  38834. ? normalized % visual.length
  38835. : normalized
  38836. ];
  38837. }
  38838. function doMapFixed() {
  38839. return this.option.visual[0];
  38840. }
  38841. function makeDoMap(sourceExtent) {
  38842. return {
  38843. linear: function (normalized) {
  38844. return linearMap(normalized, sourceExtent, this.option.visual, true);
  38845. },
  38846. category: doMapCategory,
  38847. piecewise: function (normalized, value) {
  38848. var result = getSpecifiedVisual.call(this, value);
  38849. if (result == null) {
  38850. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  38851. }
  38852. return result;
  38853. },
  38854. fixed: doMapFixed
  38855. };
  38856. }
  38857. function getSpecifiedVisual(value) {
  38858. var thisOption = this.option;
  38859. var pieceList = thisOption.pieceList;
  38860. if (thisOption.hasSpecialVisual) {
  38861. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  38862. var piece = pieceList[pieceIndex];
  38863. if (piece && piece.visual) {
  38864. return piece.visual[this.type];
  38865. }
  38866. }
  38867. }
  38868. function setVisualToOption(thisOption, visualArr) {
  38869. thisOption.visual = visualArr;
  38870. if (thisOption.type === 'color') {
  38871. thisOption.parsedVisual = map(visualArr, function (item) {
  38872. return parse(item);
  38873. });
  38874. }
  38875. return visualArr;
  38876. }
  38877. /**
  38878. * Normalizers by mapping methods.
  38879. */
  38880. var normalizers = {
  38881. linear: function (value) {
  38882. return linearMap(value, this.option.dataExtent, [0, 1], true);
  38883. },
  38884. piecewise: function (value) {
  38885. var pieceList = this.option.pieceList;
  38886. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  38887. if (pieceIndex != null) {
  38888. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  38889. }
  38890. },
  38891. category: function (value) {
  38892. var index = this.option.categories
  38893. ? this.option.categoryMap[value]
  38894. : value; // ordinal
  38895. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  38896. },
  38897. fixed: noop
  38898. };
  38899. /**
  38900. * List available visual types.
  38901. *
  38902. * @public
  38903. * @return {Array.<string>}
  38904. */
  38905. VisualMapping.listVisualTypes = function () {
  38906. var visualTypes = [];
  38907. each$1(visualHandlers, function (handler, key) {
  38908. visualTypes.push(key);
  38909. });
  38910. return visualTypes;
  38911. };
  38912. /**
  38913. * @public
  38914. */
  38915. VisualMapping.addVisualHandler = function (name, handler) {
  38916. visualHandlers[name] = handler;
  38917. };
  38918. /**
  38919. * @public
  38920. */
  38921. VisualMapping.isValidType = function (visualType) {
  38922. return visualHandlers.hasOwnProperty(visualType);
  38923. };
  38924. /**
  38925. * Convinent method.
  38926. * Visual can be Object or Array or primary type.
  38927. *
  38928. * @public
  38929. */
  38930. VisualMapping.eachVisual = function (visual, callback, context) {
  38931. if (isObject$1(visual)) {
  38932. each$1(visual, callback, context);
  38933. }
  38934. else {
  38935. callback.call(context, visual);
  38936. }
  38937. };
  38938. VisualMapping.mapVisual = function (visual, callback, context) {
  38939. var isPrimary;
  38940. var newVisual = isArray(visual)
  38941. ? []
  38942. : isObject$1(visual)
  38943. ? {}
  38944. : (isPrimary = true, null);
  38945. VisualMapping.eachVisual(visual, function (v, key) {
  38946. var newVal = callback.call(context, v, key);
  38947. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  38948. });
  38949. return newVisual;
  38950. };
  38951. /**
  38952. * @public
  38953. * @param {Object} obj
  38954. * @return {Object} new object containers visual values.
  38955. * If no visuals, return null.
  38956. */
  38957. VisualMapping.retrieveVisuals = function (obj) {
  38958. var ret = {};
  38959. var hasVisual;
  38960. obj && each$10(visualHandlers, function (h, visualType) {
  38961. if (obj.hasOwnProperty(visualType)) {
  38962. ret[visualType] = obj[visualType];
  38963. hasVisual = true;
  38964. }
  38965. });
  38966. return hasVisual ? ret : null;
  38967. };
  38968. /**
  38969. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  38970. *
  38971. * @public
  38972. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  38973. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  38974. * @return {Array.<string>} Sorted visual types.
  38975. */
  38976. VisualMapping.prepareVisualTypes = function (visualTypes) {
  38977. if (isObject$5(visualTypes)) {
  38978. var types = [];
  38979. each$10(visualTypes, function (item, type) {
  38980. types.push(type);
  38981. });
  38982. visualTypes = types;
  38983. }
  38984. else if (isArray(visualTypes)) {
  38985. visualTypes = visualTypes.slice();
  38986. }
  38987. else {
  38988. return [];
  38989. }
  38990. visualTypes.sort(function (type1, type2) {
  38991. // color should be front of colorSaturation, colorAlpha, ...
  38992. // symbol and symbolSize do not matter.
  38993. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  38994. ? 1 : -1;
  38995. });
  38996. return visualTypes;
  38997. };
  38998. /**
  38999. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  39000. * Other visuals are only depends on themself.
  39001. *
  39002. * @public
  39003. * @param {string} visualType1
  39004. * @param {string} visualType2
  39005. * @return {boolean}
  39006. */
  39007. VisualMapping.dependsOn = function (visualType1, visualType2) {
  39008. return visualType2 === 'color'
  39009. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  39010. : visualType1 === visualType2;
  39011. };
  39012. /**
  39013. * @param {number} value
  39014. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  39015. * Always from small to big.
  39016. * @param {boolean} [findClosestWhenOutside=false]
  39017. * @return {number} index
  39018. */
  39019. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  39020. var possibleI;
  39021. var abs = Infinity;
  39022. // value has the higher priority.
  39023. for (var i = 0, len = pieceList.length; i < len; i++) {
  39024. var pieceValue = pieceList[i].value;
  39025. if (pieceValue != null) {
  39026. if (pieceValue === value
  39027. // FIXME
  39028. // It is supposed to compare value according to value type of dimension,
  39029. // but currently value type can exactly be string or number.
  39030. // Compromise for numeric-like string (like '12'), especially
  39031. // in the case that visualMap.categories is ['22', '33'].
  39032. || (typeof pieceValue === 'string' && pieceValue === value + '')
  39033. ) {
  39034. return i;
  39035. }
  39036. findClosestWhenOutside && updatePossible(pieceValue, i);
  39037. }
  39038. }
  39039. for (var i = 0, len = pieceList.length; i < len; i++) {
  39040. var piece = pieceList[i];
  39041. var interval = piece.interval;
  39042. var close = piece.close;
  39043. if (interval) {
  39044. if (interval[0] === -Infinity) {
  39045. if (littleThan(close[1], value, interval[1])) {
  39046. return i;
  39047. }
  39048. }
  39049. else if (interval[1] === Infinity) {
  39050. if (littleThan(close[0], interval[0], value)) {
  39051. return i;
  39052. }
  39053. }
  39054. else if (
  39055. littleThan(close[0], interval[0], value)
  39056. && littleThan(close[1], value, interval[1])
  39057. ) {
  39058. return i;
  39059. }
  39060. findClosestWhenOutside && updatePossible(interval[0], i);
  39061. findClosestWhenOutside && updatePossible(interval[1], i);
  39062. }
  39063. }
  39064. if (findClosestWhenOutside) {
  39065. return value === Infinity
  39066. ? pieceList.length - 1
  39067. : value === -Infinity
  39068. ? 0
  39069. : possibleI;
  39070. }
  39071. function updatePossible(val, index) {
  39072. var newAbs = Math.abs(val - value);
  39073. if (newAbs < abs) {
  39074. abs = newAbs;
  39075. possibleI = index;
  39076. }
  39077. }
  39078. };
  39079. function littleThan(close, a, b) {
  39080. return close ? a <= b : a < b;
  39081. }
  39082. var isArray$2 = isArray;
  39083. var ITEM_STYLE_NORMAL = 'itemStyle';
  39084. var treemapVisual = {
  39085. seriesType: 'treemap',
  39086. reset: function (seriesModel, ecModel, api, payload) {
  39087. var tree = seriesModel.getData().tree;
  39088. var root = tree.root;
  39089. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  39090. if (root.isRemoved()) {
  39091. return;
  39092. }
  39093. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  39094. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  39095. });
  39096. travelTree(
  39097. root, // Visual should calculate from tree root but not view root.
  39098. {},
  39099. levelItemStyles,
  39100. seriesItemStyleModel,
  39101. seriesModel.getViewRoot().getAncestors(),
  39102. seriesModel
  39103. );
  39104. }
  39105. };
  39106. function travelTree(
  39107. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  39108. viewRootAncestors, seriesModel
  39109. ) {
  39110. var nodeModel = node.getModel();
  39111. var nodeLayout = node.getLayout();
  39112. // Optimize
  39113. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  39114. return;
  39115. }
  39116. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  39117. var levelItemStyle = levelItemStyles[node.depth];
  39118. var visuals = buildVisuals(
  39119. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  39120. );
  39121. // calculate border color
  39122. var borderColor = nodeItemStyleModel.get('borderColor');
  39123. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  39124. var thisNodeColor;
  39125. if (borderColorSaturation != null) {
  39126. // For performance, do not always execute 'calculateColor'.
  39127. thisNodeColor = calculateColor(visuals, node);
  39128. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  39129. }
  39130. node.setVisual('borderColor', borderColor);
  39131. var viewChildren = node.viewChildren;
  39132. if (!viewChildren || !viewChildren.length) {
  39133. thisNodeColor = calculateColor(visuals, node);
  39134. // Apply visual to this node.
  39135. node.setVisual('color', thisNodeColor);
  39136. }
  39137. else {
  39138. var mapping = buildVisualMapping(
  39139. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  39140. );
  39141. // Designate visual to children.
  39142. each$1(viewChildren, function (child, index) {
  39143. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  39144. if (child.depth >= viewRootAncestors.length
  39145. || child === viewRootAncestors[child.depth]
  39146. ) {
  39147. var childVisual = mapVisual$1(
  39148. nodeModel, visuals, child, index, mapping, seriesModel
  39149. );
  39150. travelTree(
  39151. child, childVisual, levelItemStyles, seriesItemStyleModel,
  39152. viewRootAncestors, seriesModel
  39153. );
  39154. }
  39155. });
  39156. }
  39157. }
  39158. function buildVisuals(
  39159. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  39160. ) {
  39161. var visuals = extend({}, designatedVisual);
  39162. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  39163. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  39164. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  39165. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  39166. val == null && (val = designatedVisual[visualName]);
  39167. val == null && (val = seriesItemStyleModel.get(visualName));
  39168. val != null && (visuals[visualName] = val);
  39169. });
  39170. return visuals;
  39171. }
  39172. function calculateColor(visuals) {
  39173. var color = getValueVisualDefine(visuals, 'color');
  39174. if (color) {
  39175. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  39176. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  39177. if (colorSaturation) {
  39178. color = modifyHSL(color, null, null, colorSaturation);
  39179. }
  39180. if (colorAlpha) {
  39181. color = modifyAlpha(color, colorAlpha);
  39182. }
  39183. return color;
  39184. }
  39185. }
  39186. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  39187. return thisNodeColor != null
  39188. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  39189. : null;
  39190. }
  39191. function getValueVisualDefine(visuals, name) {
  39192. var value = visuals[name];
  39193. if (value != null && value !== 'none') {
  39194. return value;
  39195. }
  39196. }
  39197. function buildVisualMapping(
  39198. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  39199. ) {
  39200. if (!viewChildren || !viewChildren.length) {
  39201. return;
  39202. }
  39203. var rangeVisual = getRangeVisual(nodeModel, 'color')
  39204. || (
  39205. visuals.color != null
  39206. && visuals.color !== 'none'
  39207. && (
  39208. getRangeVisual(nodeModel, 'colorAlpha')
  39209. || getRangeVisual(nodeModel, 'colorSaturation')
  39210. )
  39211. );
  39212. if (!rangeVisual) {
  39213. return;
  39214. }
  39215. var visualMin = nodeModel.get('visualMin');
  39216. var visualMax = nodeModel.get('visualMax');
  39217. var dataExtent = nodeLayout.dataExtent.slice();
  39218. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  39219. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  39220. var colorMappingBy = nodeModel.get('colorMappingBy');
  39221. var opt = {
  39222. type: rangeVisual.name,
  39223. dataExtent: dataExtent,
  39224. visual: rangeVisual.range
  39225. };
  39226. if (opt.type === 'color'
  39227. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  39228. ) {
  39229. opt.mappingMethod = 'category';
  39230. opt.loop = true;
  39231. // categories is ordinal, so do not set opt.categories.
  39232. }
  39233. else {
  39234. opt.mappingMethod = 'linear';
  39235. }
  39236. var mapping = new VisualMapping(opt);
  39237. mapping.__drColorMappingBy = colorMappingBy;
  39238. return mapping;
  39239. }
  39240. // Notice: If we dont have the attribute 'colorRange', but only use
  39241. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  39242. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  39243. // this problem will be encountered:
  39244. // If a level-1 node dont have children, and its siblings has children,
  39245. // and colorRange is set on level-1, then the node can not be colored.
  39246. // So we separate 'colorRange' and 'color' to different attributes.
  39247. function getRangeVisual(nodeModel, name) {
  39248. // 'colorRange', 'colorARange', 'colorSRange'.
  39249. // If not exsits on this node, fetch from levels and series.
  39250. var range = nodeModel.get(name);
  39251. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  39252. }
  39253. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  39254. var childVisuals = extend({}, visuals);
  39255. if (mapping) {
  39256. var mappingType = mapping.type;
  39257. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  39258. var value =
  39259. colorMappingBy === 'index'
  39260. ? index
  39261. : colorMappingBy === 'id'
  39262. ? seriesModel.mapIdToIndex(child.getId())
  39263. : child.getValue(nodeModel.get('visualDimension'));
  39264. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  39265. }
  39266. return childVisuals;
  39267. }
  39268. var mathMax$4 = Math.max;
  39269. var mathMin$4 = Math.min;
  39270. var retrieveValue = retrieve;
  39271. var each$11 = each$1;
  39272. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  39273. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  39274. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  39275. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  39276. /**
  39277. * @public
  39278. */
  39279. var treemapLayout = {
  39280. seriesType: 'treemap',
  39281. reset: function (seriesModel, ecModel, api, payload) {
  39282. // Layout result in each node:
  39283. // {x, y, width, height, area, borderWidth}
  39284. var ecWidth = api.getWidth();
  39285. var ecHeight = api.getHeight();
  39286. var seriesOption = seriesModel.option;
  39287. var layoutInfo = getLayoutRect(
  39288. seriesModel.getBoxLayoutParams(),
  39289. {
  39290. width: api.getWidth(),
  39291. height: api.getHeight()
  39292. }
  39293. );
  39294. var size = seriesOption.size || []; // Compatible with ec2.
  39295. var containerWidth = parsePercent$1(
  39296. retrieveValue(layoutInfo.width, size[0]),
  39297. ecWidth
  39298. );
  39299. var containerHeight = parsePercent$1(
  39300. retrieveValue(layoutInfo.height, size[1]),
  39301. ecHeight
  39302. );
  39303. // Fetch payload info.
  39304. var payloadType = payload && payload.type;
  39305. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  39306. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  39307. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  39308. ? payload.rootRect : null;
  39309. var viewRoot = seriesModel.getViewRoot();
  39310. var viewAbovePath = getPathToRoot(viewRoot);
  39311. if (payloadType !== 'treemapMove') {
  39312. var rootSize = payloadType === 'treemapZoomToNode'
  39313. ? estimateRootSize(
  39314. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  39315. )
  39316. : rootRect
  39317. ? [rootRect.width, rootRect.height]
  39318. : [containerWidth, containerHeight];
  39319. var sort = seriesOption.sort;
  39320. if (sort && sort !== 'asc' && sort !== 'desc') {
  39321. sort = 'desc';
  39322. }
  39323. var options = {
  39324. squareRatio: seriesOption.squareRatio,
  39325. sort: sort,
  39326. leafDepth: seriesOption.leafDepth
  39327. };
  39328. // layout should be cleared because using updateView but not update.
  39329. viewRoot.hostTree.clearLayouts();
  39330. // TODO
  39331. // optimize: if out of view clip, do not layout.
  39332. // But take care that if do not render node out of view clip,
  39333. // how to calculate start po
  39334. var viewRootLayout = {
  39335. x: 0, y: 0,
  39336. width: rootSize[0], height: rootSize[1],
  39337. area: rootSize[0] * rootSize[1]
  39338. };
  39339. viewRoot.setLayout(viewRootLayout);
  39340. squarify(viewRoot, options, false, 0);
  39341. // Supplement layout.
  39342. var viewRootLayout = viewRoot.getLayout();
  39343. each$11(viewAbovePath, function (node, index) {
  39344. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  39345. node.setLayout(extend(
  39346. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  39347. viewRootLayout
  39348. ));
  39349. });
  39350. }
  39351. var treeRoot = seriesModel.getData().tree.root;
  39352. treeRoot.setLayout(
  39353. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  39354. true
  39355. );
  39356. seriesModel.setLayoutInfo(layoutInfo);
  39357. // FIXME
  39358. // 现在没有clip功能,暂时取ec高宽。
  39359. prunning(
  39360. treeRoot,
  39361. // Transform to base element coordinate system.
  39362. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  39363. viewAbovePath,
  39364. viewRoot,
  39365. 0
  39366. );
  39367. }
  39368. };
  39369. /**
  39370. * Layout treemap with squarify algorithm.
  39371. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  39372. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  39373. *
  39374. * @protected
  39375. * @param {module:echarts/data/Tree~TreeNode} node
  39376. * @param {Object} options
  39377. * @param {string} options.sort 'asc' or 'desc'
  39378. * @param {number} options.squareRatio
  39379. * @param {boolean} hideChildren
  39380. * @param {number} depth
  39381. */
  39382. function squarify(node, options, hideChildren, depth) {
  39383. var width;
  39384. var height;
  39385. if (node.isRemoved()) {
  39386. return;
  39387. }
  39388. var thisLayout = node.getLayout();
  39389. width = thisLayout.width;
  39390. height = thisLayout.height;
  39391. // Considering border and gap
  39392. var nodeModel = node.getModel();
  39393. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  39394. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  39395. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  39396. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  39397. var layoutOffset = borderWidth - halfGapWidth;
  39398. var layoutOffsetUpper = upperHeight - halfGapWidth;
  39399. var nodeModel = node.getModel();
  39400. node.setLayout({
  39401. borderWidth: borderWidth,
  39402. upperHeight: upperHeight,
  39403. upperLabelHeight: upperLabelHeight
  39404. }, true);
  39405. width = mathMax$4(width - 2 * layoutOffset, 0);
  39406. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  39407. var totalArea = width * height;
  39408. var viewChildren = initChildren(
  39409. node, nodeModel, totalArea, options, hideChildren, depth
  39410. );
  39411. if (!viewChildren.length) {
  39412. return;
  39413. }
  39414. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  39415. var rowFixedLength = mathMin$4(width, height);
  39416. var best = Infinity; // the best row score so far
  39417. var row = [];
  39418. row.area = 0;
  39419. for (var i = 0, len = viewChildren.length; i < len;) {
  39420. var child = viewChildren[i];
  39421. row.push(child);
  39422. row.area += child.getLayout().area;
  39423. var score = worst(row, rowFixedLength, options.squareRatio);
  39424. // continue with this orientation
  39425. if (score <= best) {
  39426. i++;
  39427. best = score;
  39428. }
  39429. // abort, and try a different orientation
  39430. else {
  39431. row.area -= row.pop().getLayout().area;
  39432. position(row, rowFixedLength, rect, halfGapWidth, false);
  39433. rowFixedLength = mathMin$4(rect.width, rect.height);
  39434. row.length = row.area = 0;
  39435. best = Infinity;
  39436. }
  39437. }
  39438. if (row.length) {
  39439. position(row, rowFixedLength, rect, halfGapWidth, true);
  39440. }
  39441. if (!hideChildren) {
  39442. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  39443. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  39444. hideChildren = true;
  39445. }
  39446. }
  39447. for (var i = 0, len = viewChildren.length; i < len; i++) {
  39448. squarify(viewChildren[i], options, hideChildren, depth + 1);
  39449. }
  39450. }
  39451. /**
  39452. * Set area to each child, and calculate data extent for visual coding.
  39453. */
  39454. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  39455. var viewChildren = node.children || [];
  39456. var orderBy = options.sort;
  39457. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  39458. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  39459. // leafDepth has higher priority.
  39460. if (hideChildren && !overLeafDepth) {
  39461. return (node.viewChildren = []);
  39462. }
  39463. // Sort children, order by desc.
  39464. viewChildren = filter(viewChildren, function (child) {
  39465. return !child.isRemoved();
  39466. });
  39467. sort$1(viewChildren, orderBy);
  39468. var info = statistic(nodeModel, viewChildren, orderBy);
  39469. if (info.sum === 0) {
  39470. return (node.viewChildren = []);
  39471. }
  39472. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  39473. if (info.sum === 0) {
  39474. return (node.viewChildren = []);
  39475. }
  39476. // Set area to each child.
  39477. for (var i = 0, len = viewChildren.length; i < len; i++) {
  39478. var area = viewChildren[i].getValue() / info.sum * totalArea;
  39479. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  39480. viewChildren[i].setLayout({area: area});
  39481. }
  39482. if (overLeafDepth) {
  39483. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  39484. viewChildren.length = 0;
  39485. }
  39486. node.viewChildren = viewChildren;
  39487. node.setLayout({dataExtent: info.dataExtent}, true);
  39488. return viewChildren;
  39489. }
  39490. /**
  39491. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  39492. */
  39493. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  39494. // visibleMin is not supported yet when no option.sort.
  39495. if (!orderBy) {
  39496. return sum;
  39497. }
  39498. var visibleMin = nodeModel.get('visibleMin');
  39499. var len = orderedChildren.length;
  39500. var deletePoint = len;
  39501. // Always travel from little value to big value.
  39502. for (var i = len - 1; i >= 0; i--) {
  39503. var value = orderedChildren[
  39504. orderBy === 'asc' ? len - i - 1 : i
  39505. ].getValue();
  39506. if (value / sum * totalArea < visibleMin) {
  39507. deletePoint = i;
  39508. sum -= value;
  39509. }
  39510. }
  39511. orderBy === 'asc'
  39512. ? orderedChildren.splice(0, len - deletePoint)
  39513. : orderedChildren.splice(deletePoint, len - deletePoint);
  39514. return sum;
  39515. }
  39516. /**
  39517. * Sort
  39518. */
  39519. function sort$1(viewChildren, orderBy) {
  39520. if (orderBy) {
  39521. viewChildren.sort(function (a, b) {
  39522. var diff = orderBy === 'asc'
  39523. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  39524. return diff === 0
  39525. ? (orderBy === 'asc'
  39526. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  39527. )
  39528. : diff;
  39529. });
  39530. }
  39531. return viewChildren;
  39532. }
  39533. /**
  39534. * Statistic
  39535. */
  39536. function statistic(nodeModel, children, orderBy) {
  39537. // Calculate sum.
  39538. var sum = 0;
  39539. for (var i = 0, len = children.length; i < len; i++) {
  39540. sum += children[i].getValue();
  39541. }
  39542. // Statistic data extent for latter visual coding.
  39543. // Notice: data extent should be calculate based on raw children
  39544. // but not filtered view children, otherwise visual mapping will not
  39545. // be stable when zoom (where children is filtered by visibleMin).
  39546. var dimension = nodeModel.get('visualDimension');
  39547. var dataExtent;
  39548. // The same as area dimension.
  39549. if (!children || !children.length) {
  39550. dataExtent = [NaN, NaN];
  39551. }
  39552. else if (dimension === 'value' && orderBy) {
  39553. dataExtent = [
  39554. children[children.length - 1].getValue(),
  39555. children[0].getValue()
  39556. ];
  39557. orderBy === 'asc' && dataExtent.reverse();
  39558. }
  39559. // Other dimension.
  39560. else {
  39561. var dataExtent = [Infinity, -Infinity];
  39562. each$11(children, function (child) {
  39563. var value = child.getValue(dimension);
  39564. value < dataExtent[0] && (dataExtent[0] = value);
  39565. value > dataExtent[1] && (dataExtent[1] = value);
  39566. });
  39567. }
  39568. return {sum: sum, dataExtent: dataExtent};
  39569. }
  39570. /**
  39571. * Computes the score for the specified row,
  39572. * as the worst aspect ratio.
  39573. */
  39574. function worst(row, rowFixedLength, ratio) {
  39575. var areaMax = 0;
  39576. var areaMin = Infinity;
  39577. for (var i = 0, area, len = row.length; i < len; i++) {
  39578. area = row[i].getLayout().area;
  39579. if (area) {
  39580. area < areaMin && (areaMin = area);
  39581. area > areaMax && (areaMax = area);
  39582. }
  39583. }
  39584. var squareArea = row.area * row.area;
  39585. var f = rowFixedLength * rowFixedLength * ratio;
  39586. return squareArea
  39587. ? mathMax$4(
  39588. (f * areaMax) / squareArea,
  39589. squareArea / (f * areaMin)
  39590. )
  39591. : Infinity;
  39592. }
  39593. /**
  39594. * Positions the specified row of nodes. Modifies `rect`.
  39595. */
  39596. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  39597. // When rowFixedLength === rect.width,
  39598. // it is horizontal subdivision,
  39599. // rowFixedLength is the width of the subdivision,
  39600. // rowOtherLength is the height of the subdivision,
  39601. // and nodes will be positioned from left to right.
  39602. // wh[idx0WhenH] means: when horizontal,
  39603. // wh[idx0WhenH] => wh[0] => 'width'.
  39604. // xy[idx1WhenH] => xy[1] => 'y'.
  39605. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  39606. var idx1WhenH = 1 - idx0WhenH;
  39607. var xy = ['x', 'y'];
  39608. var wh = ['width', 'height'];
  39609. var last = rect[xy[idx0WhenH]];
  39610. var rowOtherLength = rowFixedLength
  39611. ? row.area / rowFixedLength : 0;
  39612. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  39613. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  39614. }
  39615. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  39616. var node = row[i];
  39617. var nodeLayout = {};
  39618. var step = rowOtherLength
  39619. ? node.getLayout().area / rowOtherLength : 0;
  39620. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  39621. // We use Math.max/min to avoid negative width/height when considering gap width.
  39622. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  39623. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  39624. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  39625. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  39626. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  39627. last += modWH;
  39628. node.setLayout(nodeLayout, true);
  39629. }
  39630. rect[xy[idx1WhenH]] += rowOtherLength;
  39631. rect[wh[idx1WhenH]] -= rowOtherLength;
  39632. }
  39633. // Return [containerWidth, containerHeight] as defualt.
  39634. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  39635. // If targetInfo.node exists, we zoom to the node,
  39636. // so estimate whold width and heigth by target node.
  39637. var currNode = (targetInfo || {}).node;
  39638. var defaultSize = [containerWidth, containerHeight];
  39639. if (!currNode || currNode === viewRoot) {
  39640. return defaultSize;
  39641. }
  39642. var parent;
  39643. var viewArea = containerWidth * containerHeight;
  39644. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  39645. while (parent = currNode.parentNode) { // jshint ignore:line
  39646. var sum = 0;
  39647. var siblings = parent.children;
  39648. for (var i = 0, len = siblings.length; i < len; i++) {
  39649. sum += siblings[i].getValue();
  39650. }
  39651. var currNodeValue = currNode.getValue();
  39652. if (currNodeValue === 0) {
  39653. return defaultSize;
  39654. }
  39655. area *= sum / currNodeValue;
  39656. // Considering border, suppose aspect ratio is 1.
  39657. var parentModel = parent.getModel();
  39658. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  39659. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  39660. area += 4 * borderWidth * borderWidth
  39661. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  39662. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  39663. currNode = parent;
  39664. }
  39665. area < viewArea && (area = viewArea);
  39666. var scale = Math.pow(area / viewArea, 0.5);
  39667. return [containerWidth * scale, containerHeight * scale];
  39668. }
  39669. // Root postion base on coord of containerGroup
  39670. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  39671. if (rootRect) {
  39672. return {x: rootRect.x, y: rootRect.y};
  39673. }
  39674. var defaultPosition = {x: 0, y: 0};
  39675. if (!targetInfo) {
  39676. return defaultPosition;
  39677. }
  39678. // If targetInfo is fetched by 'retrieveTargetInfo',
  39679. // old tree and new tree are the same tree,
  39680. // so the node still exists and we can visit it.
  39681. var targetNode = targetInfo.node;
  39682. var layout = targetNode.getLayout();
  39683. if (!layout) {
  39684. return defaultPosition;
  39685. }
  39686. // Transform coord from local to container.
  39687. var targetCenter = [layout.width / 2, layout.height / 2];
  39688. var node = targetNode;
  39689. while (node) {
  39690. var nodeLayout = node.getLayout();
  39691. targetCenter[0] += nodeLayout.x;
  39692. targetCenter[1] += nodeLayout.y;
  39693. node = node.parentNode;
  39694. }
  39695. return {
  39696. x: layoutInfo.width / 2 - targetCenter[0],
  39697. y: layoutInfo.height / 2 - targetCenter[1]
  39698. };
  39699. }
  39700. // Mark nodes visible for prunning when visual coding and rendering.
  39701. // Prunning depends on layout and root position, so we have to do it after layout.
  39702. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  39703. var nodeLayout = node.getLayout();
  39704. var nodeInViewAbovePath = viewAbovePath[depth];
  39705. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  39706. if (
  39707. (nodeInViewAbovePath && !isAboveViewRoot)
  39708. || (depth === viewAbovePath.length && node !== viewRoot)
  39709. ) {
  39710. return;
  39711. }
  39712. node.setLayout({
  39713. // isInView means: viewRoot sub tree + viewAbovePath
  39714. isInView: true,
  39715. // invisible only means: outside view clip so that the node can not
  39716. // see but still layout for animation preparation but not render.
  39717. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  39718. isAboveViewRoot: isAboveViewRoot
  39719. }, true);
  39720. // Transform to child coordinate.
  39721. var childClipRect = new BoundingRect(
  39722. clipRect.x - nodeLayout.x,
  39723. clipRect.y - nodeLayout.y,
  39724. clipRect.width,
  39725. clipRect.height
  39726. );
  39727. each$11(node.viewChildren || [], function (child) {
  39728. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  39729. });
  39730. }
  39731. function getUpperLabelHeight(model) {
  39732. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  39733. }
  39734. registerVisual(treemapVisual);
  39735. registerLayout(treemapLayout);
  39736. /**
  39737. * Graph data structure
  39738. *
  39739. * @module echarts/data/Graph
  39740. * @author Yi Shen(https://www.github.com/pissang)
  39741. */
  39742. // id may be function name of Object, add a prefix to avoid this problem.
  39743. function generateNodeKey (id) {
  39744. return '_EC_' + id;
  39745. }
  39746. /**
  39747. * @alias module:echarts/data/Graph
  39748. * @constructor
  39749. * @param {boolean} directed
  39750. */
  39751. var Graph = function(directed) {
  39752. /**
  39753. * 是否是有向图
  39754. * @type {boolean}
  39755. * @private
  39756. */
  39757. this._directed = directed || false;
  39758. /**
  39759. * @type {Array.<module:echarts/data/Graph.Node>}
  39760. * @readOnly
  39761. */
  39762. this.nodes = [];
  39763. /**
  39764. * @type {Array.<module:echarts/data/Graph.Edge>}
  39765. * @readOnly
  39766. */
  39767. this.edges = [];
  39768. /**
  39769. * @type {Object.<string, module:echarts/data/Graph.Node>}
  39770. * @private
  39771. */
  39772. this._nodesMap = {};
  39773. /**
  39774. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  39775. * @private
  39776. */
  39777. this._edgesMap = {};
  39778. /**
  39779. * @type {module:echarts/data/List}
  39780. * @readOnly
  39781. */
  39782. this.data;
  39783. /**
  39784. * @type {module:echarts/data/List}
  39785. * @readOnly
  39786. */
  39787. this.edgeData;
  39788. };
  39789. var graphProto = Graph.prototype;
  39790. /**
  39791. * @type {string}
  39792. */
  39793. graphProto.type = 'graph';
  39794. /**
  39795. * If is directed graph
  39796. * @return {boolean}
  39797. */
  39798. graphProto.isDirected = function () {
  39799. return this._directed;
  39800. };
  39801. /**
  39802. * Add a new node
  39803. * @param {string} id
  39804. * @param {number} [dataIndex]
  39805. */
  39806. graphProto.addNode = function (id, dataIndex) {
  39807. id = id || ('' + dataIndex);
  39808. var nodesMap = this._nodesMap;
  39809. if (nodesMap[generateNodeKey(id)]) {
  39810. if (__DEV__) {
  39811. console.error('Graph nodes have duplicate name or id');
  39812. }
  39813. return;
  39814. }
  39815. var node = new Node(id, dataIndex);
  39816. node.hostGraph = this;
  39817. this.nodes.push(node);
  39818. nodesMap[generateNodeKey(id)] = node;
  39819. return node;
  39820. };
  39821. /**
  39822. * Get node by data index
  39823. * @param {number} dataIndex
  39824. * @return {module:echarts/data/Graph~Node}
  39825. */
  39826. graphProto.getNodeByIndex = function (dataIndex) {
  39827. var rawIdx = this.data.getRawIndex(dataIndex);
  39828. return this.nodes[rawIdx];
  39829. };
  39830. /**
  39831. * Get node by id
  39832. * @param {string} id
  39833. * @return {module:echarts/data/Graph.Node}
  39834. */
  39835. graphProto.getNodeById = function (id) {
  39836. return this._nodesMap[generateNodeKey(id)];
  39837. };
  39838. /**
  39839. * Add a new edge
  39840. * @param {number|string|module:echarts/data/Graph.Node} n1
  39841. * @param {number|string|module:echarts/data/Graph.Node} n2
  39842. * @param {number} [dataIndex=-1]
  39843. * @return {module:echarts/data/Graph.Edge}
  39844. */
  39845. graphProto.addEdge = function (n1, n2, dataIndex) {
  39846. var nodesMap = this._nodesMap;
  39847. var edgesMap = this._edgesMap;
  39848. // PNEDING
  39849. if (typeof n1 === 'number') {
  39850. n1 = this.nodes[n1];
  39851. }
  39852. if (typeof n2 === 'number') {
  39853. n2 = this.nodes[n2];
  39854. }
  39855. if (!Node.isInstance(n1)) {
  39856. n1 = nodesMap[generateNodeKey(n1)];
  39857. }
  39858. if (!Node.isInstance(n2)) {
  39859. n2 = nodesMap[generateNodeKey(n2)];
  39860. }
  39861. if (!n1 || !n2) {
  39862. return;
  39863. }
  39864. var key = n1.id + '-' + n2.id;
  39865. // PENDING
  39866. if (edgesMap[key]) {
  39867. return;
  39868. }
  39869. var edge = new Edge(n1, n2, dataIndex);
  39870. edge.hostGraph = this;
  39871. if (this._directed) {
  39872. n1.outEdges.push(edge);
  39873. n2.inEdges.push(edge);
  39874. }
  39875. n1.edges.push(edge);
  39876. if (n1 !== n2) {
  39877. n2.edges.push(edge);
  39878. }
  39879. this.edges.push(edge);
  39880. edgesMap[key] = edge;
  39881. return edge;
  39882. };
  39883. /**
  39884. * Get edge by data index
  39885. * @param {number} dataIndex
  39886. * @return {module:echarts/data/Graph~Node}
  39887. */
  39888. graphProto.getEdgeByIndex = function (dataIndex) {
  39889. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  39890. return this.edges[rawIdx];
  39891. };
  39892. /**
  39893. * Get edge by two linked nodes
  39894. * @param {module:echarts/data/Graph.Node|string} n1
  39895. * @param {module:echarts/data/Graph.Node|string} n2
  39896. * @return {module:echarts/data/Graph.Edge}
  39897. */
  39898. graphProto.getEdge = function (n1, n2) {
  39899. if (Node.isInstance(n1)) {
  39900. n1 = n1.id;
  39901. }
  39902. if (Node.isInstance(n2)) {
  39903. n2 = n2.id;
  39904. }
  39905. var edgesMap = this._edgesMap;
  39906. if (this._directed) {
  39907. return edgesMap[n1 + '-' + n2];
  39908. } else {
  39909. return edgesMap[n1 + '-' + n2]
  39910. || edgesMap[n2 + '-' + n1];
  39911. }
  39912. };
  39913. /**
  39914. * Iterate all nodes
  39915. * @param {Function} cb
  39916. * @param {*} [context]
  39917. */
  39918. graphProto.eachNode = function (cb, context) {
  39919. var nodes = this.nodes;
  39920. var len = nodes.length;
  39921. for (var i = 0; i < len; i++) {
  39922. if (nodes[i].dataIndex >= 0) {
  39923. cb.call(context, nodes[i], i);
  39924. }
  39925. }
  39926. };
  39927. /**
  39928. * Iterate all edges
  39929. * @param {Function} cb
  39930. * @param {*} [context]
  39931. */
  39932. graphProto.eachEdge = function (cb, context) {
  39933. var edges = this.edges;
  39934. var len = edges.length;
  39935. for (var i = 0; i < len; i++) {
  39936. if (edges[i].dataIndex >= 0
  39937. && edges[i].node1.dataIndex >= 0
  39938. && edges[i].node2.dataIndex >= 0
  39939. ) {
  39940. cb.call(context, edges[i], i);
  39941. }
  39942. }
  39943. };
  39944. /**
  39945. * Breadth first traverse
  39946. * @param {Function} cb
  39947. * @param {module:echarts/data/Graph.Node} startNode
  39948. * @param {string} [direction='none'] 'none'|'in'|'out'
  39949. * @param {*} [context]
  39950. */
  39951. graphProto.breadthFirstTraverse = function (
  39952. cb, startNode, direction, context
  39953. ) {
  39954. if (!Node.isInstance(startNode)) {
  39955. startNode = this._nodesMap[generateNodeKey(startNode)];
  39956. }
  39957. if (!startNode) {
  39958. return;
  39959. }
  39960. var edgeType = direction === 'out'
  39961. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  39962. for (var i = 0; i < this.nodes.length; i++) {
  39963. this.nodes[i].__visited = false;
  39964. }
  39965. if (cb.call(context, startNode, null)) {
  39966. return;
  39967. }
  39968. var queue = [startNode];
  39969. while (queue.length) {
  39970. var currentNode = queue.shift();
  39971. var edges = currentNode[edgeType];
  39972. for (var i = 0; i < edges.length; i++) {
  39973. var e = edges[i];
  39974. var otherNode = e.node1 === currentNode
  39975. ? e.node2 : e.node1;
  39976. if (!otherNode.__visited) {
  39977. if (cb.call(context, otherNode, currentNode)) {
  39978. // Stop traversing
  39979. return;
  39980. }
  39981. queue.push(otherNode);
  39982. otherNode.__visited = true;
  39983. }
  39984. }
  39985. }
  39986. };
  39987. // TODO
  39988. // graphProto.depthFirstTraverse = function (
  39989. // cb, startNode, direction, context
  39990. // ) {
  39991. // };
  39992. // Filter update
  39993. graphProto.update = function () {
  39994. var data = this.data;
  39995. var edgeData = this.edgeData;
  39996. var nodes = this.nodes;
  39997. var edges = this.edges;
  39998. for (var i = 0, len = nodes.length; i < len; i++) {
  39999. nodes[i].dataIndex = -1;
  40000. }
  40001. for (var i = 0, len = data.count(); i < len; i++) {
  40002. nodes[data.getRawIndex(i)].dataIndex = i;
  40003. }
  40004. edgeData.filterSelf(function (idx) {
  40005. var edge = edges[edgeData.getRawIndex(idx)];
  40006. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  40007. });
  40008. // Update edge
  40009. for (var i = 0, len = edges.length; i < len; i++) {
  40010. edges[i].dataIndex = -1;
  40011. }
  40012. for (var i = 0, len = edgeData.count(); i < len; i++) {
  40013. edges[edgeData.getRawIndex(i)].dataIndex = i;
  40014. }
  40015. };
  40016. /**
  40017. * @return {module:echarts/data/Graph}
  40018. */
  40019. graphProto.clone = function () {
  40020. var graph = new Graph(this._directed);
  40021. var nodes = this.nodes;
  40022. var edges = this.edges;
  40023. for (var i = 0; i < nodes.length; i++) {
  40024. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  40025. }
  40026. for (var i = 0; i < edges.length; i++) {
  40027. var e = edges[i];
  40028. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  40029. }
  40030. return graph;
  40031. };
  40032. /**
  40033. * @alias module:echarts/data/Graph.Node
  40034. */
  40035. function Node(id, dataIndex) {
  40036. /**
  40037. * @type {string}
  40038. */
  40039. this.id = id == null ? '' : id;
  40040. /**
  40041. * @type {Array.<module:echarts/data/Graph.Edge>}
  40042. */
  40043. this.inEdges = [];
  40044. /**
  40045. * @type {Array.<module:echarts/data/Graph.Edge>}
  40046. */
  40047. this.outEdges = [];
  40048. /**
  40049. * @type {Array.<module:echarts/data/Graph.Edge>}
  40050. */
  40051. this.edges = [];
  40052. /**
  40053. * @type {module:echarts/data/Graph}
  40054. */
  40055. this.hostGraph;
  40056. /**
  40057. * @type {number}
  40058. */
  40059. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  40060. }
  40061. Node.prototype = {
  40062. constructor: Node,
  40063. /**
  40064. * @return {number}
  40065. */
  40066. degree: function () {
  40067. return this.edges.length;
  40068. },
  40069. /**
  40070. * @return {number}
  40071. */
  40072. inDegree: function () {
  40073. return this.inEdges.length;
  40074. },
  40075. /**
  40076. * @return {number}
  40077. */
  40078. outDegree: function () {
  40079. return this.outEdges.length;
  40080. },
  40081. /**
  40082. * @param {string} [path]
  40083. * @return {module:echarts/model/Model}
  40084. */
  40085. getModel: function (path) {
  40086. if (this.dataIndex < 0) {
  40087. return;
  40088. }
  40089. var graph = this.hostGraph;
  40090. var itemModel = graph.data.getItemModel(this.dataIndex);
  40091. return itemModel.getModel(path);
  40092. }
  40093. };
  40094. /**
  40095. * 图边
  40096. * @alias module:echarts/data/Graph.Edge
  40097. * @param {module:echarts/data/Graph.Node} n1
  40098. * @param {module:echarts/data/Graph.Node} n2
  40099. * @param {number} [dataIndex=-1]
  40100. */
  40101. function Edge(n1, n2, dataIndex) {
  40102. /**
  40103. * 节点1,如果是有向图则为源节点
  40104. * @type {module:echarts/data/Graph.Node}
  40105. */
  40106. this.node1 = n1;
  40107. /**
  40108. * 节点2,如果是有向图则为目标节点
  40109. * @type {module:echarts/data/Graph.Node}
  40110. */
  40111. this.node2 = n2;
  40112. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  40113. }
  40114. /**
  40115. * @param {string} [path]
  40116. * @return {module:echarts/model/Model}
  40117. */
  40118. Edge.prototype.getModel = function (path) {
  40119. if (this.dataIndex < 0) {
  40120. return;
  40121. }
  40122. var graph = this.hostGraph;
  40123. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  40124. return itemModel.getModel(path);
  40125. };
  40126. var createGraphDataProxyMixin = function (hostName, dataName) {
  40127. return {
  40128. /**
  40129. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  40130. * @return {number}
  40131. */
  40132. getValue: function (dimension) {
  40133. var data = this[hostName][dataName];
  40134. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  40135. },
  40136. /**
  40137. * @param {Object|string} key
  40138. * @param {*} [value]
  40139. */
  40140. setVisual: function (key, value) {
  40141. this.dataIndex >= 0
  40142. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  40143. },
  40144. /**
  40145. * @param {string} key
  40146. * @return {boolean}
  40147. */
  40148. getVisual: function (key, ignoreParent) {
  40149. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  40150. },
  40151. /**
  40152. * @param {Object} layout
  40153. * @return {boolean} [merge=false]
  40154. */
  40155. setLayout: function (layout, merge$$1) {
  40156. this.dataIndex >= 0
  40157. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  40158. },
  40159. /**
  40160. * @return {Object}
  40161. */
  40162. getLayout: function () {
  40163. return this[hostName][dataName].getItemLayout(this.dataIndex);
  40164. },
  40165. /**
  40166. * @return {module:zrender/Element}
  40167. */
  40168. getGraphicEl: function () {
  40169. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  40170. },
  40171. /**
  40172. * @return {number}
  40173. */
  40174. getRawIndex: function () {
  40175. return this[hostName][dataName].getRawIndex(this.dataIndex);
  40176. }
  40177. };
  40178. };
  40179. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  40180. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  40181. Graph.Node = Node;
  40182. Graph.Edge = Edge;
  40183. enableClassCheck(Node);
  40184. enableClassCheck(Edge);
  40185. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  40186. // ??? TODO
  40187. // support dataset?
  40188. var graph = new Graph(directed);
  40189. for (var i = 0; i < nodes.length; i++) {
  40190. graph.addNode(retrieve(
  40191. // Id, name, dataIndex
  40192. nodes[i].id, nodes[i].name, i
  40193. ), i);
  40194. }
  40195. var linkNameList = [];
  40196. var validEdges = [];
  40197. var linkCount = 0;
  40198. for (var i = 0; i < edges.length; i++) {
  40199. var link = edges[i];
  40200. var source = link.source;
  40201. var target = link.target;
  40202. // addEdge may fail when source or target not exists
  40203. if (graph.addEdge(source, target, linkCount)) {
  40204. validEdges.push(link);
  40205. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  40206. linkCount++;
  40207. }
  40208. }
  40209. var coordSys = seriesModel.get('coordinateSystem');
  40210. var nodeData;
  40211. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  40212. nodeData = createListFromArray(nodes, seriesModel);
  40213. }
  40214. else {
  40215. // FIXME
  40216. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  40217. // FIXME
  40218. var dimensionNames = createDimensions(nodes, {
  40219. coordDimensions: (
  40220. (coordSysCtor && coordSysCtor.type !== 'view')
  40221. ? (coordSysCtor.dimensions || []) : []
  40222. ).concat(['value'])
  40223. });
  40224. nodeData = new List(dimensionNames, seriesModel);
  40225. nodeData.initData(nodes);
  40226. }
  40227. var edgeData = new List(['value'], seriesModel);
  40228. edgeData.initData(validEdges, linkNameList);
  40229. beforeLink && beforeLink(nodeData, edgeData);
  40230. linkList({
  40231. mainData: nodeData,
  40232. struct: graph,
  40233. structAttr: 'graph',
  40234. datas: {node: nodeData, edge: edgeData},
  40235. datasAttr: {node: 'data', edge: 'edgeData'}
  40236. });
  40237. // Update dataIndex of nodes and edges because invalid edge may be removed
  40238. graph.update();
  40239. return graph;
  40240. };
  40241. var GraphSeries = extendSeriesModel({
  40242. type: 'series.graph',
  40243. init: function (option) {
  40244. GraphSeries.superApply(this, 'init', arguments);
  40245. // Provide data for legend select
  40246. this.legendDataProvider = function () {
  40247. return this._categoriesData;
  40248. };
  40249. this.fillDataTextStyle(option.edges || option.links);
  40250. this._updateCategoriesData();
  40251. },
  40252. mergeOption: function (option) {
  40253. GraphSeries.superApply(this, 'mergeOption', arguments);
  40254. this.fillDataTextStyle(option.edges || option.links);
  40255. this._updateCategoriesData();
  40256. },
  40257. mergeDefaultAndTheme: function (option) {
  40258. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  40259. defaultEmphasis(option, ['edgeLabel'], ['show']);
  40260. },
  40261. getInitialData: function (option, ecModel) {
  40262. var edges = option.edges || option.links || [];
  40263. var nodes = option.data || option.nodes || [];
  40264. var self = this;
  40265. if (nodes && edges) {
  40266. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  40267. }
  40268. function beforeLink(nodeData, edgeData) {
  40269. // Overwrite nodeData.getItemModel to
  40270. nodeData.wrapMethod('getItemModel', function (model) {
  40271. var categoriesModels = self._categoriesModels;
  40272. var categoryIdx = model.getShallow('category');
  40273. var categoryModel = categoriesModels[categoryIdx];
  40274. if (categoryModel) {
  40275. categoryModel.parentModel = model.parentModel;
  40276. model.parentModel = categoryModel;
  40277. }
  40278. return model;
  40279. });
  40280. var edgeLabelModel = self.getModel('edgeLabel');
  40281. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  40282. var fakeSeriesModel = new Model(
  40283. {label: edgeLabelModel.option},
  40284. edgeLabelModel.parentModel,
  40285. ecModel
  40286. );
  40287. edgeData.wrapMethod('getItemModel', function (model) {
  40288. model.customizeGetParent(edgeGetParent);
  40289. return model;
  40290. });
  40291. function edgeGetParent(path) {
  40292. path = this.parsePath(path);
  40293. return (path && path[0] === 'label')
  40294. ? fakeSeriesModel
  40295. : this.parentModel;
  40296. }
  40297. }
  40298. },
  40299. /**
  40300. * @return {module:echarts/data/Graph}
  40301. */
  40302. getGraph: function () {
  40303. return this.getData().graph;
  40304. },
  40305. /**
  40306. * @return {module:echarts/data/List}
  40307. */
  40308. getEdgeData: function () {
  40309. return this.getGraph().edgeData;
  40310. },
  40311. /**
  40312. * @return {module:echarts/data/List}
  40313. */
  40314. getCategoriesData: function () {
  40315. return this._categoriesData;
  40316. },
  40317. /**
  40318. * @override
  40319. */
  40320. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  40321. if (dataType === 'edge') {
  40322. var nodeData = this.getData();
  40323. var params = this.getDataParams(dataIndex, dataType);
  40324. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  40325. var sourceName = nodeData.getName(edge.node1.dataIndex);
  40326. var targetName = nodeData.getName(edge.node2.dataIndex);
  40327. var html = [];
  40328. sourceName != null && html.push(sourceName);
  40329. targetName != null && html.push(targetName);
  40330. html = encodeHTML(html.join(' > '));
  40331. if (params.value) {
  40332. html += ' : ' + encodeHTML(params.value);
  40333. }
  40334. return html;
  40335. }
  40336. else { // dataType === 'node' or empty
  40337. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  40338. }
  40339. },
  40340. _updateCategoriesData: function () {
  40341. var categories = map(this.option.categories || [], function (category) {
  40342. // Data must has value
  40343. return category.value != null ? category : extend({
  40344. value: 0
  40345. }, category);
  40346. });
  40347. var categoriesData = new List(['value'], this);
  40348. categoriesData.initData(categories);
  40349. this._categoriesData = categoriesData;
  40350. this._categoriesModels = categoriesData.mapArray(function (idx) {
  40351. return categoriesData.getItemModel(idx, true);
  40352. });
  40353. },
  40354. setZoom: function (zoom) {
  40355. this.option.zoom = zoom;
  40356. },
  40357. setCenter: function (center) {
  40358. this.option.center = center;
  40359. },
  40360. isAnimationEnabled: function () {
  40361. return GraphSeries.superCall(this, 'isAnimationEnabled')
  40362. // Not enable animation when do force layout
  40363. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  40364. },
  40365. defaultOption: {
  40366. zlevel: 0,
  40367. z: 2,
  40368. coordinateSystem: 'view',
  40369. // Default option for all coordinate systems
  40370. // xAxisIndex: 0,
  40371. // yAxisIndex: 0,
  40372. // polarIndex: 0,
  40373. // geoIndex: 0,
  40374. legendHoverLink: true,
  40375. hoverAnimation: true,
  40376. layout: null,
  40377. focusNodeAdjacency: false,
  40378. // Configuration of circular layout
  40379. circular: {
  40380. rotateLabel: false
  40381. },
  40382. // Configuration of force directed layout
  40383. force: {
  40384. initLayout: null,
  40385. // Node repulsion. Can be an array to represent range.
  40386. repulsion: [0, 50],
  40387. gravity: 0.1,
  40388. // Edge length. Can be an array to represent range.
  40389. edgeLength: 30,
  40390. layoutAnimation: true
  40391. },
  40392. left: 'center',
  40393. top: 'center',
  40394. // right: null,
  40395. // bottom: null,
  40396. // width: '80%',
  40397. // height: '80%',
  40398. symbol: 'circle',
  40399. symbolSize: 10,
  40400. edgeSymbol: ['none', 'none'],
  40401. edgeSymbolSize: 10,
  40402. edgeLabel: {
  40403. position: 'middle'
  40404. },
  40405. draggable: false,
  40406. roam: false,
  40407. // Default on center of graph
  40408. center: null,
  40409. zoom: 1,
  40410. // Symbol size scale ratio in roam
  40411. nodeScaleRatio: 0.6,
  40412. // cursor: null,
  40413. // categories: [],
  40414. // data: []
  40415. // Or
  40416. // nodes: []
  40417. //
  40418. // links: []
  40419. // Or
  40420. // edges: []
  40421. label: {
  40422. show: false,
  40423. formatter: '{b}'
  40424. },
  40425. itemStyle: {},
  40426. lineStyle: {
  40427. color: '#aaa',
  40428. width: 1,
  40429. curveness: 0,
  40430. opacity: 0.5
  40431. },
  40432. emphasis: {
  40433. label: {
  40434. show: true
  40435. }
  40436. }
  40437. }
  40438. });
  40439. /**
  40440. * Line path for bezier and straight line draw
  40441. */
  40442. var straightLineProto = Line.prototype;
  40443. var bezierCurveProto = BezierCurve.prototype;
  40444. function isLine(shape) {
  40445. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  40446. }
  40447. var LinePath = extendShape({
  40448. type: 'ec-line',
  40449. style: {
  40450. stroke: '#000',
  40451. fill: null
  40452. },
  40453. shape: {
  40454. x1: 0,
  40455. y1: 0,
  40456. x2: 0,
  40457. y2: 0,
  40458. percent: 1,
  40459. cpx1: null,
  40460. cpy1: null
  40461. },
  40462. buildPath: function (ctx, shape) {
  40463. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  40464. },
  40465. pointAt: function (t) {
  40466. return isLine(this.shape)
  40467. ? straightLineProto.pointAt.call(this, t)
  40468. : bezierCurveProto.pointAt.call(this, t);
  40469. },
  40470. tangentAt: function (t) {
  40471. var shape = this.shape;
  40472. var p = isLine(shape)
  40473. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  40474. : bezierCurveProto.tangentAt.call(this, t);
  40475. return normalize(p, p);
  40476. }
  40477. });
  40478. /**
  40479. * @module echarts/chart/helper/Line
  40480. */
  40481. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  40482. function makeSymbolTypeKey(symbolCategory) {
  40483. return '_' + symbolCategory + 'Type';
  40484. }
  40485. /**
  40486. * @inner
  40487. */
  40488. function createSymbol$1(name, lineData, idx) {
  40489. var color = lineData.getItemVisual(idx, 'color');
  40490. var symbolType = lineData.getItemVisual(idx, name);
  40491. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  40492. if (!symbolType || symbolType === 'none') {
  40493. return;
  40494. }
  40495. if (!isArray(symbolSize)) {
  40496. symbolSize = [symbolSize, symbolSize];
  40497. }
  40498. var symbolPath = createSymbol(
  40499. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  40500. symbolSize[0], symbolSize[1], color
  40501. );
  40502. symbolPath.name = name;
  40503. return symbolPath;
  40504. }
  40505. function createLine(points) {
  40506. var line = new LinePath({
  40507. name: 'line'
  40508. });
  40509. setLinePoints(line.shape, points);
  40510. return line;
  40511. }
  40512. function setLinePoints(targetShape, points) {
  40513. var p1 = points[0];
  40514. var p2 = points[1];
  40515. var cp1 = points[2];
  40516. targetShape.x1 = p1[0];
  40517. targetShape.y1 = p1[1];
  40518. targetShape.x2 = p2[0];
  40519. targetShape.y2 = p2[1];
  40520. targetShape.percent = 1;
  40521. if (cp1) {
  40522. targetShape.cpx1 = cp1[0];
  40523. targetShape.cpy1 = cp1[1];
  40524. }
  40525. else {
  40526. targetShape.cpx1 = NaN;
  40527. targetShape.cpy1 = NaN;
  40528. }
  40529. }
  40530. function updateSymbolAndLabelBeforeLineUpdate () {
  40531. var lineGroup = this;
  40532. var symbolFrom = lineGroup.childOfName('fromSymbol');
  40533. var symbolTo = lineGroup.childOfName('toSymbol');
  40534. var label = lineGroup.childOfName('label');
  40535. // Quick reject
  40536. if (!symbolFrom && !symbolTo && label.ignore) {
  40537. return;
  40538. }
  40539. var invScale = 1;
  40540. var parentNode = this.parent;
  40541. while (parentNode) {
  40542. if (parentNode.scale) {
  40543. invScale /= parentNode.scale[0];
  40544. }
  40545. parentNode = parentNode.parent;
  40546. }
  40547. var line = lineGroup.childOfName('line');
  40548. // If line not changed
  40549. // FIXME Parent scale changed
  40550. if (!this.__dirty && !line.__dirty) {
  40551. return;
  40552. }
  40553. var percent = line.shape.percent;
  40554. var fromPos = line.pointAt(0);
  40555. var toPos = line.pointAt(percent);
  40556. var d = sub([], toPos, fromPos);
  40557. normalize(d, d);
  40558. if (symbolFrom) {
  40559. symbolFrom.attr('position', fromPos);
  40560. var tangent = line.tangentAt(0);
  40561. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  40562. tangent[1], tangent[0]
  40563. ));
  40564. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  40565. }
  40566. if (symbolTo) {
  40567. symbolTo.attr('position', toPos);
  40568. var tangent = line.tangentAt(1);
  40569. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  40570. tangent[1], tangent[0]
  40571. ));
  40572. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  40573. }
  40574. if (!label.ignore) {
  40575. label.attr('position', toPos);
  40576. var textPosition;
  40577. var textAlign;
  40578. var textVerticalAlign;
  40579. var distance$$1 = 5 * invScale;
  40580. // End
  40581. if (label.__position === 'end') {
  40582. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  40583. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  40584. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  40585. }
  40586. // Middle
  40587. else if (label.__position === 'middle') {
  40588. var halfPercent = percent / 2;
  40589. var tangent = line.tangentAt(halfPercent);
  40590. var n = [tangent[1], -tangent[0]];
  40591. var cp = line.pointAt(halfPercent);
  40592. if (n[1] > 0) {
  40593. n[0] = -n[0];
  40594. n[1] = -n[1];
  40595. }
  40596. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  40597. textAlign = 'center';
  40598. textVerticalAlign = 'bottom';
  40599. var rotation = -Math.atan2(tangent[1], tangent[0]);
  40600. if (toPos[0] < fromPos[0]) {
  40601. rotation = Math.PI + rotation;
  40602. }
  40603. label.attr('rotation', rotation);
  40604. }
  40605. // Start
  40606. else {
  40607. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  40608. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  40609. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  40610. }
  40611. label.attr({
  40612. style: {
  40613. // Use the user specified text align and baseline first
  40614. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  40615. textAlign: label.__textAlign || textAlign
  40616. },
  40617. position: textPosition,
  40618. scale: [invScale, invScale]
  40619. });
  40620. }
  40621. }
  40622. /**
  40623. * @constructor
  40624. * @extends {module:zrender/graphic/Group}
  40625. * @alias {module:echarts/chart/helper/Line}
  40626. */
  40627. function Line$1(lineData, idx, seriesScope) {
  40628. Group.call(this);
  40629. this._createLine(lineData, idx, seriesScope);
  40630. }
  40631. var lineProto = Line$1.prototype;
  40632. // Update symbol position and rotation
  40633. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  40634. lineProto._createLine = function (lineData, idx, seriesScope) {
  40635. var seriesModel = lineData.hostModel;
  40636. var linePoints = lineData.getItemLayout(idx);
  40637. var line = createLine(linePoints);
  40638. line.shape.percent = 0;
  40639. initProps(line, {
  40640. shape: {
  40641. percent: 1
  40642. }
  40643. }, seriesModel, idx);
  40644. this.add(line);
  40645. var label = new Text({
  40646. name: 'label'
  40647. });
  40648. this.add(label);
  40649. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40650. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  40651. // symbols must added after line to make sure
  40652. // it will be updated after line#update.
  40653. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  40654. this.add(symbol);
  40655. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  40656. }, this);
  40657. this._updateCommonStl(lineData, idx, seriesScope);
  40658. };
  40659. lineProto.updateData = function (lineData, idx, seriesScope) {
  40660. var seriesModel = lineData.hostModel;
  40661. var line = this.childOfName('line');
  40662. var linePoints = lineData.getItemLayout(idx);
  40663. var target = {
  40664. shape: {}
  40665. };
  40666. setLinePoints(target.shape, linePoints);
  40667. updateProps(line, target, seriesModel, idx);
  40668. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40669. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  40670. var key = makeSymbolTypeKey(symbolCategory);
  40671. // Symbol changed
  40672. if (this[key] !== symbolType) {
  40673. this.remove(this.childOfName(symbolCategory));
  40674. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  40675. this.add(symbol);
  40676. }
  40677. this[key] = symbolType;
  40678. }, this);
  40679. this._updateCommonStl(lineData, idx, seriesScope);
  40680. };
  40681. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  40682. var seriesModel = lineData.hostModel;
  40683. var line = this.childOfName('line');
  40684. var lineStyle = seriesScope && seriesScope.lineStyle;
  40685. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  40686. var labelModel = seriesScope && seriesScope.labelModel;
  40687. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  40688. // Optimization for large dataset
  40689. if (!seriesScope || lineData.hasItemOption) {
  40690. var itemModel = lineData.getItemModel(idx);
  40691. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  40692. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  40693. labelModel = itemModel.getModel('label');
  40694. hoverLabelModel = itemModel.getModel('emphasis.label');
  40695. }
  40696. var visualColor = lineData.getItemVisual(idx, 'color');
  40697. var visualOpacity = retrieve3(
  40698. lineData.getItemVisual(idx, 'opacity'),
  40699. lineStyle.opacity,
  40700. 1
  40701. );
  40702. line.useStyle(defaults(
  40703. {
  40704. strokeNoScale: true,
  40705. fill: 'none',
  40706. stroke: visualColor,
  40707. opacity: visualOpacity
  40708. },
  40709. lineStyle
  40710. ));
  40711. line.hoverStyle = hoverLineStyle;
  40712. // Update symbol
  40713. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40714. var symbol = this.childOfName(symbolCategory);
  40715. if (symbol) {
  40716. symbol.setColor(visualColor);
  40717. symbol.setStyle({
  40718. opacity: visualOpacity
  40719. });
  40720. }
  40721. }, this);
  40722. var showLabel = labelModel.getShallow('show');
  40723. var hoverShowLabel = hoverLabelModel.getShallow('show');
  40724. var label = this.childOfName('label');
  40725. var defaultLabelColor;
  40726. var normalText;
  40727. var emphasisText;
  40728. if (showLabel || hoverShowLabel) {
  40729. defaultLabelColor = visualColor || '#000';
  40730. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  40731. if (normalText == null) {
  40732. var rawVal = seriesModel.getRawValue(idx);
  40733. normalText = rawVal == null
  40734. ? lineData.getName(idx)
  40735. : isFinite(rawVal)
  40736. ? round$1(rawVal)
  40737. : rawVal;
  40738. }
  40739. emphasisText = retrieve2(
  40740. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  40741. normalText
  40742. );
  40743. }
  40744. // label.afterUpdate = lineAfterUpdate;
  40745. if (showLabel) {
  40746. var labelStyle = setTextStyle(label.style, labelModel, {
  40747. text: normalText
  40748. }, {
  40749. autoColor: defaultLabelColor
  40750. });
  40751. label.__textAlign = labelStyle.textAlign;
  40752. label.__verticalAlign = labelStyle.textVerticalAlign;
  40753. // 'start', 'middle', 'end'
  40754. label.__position = labelModel.get('position') || 'middle';
  40755. }
  40756. else {
  40757. label.setStyle('text', null);
  40758. }
  40759. if (hoverShowLabel) {
  40760. // Only these properties supported in this emphasis style here.
  40761. label.hoverStyle = {
  40762. text: emphasisText,
  40763. textFill: hoverLabelModel.getTextColor(true),
  40764. // For merging hover style to normal style, do not use
  40765. // `hoverLabelModel.getFont()` here.
  40766. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  40767. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  40768. fontSize: hoverLabelModel.getShallow('fontSize'),
  40769. fontFamily: hoverLabelModel.getShallow('fontFamily')
  40770. };
  40771. }
  40772. else {
  40773. label.hoverStyle = {
  40774. text: null
  40775. };
  40776. }
  40777. label.ignore = !showLabel && !hoverShowLabel;
  40778. setHoverStyle(this);
  40779. };
  40780. lineProto.highlight = function () {
  40781. this.trigger('emphasis');
  40782. };
  40783. lineProto.downplay = function () {
  40784. this.trigger('normal');
  40785. };
  40786. lineProto.updateLayout = function (lineData, idx) {
  40787. this.setLinePoints(lineData.getItemLayout(idx));
  40788. };
  40789. lineProto.setLinePoints = function (points) {
  40790. var linePath = this.childOfName('line');
  40791. setLinePoints(linePath.shape, points);
  40792. linePath.dirty();
  40793. };
  40794. inherits(Line$1, Group);
  40795. /**
  40796. * @module echarts/chart/helper/LineDraw
  40797. */
  40798. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  40799. /**
  40800. * @alias module:echarts/component/marker/LineDraw
  40801. * @constructor
  40802. */
  40803. function LineDraw(ctor) {
  40804. this._ctor = ctor || Line$1;
  40805. this.group = new Group();
  40806. }
  40807. var lineDrawProto = LineDraw.prototype;
  40808. lineDrawProto.isPersistent = function () {
  40809. return true;
  40810. };
  40811. /**
  40812. * @param {module:echarts/data/List} lineData
  40813. */
  40814. lineDrawProto.updateData = function (lineData) {
  40815. var lineDraw = this;
  40816. var group = lineDraw.group;
  40817. var oldLineData = lineDraw._lineData;
  40818. lineDraw._lineData = lineData;
  40819. // There is no oldLineData only when first rendering or switching from
  40820. // stream mode to normal mode, where previous elements should be removed.
  40821. if (!oldLineData) {
  40822. group.removeAll();
  40823. }
  40824. var seriesScope = makeSeriesScope$1(lineData);
  40825. lineData.diff(oldLineData)
  40826. .add(function (idx) {
  40827. doAdd(lineDraw, lineData, idx, seriesScope);
  40828. })
  40829. .update(function (newIdx, oldIdx) {
  40830. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  40831. })
  40832. .remove(function (idx) {
  40833. group.remove(oldLineData.getItemGraphicEl(idx));
  40834. })
  40835. .execute();
  40836. };
  40837. function doAdd(lineDraw, lineData, idx, seriesScope) {
  40838. var itemLayout = lineData.getItemLayout(idx);
  40839. if (!lineNeedsDraw(itemLayout)) {
  40840. return;
  40841. }
  40842. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  40843. lineData.setItemGraphicEl(idx, el);
  40844. lineDraw.group.add(el);
  40845. }
  40846. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  40847. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  40848. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  40849. lineDraw.group.remove(itemEl);
  40850. return;
  40851. }
  40852. if (!itemEl) {
  40853. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  40854. }
  40855. else {
  40856. itemEl.updateData(newLineData, newIdx, seriesScope);
  40857. }
  40858. newLineData.setItemGraphicEl(newIdx, itemEl);
  40859. lineDraw.group.add(itemEl);
  40860. }
  40861. lineDrawProto.updateLayout = function () {
  40862. var lineData = this._lineData;
  40863. lineData.eachItemGraphicEl(function (el, idx) {
  40864. el.updateLayout(lineData, idx);
  40865. }, this);
  40866. };
  40867. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  40868. this._seriesScope = makeSeriesScope$1(lineData);
  40869. this._lineData = null;
  40870. this.group.removeAll();
  40871. };
  40872. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  40873. function updateIncrementalAndHover(el) {
  40874. if (!el.isGroup) {
  40875. el.incremental = el.useHoverLayer = true;
  40876. }
  40877. }
  40878. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  40879. var itemLayout = lineData.getItemLayout(idx);
  40880. if (lineNeedsDraw(itemLayout)) {
  40881. var el = new this._ctor(lineData, idx, this._seriesScope);
  40882. el.traverse(updateIncrementalAndHover);
  40883. this.group.add(el);
  40884. }
  40885. }
  40886. };
  40887. function makeSeriesScope$1(lineData) {
  40888. var hostModel = lineData.hostModel;
  40889. return {
  40890. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  40891. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  40892. labelModel: hostModel.getModel('label'),
  40893. hoverLabelModel: hostModel.getModel('emphasis.label')
  40894. };
  40895. }
  40896. lineDrawProto.remove = function () {
  40897. this._clearIncremental();
  40898. this._incremental = null;
  40899. this.group.removeAll();
  40900. };
  40901. lineDrawProto._clearIncremental = function () {
  40902. var incremental = this._incremental;
  40903. if (incremental) {
  40904. incremental.clearDisplaybles();
  40905. }
  40906. };
  40907. function isPointNaN(pt) {
  40908. return isNaN(pt[0]) || isNaN(pt[1]);
  40909. }
  40910. function lineNeedsDraw(pts) {
  40911. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  40912. }
  40913. var v1 = [];
  40914. var v2 = [];
  40915. var v3 = [];
  40916. var quadraticAt$1 = quadraticAt;
  40917. var v2DistSquare = distSquare;
  40918. var mathAbs$1 = Math.abs;
  40919. function intersectCurveCircle(curvePoints, center, radius) {
  40920. var p0 = curvePoints[0];
  40921. var p1 = curvePoints[1];
  40922. var p2 = curvePoints[2];
  40923. var d = Infinity;
  40924. var t;
  40925. var radiusSquare = radius * radius;
  40926. var interval = 0.1;
  40927. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  40928. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  40929. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  40930. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  40931. if (diff < d) {
  40932. d = diff;
  40933. t = _t;
  40934. }
  40935. }
  40936. // Assume the segment is monotone,Find root through Bisection method
  40937. // At most 32 iteration
  40938. for (var i = 0; i < 32; i++) {
  40939. // var prev = t - interval;
  40940. var next = t + interval;
  40941. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  40942. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  40943. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  40944. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  40945. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  40946. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  40947. var diff = v2DistSquare(v2, center) - radiusSquare;
  40948. if (mathAbs$1(diff) < 1e-2) {
  40949. break;
  40950. }
  40951. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  40952. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  40953. interval /= 2;
  40954. if (diff < 0) {
  40955. if (nextDiff >= 0) {
  40956. t = t + interval;
  40957. }
  40958. else {
  40959. t = t - interval;
  40960. }
  40961. }
  40962. else {
  40963. if (nextDiff >= 0) {
  40964. t = t - interval;
  40965. }
  40966. else {
  40967. t = t + interval;
  40968. }
  40969. }
  40970. }
  40971. return t;
  40972. }
  40973. // Adjust edge to avoid
  40974. var adjustEdge = function (graph, scale$$1) {
  40975. var tmp0 = [];
  40976. var quadraticSubdivide$$1 = quadraticSubdivide;
  40977. var pts = [[], [], []];
  40978. var pts2 = [[], []];
  40979. var v = [];
  40980. scale$$1 /= 2;
  40981. function getSymbolSize(node) {
  40982. var symbolSize = node.getVisual('symbolSize');
  40983. if (symbolSize instanceof Array) {
  40984. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  40985. }
  40986. return symbolSize;
  40987. }
  40988. graph.eachEdge(function (edge, idx) {
  40989. var linePoints = edge.getLayout();
  40990. var fromSymbol = edge.getVisual('fromSymbol');
  40991. var toSymbol = edge.getVisual('toSymbol');
  40992. if (!linePoints.__original) {
  40993. linePoints.__original = [
  40994. clone$1(linePoints[0]),
  40995. clone$1(linePoints[1])
  40996. ];
  40997. if (linePoints[2]) {
  40998. linePoints.__original.push(clone$1(linePoints[2]));
  40999. }
  41000. }
  41001. var originalPoints = linePoints.__original;
  41002. // Quadratic curve
  41003. if (linePoints[2] != null) {
  41004. copy(pts[0], originalPoints[0]);
  41005. copy(pts[1], originalPoints[2]);
  41006. copy(pts[2], originalPoints[1]);
  41007. if (fromSymbol && fromSymbol != 'none') {
  41008. var symbolSize = getSymbolSize(edge.node1);
  41009. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  41010. // Subdivide and get the second
  41011. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  41012. pts[0][0] = tmp0[3];
  41013. pts[1][0] = tmp0[4];
  41014. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  41015. pts[0][1] = tmp0[3];
  41016. pts[1][1] = tmp0[4];
  41017. }
  41018. if (toSymbol && toSymbol != 'none') {
  41019. var symbolSize = getSymbolSize(edge.node2);
  41020. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  41021. // Subdivide and get the first
  41022. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  41023. pts[1][0] = tmp0[1];
  41024. pts[2][0] = tmp0[2];
  41025. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  41026. pts[1][1] = tmp0[1];
  41027. pts[2][1] = tmp0[2];
  41028. }
  41029. // Copy back to layout
  41030. copy(linePoints[0], pts[0]);
  41031. copy(linePoints[1], pts[2]);
  41032. copy(linePoints[2], pts[1]);
  41033. }
  41034. // Line
  41035. else {
  41036. copy(pts2[0], originalPoints[0]);
  41037. copy(pts2[1], originalPoints[1]);
  41038. sub(v, pts2[1], pts2[0]);
  41039. normalize(v, v);
  41040. if (fromSymbol && fromSymbol != 'none') {
  41041. var symbolSize = getSymbolSize(edge.node1);
  41042. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  41043. }
  41044. if (toSymbol && toSymbol != 'none') {
  41045. var symbolSize = getSymbolSize(edge.node2);
  41046. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  41047. }
  41048. copy(linePoints[0], pts2[0]);
  41049. copy(linePoints[1], pts2[1]);
  41050. }
  41051. });
  41052. };
  41053. var nodeOpacityPath = ['itemStyle', 'opacity'];
  41054. var lineOpacityPath = ['lineStyle', 'opacity'];
  41055. function getItemOpacity(item, opacityPath) {
  41056. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  41057. }
  41058. function fadeOutItem(item, opacityPath, opacityRatio) {
  41059. var el = item.getGraphicEl();
  41060. var opacity = getItemOpacity(item, opacityPath);
  41061. if (opacityRatio != null) {
  41062. opacity == null && (opacity = 1);
  41063. opacity *= opacityRatio;
  41064. }
  41065. el.downplay && el.downplay();
  41066. el.traverse(function (child) {
  41067. if (child.type !== 'group') {
  41068. child.setStyle('opacity', opacity);
  41069. }
  41070. });
  41071. }
  41072. function fadeInItem(item, opacityPath) {
  41073. var opacity = getItemOpacity(item, opacityPath);
  41074. var el = item.getGraphicEl();
  41075. el.highlight && el.highlight();
  41076. el.traverse(function (child) {
  41077. if (child.type !== 'group') {
  41078. child.setStyle('opacity', opacity);
  41079. }
  41080. });
  41081. }
  41082. extendChartView({
  41083. type: 'graph',
  41084. init: function (ecModel, api) {
  41085. var symbolDraw = new SymbolDraw();
  41086. var lineDraw = new LineDraw();
  41087. var group = this.group;
  41088. this._controller = new RoamController(api.getZr());
  41089. this._controllerHost = {target: group};
  41090. group.add(symbolDraw.group);
  41091. group.add(lineDraw.group);
  41092. this._symbolDraw = symbolDraw;
  41093. this._lineDraw = lineDraw;
  41094. this._firstRender = true;
  41095. },
  41096. render: function (seriesModel, ecModel, api) {
  41097. var coordSys = seriesModel.coordinateSystem;
  41098. this._model = seriesModel;
  41099. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  41100. var symbolDraw = this._symbolDraw;
  41101. var lineDraw = this._lineDraw;
  41102. var group = this.group;
  41103. if (coordSys.type === 'view') {
  41104. var groupNewProp = {
  41105. position: coordSys.position,
  41106. scale: coordSys.scale
  41107. };
  41108. if (this._firstRender) {
  41109. group.attr(groupNewProp);
  41110. }
  41111. else {
  41112. updateProps(group, groupNewProp, seriesModel);
  41113. }
  41114. }
  41115. // Fix edge contact point with node
  41116. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41117. var data = seriesModel.getData();
  41118. symbolDraw.updateData(data);
  41119. var edgeData = seriesModel.getEdgeData();
  41120. lineDraw.updateData(edgeData);
  41121. this._updateNodeAndLinkScale();
  41122. this._updateController(seriesModel, ecModel, api);
  41123. clearTimeout(this._layoutTimeout);
  41124. var forceLayout = seriesModel.forceLayout;
  41125. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  41126. if (forceLayout) {
  41127. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  41128. }
  41129. data.eachItemGraphicEl(function (el, idx) {
  41130. var itemModel = data.getItemModel(idx);
  41131. // Update draggable
  41132. el.off('drag').off('dragend');
  41133. var draggable = data.getItemModel(idx).get('draggable');
  41134. if (draggable) {
  41135. el.on('drag', function () {
  41136. if (forceLayout) {
  41137. forceLayout.warmUp();
  41138. !this._layouting
  41139. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  41140. forceLayout.setFixed(idx);
  41141. // Write position back to layout
  41142. data.setItemLayout(idx, el.position);
  41143. }
  41144. }, this).on('dragend', function () {
  41145. if (forceLayout) {
  41146. forceLayout.setUnfixed(idx);
  41147. }
  41148. }, this);
  41149. }
  41150. el.setDraggable(draggable && forceLayout);
  41151. el.off('mouseover', el.__focusNodeAdjacency);
  41152. el.off('mouseout', el.__unfocusNodeAdjacency);
  41153. if (itemModel.get('focusNodeAdjacency')) {
  41154. el.on('mouseover', el.__focusNodeAdjacency = function () {
  41155. api.dispatchAction({
  41156. type: 'focusNodeAdjacency',
  41157. seriesId: seriesModel.id,
  41158. dataIndex: el.dataIndex
  41159. });
  41160. });
  41161. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  41162. api.dispatchAction({
  41163. type: 'unfocusNodeAdjacency',
  41164. seriesId: seriesModel.id
  41165. });
  41166. });
  41167. }
  41168. }, this);
  41169. data.graph.eachEdge(function (edge) {
  41170. var el = edge.getGraphicEl();
  41171. el.off('mouseover', el.__focusNodeAdjacency);
  41172. el.off('mouseout', el.__unfocusNodeAdjacency);
  41173. if (edge.getModel().get('focusNodeAdjacency')) {
  41174. el.on('mouseover', el.__focusNodeAdjacency = function () {
  41175. api.dispatchAction({
  41176. type: 'focusNodeAdjacency',
  41177. seriesId: seriesModel.id,
  41178. edgeDataIndex: edge.dataIndex
  41179. });
  41180. });
  41181. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  41182. api.dispatchAction({
  41183. type: 'unfocusNodeAdjacency',
  41184. seriesId: seriesModel.id
  41185. });
  41186. });
  41187. }
  41188. });
  41189. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  41190. && seriesModel.get('circular.rotateLabel');
  41191. var cx = data.getLayout('cx');
  41192. var cy = data.getLayout('cy');
  41193. data.eachItemGraphicEl(function (el, idx) {
  41194. var symbolPath = el.getSymbolPath();
  41195. if (circularRotateLabel) {
  41196. var pos = data.getItemLayout(idx);
  41197. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  41198. if (rad < 0) {
  41199. rad = Math.PI * 2 + rad;
  41200. }
  41201. var isLeft = pos[0] < cx;
  41202. if (isLeft) {
  41203. rad = rad - Math.PI;
  41204. }
  41205. var textPosition = isLeft ? 'left' : 'right';
  41206. symbolPath.setStyle({
  41207. textRotation: -rad,
  41208. textPosition: textPosition,
  41209. textOrigin: 'center'
  41210. });
  41211. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  41212. }
  41213. else {
  41214. symbolPath.setStyle({
  41215. textRotation: 0
  41216. });
  41217. }
  41218. });
  41219. this._firstRender = false;
  41220. },
  41221. dispose: function () {
  41222. this._controller && this._controller.dispose();
  41223. this._controllerHost = {};
  41224. },
  41225. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  41226. var data = this._model.getData();
  41227. var graph = data.graph;
  41228. var dataIndex = payload.dataIndex;
  41229. var edgeDataIndex = payload.edgeDataIndex;
  41230. var node = graph.getNodeByIndex(dataIndex);
  41231. var edge = graph.getEdgeByIndex(edgeDataIndex);
  41232. if (!node && !edge) {
  41233. return;
  41234. }
  41235. graph.eachNode(function (node) {
  41236. fadeOutItem(node, nodeOpacityPath, 0.1);
  41237. });
  41238. graph.eachEdge(function (edge) {
  41239. fadeOutItem(edge, lineOpacityPath, 0.1);
  41240. });
  41241. if (node) {
  41242. fadeInItem(node, nodeOpacityPath);
  41243. each$1(node.edges, function (adjacentEdge) {
  41244. if (adjacentEdge.dataIndex < 0) {
  41245. return;
  41246. }
  41247. fadeInItem(adjacentEdge, lineOpacityPath);
  41248. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  41249. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  41250. });
  41251. }
  41252. if (edge) {
  41253. fadeInItem(edge, lineOpacityPath);
  41254. fadeInItem(edge.node1, nodeOpacityPath);
  41255. fadeInItem(edge.node2, nodeOpacityPath);
  41256. }
  41257. },
  41258. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  41259. var graph = this._model.getData().graph;
  41260. graph.eachNode(function (node) {
  41261. fadeOutItem(node, nodeOpacityPath);
  41262. });
  41263. graph.eachEdge(function (edge) {
  41264. fadeOutItem(edge, lineOpacityPath);
  41265. });
  41266. },
  41267. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  41268. var self = this;
  41269. (function step() {
  41270. forceLayout.step(function (stopped) {
  41271. self.updateLayout(self._model);
  41272. (self._layouting = !stopped) && (
  41273. layoutAnimation
  41274. ? (self._layoutTimeout = setTimeout(step, 16))
  41275. : step()
  41276. );
  41277. });
  41278. })();
  41279. },
  41280. _updateController: function (seriesModel, ecModel, api) {
  41281. var controller = this._controller;
  41282. var controllerHost = this._controllerHost;
  41283. var group = this.group;
  41284. controller.setPointerChecker(function (e, x, y) {
  41285. var rect = group.getBoundingRect();
  41286. rect.applyTransform(group.transform);
  41287. return rect.contain(x, y)
  41288. && !onIrrelevantElement(e, api, seriesModel);
  41289. });
  41290. if (seriesModel.coordinateSystem.type !== 'view') {
  41291. controller.disable();
  41292. return;
  41293. }
  41294. controller.enable(seriesModel.get('roam'));
  41295. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  41296. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  41297. controller
  41298. .off('pan')
  41299. .off('zoom')
  41300. .on('pan', function (dx, dy) {
  41301. updateViewOnPan(controllerHost, dx, dy);
  41302. api.dispatchAction({
  41303. seriesId: seriesModel.id,
  41304. type: 'graphRoam',
  41305. dx: dx,
  41306. dy: dy
  41307. });
  41308. })
  41309. .on('zoom', function (zoom, mouseX, mouseY) {
  41310. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  41311. api.dispatchAction({
  41312. seriesId: seriesModel.id,
  41313. type: 'graphRoam',
  41314. zoom: zoom,
  41315. originX: mouseX,
  41316. originY: mouseY
  41317. });
  41318. this._updateNodeAndLinkScale();
  41319. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41320. this._lineDraw.updateLayout();
  41321. }, this);
  41322. },
  41323. _updateNodeAndLinkScale: function () {
  41324. var seriesModel = this._model;
  41325. var data = seriesModel.getData();
  41326. var nodeScale = this._getNodeGlobalScale(seriesModel);
  41327. var invScale = [nodeScale, nodeScale];
  41328. data.eachItemGraphicEl(function (el, idx) {
  41329. el.attr('scale', invScale);
  41330. });
  41331. },
  41332. _getNodeGlobalScale: function (seriesModel) {
  41333. var coordSys = seriesModel.coordinateSystem;
  41334. if (coordSys.type !== 'view') {
  41335. return 1;
  41336. }
  41337. var nodeScaleRatio = this._nodeScaleRatio;
  41338. var groupScale = coordSys.scale;
  41339. var groupZoom = (groupScale && groupScale[0]) || 1;
  41340. // Scale node when zoom changes
  41341. var roamZoom = coordSys.getZoom();
  41342. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  41343. return nodeScale / groupZoom;
  41344. },
  41345. updateLayout: function (seriesModel) {
  41346. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41347. this._symbolDraw.updateLayout();
  41348. this._lineDraw.updateLayout();
  41349. },
  41350. remove: function (ecModel, api) {
  41351. this._symbolDraw && this._symbolDraw.remove();
  41352. this._lineDraw && this._lineDraw.remove();
  41353. }
  41354. });
  41355. var actionInfo = {
  41356. type: 'graphRoam',
  41357. event: 'graphRoam',
  41358. update: 'none'
  41359. };
  41360. /**
  41361. * @payload
  41362. * @property {string} name Series name
  41363. * @property {number} [dx]
  41364. * @property {number} [dy]
  41365. * @property {number} [zoom]
  41366. * @property {number} [originX]
  41367. * @property {number} [originY]
  41368. */
  41369. registerAction(actionInfo, function (payload, ecModel) {
  41370. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  41371. var coordSys = seriesModel.coordinateSystem;
  41372. var res = updateCenterAndZoom(coordSys, payload);
  41373. seriesModel.setCenter
  41374. && seriesModel.setCenter(res.center);
  41375. seriesModel.setZoom
  41376. && seriesModel.setZoom(res.zoom);
  41377. });
  41378. });
  41379. /**
  41380. * @payload
  41381. * @property {number} [seriesIndex]
  41382. * @property {string} [seriesId]
  41383. * @property {string} [seriesName]
  41384. * @property {number} [dataIndex]
  41385. */
  41386. registerAction({
  41387. type: 'focusNodeAdjacency',
  41388. event: 'focusNodeAdjacency',
  41389. update: 'series.graph:focusNodeAdjacency'
  41390. }, function () {});
  41391. /**
  41392. * @payload
  41393. * @property {number} [seriesIndex]
  41394. * @property {string} [seriesId]
  41395. * @property {string} [seriesName]
  41396. */
  41397. registerAction({
  41398. type: 'unfocusNodeAdjacency',
  41399. event: 'unfocusNodeAdjacency',
  41400. update: 'series.graph:unfocusNodeAdjacency'
  41401. }, function () {});
  41402. var categoryFilter = function (ecModel) {
  41403. var legendModels = ecModel.findComponents({
  41404. mainType: 'legend'
  41405. });
  41406. if (!legendModels || !legendModels.length) {
  41407. return;
  41408. }
  41409. ecModel.eachSeriesByType('graph', function (graphSeries) {
  41410. var categoriesData = graphSeries.getCategoriesData();
  41411. var graph = graphSeries.getGraph();
  41412. var data = graph.data;
  41413. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  41414. data.filterSelf(function (idx) {
  41415. var model = data.getItemModel(idx);
  41416. var category = model.getShallow('category');
  41417. if (category != null) {
  41418. if (typeof category === 'number') {
  41419. category = categoryNames[category];
  41420. }
  41421. // If in any legend component the status is not selected.
  41422. for (var i = 0; i < legendModels.length; i++) {
  41423. if (!legendModels[i].isSelected(category)) {
  41424. return false;
  41425. }
  41426. }
  41427. }
  41428. return true;
  41429. });
  41430. }, this);
  41431. };
  41432. var categoryVisual = function (ecModel) {
  41433. var paletteScope = {};
  41434. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41435. var categoriesData = seriesModel.getCategoriesData();
  41436. var data = seriesModel.getData();
  41437. var categoryNameIdxMap = {};
  41438. categoriesData.each(function (idx) {
  41439. var name = categoriesData.getName(idx);
  41440. // Add prefix to avoid conflict with Object.prototype.
  41441. categoryNameIdxMap['ec-' + name] = idx;
  41442. var itemModel = categoriesData.getItemModel(idx);
  41443. var color = itemModel.get('itemStyle.color')
  41444. || seriesModel.getColorFromPalette(name, paletteScope);
  41445. categoriesData.setItemVisual(idx, 'color', color);
  41446. });
  41447. // Assign category color to visual
  41448. if (categoriesData.count()) {
  41449. data.each(function (idx) {
  41450. var model = data.getItemModel(idx);
  41451. var category = model.getShallow('category');
  41452. if (category != null) {
  41453. if (typeof category === 'string') {
  41454. category = categoryNameIdxMap['ec-' + category];
  41455. }
  41456. if (!data.getItemVisual(idx, 'color', true)) {
  41457. data.setItemVisual(
  41458. idx, 'color',
  41459. categoriesData.getItemVisual(category, 'color')
  41460. );
  41461. }
  41462. }
  41463. });
  41464. }
  41465. });
  41466. };
  41467. function normalize$1(a) {
  41468. if (!(a instanceof Array)) {
  41469. a = [a, a];
  41470. }
  41471. return a;
  41472. }
  41473. var edgeVisual = function (ecModel) {
  41474. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41475. var graph = seriesModel.getGraph();
  41476. var edgeData = seriesModel.getEdgeData();
  41477. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  41478. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  41479. var colorQuery = 'lineStyle.color'.split('.');
  41480. var opacityQuery = 'lineStyle.opacity'.split('.');
  41481. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  41482. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  41483. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  41484. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  41485. edgeData.setVisual('color', seriesModel.get(colorQuery));
  41486. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  41487. edgeData.each(function (idx) {
  41488. var itemModel = edgeData.getItemModel(idx);
  41489. var edge = graph.getEdgeByIndex(idx);
  41490. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  41491. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  41492. // Edge visual must after node visual
  41493. var color = itemModel.get(colorQuery);
  41494. var opacity = itemModel.get(opacityQuery);
  41495. switch (color) {
  41496. case 'source':
  41497. color = edge.node1.getVisual('color');
  41498. break;
  41499. case 'target':
  41500. color = edge.node2.getVisual('color');
  41501. break;
  41502. }
  41503. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  41504. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  41505. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  41506. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  41507. edge.setVisual('color', color);
  41508. edge.setVisual('opacity', opacity);
  41509. });
  41510. });
  41511. };
  41512. function simpleLayout$1(seriesModel) {
  41513. var coordSys = seriesModel.coordinateSystem;
  41514. if (coordSys && coordSys.type !== 'view') {
  41515. return;
  41516. }
  41517. var graph = seriesModel.getGraph();
  41518. graph.eachNode(function (node) {
  41519. var model = node.getModel();
  41520. node.setLayout([+model.get('x'), +model.get('y')]);
  41521. });
  41522. simpleLayoutEdge(graph);
  41523. }
  41524. function simpleLayoutEdge(graph) {
  41525. graph.eachEdge(function (edge) {
  41526. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  41527. var p1 = clone$1(edge.node1.getLayout());
  41528. var p2 = clone$1(edge.node2.getLayout());
  41529. var points = [p1, p2];
  41530. if (+curveness) {
  41531. points.push([
  41532. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  41533. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  41534. ]);
  41535. }
  41536. edge.setLayout(points);
  41537. });
  41538. }
  41539. var simpleLayout = function (ecModel, api) {
  41540. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41541. var layout = seriesModel.get('layout');
  41542. var coordSys = seriesModel.coordinateSystem;
  41543. if (coordSys && coordSys.type !== 'view') {
  41544. var data = seriesModel.getData();
  41545. var dimensions = [];
  41546. each$1(coordSys.dimensions, function (coordDim) {
  41547. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  41548. });
  41549. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  41550. var value = [];
  41551. var hasValue = false;
  41552. for (var i = 0; i < dimensions.length; i++) {
  41553. var val = data.get(dimensions[i], dataIndex);
  41554. if (!isNaN(val)) {
  41555. hasValue = true;
  41556. }
  41557. value.push(val);
  41558. }
  41559. if (hasValue) {
  41560. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  41561. }
  41562. else {
  41563. // Also {Array.<number>}, not undefined to avoid if...else... statement
  41564. data.setItemLayout(dataIndex, [NaN, NaN]);
  41565. }
  41566. }
  41567. simpleLayoutEdge(data.graph);
  41568. }
  41569. else if (!layout || layout === 'none') {
  41570. simpleLayout$1(seriesModel);
  41571. }
  41572. });
  41573. };
  41574. function circularLayout$1(seriesModel) {
  41575. var coordSys = seriesModel.coordinateSystem;
  41576. if (coordSys && coordSys.type !== 'view') {
  41577. return;
  41578. }
  41579. var rect = coordSys.getBoundingRect();
  41580. var nodeData = seriesModel.getData();
  41581. var graph = nodeData.graph;
  41582. var angle = 0;
  41583. var sum = nodeData.getSum('value');
  41584. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  41585. var cx = rect.width / 2 + rect.x;
  41586. var cy = rect.height / 2 + rect.y;
  41587. var r = Math.min(rect.width, rect.height) / 2;
  41588. graph.eachNode(function (node) {
  41589. var value = node.getValue('value');
  41590. angle += unitAngle * (sum ? value : 1) / 2;
  41591. node.setLayout([
  41592. r * Math.cos(angle) + cx,
  41593. r * Math.sin(angle) + cy
  41594. ]);
  41595. angle += unitAngle * (sum ? value : 1) / 2;
  41596. });
  41597. nodeData.setLayout({
  41598. cx: cx,
  41599. cy: cy
  41600. });
  41601. graph.eachEdge(function (edge) {
  41602. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  41603. var p1 = clone$1(edge.node1.getLayout());
  41604. var p2 = clone$1(edge.node2.getLayout());
  41605. var cp1;
  41606. var x12 = (p1[0] + p2[0]) / 2;
  41607. var y12 = (p1[1] + p2[1]) / 2;
  41608. if (+curveness) {
  41609. curveness *= 3;
  41610. cp1 = [
  41611. cx * curveness + x12 * (1 - curveness),
  41612. cy * curveness + y12 * (1 - curveness)
  41613. ];
  41614. }
  41615. edge.setLayout([p1, p2, cp1]);
  41616. });
  41617. }
  41618. var circularLayout = function (ecModel) {
  41619. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41620. if (seriesModel.get('layout') === 'circular') {
  41621. circularLayout$1(seriesModel);
  41622. }
  41623. });
  41624. };
  41625. var scaleAndAdd$2 = scaleAndAdd;
  41626. // function adjacentNode(n, e) {
  41627. // return e.n1 === n ? e.n2 : e.n1;
  41628. // }
  41629. function forceLayout$1(nodes, edges, opts) {
  41630. var rect = opts.rect;
  41631. var width = rect.width;
  41632. var height = rect.height;
  41633. var center = [rect.x + width / 2, rect.y + height / 2];
  41634. // var scale = opts.scale || 1;
  41635. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  41636. // for (var i = 0; i < edges.length; i++) {
  41637. // var e = edges[i];
  41638. // var n1 = e.n1;
  41639. // var n2 = e.n2;
  41640. // n1.edges = n1.edges || [];
  41641. // n2.edges = n2.edges || [];
  41642. // n1.edges.push(e);
  41643. // n2.edges.push(e);
  41644. // }
  41645. // Init position
  41646. for (var i = 0; i < nodes.length; i++) {
  41647. var n = nodes[i];
  41648. if (!n.p) {
  41649. // Use the position from first adjecent node with defined position
  41650. // Or use a random position
  41651. // From d3
  41652. // if (n.edges) {
  41653. // var j = -1;
  41654. // while (++j < n.edges.length) {
  41655. // var e = n.edges[j];
  41656. // var other = adjacentNode(n, e);
  41657. // if (other.p) {
  41658. // n.p = vec2.clone(other.p);
  41659. // break;
  41660. // }
  41661. // }
  41662. // }
  41663. // if (!n.p) {
  41664. n.p = create(
  41665. width * (Math.random() - 0.5) + center[0],
  41666. height * (Math.random() - 0.5) + center[1]
  41667. );
  41668. // }
  41669. }
  41670. n.pp = clone$1(n.p);
  41671. n.edges = null;
  41672. }
  41673. // Formula in 'Graph Drawing by Force-directed Placement'
  41674. // var k = scale * Math.sqrt(width * height / nodes.length);
  41675. // var k2 = k * k;
  41676. var friction = 0.6;
  41677. return {
  41678. warmUp: function () {
  41679. friction = 0.5;
  41680. },
  41681. setFixed: function (idx) {
  41682. nodes[idx].fixed = true;
  41683. },
  41684. setUnfixed: function (idx) {
  41685. nodes[idx].fixed = false;
  41686. },
  41687. step: function (cb) {
  41688. var v12 = [];
  41689. var nLen = nodes.length;
  41690. for (var i = 0; i < edges.length; i++) {
  41691. var e = edges[i];
  41692. var n1 = e.n1;
  41693. var n2 = e.n2;
  41694. sub(v12, n2.p, n1.p);
  41695. var d = len(v12) - e.d;
  41696. var w = n2.w / (n1.w + n2.w);
  41697. if (isNaN(w)) {
  41698. w = 0;
  41699. }
  41700. normalize(v12, v12);
  41701. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  41702. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  41703. }
  41704. // Gravity
  41705. for (var i = 0; i < nLen; i++) {
  41706. var n = nodes[i];
  41707. if (!n.fixed) {
  41708. sub(v12, center, n.p);
  41709. // var d = vec2.len(v12);
  41710. // vec2.scale(v12, v12, 1 / d);
  41711. // var gravityFactor = gravity;
  41712. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  41713. }
  41714. }
  41715. // Repulsive
  41716. // PENDING
  41717. for (var i = 0; i < nLen; i++) {
  41718. var n1 = nodes[i];
  41719. for (var j = i + 1; j < nLen; j++) {
  41720. var n2 = nodes[j];
  41721. sub(v12, n2.p, n1.p);
  41722. var d = len(v12);
  41723. if (d === 0) {
  41724. // Random repulse
  41725. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  41726. d = 1;
  41727. }
  41728. var repFact = (n1.rep + n2.rep) / d / d;
  41729. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  41730. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  41731. }
  41732. }
  41733. var v = [];
  41734. for (var i = 0; i < nLen; i++) {
  41735. var n = nodes[i];
  41736. if (!n.fixed) {
  41737. sub(v, n.p, n.pp);
  41738. scaleAndAdd$2(n.p, n.p, v, friction);
  41739. copy(n.pp, n.p);
  41740. }
  41741. }
  41742. friction = friction * 0.992;
  41743. cb && cb(nodes, edges, friction < 0.01);
  41744. }
  41745. };
  41746. }
  41747. var forceLayout = function (ecModel) {
  41748. ecModel.eachSeriesByType('graph', function (graphSeries) {
  41749. var coordSys = graphSeries.coordinateSystem;
  41750. if (coordSys && coordSys.type !== 'view') {
  41751. return;
  41752. }
  41753. if (graphSeries.get('layout') === 'force') {
  41754. var preservedPoints = graphSeries.preservedPoints || {};
  41755. var graph = graphSeries.getGraph();
  41756. var nodeData = graph.data;
  41757. var edgeData = graph.edgeData;
  41758. var forceModel = graphSeries.getModel('force');
  41759. var initLayout = forceModel.get('initLayout');
  41760. if (graphSeries.preservedPoints) {
  41761. nodeData.each(function (idx) {
  41762. var id = nodeData.getId(idx);
  41763. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  41764. });
  41765. }
  41766. else if (!initLayout || initLayout === 'none') {
  41767. simpleLayout$1(graphSeries);
  41768. }
  41769. else if (initLayout === 'circular') {
  41770. circularLayout$1(graphSeries);
  41771. }
  41772. var nodeDataExtent = nodeData.getDataExtent('value');
  41773. var edgeDataExtent = edgeData.getDataExtent('value');
  41774. // var edgeDataExtent = edgeData.getDataExtent('value');
  41775. var repulsion = forceModel.get('repulsion');
  41776. var edgeLength = forceModel.get('edgeLength');
  41777. if (!isArray(repulsion)) {
  41778. repulsion = [repulsion, repulsion];
  41779. }
  41780. if (!isArray(edgeLength)) {
  41781. edgeLength = [edgeLength, edgeLength];
  41782. }
  41783. // Larger value has smaller length
  41784. edgeLength = [edgeLength[1], edgeLength[0]];
  41785. var nodes = nodeData.mapArray('value', function (value, idx) {
  41786. var point = nodeData.getItemLayout(idx);
  41787. var rep = linearMap(value, nodeDataExtent, repulsion);
  41788. if (isNaN(rep)) {
  41789. rep = (repulsion[0] + repulsion[1]) / 2;
  41790. }
  41791. return {
  41792. w: rep,
  41793. rep: rep,
  41794. fixed: nodeData.getItemModel(idx).get('fixed'),
  41795. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  41796. };
  41797. });
  41798. var edges = edgeData.mapArray('value', function (value, idx) {
  41799. var edge = graph.getEdgeByIndex(idx);
  41800. var d = linearMap(value, edgeDataExtent, edgeLength);
  41801. if (isNaN(d)) {
  41802. d = (edgeLength[0] + edgeLength[1]) / 2;
  41803. }
  41804. return {
  41805. n1: nodes[edge.node1.dataIndex],
  41806. n2: nodes[edge.node2.dataIndex],
  41807. d: d,
  41808. curveness: edge.getModel().get('lineStyle.curveness') || 0
  41809. };
  41810. });
  41811. var coordSys = graphSeries.coordinateSystem;
  41812. var rect = coordSys.getBoundingRect();
  41813. var forceInstance = forceLayout$1(nodes, edges, {
  41814. rect: rect,
  41815. gravity: forceModel.get('gravity')
  41816. });
  41817. var oldStep = forceInstance.step;
  41818. forceInstance.step = function (cb) {
  41819. for (var i = 0, l = nodes.length; i < l; i++) {
  41820. if (nodes[i].fixed) {
  41821. // Write back to layout instance
  41822. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  41823. }
  41824. }
  41825. oldStep(function (nodes, edges, stopped) {
  41826. for (var i = 0, l = nodes.length; i < l; i++) {
  41827. if (!nodes[i].fixed) {
  41828. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  41829. }
  41830. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  41831. }
  41832. for (var i = 0, l = edges.length; i < l; i++) {
  41833. var e = edges[i];
  41834. var edge = graph.getEdgeByIndex(i);
  41835. var p1 = e.n1.p;
  41836. var p2 = e.n2.p;
  41837. var points = edge.getLayout();
  41838. points = points ? points.slice() : [];
  41839. points[0] = points[0] || [];
  41840. points[1] = points[1] || [];
  41841. copy(points[0], p1);
  41842. copy(points[1], p2);
  41843. if (+e.curveness) {
  41844. points[2] = [
  41845. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  41846. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  41847. ];
  41848. }
  41849. edge.setLayout(points);
  41850. }
  41851. // Update layout
  41852. cb && cb(stopped);
  41853. });
  41854. };
  41855. graphSeries.forceLayout = forceInstance;
  41856. graphSeries.preservedPoints = preservedPoints;
  41857. // Step to get the layout
  41858. forceInstance.step();
  41859. }
  41860. else {
  41861. // Remove prev injected forceLayout instance
  41862. graphSeries.forceLayout = null;
  41863. }
  41864. });
  41865. };
  41866. // FIXME Where to create the simple view coordinate system
  41867. function getViewRect$1(seriesModel, api, aspect) {
  41868. var option = seriesModel.getBoxLayoutParams();
  41869. option.aspect = aspect;
  41870. return getLayoutRect(option, {
  41871. width: api.getWidth(),
  41872. height: api.getHeight()
  41873. });
  41874. }
  41875. var createView = function (ecModel, api) {
  41876. var viewList = [];
  41877. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41878. var coordSysType = seriesModel.get('coordinateSystem');
  41879. if (!coordSysType || coordSysType === 'view') {
  41880. var data = seriesModel.getData();
  41881. var positions = data.mapArray(function (idx) {
  41882. var itemModel = data.getItemModel(idx);
  41883. return [+itemModel.get('x'), +itemModel.get('y')];
  41884. });
  41885. var min = [];
  41886. var max = [];
  41887. fromPoints(positions, min, max);
  41888. // If width or height is 0
  41889. if (max[0] - min[0] === 0) {
  41890. max[0] += 1;
  41891. min[0] -= 1;
  41892. }
  41893. if (max[1] - min[1] === 0) {
  41894. max[1] += 1;
  41895. min[1] -= 1;
  41896. }
  41897. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  41898. // FIXME If get view rect after data processed?
  41899. var viewRect = getViewRect$1(seriesModel, api, aspect);
  41900. // Position may be NaN, use view rect instead
  41901. if (isNaN(aspect)) {
  41902. min = [viewRect.x, viewRect.y];
  41903. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  41904. }
  41905. var bbWidth = max[0] - min[0];
  41906. var bbHeight = max[1] - min[1];
  41907. var viewWidth = viewRect.width;
  41908. var viewHeight = viewRect.height;
  41909. var viewCoordSys = seriesModel.coordinateSystem = new View();
  41910. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  41911. viewCoordSys.setBoundingRect(
  41912. min[0], min[1], bbWidth, bbHeight
  41913. );
  41914. viewCoordSys.setViewRect(
  41915. viewRect.x, viewRect.y, viewWidth, viewHeight
  41916. );
  41917. // Update roam info
  41918. viewCoordSys.setCenter(seriesModel.get('center'));
  41919. viewCoordSys.setZoom(seriesModel.get('zoom'));
  41920. viewList.push(viewCoordSys);
  41921. }
  41922. });
  41923. return viewList;
  41924. };
  41925. registerProcessor(categoryFilter);
  41926. registerVisual(visualSymbol('graph', 'circle', null));
  41927. registerVisual(categoryVisual);
  41928. registerVisual(edgeVisual);
  41929. registerLayout(simpleLayout);
  41930. registerLayout(circularLayout);
  41931. registerLayout(forceLayout);
  41932. // Graph view coordinate system
  41933. registerCoordinateSystem('graphView', {
  41934. create: createView
  41935. });
  41936. var GaugeSeries = SeriesModel.extend({
  41937. type: 'series.gauge',
  41938. getInitialData: function (option, ecModel) {
  41939. var dataOpt = option.data || [];
  41940. if (!isArray(dataOpt)) {
  41941. dataOpt = [dataOpt];
  41942. }
  41943. option.data = dataOpt;
  41944. return createListSimply(this, ['value']);
  41945. },
  41946. defaultOption: {
  41947. zlevel: 0,
  41948. z: 2,
  41949. // 默认全局居中
  41950. center: ['50%', '50%'],
  41951. legendHoverLink: true,
  41952. radius: '75%',
  41953. startAngle: 225,
  41954. endAngle: -45,
  41955. clockwise: true,
  41956. // 最小值
  41957. min: 0,
  41958. // 最大值
  41959. max: 100,
  41960. // 分割段数,默认为10
  41961. splitNumber: 10,
  41962. // 坐标轴线
  41963. axisLine: {
  41964. // 默认显示,属性show控制显示与否
  41965. show: true,
  41966. lineStyle: { // 属性lineStyle控制线条样式
  41967. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  41968. width: 30
  41969. }
  41970. },
  41971. // 分隔线
  41972. splitLine: {
  41973. // 默认显示,属性show控制显示与否
  41974. show: true,
  41975. // 属性length控制线长
  41976. length: 30,
  41977. // 属性lineStyle(详见lineStyle)控制线条样式
  41978. lineStyle: {
  41979. color: '#eee',
  41980. width: 2,
  41981. type: 'solid'
  41982. }
  41983. },
  41984. // 坐标轴小标记
  41985. axisTick: {
  41986. // 属性show控制显示与否,默认不显示
  41987. show: true,
  41988. // 每份split细分多少段
  41989. splitNumber: 5,
  41990. // 属性length控制线长
  41991. length: 8,
  41992. // 属性lineStyle控制线条样式
  41993. lineStyle: {
  41994. color: '#eee',
  41995. width: 1,
  41996. type: 'solid'
  41997. }
  41998. },
  41999. axisLabel: {
  42000. show: true,
  42001. distance: 5,
  42002. // formatter: null,
  42003. color: 'auto'
  42004. },
  42005. pointer: {
  42006. show: true,
  42007. length: '80%',
  42008. width: 8
  42009. },
  42010. itemStyle: {
  42011. color: 'auto'
  42012. },
  42013. title: {
  42014. show: true,
  42015. // x, y,单位px
  42016. offsetCenter: [0, '-40%'],
  42017. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  42018. color: '#333',
  42019. fontSize: 15
  42020. },
  42021. detail: {
  42022. show: true,
  42023. backgroundColor: 'rgba(0,0,0,0)',
  42024. borderWidth: 0,
  42025. borderColor: '#ccc',
  42026. width: 100,
  42027. height: null, // self-adaption
  42028. padding: [5, 10],
  42029. // x, y,单位px
  42030. offsetCenter: [0, '40%'],
  42031. // formatter: null,
  42032. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  42033. color: 'auto',
  42034. fontSize: 30
  42035. }
  42036. }
  42037. });
  42038. var PointerPath = Path.extend({
  42039. type: 'echartsGaugePointer',
  42040. shape: {
  42041. angle: 0,
  42042. width: 10,
  42043. r: 10,
  42044. x: 0,
  42045. y: 0
  42046. },
  42047. buildPath: function (ctx, shape) {
  42048. var mathCos = Math.cos;
  42049. var mathSin = Math.sin;
  42050. var r = shape.r;
  42051. var width = shape.width;
  42052. var angle = shape.angle;
  42053. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  42054. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  42055. angle = shape.angle - Math.PI / 2;
  42056. ctx.moveTo(x, y);
  42057. ctx.lineTo(
  42058. shape.x + mathCos(angle) * width,
  42059. shape.y + mathSin(angle) * width
  42060. );
  42061. ctx.lineTo(
  42062. shape.x + mathCos(shape.angle) * r,
  42063. shape.y + mathSin(shape.angle) * r
  42064. );
  42065. ctx.lineTo(
  42066. shape.x - mathCos(angle) * width,
  42067. shape.y - mathSin(angle) * width
  42068. );
  42069. ctx.lineTo(x, y);
  42070. return;
  42071. }
  42072. });
  42073. function parsePosition(seriesModel, api) {
  42074. var center = seriesModel.get('center');
  42075. var width = api.getWidth();
  42076. var height = api.getHeight();
  42077. var size = Math.min(width, height);
  42078. var cx = parsePercent$1(center[0], api.getWidth());
  42079. var cy = parsePercent$1(center[1], api.getHeight());
  42080. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  42081. return {
  42082. cx: cx,
  42083. cy: cy,
  42084. r: r
  42085. };
  42086. }
  42087. function formatLabel(label, labelFormatter) {
  42088. if (labelFormatter) {
  42089. if (typeof labelFormatter === 'string') {
  42090. label = labelFormatter.replace('{value}', label != null ? label : '');
  42091. }
  42092. else if (typeof labelFormatter === 'function') {
  42093. label = labelFormatter(label);
  42094. }
  42095. }
  42096. return label;
  42097. }
  42098. var PI2$5 = Math.PI * 2;
  42099. var GaugeView = Chart.extend({
  42100. type: 'gauge',
  42101. render: function (seriesModel, ecModel, api) {
  42102. this.group.removeAll();
  42103. var colorList = seriesModel.get('axisLine.lineStyle.color');
  42104. var posInfo = parsePosition(seriesModel, api);
  42105. this._renderMain(
  42106. seriesModel, ecModel, api, colorList, posInfo
  42107. );
  42108. },
  42109. dispose: function () {},
  42110. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  42111. var group = this.group;
  42112. var axisLineModel = seriesModel.getModel('axisLine');
  42113. var lineStyleModel = axisLineModel.getModel('lineStyle');
  42114. var clockwise = seriesModel.get('clockwise');
  42115. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  42116. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  42117. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  42118. var prevEndAngle = startAngle;
  42119. var axisLineWidth = lineStyleModel.get('width');
  42120. for (var i = 0; i < colorList.length; i++) {
  42121. // Clamp
  42122. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  42123. var endAngle = startAngle + angleRangeSpan * percent;
  42124. var sector = new Sector({
  42125. shape: {
  42126. startAngle: prevEndAngle,
  42127. endAngle: endAngle,
  42128. cx: posInfo.cx,
  42129. cy: posInfo.cy,
  42130. clockwise: clockwise,
  42131. r0: posInfo.r - axisLineWidth,
  42132. r: posInfo.r
  42133. },
  42134. silent: true
  42135. });
  42136. sector.setStyle({
  42137. fill: colorList[i][1]
  42138. });
  42139. sector.setStyle(lineStyleModel.getLineStyle(
  42140. // Because we use sector to simulate arc
  42141. // so the properties for stroking are useless
  42142. ['color', 'borderWidth', 'borderColor']
  42143. ));
  42144. group.add(sector);
  42145. prevEndAngle = endAngle;
  42146. }
  42147. var getColor = function (percent) {
  42148. // Less than 0
  42149. if (percent <= 0) {
  42150. return colorList[0][1];
  42151. }
  42152. for (var i = 0; i < colorList.length; i++) {
  42153. if (colorList[i][0] >= percent
  42154. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  42155. ) {
  42156. return colorList[i][1];
  42157. }
  42158. }
  42159. // More than 1
  42160. return colorList[i - 1][1];
  42161. };
  42162. if (!clockwise) {
  42163. var tmp = startAngle;
  42164. startAngle = endAngle;
  42165. endAngle = tmp;
  42166. }
  42167. this._renderTicks(
  42168. seriesModel, ecModel, api, getColor, posInfo,
  42169. startAngle, endAngle, clockwise
  42170. );
  42171. this._renderPointer(
  42172. seriesModel, ecModel, api, getColor, posInfo,
  42173. startAngle, endAngle, clockwise
  42174. );
  42175. this._renderTitle(
  42176. seriesModel, ecModel, api, getColor, posInfo
  42177. );
  42178. this._renderDetail(
  42179. seriesModel, ecModel, api, getColor, posInfo
  42180. );
  42181. },
  42182. _renderTicks: function (
  42183. seriesModel, ecModel, api, getColor, posInfo,
  42184. startAngle, endAngle, clockwise
  42185. ) {
  42186. var group = this.group;
  42187. var cx = posInfo.cx;
  42188. var cy = posInfo.cy;
  42189. var r = posInfo.r;
  42190. var minVal = +seriesModel.get('min');
  42191. var maxVal = +seriesModel.get('max');
  42192. var splitLineModel = seriesModel.getModel('splitLine');
  42193. var tickModel = seriesModel.getModel('axisTick');
  42194. var labelModel = seriesModel.getModel('axisLabel');
  42195. var splitNumber = seriesModel.get('splitNumber');
  42196. var subSplitNumber = tickModel.get('splitNumber');
  42197. var splitLineLen = parsePercent$1(
  42198. splitLineModel.get('length'), r
  42199. );
  42200. var tickLen = parsePercent$1(
  42201. tickModel.get('length'), r
  42202. );
  42203. var angle = startAngle;
  42204. var step = (endAngle - startAngle) / splitNumber;
  42205. var subStep = step / subSplitNumber;
  42206. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  42207. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  42208. for (var i = 0; i <= splitNumber; i++) {
  42209. var unitX = Math.cos(angle);
  42210. var unitY = Math.sin(angle);
  42211. // Split line
  42212. if (splitLineModel.get('show')) {
  42213. var splitLine = new Line({
  42214. shape: {
  42215. x1: unitX * r + cx,
  42216. y1: unitY * r + cy,
  42217. x2: unitX * (r - splitLineLen) + cx,
  42218. y2: unitY * (r - splitLineLen) + cy
  42219. },
  42220. style: splitLineStyle,
  42221. silent: true
  42222. });
  42223. if (splitLineStyle.stroke === 'auto') {
  42224. splitLine.setStyle({
  42225. stroke: getColor(i / splitNumber)
  42226. });
  42227. }
  42228. group.add(splitLine);
  42229. }
  42230. // Label
  42231. if (labelModel.get('show')) {
  42232. var label = formatLabel(
  42233. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  42234. labelModel.get('formatter')
  42235. );
  42236. var distance = labelModel.get('distance');
  42237. var autoColor = getColor(i / splitNumber);
  42238. group.add(new Text({
  42239. style: setTextStyle({}, labelModel, {
  42240. text: label,
  42241. x: unitX * (r - splitLineLen - distance) + cx,
  42242. y: unitY * (r - splitLineLen - distance) + cy,
  42243. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  42244. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  42245. }, {autoColor: autoColor}),
  42246. silent: true
  42247. }));
  42248. }
  42249. // Axis tick
  42250. if (tickModel.get('show') && i !== splitNumber) {
  42251. for (var j = 0; j <= subSplitNumber; j++) {
  42252. var unitX = Math.cos(angle);
  42253. var unitY = Math.sin(angle);
  42254. var tickLine = new Line({
  42255. shape: {
  42256. x1: unitX * r + cx,
  42257. y1: unitY * r + cy,
  42258. x2: unitX * (r - tickLen) + cx,
  42259. y2: unitY * (r - tickLen) + cy
  42260. },
  42261. silent: true,
  42262. style: tickLineStyle
  42263. });
  42264. if (tickLineStyle.stroke === 'auto') {
  42265. tickLine.setStyle({
  42266. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  42267. });
  42268. }
  42269. group.add(tickLine);
  42270. angle += subStep;
  42271. }
  42272. angle -= subStep;
  42273. }
  42274. else {
  42275. angle += step;
  42276. }
  42277. }
  42278. },
  42279. _renderPointer: function (
  42280. seriesModel, ecModel, api, getColor, posInfo,
  42281. startAngle, endAngle, clockwise
  42282. ) {
  42283. var group = this.group;
  42284. var oldData = this._data;
  42285. if (!seriesModel.get('pointer.show')) {
  42286. // Remove old element
  42287. oldData && oldData.eachItemGraphicEl(function (el) {
  42288. group.remove(el);
  42289. });
  42290. return;
  42291. }
  42292. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  42293. var angleExtent = [startAngle, endAngle];
  42294. var data = seriesModel.getData();
  42295. var valueDim = data.mapDimension('value');
  42296. data.diff(oldData)
  42297. .add(function (idx) {
  42298. var pointer = new PointerPath({
  42299. shape: {
  42300. angle: startAngle
  42301. }
  42302. });
  42303. initProps(pointer, {
  42304. shape: {
  42305. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  42306. }
  42307. }, seriesModel);
  42308. group.add(pointer);
  42309. data.setItemGraphicEl(idx, pointer);
  42310. })
  42311. .update(function (newIdx, oldIdx) {
  42312. var pointer = oldData.getItemGraphicEl(oldIdx);
  42313. updateProps(pointer, {
  42314. shape: {
  42315. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  42316. }
  42317. }, seriesModel);
  42318. group.add(pointer);
  42319. data.setItemGraphicEl(newIdx, pointer);
  42320. })
  42321. .remove(function (idx) {
  42322. var pointer = oldData.getItemGraphicEl(idx);
  42323. group.remove(pointer);
  42324. })
  42325. .execute();
  42326. data.eachItemGraphicEl(function (pointer, idx) {
  42327. var itemModel = data.getItemModel(idx);
  42328. var pointerModel = itemModel.getModel('pointer');
  42329. pointer.setShape({
  42330. x: posInfo.cx,
  42331. y: posInfo.cy,
  42332. width: parsePercent$1(
  42333. pointerModel.get('width'), posInfo.r
  42334. ),
  42335. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  42336. });
  42337. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  42338. if (pointer.style.fill === 'auto') {
  42339. pointer.setStyle('fill', getColor(
  42340. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  42341. ));
  42342. }
  42343. setHoverStyle(
  42344. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  42345. );
  42346. });
  42347. this._data = data;
  42348. },
  42349. _renderTitle: function (
  42350. seriesModel, ecModel, api, getColor, posInfo
  42351. ) {
  42352. var data = seriesModel.getData();
  42353. var valueDim = data.mapDimension('value');
  42354. var titleModel = seriesModel.getModel('title');
  42355. if (titleModel.get('show')) {
  42356. var offsetCenter = titleModel.get('offsetCenter');
  42357. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  42358. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  42359. var minVal = +seriesModel.get('min');
  42360. var maxVal = +seriesModel.get('max');
  42361. var value = seriesModel.getData().get(valueDim, 0);
  42362. var autoColor = getColor(
  42363. linearMap(value, [minVal, maxVal], [0, 1], true)
  42364. );
  42365. this.group.add(new Text({
  42366. silent: true,
  42367. style: setTextStyle({}, titleModel, {
  42368. x: x,
  42369. y: y,
  42370. // FIXME First data name ?
  42371. text: data.getName(0),
  42372. textAlign: 'center',
  42373. textVerticalAlign: 'middle'
  42374. }, {autoColor: autoColor, forceRich: true})
  42375. }));
  42376. }
  42377. },
  42378. _renderDetail: function (
  42379. seriesModel, ecModel, api, getColor, posInfo
  42380. ) {
  42381. var detailModel = seriesModel.getModel('detail');
  42382. var minVal = +seriesModel.get('min');
  42383. var maxVal = +seriesModel.get('max');
  42384. if (detailModel.get('show')) {
  42385. var offsetCenter = detailModel.get('offsetCenter');
  42386. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  42387. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  42388. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  42389. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  42390. var data = seriesModel.getData();
  42391. var value = data.get(data.mapDimension('value'), 0);
  42392. var autoColor = getColor(
  42393. linearMap(value, [minVal, maxVal], [0, 1], true)
  42394. );
  42395. this.group.add(new Text({
  42396. silent: true,
  42397. style: setTextStyle({}, detailModel, {
  42398. x: x,
  42399. y: y,
  42400. text: formatLabel(
  42401. // FIXME First data name ?
  42402. value, detailModel.get('formatter')
  42403. ),
  42404. textWidth: isNaN(width) ? null : width,
  42405. textHeight: isNaN(height) ? null : height,
  42406. textAlign: 'center',
  42407. textVerticalAlign: 'middle'
  42408. }, {autoColor: autoColor, forceRich: true})
  42409. }));
  42410. }
  42411. }
  42412. });
  42413. var FunnelSeries = extendSeriesModel({
  42414. type: 'series.funnel',
  42415. init: function (option) {
  42416. FunnelSeries.superApply(this, 'init', arguments);
  42417. // Enable legend selection for each data item
  42418. // Use a function instead of direct access because data reference may changed
  42419. this.legendDataProvider = function () {
  42420. return this.getRawData();
  42421. };
  42422. // Extend labelLine emphasis
  42423. this._defaultLabelLine(option);
  42424. },
  42425. getInitialData: function (option, ecModel) {
  42426. return createListSimply(this, ['value']);
  42427. },
  42428. _defaultLabelLine: function (option) {
  42429. // Extend labelLine emphasis
  42430. defaultEmphasis(option, 'labelLine', ['show']);
  42431. var labelLineNormalOpt = option.labelLine;
  42432. var labelLineEmphasisOpt = option.emphasis.labelLine;
  42433. // Not show label line if `label.normal.show = false`
  42434. labelLineNormalOpt.show = labelLineNormalOpt.show
  42435. && option.label.show;
  42436. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  42437. && option.emphasis.label.show;
  42438. },
  42439. // Overwrite
  42440. getDataParams: function (dataIndex) {
  42441. var data = this.getData();
  42442. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  42443. var valueDim = data.mapDimension('value');
  42444. var sum = data.getSum(valueDim);
  42445. // Percent is 0 if sum is 0
  42446. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  42447. params.$vars.push('percent');
  42448. return params;
  42449. },
  42450. defaultOption: {
  42451. zlevel: 0, // 一级层叠
  42452. z: 2, // 二级层叠
  42453. legendHoverLink: true,
  42454. left: 80,
  42455. top: 60,
  42456. right: 80,
  42457. bottom: 60,
  42458. // width: {totalWidth} - left - right,
  42459. // height: {totalHeight} - top - bottom,
  42460. // 默认取数据最小最大值
  42461. // min: 0,
  42462. // max: 100,
  42463. minSize: '0%',
  42464. maxSize: '100%',
  42465. sort: 'descending', // 'ascending', 'descending'
  42466. gap: 0,
  42467. funnelAlign: 'center',
  42468. label: {
  42469. show: true,
  42470. position: 'outer'
  42471. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  42472. },
  42473. labelLine: {
  42474. show: true,
  42475. length: 20,
  42476. lineStyle: {
  42477. // color: 各异,
  42478. width: 1,
  42479. type: 'solid'
  42480. }
  42481. },
  42482. itemStyle: {
  42483. // color: 各异,
  42484. borderColor: '#fff',
  42485. borderWidth: 1
  42486. },
  42487. emphasis: {
  42488. label: {
  42489. show: true
  42490. }
  42491. }
  42492. }
  42493. });
  42494. /**
  42495. * Piece of pie including Sector, Label, LabelLine
  42496. * @constructor
  42497. * @extends {module:zrender/graphic/Group}
  42498. */
  42499. function FunnelPiece(data, idx) {
  42500. Group.call(this);
  42501. var polygon = new Polygon();
  42502. var labelLine = new Polyline();
  42503. var text = new Text();
  42504. this.add(polygon);
  42505. this.add(labelLine);
  42506. this.add(text);
  42507. this.updateData(data, idx, true);
  42508. // Hover to change label and labelLine
  42509. function onEmphasis() {
  42510. labelLine.ignore = labelLine.hoverIgnore;
  42511. text.ignore = text.hoverIgnore;
  42512. }
  42513. function onNormal() {
  42514. labelLine.ignore = labelLine.normalIgnore;
  42515. text.ignore = text.normalIgnore;
  42516. }
  42517. this.on('emphasis', onEmphasis)
  42518. .on('normal', onNormal)
  42519. .on('mouseover', onEmphasis)
  42520. .on('mouseout', onNormal);
  42521. }
  42522. var funnelPieceProto = FunnelPiece.prototype;
  42523. var opacityAccessPath = ['itemStyle', 'opacity'];
  42524. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  42525. var polygon = this.childAt(0);
  42526. var seriesModel = data.hostModel;
  42527. var itemModel = data.getItemModel(idx);
  42528. var layout = data.getItemLayout(idx);
  42529. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  42530. opacity = opacity == null ? 1 : opacity;
  42531. // Reset style
  42532. polygon.useStyle({});
  42533. if (firstCreate) {
  42534. polygon.setShape({
  42535. points: layout.points
  42536. });
  42537. polygon.setStyle({ opacity : 0 });
  42538. initProps(polygon, {
  42539. style: {
  42540. opacity: opacity
  42541. }
  42542. }, seriesModel, idx);
  42543. }
  42544. else {
  42545. updateProps(polygon, {
  42546. style: {
  42547. opacity: opacity
  42548. },
  42549. shape: {
  42550. points: layout.points
  42551. }
  42552. }, seriesModel, idx);
  42553. }
  42554. // Update common style
  42555. var itemStyleModel = itemModel.getModel('itemStyle');
  42556. var visualColor = data.getItemVisual(idx, 'color');
  42557. polygon.setStyle(
  42558. defaults(
  42559. {
  42560. lineJoin: 'round',
  42561. fill: visualColor
  42562. },
  42563. itemStyleModel.getItemStyle(['opacity'])
  42564. )
  42565. );
  42566. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  42567. this._updateLabel(data, idx);
  42568. setHoverStyle(this);
  42569. };
  42570. funnelPieceProto._updateLabel = function (data, idx) {
  42571. var labelLine = this.childAt(1);
  42572. var labelText = this.childAt(2);
  42573. var seriesModel = data.hostModel;
  42574. var itemModel = data.getItemModel(idx);
  42575. var layout = data.getItemLayout(idx);
  42576. var labelLayout = layout.label;
  42577. var visualColor = data.getItemVisual(idx, 'color');
  42578. updateProps(labelLine, {
  42579. shape: {
  42580. points: labelLayout.linePoints || labelLayout.linePoints
  42581. }
  42582. }, seriesModel, idx);
  42583. updateProps(labelText, {
  42584. style: {
  42585. x: labelLayout.x,
  42586. y: labelLayout.y
  42587. }
  42588. }, seriesModel, idx);
  42589. labelText.attr({
  42590. rotation: labelLayout.rotation,
  42591. origin: [labelLayout.x, labelLayout.y],
  42592. z2: 10
  42593. });
  42594. var labelModel = itemModel.getModel('label');
  42595. var labelHoverModel = itemModel.getModel('emphasis.label');
  42596. var labelLineModel = itemModel.getModel('labelLine');
  42597. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  42598. var visualColor = data.getItemVisual(idx, 'color');
  42599. setLabelStyle(
  42600. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  42601. {
  42602. labelFetcher: data.hostModel,
  42603. labelDataIndex: idx,
  42604. defaultText: data.getName(idx),
  42605. autoColor: visualColor,
  42606. useInsideStyle: !!labelLayout.inside
  42607. },
  42608. {
  42609. textAlign: labelLayout.textAlign,
  42610. textVerticalAlign: labelLayout.verticalAlign
  42611. }
  42612. );
  42613. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  42614. labelText.hoverIgnore = !labelHoverModel.get('show');
  42615. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  42616. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  42617. // Default use item visual color
  42618. labelLine.setStyle({
  42619. stroke: visualColor
  42620. });
  42621. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  42622. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  42623. };
  42624. inherits(FunnelPiece, Group);
  42625. var FunnelView = Chart.extend({
  42626. type: 'funnel',
  42627. render: function (seriesModel, ecModel, api) {
  42628. var data = seriesModel.getData();
  42629. var oldData = this._data;
  42630. var group = this.group;
  42631. data.diff(oldData)
  42632. .add(function (idx) {
  42633. var funnelPiece = new FunnelPiece(data, idx);
  42634. data.setItemGraphicEl(idx, funnelPiece);
  42635. group.add(funnelPiece);
  42636. })
  42637. .update(function (newIdx, oldIdx) {
  42638. var piePiece = oldData.getItemGraphicEl(oldIdx);
  42639. piePiece.updateData(data, newIdx);
  42640. group.add(piePiece);
  42641. data.setItemGraphicEl(newIdx, piePiece);
  42642. })
  42643. .remove(function (idx) {
  42644. var piePiece = oldData.getItemGraphicEl(idx);
  42645. group.remove(piePiece);
  42646. })
  42647. .execute();
  42648. this._data = data;
  42649. },
  42650. remove: function () {
  42651. this.group.removeAll();
  42652. this._data = null;
  42653. },
  42654. dispose: function () {}
  42655. });
  42656. function getViewRect$2(seriesModel, api) {
  42657. return getLayoutRect(
  42658. seriesModel.getBoxLayoutParams(), {
  42659. width: api.getWidth(),
  42660. height: api.getHeight()
  42661. }
  42662. );
  42663. }
  42664. function getSortedIndices(data, sort) {
  42665. var valueDim = data.mapDimension('value');
  42666. var valueArr = data.mapArray(valueDim, function (val) {
  42667. return val;
  42668. });
  42669. var indices = [];
  42670. var isAscending = sort === 'ascending';
  42671. for (var i = 0, len = data.count(); i < len; i++) {
  42672. indices[i] = i;
  42673. }
  42674. // Add custom sortable function & none sortable opetion by "options.sort"
  42675. if (typeof sort === 'function') {
  42676. indices.sort(sort);
  42677. } else if (sort !== 'none') {
  42678. indices.sort(function (a, b) {
  42679. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  42680. });
  42681. }
  42682. return indices;
  42683. }
  42684. function labelLayout$1(data) {
  42685. data.each(function (idx) {
  42686. var itemModel = data.getItemModel(idx);
  42687. var labelModel = itemModel.getModel('label');
  42688. var labelPosition = labelModel.get('position');
  42689. var labelLineModel = itemModel.getModel('labelLine');
  42690. var layout = data.getItemLayout(idx);
  42691. var points = layout.points;
  42692. var isLabelInside = labelPosition === 'inner'
  42693. || labelPosition === 'inside' || labelPosition === 'center';
  42694. var textAlign;
  42695. var textX;
  42696. var textY;
  42697. var linePoints;
  42698. if (isLabelInside) {
  42699. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  42700. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  42701. textAlign = 'center';
  42702. linePoints = [
  42703. [textX, textY], [textX, textY]
  42704. ];
  42705. }
  42706. else {
  42707. var x1;
  42708. var y1;
  42709. var x2;
  42710. var labelLineLen = labelLineModel.get('length');
  42711. if (labelPosition === 'left') {
  42712. // Left side
  42713. x1 = (points[3][0] + points[0][0]) / 2;
  42714. y1 = (points[3][1] + points[0][1]) / 2;
  42715. x2 = x1 - labelLineLen;
  42716. textX = x2 - 5;
  42717. textAlign = 'right';
  42718. }
  42719. else {
  42720. // Right side
  42721. x1 = (points[1][0] + points[2][0]) / 2;
  42722. y1 = (points[1][1] + points[2][1]) / 2;
  42723. x2 = x1 + labelLineLen;
  42724. textX = x2 + 5;
  42725. textAlign = 'left';
  42726. }
  42727. var y2 = y1;
  42728. linePoints = [[x1, y1], [x2, y2]];
  42729. textY = y2;
  42730. }
  42731. layout.label = {
  42732. linePoints: linePoints,
  42733. x: textX,
  42734. y: textY,
  42735. verticalAlign: 'middle',
  42736. textAlign: textAlign,
  42737. inside: isLabelInside
  42738. };
  42739. });
  42740. }
  42741. var funnelLayout = function (ecModel, api, payload) {
  42742. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  42743. var data = seriesModel.getData();
  42744. var valueDim = data.mapDimension('value');
  42745. var sort = seriesModel.get('sort');
  42746. var viewRect = getViewRect$2(seriesModel, api);
  42747. var indices = getSortedIndices(data, sort);
  42748. var sizeExtent = [
  42749. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  42750. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  42751. ];
  42752. var dataExtent = data.getDataExtent(valueDim);
  42753. var min = seriesModel.get('min');
  42754. var max = seriesModel.get('max');
  42755. if (min == null) {
  42756. min = Math.min(dataExtent[0], 0);
  42757. }
  42758. if (max == null) {
  42759. max = dataExtent[1];
  42760. }
  42761. var funnelAlign = seriesModel.get('funnelAlign');
  42762. var gap = seriesModel.get('gap');
  42763. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  42764. var y = viewRect.y;
  42765. var getLinePoints = function (idx, offY) {
  42766. // End point index is data.count() and we assign it 0
  42767. var val = data.get(valueDim, idx) || 0;
  42768. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  42769. var x0;
  42770. switch (funnelAlign) {
  42771. case 'left':
  42772. x0 = viewRect.x;
  42773. break;
  42774. case 'center':
  42775. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  42776. break;
  42777. case 'right':
  42778. x0 = viewRect.x + viewRect.width - itemWidth;
  42779. break;
  42780. }
  42781. return [
  42782. [x0, offY],
  42783. [x0 + itemWidth, offY]
  42784. ];
  42785. };
  42786. if (sort === 'ascending') {
  42787. // From bottom to top
  42788. itemHeight = -itemHeight;
  42789. gap = -gap;
  42790. y += viewRect.height;
  42791. indices = indices.reverse();
  42792. }
  42793. for (var i = 0; i < indices.length; i++) {
  42794. var idx = indices[i];
  42795. var nextIdx = indices[i + 1];
  42796. var itemModel = data.getItemModel(idx);
  42797. var height = itemModel.get('itemStyle.height');
  42798. if (height == null) {
  42799. height = itemHeight;
  42800. }
  42801. else {
  42802. height = parsePercent$1(height, viewRect.height);
  42803. if (sort === 'ascending') {
  42804. height = -height;
  42805. }
  42806. }
  42807. var start = getLinePoints(idx, y);
  42808. var end = getLinePoints(nextIdx, y + height);
  42809. y += height + gap;
  42810. data.setItemLayout(idx, {
  42811. points: start.concat(end.slice().reverse())
  42812. });
  42813. }
  42814. labelLayout$1(data);
  42815. });
  42816. };
  42817. registerVisual(dataColor('funnel'));
  42818. registerLayout(funnelLayout);
  42819. registerProcessor(dataFilter('funnel'));
  42820. var parallelPreprocessor = function (option) {
  42821. createParallelIfNeeded(option);
  42822. mergeAxisOptionFromParallel(option);
  42823. };
  42824. /**
  42825. * Create a parallel coordinate if not exists.
  42826. * @inner
  42827. */
  42828. function createParallelIfNeeded(option) {
  42829. if (option.parallel) {
  42830. return;
  42831. }
  42832. var hasParallelSeries = false;
  42833. each$1(option.series, function (seriesOpt) {
  42834. if (seriesOpt && seriesOpt.type === 'parallel') {
  42835. hasParallelSeries = true;
  42836. }
  42837. });
  42838. if (hasParallelSeries) {
  42839. option.parallel = [{}];
  42840. }
  42841. }
  42842. /**
  42843. * Merge aixs definition from parallel option (if exists) to axis option.
  42844. * @inner
  42845. */
  42846. function mergeAxisOptionFromParallel(option) {
  42847. var axes = normalizeToArray(option.parallelAxis);
  42848. each$1(axes, function (axisOption) {
  42849. if (!isObject$1(axisOption)) {
  42850. return;
  42851. }
  42852. var parallelIndex = axisOption.parallelIndex || 0;
  42853. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  42854. if (parallelOption && parallelOption.parallelAxisDefault) {
  42855. merge(axisOption, parallelOption.parallelAxisDefault, false);
  42856. }
  42857. });
  42858. }
  42859. /**
  42860. * @constructor module:echarts/coord/parallel/ParallelAxis
  42861. * @extends {module:echarts/coord/Axis}
  42862. * @param {string} dim
  42863. * @param {*} scale
  42864. * @param {Array.<number>} coordExtent
  42865. * @param {string} axisType
  42866. */
  42867. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  42868. Axis.call(this, dim, scale, coordExtent);
  42869. /**
  42870. * Axis type
  42871. * - 'category'
  42872. * - 'value'
  42873. * - 'time'
  42874. * - 'log'
  42875. * @type {string}
  42876. */
  42877. this.type = axisType || 'value';
  42878. /**
  42879. * @type {number}
  42880. * @readOnly
  42881. */
  42882. this.axisIndex = axisIndex;
  42883. };
  42884. ParallelAxis.prototype = {
  42885. constructor: ParallelAxis,
  42886. /**
  42887. * Axis model
  42888. * @param {module:echarts/coord/parallel/AxisModel}
  42889. */
  42890. model: null,
  42891. /**
  42892. * @override
  42893. */
  42894. isHorizontal: function () {
  42895. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  42896. }
  42897. };
  42898. inherits(ParallelAxis, Axis);
  42899. /**
  42900. * Calculate slider move result.
  42901. * Usage:
  42902. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  42903. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  42904. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  42905. *
  42906. * @param {number} delta Move length.
  42907. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  42908. * handleEnds will be modified in this method.
  42909. * @param {Array.<number>} extent handleEnds is restricted by extent.
  42910. * extent[0] should less or equals than extent[1].
  42911. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  42912. * where the input minSpan and maxSpan will not work.
  42913. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  42914. * If not set, handle0 and cross handle1. If set as a non-negative
  42915. * number (including `0`), handles will push each other when reaching
  42916. * the minSpan.
  42917. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  42918. * @return {Array.<number>} The input handleEnds.
  42919. */
  42920. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  42921. // Normalize firstly.
  42922. handleEnds[0] = restrict$1(handleEnds[0], extent);
  42923. handleEnds[1] = restrict$1(handleEnds[1], extent);
  42924. delta = delta || 0;
  42925. var extentSpan = extent[1] - extent[0];
  42926. // Notice maxSpan and minSpan can be null/undefined.
  42927. if (minSpan != null) {
  42928. minSpan = restrict$1(minSpan, [0, extentSpan]);
  42929. }
  42930. if (maxSpan != null) {
  42931. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  42932. }
  42933. if (handleIndex === 'all') {
  42934. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  42935. handleIndex = 0;
  42936. }
  42937. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  42938. handleEnds[handleIndex] += delta;
  42939. // Restrict in extent.
  42940. var extentMinSpan = minSpan || 0;
  42941. var realExtent = extent.slice();
  42942. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  42943. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  42944. // Expand span.
  42945. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42946. if (minSpan != null && (
  42947. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  42948. )) {
  42949. // If minSpan exists, 'cross' is forbinden.
  42950. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  42951. }
  42952. // Shrink span.
  42953. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42954. if (maxSpan != null && currDistSign.span > maxSpan) {
  42955. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  42956. }
  42957. return handleEnds;
  42958. };
  42959. function getSpanSign(handleEnds, handleIndex) {
  42960. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  42961. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  42962. // is at left of handleEnds[1] for non-cross case.
  42963. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  42964. }
  42965. function restrict$1(value, extend) {
  42966. return Math.min(extend[1], Math.max(extend[0], value));
  42967. }
  42968. /**
  42969. * Parallel Coordinates
  42970. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  42971. */
  42972. var each$12 = each$1;
  42973. var mathMin$5 = Math.min;
  42974. var mathMax$5 = Math.max;
  42975. var mathFloor$2 = Math.floor;
  42976. var mathCeil$2 = Math.ceil;
  42977. var round$2 = round$1;
  42978. var PI$3 = Math.PI;
  42979. function Parallel(parallelModel, ecModel, api) {
  42980. /**
  42981. * key: dimension
  42982. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  42983. * @private
  42984. */
  42985. this._axesMap = createHashMap();
  42986. /**
  42987. * key: dimension
  42988. * value: {position: [], rotation, }
  42989. * @type {Object.<string, Object>}
  42990. * @private
  42991. */
  42992. this._axesLayout = {};
  42993. /**
  42994. * Always follow axis order.
  42995. * @type {Array.<string>}
  42996. * @readOnly
  42997. */
  42998. this.dimensions = parallelModel.dimensions;
  42999. /**
  43000. * @type {module:zrender/core/BoundingRect}
  43001. */
  43002. this._rect;
  43003. /**
  43004. * @type {module:echarts/coord/parallel/ParallelModel}
  43005. */
  43006. this._model = parallelModel;
  43007. this._init(parallelModel, ecModel, api);
  43008. }
  43009. Parallel.prototype = {
  43010. type: 'parallel',
  43011. constructor: Parallel,
  43012. /**
  43013. * Initialize cartesian coordinate systems
  43014. * @private
  43015. */
  43016. _init: function (parallelModel, ecModel, api) {
  43017. var dimensions = parallelModel.dimensions;
  43018. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  43019. each$12(dimensions, function (dim, idx) {
  43020. var axisIndex = parallelAxisIndex[idx];
  43021. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  43022. var axis = this._axesMap.set(dim, new ParallelAxis(
  43023. dim,
  43024. createScaleByModel(axisModel),
  43025. [0, 0],
  43026. axisModel.get('type'),
  43027. axisIndex
  43028. ));
  43029. var isCategory = axis.type === 'category';
  43030. axis.onBand = isCategory && axisModel.get('boundaryGap');
  43031. axis.inverse = axisModel.get('inverse');
  43032. // Injection
  43033. axisModel.axis = axis;
  43034. axis.model = axisModel;
  43035. axis.coordinateSystem = axisModel.coordinateSystem = this;
  43036. }, this);
  43037. },
  43038. /**
  43039. * Update axis scale after data processed
  43040. * @param {module:echarts/model/Global} ecModel
  43041. * @param {module:echarts/ExtensionAPI} api
  43042. */
  43043. update: function (ecModel, api) {
  43044. this._updateAxesFromSeries(this._model, ecModel);
  43045. },
  43046. /**
  43047. * @override
  43048. */
  43049. containPoint: function (point) {
  43050. var layoutInfo = this._makeLayoutInfo();
  43051. var axisBase = layoutInfo.axisBase;
  43052. var layoutBase = layoutInfo.layoutBase;
  43053. var pixelDimIndex = layoutInfo.pixelDimIndex;
  43054. var pAxis = point[1 - pixelDimIndex];
  43055. var pLayout = point[pixelDimIndex];
  43056. return pAxis >= axisBase
  43057. && pAxis <= axisBase + layoutInfo.axisLength
  43058. && pLayout >= layoutBase
  43059. && pLayout <= layoutBase + layoutInfo.layoutLength;
  43060. },
  43061. getModel: function () {
  43062. return this._model;
  43063. },
  43064. /**
  43065. * Update properties from series
  43066. * @private
  43067. */
  43068. _updateAxesFromSeries: function (parallelModel, ecModel) {
  43069. ecModel.eachSeries(function (seriesModel) {
  43070. if (!parallelModel.contains(seriesModel, ecModel)) {
  43071. return;
  43072. }
  43073. var data = seriesModel.getData();
  43074. each$12(this.dimensions, function (dim) {
  43075. var axis = this._axesMap.get(dim);
  43076. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  43077. niceScaleExtent(axis.scale, axis.model);
  43078. }, this);
  43079. }, this);
  43080. },
  43081. /**
  43082. * Resize the parallel coordinate system.
  43083. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  43084. * @param {module:echarts/ExtensionAPI} api
  43085. */
  43086. resize: function (parallelModel, api) {
  43087. this._rect = getLayoutRect(
  43088. parallelModel.getBoxLayoutParams(),
  43089. {
  43090. width: api.getWidth(),
  43091. height: api.getHeight()
  43092. }
  43093. );
  43094. this._layoutAxes();
  43095. },
  43096. /**
  43097. * @return {module:zrender/core/BoundingRect}
  43098. */
  43099. getRect: function () {
  43100. return this._rect;
  43101. },
  43102. /**
  43103. * @private
  43104. */
  43105. _makeLayoutInfo: function () {
  43106. var parallelModel = this._model;
  43107. var rect = this._rect;
  43108. var xy = ['x', 'y'];
  43109. var wh = ['width', 'height'];
  43110. var layout = parallelModel.get('layout');
  43111. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  43112. var layoutLength = rect[wh[pixelDimIndex]];
  43113. var layoutExtent = [0, layoutLength];
  43114. var axisCount = this.dimensions.length;
  43115. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  43116. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  43117. var axisExpandable = parallelModel.get('axisExpandable')
  43118. && axisCount > 3
  43119. && axisCount > axisExpandCount
  43120. && axisExpandCount > 1
  43121. && axisExpandWidth > 0
  43122. && layoutLength > 0;
  43123. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  43124. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  43125. // where collapsed axes should be overlapped.
  43126. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  43127. var winSize;
  43128. if (!axisExpandWindow) {
  43129. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  43130. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  43131. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  43132. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  43133. }
  43134. else {
  43135. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  43136. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  43137. }
  43138. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  43139. // Avoid axisCollapseWidth is too small.
  43140. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  43141. // Find the first and last indices > ewin[0] and < ewin[1].
  43142. var winInnerIndices = [
  43143. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  43144. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  43145. ];
  43146. // Pos in ec coordinates.
  43147. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  43148. return {
  43149. layout: layout,
  43150. pixelDimIndex: pixelDimIndex,
  43151. layoutBase: rect[xy[pixelDimIndex]],
  43152. layoutLength: layoutLength,
  43153. axisBase: rect[xy[1 - pixelDimIndex]],
  43154. axisLength: rect[wh[1 - pixelDimIndex]],
  43155. axisExpandable: axisExpandable,
  43156. axisExpandWidth: axisExpandWidth,
  43157. axisCollapseWidth: axisCollapseWidth,
  43158. axisExpandWindow: axisExpandWindow,
  43159. axisCount: axisCount,
  43160. winInnerIndices: winInnerIndices,
  43161. axisExpandWindow0Pos: axisExpandWindow0Pos
  43162. };
  43163. },
  43164. /**
  43165. * @private
  43166. */
  43167. _layoutAxes: function () {
  43168. var rect = this._rect;
  43169. var axes = this._axesMap;
  43170. var dimensions = this.dimensions;
  43171. var layoutInfo = this._makeLayoutInfo();
  43172. var layout = layoutInfo.layout;
  43173. axes.each(function (axis) {
  43174. var axisExtent = [0, layoutInfo.axisLength];
  43175. var idx = axis.inverse ? 1 : 0;
  43176. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  43177. });
  43178. each$12(dimensions, function (dim, idx) {
  43179. var posInfo = (layoutInfo.axisExpandable
  43180. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  43181. )(idx, layoutInfo);
  43182. var positionTable = {
  43183. horizontal: {
  43184. x: posInfo.position,
  43185. y: layoutInfo.axisLength
  43186. },
  43187. vertical: {
  43188. x: 0,
  43189. y: posInfo.position
  43190. }
  43191. };
  43192. var rotationTable = {
  43193. horizontal: PI$3 / 2,
  43194. vertical: 0
  43195. };
  43196. var position = [
  43197. positionTable[layout].x + rect.x,
  43198. positionTable[layout].y + rect.y
  43199. ];
  43200. var rotation = rotationTable[layout];
  43201. var transform = create$1();
  43202. rotate(transform, transform, rotation);
  43203. translate(transform, transform, position);
  43204. // TODO
  43205. // tick等排布信息。
  43206. // TODO
  43207. // 根据axis order 更新 dimensions顺序。
  43208. this._axesLayout[dim] = {
  43209. position: position,
  43210. rotation: rotation,
  43211. transform: transform,
  43212. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  43213. axisLabelShow: posInfo.axisLabelShow,
  43214. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  43215. tickDirection: 1,
  43216. labelDirection: 1,
  43217. labelInterval: axes.get(dim).getLabelInterval()
  43218. };
  43219. }, this);
  43220. },
  43221. /**
  43222. * Get axis by dim.
  43223. * @param {string} dim
  43224. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  43225. */
  43226. getAxis: function (dim) {
  43227. return this._axesMap.get(dim);
  43228. },
  43229. /**
  43230. * Convert a dim value of a single item of series data to Point.
  43231. * @param {*} value
  43232. * @param {string} dim
  43233. * @return {Array}
  43234. */
  43235. dataToPoint: function (value, dim) {
  43236. return this.axisCoordToPoint(
  43237. this._axesMap.get(dim).dataToCoord(value),
  43238. dim
  43239. );
  43240. },
  43241. /**
  43242. * Travel data for one time, get activeState of each data item.
  43243. * @param {module:echarts/data/List} data
  43244. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  43245. * {number} dataIndex
  43246. * @param {Object} context
  43247. */
  43248. eachActiveState: function (data, callback, context) {
  43249. var dimensions = this.dimensions;
  43250. var dataDimensions = map(dimensions, function (axisDim) {
  43251. return data.mapDimension(axisDim);
  43252. });
  43253. var axesMap = this._axesMap;
  43254. var hasActiveSet = this.hasAxisBrushed();
  43255. for (var i = 0, len = data.count(); i < len; i++) {
  43256. var values = data.getValues(dataDimensions, i);
  43257. var activeState;
  43258. if (!hasActiveSet) {
  43259. activeState = 'normal';
  43260. }
  43261. else {
  43262. activeState = 'active';
  43263. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  43264. var dimName = dimensions[j];
  43265. var state = axesMap.get(dimName).model.getActiveState(values[j], j);
  43266. if (state === 'inactive') {
  43267. activeState = 'inactive';
  43268. break;
  43269. }
  43270. }
  43271. }
  43272. callback.call(context, activeState, i);
  43273. }
  43274. },
  43275. /**
  43276. * Whether has any activeSet.
  43277. * @return {boolean}
  43278. */
  43279. hasAxisBrushed: function () {
  43280. var dimensions = this.dimensions;
  43281. var axesMap = this._axesMap;
  43282. var hasActiveSet = false;
  43283. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  43284. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  43285. hasActiveSet = true;
  43286. }
  43287. }
  43288. return hasActiveSet;
  43289. },
  43290. /**
  43291. * Convert coords of each axis to Point.
  43292. * Return point. For example: [10, 20]
  43293. * @param {Array.<number>} coords
  43294. * @param {string} dim
  43295. * @return {Array.<number>}
  43296. */
  43297. axisCoordToPoint: function (coord, dim) {
  43298. var axisLayout = this._axesLayout[dim];
  43299. return applyTransform$1([coord, 0], axisLayout.transform);
  43300. },
  43301. /**
  43302. * Get axis layout.
  43303. */
  43304. getAxisLayout: function (dim) {
  43305. return clone(this._axesLayout[dim]);
  43306. },
  43307. /**
  43308. * @param {Array.<number>} point
  43309. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  43310. */
  43311. getSlidedAxisExpandWindow: function (point) {
  43312. var layoutInfo = this._makeLayoutInfo();
  43313. var pixelDimIndex = layoutInfo.pixelDimIndex;
  43314. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  43315. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  43316. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  43317. // Out of the area of coordinate system.
  43318. if (!this.containPoint(point)) {
  43319. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  43320. }
  43321. // Conver the point from global to expand coordinates.
  43322. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  43323. // For dragging operation convenience, the window should not be
  43324. // slided when mouse is the center area of the window.
  43325. var delta;
  43326. var behavior = 'slide';
  43327. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  43328. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  43329. // But consider touch device, jump is necessary.
  43330. var useJump = triggerArea[0] != null;
  43331. if (axisCollapseWidth) {
  43332. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  43333. behavior = 'jump';
  43334. delta = pointCoord - winSize * triggerArea[2];
  43335. }
  43336. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  43337. behavior = 'jump';
  43338. delta = pointCoord - winSize * (1 - triggerArea[2]);
  43339. }
  43340. else {
  43341. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  43342. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  43343. && (delta = 0);
  43344. }
  43345. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  43346. delta
  43347. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  43348. // Avoid nonsense triger on mousemove.
  43349. : (behavior = 'none');
  43350. }
  43351. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  43352. else {
  43353. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  43354. var pos = extent[1] * pointCoord / winSize;
  43355. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  43356. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  43357. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  43358. }
  43359. return {
  43360. axisExpandWindow: axisExpandWindow,
  43361. behavior: behavior
  43362. };
  43363. }
  43364. };
  43365. function restrict(len, extent) {
  43366. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  43367. }
  43368. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  43369. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  43370. return {
  43371. position: step * axisIndex,
  43372. axisNameAvailableWidth: step,
  43373. axisLabelShow: true
  43374. };
  43375. }
  43376. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  43377. var layoutLength = layoutInfo.layoutLength;
  43378. var axisExpandWidth = layoutInfo.axisExpandWidth;
  43379. var axisCount = layoutInfo.axisCount;
  43380. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  43381. var winInnerIndices = layoutInfo.winInnerIndices;
  43382. var position;
  43383. var axisNameAvailableWidth = axisCollapseWidth;
  43384. var axisLabelShow = false;
  43385. var nameTruncateMaxWidth;
  43386. if (axisIndex < winInnerIndices[0]) {
  43387. position = axisIndex * axisCollapseWidth;
  43388. nameTruncateMaxWidth = axisCollapseWidth;
  43389. }
  43390. else if (axisIndex <= winInnerIndices[1]) {
  43391. position = layoutInfo.axisExpandWindow0Pos
  43392. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  43393. axisNameAvailableWidth = axisExpandWidth;
  43394. axisLabelShow = true;
  43395. }
  43396. else {
  43397. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  43398. nameTruncateMaxWidth = axisCollapseWidth;
  43399. }
  43400. return {
  43401. position: position,
  43402. axisNameAvailableWidth: axisNameAvailableWidth,
  43403. axisLabelShow: axisLabelShow,
  43404. nameTruncateMaxWidth: nameTruncateMaxWidth
  43405. };
  43406. }
  43407. /**
  43408. * Parallel coordinate system creater.
  43409. */
  43410. function create$2(ecModel, api) {
  43411. var coordSysList = [];
  43412. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  43413. var coordSys = new Parallel(parallelModel, ecModel, api);
  43414. coordSys.name = 'parallel_' + idx;
  43415. coordSys.resize(parallelModel, api);
  43416. parallelModel.coordinateSystem = coordSys;
  43417. coordSys.model = parallelModel;
  43418. coordSysList.push(coordSys);
  43419. });
  43420. // Inject the coordinateSystems into seriesModel
  43421. ecModel.eachSeries(function (seriesModel) {
  43422. if (seriesModel.get('coordinateSystem') === 'parallel') {
  43423. var parallelModel = ecModel.queryComponents({
  43424. mainType: 'parallel',
  43425. index: seriesModel.get('parallelIndex'),
  43426. id: seriesModel.get('parallelId')
  43427. })[0];
  43428. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  43429. }
  43430. });
  43431. return coordSysList;
  43432. }
  43433. CoordinateSystemManager.register('parallel', {create: create$2});
  43434. var AxisModel$2 = ComponentModel.extend({
  43435. type: 'baseParallelAxis',
  43436. /**
  43437. * @type {module:echarts/coord/parallel/Axis}
  43438. */
  43439. axis: null,
  43440. /**
  43441. * @type {Array.<Array.<number>}
  43442. * @readOnly
  43443. */
  43444. activeIntervals: [],
  43445. /**
  43446. * @return {Object}
  43447. */
  43448. getAreaSelectStyle: function () {
  43449. return makeStyleMapper(
  43450. [
  43451. ['fill', 'color'],
  43452. ['lineWidth', 'borderWidth'],
  43453. ['stroke', 'borderColor'],
  43454. ['width', 'width'],
  43455. ['opacity', 'opacity']
  43456. ]
  43457. )(this.getModel('areaSelectStyle'));
  43458. },
  43459. /**
  43460. * The code of this feature is put on AxisModel but not ParallelAxis,
  43461. * because axisModel can be alive after echarts updating but instance of
  43462. * ParallelAxis having been disposed. this._activeInterval should be kept
  43463. * when action dispatched (i.e. legend click).
  43464. *
  43465. * @param {Array.<Array<number>>} intervals interval.length === 0
  43466. * means set all active.
  43467. * @public
  43468. */
  43469. setActiveIntervals: function (intervals) {
  43470. var activeIntervals = this.activeIntervals = clone(intervals);
  43471. // Normalize
  43472. if (activeIntervals) {
  43473. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  43474. asc(activeIntervals[i]);
  43475. }
  43476. }
  43477. },
  43478. /**
  43479. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  43480. * value can not be input.
  43481. * @return {string} 'normal': no activeIntervals set,
  43482. * 'active',
  43483. * 'inactive'.
  43484. * @public
  43485. */
  43486. getActiveState: function (value) {
  43487. var activeIntervals = this.activeIntervals;
  43488. if (!activeIntervals.length) {
  43489. return 'normal';
  43490. }
  43491. if (value == null) {
  43492. return 'inactive';
  43493. }
  43494. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  43495. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  43496. return 'active';
  43497. }
  43498. }
  43499. return 'inactive';
  43500. }
  43501. });
  43502. var defaultOption$1 = {
  43503. type: 'value',
  43504. /**
  43505. * @type {Array.<number>}
  43506. */
  43507. dim: null, // 0, 1, 2, ...
  43508. // parallelIndex: null,
  43509. areaSelectStyle: {
  43510. width: 20,
  43511. borderWidth: 1,
  43512. borderColor: 'rgba(160,197,232)',
  43513. color: 'rgba(160,197,232)',
  43514. opacity: 0.3
  43515. },
  43516. realtime: true, // Whether realtime update view when select.
  43517. z: 10
  43518. };
  43519. merge(AxisModel$2.prototype, axisModelCommonMixin);
  43520. function getAxisType$1(axisName, option) {
  43521. return option.type || (option.data ? 'category' : 'value');
  43522. }
  43523. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  43524. ComponentModel.extend({
  43525. type: 'parallel',
  43526. dependencies: ['parallelAxis'],
  43527. /**
  43528. * @type {module:echarts/coord/parallel/Parallel}
  43529. */
  43530. coordinateSystem: null,
  43531. /**
  43532. * Each item like: 'dim0', 'dim1', 'dim2', ...
  43533. * @type {Array.<string>}
  43534. * @readOnly
  43535. */
  43536. dimensions: null,
  43537. /**
  43538. * Coresponding to dimensions.
  43539. * @type {Array.<number>}
  43540. * @readOnly
  43541. */
  43542. parallelAxisIndex: null,
  43543. layoutMode: 'box',
  43544. defaultOption: {
  43545. zlevel: 0,
  43546. z: 0,
  43547. left: 80,
  43548. top: 60,
  43549. right: 80,
  43550. bottom: 60,
  43551. // width: {totalWidth} - left - right,
  43552. // height: {totalHeight} - top - bottom,
  43553. layout: 'horizontal', // 'horizontal' or 'vertical'
  43554. // FIXME
  43555. // naming?
  43556. axisExpandable: false,
  43557. axisExpandCenter: null,
  43558. axisExpandCount: 0,
  43559. axisExpandWidth: 50, // FIXME '10%' ?
  43560. axisExpandRate: 17,
  43561. axisExpandDebounce: 50,
  43562. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  43563. // Do not doc to user until necessary.
  43564. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  43565. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  43566. parallelAxisDefault: null
  43567. },
  43568. /**
  43569. * @override
  43570. */
  43571. init: function () {
  43572. ComponentModel.prototype.init.apply(this, arguments);
  43573. this.mergeOption({});
  43574. },
  43575. /**
  43576. * @override
  43577. */
  43578. mergeOption: function (newOption) {
  43579. var thisOption = this.option;
  43580. newOption && merge(thisOption, newOption, true);
  43581. this._initDimensions();
  43582. },
  43583. /**
  43584. * Whether series or axis is in this coordinate system.
  43585. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  43586. * @param {module:echarts/model/Global} ecModel
  43587. */
  43588. contains: function (model, ecModel) {
  43589. var parallelIndex = model.get('parallelIndex');
  43590. return parallelIndex != null
  43591. && ecModel.getComponent('parallel', parallelIndex) === this;
  43592. },
  43593. setAxisExpand: function (opt) {
  43594. each$1(
  43595. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  43596. function (name) {
  43597. if (opt.hasOwnProperty(name)) {
  43598. this.option[name] = opt[name];
  43599. }
  43600. },
  43601. this
  43602. );
  43603. },
  43604. /**
  43605. * @private
  43606. */
  43607. _initDimensions: function () {
  43608. var dimensions = this.dimensions = [];
  43609. var parallelAxisIndex = this.parallelAxisIndex = [];
  43610. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  43611. // Can not use this.contains here, because
  43612. // initialization has not been completed yet.
  43613. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  43614. }, this);
  43615. each$1(axisModels, function (axisModel) {
  43616. dimensions.push('dim' + axisModel.get('dim'));
  43617. parallelAxisIndex.push(axisModel.componentIndex);
  43618. });
  43619. }
  43620. });
  43621. /**
  43622. * @payload
  43623. * @property {string} parallelAxisId
  43624. * @property {Array.<Array.<number>>} intervals
  43625. */
  43626. var actionInfo$1 = {
  43627. type: 'axisAreaSelect',
  43628. event: 'axisAreaSelected'
  43629. // update: 'updateVisual'
  43630. };
  43631. registerAction(actionInfo$1, function (payload, ecModel) {
  43632. ecModel.eachComponent(
  43633. {mainType: 'parallelAxis', query: payload},
  43634. function (parallelAxisModel) {
  43635. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  43636. }
  43637. );
  43638. });
  43639. /**
  43640. * @payload
  43641. */
  43642. registerAction('parallelAxisExpand', function (payload, ecModel) {
  43643. ecModel.eachComponent(
  43644. {mainType: 'parallel', query: payload},
  43645. function (parallelModel) {
  43646. parallelModel.setAxisExpand(payload);
  43647. }
  43648. );
  43649. });
  43650. var curry$2 = curry;
  43651. var each$13 = each$1;
  43652. var map$2 = map;
  43653. var mathMin$6 = Math.min;
  43654. var mathMax$6 = Math.max;
  43655. var mathPow$2 = Math.pow;
  43656. var COVER_Z = 10000;
  43657. var UNSELECT_THRESHOLD = 6;
  43658. var MIN_RESIZE_LINE_WIDTH = 6;
  43659. var MUTEX_RESOURCE_KEY = 'globalPan';
  43660. var DIRECTION_MAP = {
  43661. w: [0, 0],
  43662. e: [0, 1],
  43663. n: [1, 0],
  43664. s: [1, 1]
  43665. };
  43666. var CURSOR_MAP = {
  43667. w: 'ew',
  43668. e: 'ew',
  43669. n: 'ns',
  43670. s: 'ns',
  43671. ne: 'nesw',
  43672. sw: 'nesw',
  43673. nw: 'nwse',
  43674. se: 'nwse'
  43675. };
  43676. var DEFAULT_BRUSH_OPT = {
  43677. brushStyle: {
  43678. lineWidth: 2,
  43679. stroke: 'rgba(0,0,0,0.3)',
  43680. fill: 'rgba(0,0,0,0.1)'
  43681. },
  43682. transformable: true,
  43683. brushMode: 'single',
  43684. removeOnClick: false
  43685. };
  43686. var baseUID = 0;
  43687. /**
  43688. * @alias module:echarts/component/helper/BrushController
  43689. * @constructor
  43690. * @mixin {module:zrender/mixin/Eventful}
  43691. * @event module:echarts/component/helper/BrushController#brush
  43692. * params:
  43693. * areas: Array.<Array>, coord relates to container group,
  43694. * If no container specified, to global.
  43695. * opt {
  43696. * isEnd: boolean,
  43697. * removeOnClick: boolean
  43698. * }
  43699. *
  43700. * @param {module:zrender/zrender~ZRender} zr
  43701. */
  43702. function BrushController(zr) {
  43703. if (__DEV__) {
  43704. assert$1(zr);
  43705. }
  43706. Eventful.call(this);
  43707. /**
  43708. * @type {module:zrender/zrender~ZRender}
  43709. * @private
  43710. */
  43711. this._zr = zr;
  43712. /**
  43713. * @type {module:zrender/container/Group}
  43714. * @readOnly
  43715. */
  43716. this.group = new Group();
  43717. /**
  43718. * Only for drawing (after enabledBrush).
  43719. * 'line', 'rect', 'polygon' or false
  43720. * If passing false/null/undefined, disable brush.
  43721. * If passing 'auto', determined by panel.defaultBrushType
  43722. * @private
  43723. * @type {string}
  43724. */
  43725. this._brushType;
  43726. /**
  43727. * Only for drawing (after enabledBrush).
  43728. *
  43729. * @private
  43730. * @type {Object}
  43731. */
  43732. this._brushOption;
  43733. /**
  43734. * @private
  43735. * @type {Object}
  43736. */
  43737. this._panels;
  43738. /**
  43739. * @private
  43740. * @type {Array.<nubmer>}
  43741. */
  43742. this._track = [];
  43743. /**
  43744. * @private
  43745. * @type {boolean}
  43746. */
  43747. this._dragging;
  43748. /**
  43749. * @private
  43750. * @type {Array}
  43751. */
  43752. this._covers = [];
  43753. /**
  43754. * @private
  43755. * @type {moudule:zrender/container/Group}
  43756. */
  43757. this._creatingCover;
  43758. /**
  43759. * `true` means global panel
  43760. * @private
  43761. * @type {module:zrender/container/Group|boolean}
  43762. */
  43763. this._creatingPanel;
  43764. /**
  43765. * @private
  43766. * @type {boolean}
  43767. */
  43768. this._enableGlobalPan;
  43769. /**
  43770. * @private
  43771. * @type {boolean}
  43772. */
  43773. if (__DEV__) {
  43774. this._mounted;
  43775. }
  43776. /**
  43777. * @private
  43778. * @type {string}
  43779. */
  43780. this._uid = 'brushController_' + baseUID++;
  43781. /**
  43782. * @private
  43783. * @type {Object}
  43784. */
  43785. this._handlers = {};
  43786. each$13(mouseHandlers, function (handler, eventName) {
  43787. this._handlers[eventName] = bind(handler, this);
  43788. }, this);
  43789. }
  43790. BrushController.prototype = {
  43791. constructor: BrushController,
  43792. /**
  43793. * If set to null/undefined/false, select disabled.
  43794. * @param {Object} brushOption
  43795. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  43796. * If passing false/null/undefined, disable brush.
  43797. * If passing 'auto', determined by panel.defaultBrushType.
  43798. * ('auto' can not be used in global panel)
  43799. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  43800. * @param {boolean} [brushOption.transformable=true]
  43801. * @param {boolean} [brushOption.removeOnClick=false]
  43802. * @param {Object} [brushOption.brushStyle]
  43803. * @param {number} [brushOption.brushStyle.width]
  43804. * @param {number} [brushOption.brushStyle.lineWidth]
  43805. * @param {string} [brushOption.brushStyle.stroke]
  43806. * @param {string} [brushOption.brushStyle.fill]
  43807. * @param {number} [brushOption.z]
  43808. */
  43809. enableBrush: function (brushOption) {
  43810. if (__DEV__) {
  43811. assert$1(this._mounted);
  43812. }
  43813. this._brushType && doDisableBrush(this);
  43814. brushOption.brushType && doEnableBrush(this, brushOption);
  43815. return this;
  43816. },
  43817. /**
  43818. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  43819. * Each items: {
  43820. * panelId, // mandatory.
  43821. * clipPath, // mandatory. function.
  43822. * isTargetByCursor, // mandatory. function.
  43823. * defaultBrushType, // optional, only used when brushType is 'auto'.
  43824. * getLinearBrushOtherExtent, // optional. function.
  43825. * }
  43826. */
  43827. setPanels: function (panelOpts) {
  43828. if (panelOpts && panelOpts.length) {
  43829. var panels = this._panels = {};
  43830. each$1(panelOpts, function (panelOpts) {
  43831. panels[panelOpts.panelId] = clone(panelOpts);
  43832. });
  43833. }
  43834. else {
  43835. this._panels = null;
  43836. }
  43837. return this;
  43838. },
  43839. /**
  43840. * @param {Object} [opt]
  43841. * @return {boolean} [opt.enableGlobalPan=false]
  43842. */
  43843. mount: function (opt) {
  43844. opt = opt || {};
  43845. if (__DEV__) {
  43846. this._mounted = true; // should be at first.
  43847. }
  43848. this._enableGlobalPan = opt.enableGlobalPan;
  43849. var thisGroup = this.group;
  43850. this._zr.add(thisGroup);
  43851. thisGroup.attr({
  43852. position: opt.position || [0, 0],
  43853. rotation: opt.rotation || 0,
  43854. scale: opt.scale || [1, 1]
  43855. });
  43856. this._transform = thisGroup.getLocalTransform();
  43857. return this;
  43858. },
  43859. eachCover: function (cb, context) {
  43860. each$13(this._covers, cb, context);
  43861. },
  43862. /**
  43863. * Update covers.
  43864. * @param {Array.<Object>} brushOptionList Like:
  43865. * [
  43866. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  43867. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  43868. * ...
  43869. * ]
  43870. * `brushType` is required in each cover info. (can not be 'auto')
  43871. * `id` is not mandatory.
  43872. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  43873. * If brushOptionList is null/undefined, all covers removed.
  43874. */
  43875. updateCovers: function (brushOptionList) {
  43876. if (__DEV__) {
  43877. assert$1(this._mounted);
  43878. }
  43879. brushOptionList = map(brushOptionList, function (brushOption) {
  43880. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43881. });
  43882. var tmpIdPrefix = '\0-brush-index-';
  43883. var oldCovers = this._covers;
  43884. var newCovers = this._covers = [];
  43885. var controller = this;
  43886. var creatingCover = this._creatingCover;
  43887. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  43888. .add(addOrUpdate)
  43889. .update(addOrUpdate)
  43890. .remove(remove)
  43891. .execute();
  43892. return this;
  43893. function getKey(brushOption, index) {
  43894. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  43895. + '-' + brushOption.brushType;
  43896. }
  43897. function oldGetKey(cover, index) {
  43898. return getKey(cover.__brushOption, index);
  43899. }
  43900. function addOrUpdate(newIndex, oldIndex) {
  43901. var newBrushOption = brushOptionList[newIndex];
  43902. // Consider setOption in event listener of brushSelect,
  43903. // where updating cover when creating should be forbiden.
  43904. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  43905. newCovers[newIndex] = oldCovers[oldIndex];
  43906. }
  43907. else {
  43908. var cover = newCovers[newIndex] = oldIndex != null
  43909. ? (
  43910. oldCovers[oldIndex].__brushOption = newBrushOption,
  43911. oldCovers[oldIndex]
  43912. )
  43913. : endCreating(controller, createCover(controller, newBrushOption));
  43914. updateCoverAfterCreation(controller, cover);
  43915. }
  43916. }
  43917. function remove(oldIndex) {
  43918. if (oldCovers[oldIndex] !== creatingCover) {
  43919. controller.group.remove(oldCovers[oldIndex]);
  43920. }
  43921. }
  43922. },
  43923. unmount: function () {
  43924. if (__DEV__) {
  43925. if (!this._mounted) {
  43926. return;
  43927. }
  43928. }
  43929. this.enableBrush(false);
  43930. // container may 'removeAll' outside.
  43931. clearCovers(this);
  43932. this._zr.remove(this.group);
  43933. if (__DEV__) {
  43934. this._mounted = false; // should be at last.
  43935. }
  43936. return this;
  43937. },
  43938. dispose: function () {
  43939. this.unmount();
  43940. this.off();
  43941. }
  43942. };
  43943. mixin(BrushController, Eventful);
  43944. function doEnableBrush(controller, brushOption) {
  43945. var zr = controller._zr;
  43946. // Consider roam, which takes globalPan too.
  43947. if (!controller._enableGlobalPan) {
  43948. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43949. }
  43950. each$13(controller._handlers, function (handler, eventName) {
  43951. zr.on(eventName, handler);
  43952. });
  43953. controller._brushType = brushOption.brushType;
  43954. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43955. }
  43956. function doDisableBrush(controller) {
  43957. var zr = controller._zr;
  43958. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43959. each$13(controller._handlers, function (handler, eventName) {
  43960. zr.off(eventName, handler);
  43961. });
  43962. controller._brushType = controller._brushOption = null;
  43963. }
  43964. function createCover(controller, brushOption) {
  43965. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  43966. cover.__brushOption = brushOption;
  43967. updateZ$1(cover, brushOption);
  43968. controller.group.add(cover);
  43969. return cover;
  43970. }
  43971. function endCreating(controller, creatingCover) {
  43972. var coverRenderer = getCoverRenderer(creatingCover);
  43973. if (coverRenderer.endCreating) {
  43974. coverRenderer.endCreating(controller, creatingCover);
  43975. updateZ$1(creatingCover, creatingCover.__brushOption);
  43976. }
  43977. return creatingCover;
  43978. }
  43979. function updateCoverShape(controller, cover) {
  43980. var brushOption = cover.__brushOption;
  43981. getCoverRenderer(cover).updateCoverShape(
  43982. controller, cover, brushOption.range, brushOption
  43983. );
  43984. }
  43985. function updateZ$1(cover, brushOption) {
  43986. var z = brushOption.z;
  43987. z == null && (z = COVER_Z);
  43988. cover.traverse(function (el) {
  43989. el.z = z;
  43990. el.z2 = z; // Consider in given container.
  43991. });
  43992. }
  43993. function updateCoverAfterCreation(controller, cover) {
  43994. getCoverRenderer(cover).updateCommon(controller, cover);
  43995. updateCoverShape(controller, cover);
  43996. }
  43997. function getCoverRenderer(cover) {
  43998. return coverRenderers[cover.__brushOption.brushType];
  43999. }
  44000. // return target panel or `true` (means global panel)
  44001. function getPanelByPoint(controller, e, localCursorPoint) {
  44002. var panels = controller._panels;
  44003. if (!panels) {
  44004. return true; // Global panel
  44005. }
  44006. var panel;
  44007. var transform = controller._transform;
  44008. each$13(panels, function (pn) {
  44009. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  44010. });
  44011. return panel;
  44012. }
  44013. // Return a panel or true
  44014. function getPanelByCover(controller, cover) {
  44015. var panels = controller._panels;
  44016. if (!panels) {
  44017. return true; // Global panel
  44018. }
  44019. var panelId = cover.__brushOption.panelId;
  44020. // User may give cover without coord sys info,
  44021. // which is then treated as global panel.
  44022. return panelId != null ? panels[panelId] : true;
  44023. }
  44024. function clearCovers(controller) {
  44025. var covers = controller._covers;
  44026. var originalLength = covers.length;
  44027. each$13(covers, function (cover) {
  44028. controller.group.remove(cover);
  44029. }, controller);
  44030. covers.length = 0;
  44031. return !!originalLength;
  44032. }
  44033. function trigger(controller, opt) {
  44034. var areas = map$2(controller._covers, function (cover) {
  44035. var brushOption = cover.__brushOption;
  44036. var range = clone(brushOption.range);
  44037. return {
  44038. brushType: brushOption.brushType,
  44039. panelId: brushOption.panelId,
  44040. range: range
  44041. };
  44042. });
  44043. controller.trigger('brush', areas, {
  44044. isEnd: !!opt.isEnd,
  44045. removeOnClick: !!opt.removeOnClick
  44046. });
  44047. }
  44048. function shouldShowCover(controller) {
  44049. var track = controller._track;
  44050. if (!track.length) {
  44051. return false;
  44052. }
  44053. var p2 = track[track.length - 1];
  44054. var p1 = track[0];
  44055. var dx = p2[0] - p1[0];
  44056. var dy = p2[1] - p1[1];
  44057. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  44058. return dist > UNSELECT_THRESHOLD;
  44059. }
  44060. function getTrackEnds(track) {
  44061. var tail = track.length - 1;
  44062. tail < 0 && (tail = 0);
  44063. return [track[0], track[tail]];
  44064. }
  44065. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  44066. var cover = new Group();
  44067. cover.add(new Rect({
  44068. name: 'main',
  44069. style: makeStyle(brushOption),
  44070. silent: true,
  44071. draggable: true,
  44072. cursor: 'move',
  44073. drift: curry$2(doDrift, controller, cover, 'nswe'),
  44074. ondragend: curry$2(trigger, controller, {isEnd: true})
  44075. }));
  44076. each$13(
  44077. edgeNames,
  44078. function (name) {
  44079. cover.add(new Rect({
  44080. name: name,
  44081. style: {opacity: 0},
  44082. draggable: true,
  44083. silent: true,
  44084. invisible: true,
  44085. drift: curry$2(doDrift, controller, cover, name),
  44086. ondragend: curry$2(trigger, controller, {isEnd: true})
  44087. }));
  44088. }
  44089. );
  44090. return cover;
  44091. }
  44092. function updateBaseRect(controller, cover, localRange, brushOption) {
  44093. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  44094. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  44095. var x = localRange[0][0];
  44096. var y = localRange[1][0];
  44097. var xa = x - lineWidth / 2;
  44098. var ya = y - lineWidth / 2;
  44099. var x2 = localRange[0][1];
  44100. var y2 = localRange[1][1];
  44101. var x2a = x2 - handleSize + lineWidth / 2;
  44102. var y2a = y2 - handleSize + lineWidth / 2;
  44103. var width = x2 - x;
  44104. var height = y2 - y;
  44105. var widtha = width + lineWidth;
  44106. var heighta = height + lineWidth;
  44107. updateRectShape(controller, cover, 'main', x, y, width, height);
  44108. if (brushOption.transformable) {
  44109. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  44110. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  44111. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  44112. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  44113. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  44114. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  44115. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  44116. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  44117. }
  44118. }
  44119. function updateCommon(controller, cover) {
  44120. var brushOption = cover.__brushOption;
  44121. var transformable = brushOption.transformable;
  44122. var mainEl = cover.childAt(0);
  44123. mainEl.useStyle(makeStyle(brushOption));
  44124. mainEl.attr({
  44125. silent: !transformable,
  44126. cursor: transformable ? 'move' : 'default'
  44127. });
  44128. each$13(
  44129. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  44130. function (name) {
  44131. var el = cover.childOfName(name);
  44132. var globalDir = getGlobalDirection(controller, name);
  44133. el && el.attr({
  44134. silent: !transformable,
  44135. invisible: !transformable,
  44136. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  44137. });
  44138. }
  44139. );
  44140. }
  44141. function updateRectShape(controller, cover, name, x, y, w, h) {
  44142. var el = cover.childOfName(name);
  44143. el && el.setShape(pointsToRect(
  44144. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  44145. ));
  44146. }
  44147. function makeStyle(brushOption) {
  44148. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  44149. }
  44150. function formatRectRange(x, y, x2, y2) {
  44151. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  44152. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  44153. return [
  44154. [min[0], max[0]], // x range
  44155. [min[1], max[1]] // y range
  44156. ];
  44157. }
  44158. function getTransform$1(controller) {
  44159. return getTransform(controller.group);
  44160. }
  44161. function getGlobalDirection(controller, localDirection) {
  44162. if (localDirection.length > 1) {
  44163. localDirection = localDirection.split('');
  44164. var globalDir = [
  44165. getGlobalDirection(controller, localDirection[0]),
  44166. getGlobalDirection(controller, localDirection[1])
  44167. ];
  44168. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  44169. return globalDir.join('');
  44170. }
  44171. else {
  44172. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  44173. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  44174. var globalDir = transformDirection(
  44175. map$$1[localDirection], getTransform$1(controller)
  44176. );
  44177. return inverseMap[globalDir];
  44178. }
  44179. }
  44180. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  44181. var brushOption = cover.__brushOption;
  44182. var rectRange = toRectRange(brushOption.range);
  44183. var localDelta = toLocalDelta(controller, dx, dy);
  44184. each$13(name.split(''), function (namePart) {
  44185. var ind = DIRECTION_MAP[namePart];
  44186. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  44187. });
  44188. brushOption.range = fromRectRange(formatRectRange(
  44189. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  44190. ));
  44191. updateCoverAfterCreation(controller, cover);
  44192. trigger(controller, {isEnd: false});
  44193. }
  44194. function driftPolygon(controller, cover, dx, dy, e) {
  44195. var range = cover.__brushOption.range;
  44196. var localDelta = toLocalDelta(controller, dx, dy);
  44197. each$13(range, function (point) {
  44198. point[0] += localDelta[0];
  44199. point[1] += localDelta[1];
  44200. });
  44201. updateCoverAfterCreation(controller, cover);
  44202. trigger(controller, {isEnd: false});
  44203. }
  44204. function toLocalDelta(controller, dx, dy) {
  44205. var thisGroup = controller.group;
  44206. var localD = thisGroup.transformCoordToLocal(dx, dy);
  44207. var localZero = thisGroup.transformCoordToLocal(0, 0);
  44208. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  44209. }
  44210. function clipByPanel(controller, cover, data) {
  44211. var panel = getPanelByCover(controller, cover);
  44212. return (panel && panel !== true)
  44213. ? panel.clipPath(data, controller._transform)
  44214. : clone(data);
  44215. }
  44216. function pointsToRect(points) {
  44217. var xmin = mathMin$6(points[0][0], points[1][0]);
  44218. var ymin = mathMin$6(points[0][1], points[1][1]);
  44219. var xmax = mathMax$6(points[0][0], points[1][0]);
  44220. var ymax = mathMax$6(points[0][1], points[1][1]);
  44221. return {
  44222. x: xmin,
  44223. y: ymin,
  44224. width: xmax - xmin,
  44225. height: ymax - ymin
  44226. };
  44227. }
  44228. function resetCursor(controller, e, localCursorPoint) {
  44229. // Check active
  44230. if (!controller._brushType) {
  44231. return;
  44232. }
  44233. var zr = controller._zr;
  44234. var covers = controller._covers;
  44235. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  44236. // Check whether in covers.
  44237. if (!controller._dragging) {
  44238. for (var i = 0; i < covers.length; i++) {
  44239. var brushOption = covers[i].__brushOption;
  44240. if (currPanel
  44241. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  44242. && coverRenderers[brushOption.brushType].contain(
  44243. covers[i], localCursorPoint[0], localCursorPoint[1]
  44244. )
  44245. ) {
  44246. // Use cursor style set on cover.
  44247. return;
  44248. }
  44249. }
  44250. }
  44251. currPanel && zr.setCursorStyle('crosshair');
  44252. }
  44253. function preventDefault(e) {
  44254. var rawE = e.event;
  44255. rawE.preventDefault && rawE.preventDefault();
  44256. }
  44257. function mainShapeContain(cover, x, y) {
  44258. return cover.childOfName('main').contain(x, y);
  44259. }
  44260. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  44261. var creatingCover = controller._creatingCover;
  44262. var panel = controller._creatingPanel;
  44263. var thisBrushOption = controller._brushOption;
  44264. var eventParams;
  44265. controller._track.push(localCursorPoint.slice());
  44266. if (shouldShowCover(controller) || creatingCover) {
  44267. if (panel && !creatingCover) {
  44268. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  44269. var brushOption = clone(thisBrushOption);
  44270. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  44271. brushOption.panelId = panel === true ? null : panel.panelId;
  44272. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  44273. controller._covers.push(creatingCover);
  44274. }
  44275. if (creatingCover) {
  44276. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  44277. var coverBrushOption = creatingCover.__brushOption;
  44278. coverBrushOption.range = coverRenderer.getCreatingRange(
  44279. clipByPanel(controller, creatingCover, controller._track)
  44280. );
  44281. if (isEnd) {
  44282. endCreating(controller, creatingCover);
  44283. coverRenderer.updateCommon(controller, creatingCover);
  44284. }
  44285. updateCoverShape(controller, creatingCover);
  44286. eventParams = {isEnd: isEnd};
  44287. }
  44288. }
  44289. else if (
  44290. isEnd
  44291. && thisBrushOption.brushMode === 'single'
  44292. && thisBrushOption.removeOnClick
  44293. ) {
  44294. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  44295. // But a single click do not clear covers, because user may have casual
  44296. // clicks (for example, click on other component and do not expect covers
  44297. // disappear).
  44298. // Only some cover removed, trigger action, but not every click trigger action.
  44299. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  44300. eventParams = {isEnd: isEnd, removeOnClick: true};
  44301. }
  44302. }
  44303. return eventParams;
  44304. }
  44305. function determineBrushType(brushType, panel) {
  44306. if (brushType === 'auto') {
  44307. if (__DEV__) {
  44308. assert$1(
  44309. panel && panel.defaultBrushType,
  44310. 'MUST have defaultBrushType when brushType is "atuo"'
  44311. );
  44312. }
  44313. return panel.defaultBrushType;
  44314. }
  44315. return brushType;
  44316. }
  44317. var mouseHandlers = {
  44318. mousedown: function (e) {
  44319. if (this._dragging) {
  44320. // In case some browser do not support globalOut,
  44321. // and release mose out side the browser.
  44322. handleDragEnd.call(this, e);
  44323. }
  44324. else if (!e.target || !e.target.draggable) {
  44325. preventDefault(e);
  44326. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44327. this._creatingCover = null;
  44328. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  44329. if (panel) {
  44330. this._dragging = true;
  44331. this._track = [localCursorPoint.slice()];
  44332. }
  44333. }
  44334. },
  44335. mousemove: function (e) {
  44336. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44337. resetCursor(this, e, localCursorPoint);
  44338. if (this._dragging) {
  44339. preventDefault(e);
  44340. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  44341. eventParams && trigger(this, eventParams);
  44342. }
  44343. },
  44344. mouseup: handleDragEnd //,
  44345. // FIXME
  44346. // in tooltip, globalout should not be triggered.
  44347. // globalout: handleDragEnd
  44348. };
  44349. function handleDragEnd(e) {
  44350. if (this._dragging) {
  44351. preventDefault(e);
  44352. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44353. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  44354. this._dragging = false;
  44355. this._track = [];
  44356. this._creatingCover = null;
  44357. // trigger event shoule be at final, after procedure will be nested.
  44358. eventParams && trigger(this, eventParams);
  44359. }
  44360. }
  44361. /**
  44362. * key: brushType
  44363. * @type {Object}
  44364. */
  44365. var coverRenderers = {
  44366. lineX: getLineRenderer(0),
  44367. lineY: getLineRenderer(1),
  44368. rect: {
  44369. createCover: function (controller, brushOption) {
  44370. return createBaseRectCover(
  44371. curry$2(
  44372. driftRect,
  44373. function (range) {
  44374. return range;
  44375. },
  44376. function (range) {
  44377. return range;
  44378. }
  44379. ),
  44380. controller,
  44381. brushOption,
  44382. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  44383. );
  44384. },
  44385. getCreatingRange: function (localTrack) {
  44386. var ends = getTrackEnds(localTrack);
  44387. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  44388. },
  44389. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44390. updateBaseRect(controller, cover, localRange, brushOption);
  44391. },
  44392. updateCommon: updateCommon,
  44393. contain: mainShapeContain
  44394. },
  44395. polygon: {
  44396. createCover: function (controller, brushOption) {
  44397. var cover = new Group();
  44398. // Do not use graphic.Polygon because graphic.Polyline do not close the
  44399. // border of the shape when drawing, which is a better experience for user.
  44400. cover.add(new Polyline({
  44401. name: 'main',
  44402. style: makeStyle(brushOption),
  44403. silent: true
  44404. }));
  44405. return cover;
  44406. },
  44407. getCreatingRange: function (localTrack) {
  44408. return localTrack;
  44409. },
  44410. endCreating: function (controller, cover) {
  44411. cover.remove(cover.childAt(0));
  44412. // Use graphic.Polygon close the shape.
  44413. cover.add(new Polygon({
  44414. name: 'main',
  44415. draggable: true,
  44416. drift: curry$2(driftPolygon, controller, cover),
  44417. ondragend: curry$2(trigger, controller, {isEnd: true})
  44418. }));
  44419. },
  44420. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44421. cover.childAt(0).setShape({
  44422. points: clipByPanel(controller, cover, localRange)
  44423. });
  44424. },
  44425. updateCommon: updateCommon,
  44426. contain: mainShapeContain
  44427. }
  44428. };
  44429. function getLineRenderer(xyIndex) {
  44430. return {
  44431. createCover: function (controller, brushOption) {
  44432. return createBaseRectCover(
  44433. curry$2(
  44434. driftRect,
  44435. function (range) {
  44436. var rectRange = [range, [0, 100]];
  44437. xyIndex && rectRange.reverse();
  44438. return rectRange;
  44439. },
  44440. function (rectRange) {
  44441. return rectRange[xyIndex];
  44442. }
  44443. ),
  44444. controller,
  44445. brushOption,
  44446. [['w', 'e'], ['n', 's']][xyIndex]
  44447. );
  44448. },
  44449. getCreatingRange: function (localTrack) {
  44450. var ends = getTrackEnds(localTrack);
  44451. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  44452. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  44453. return [min, max];
  44454. },
  44455. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44456. var otherExtent;
  44457. // If brushWidth not specified, fit the panel.
  44458. var panel = getPanelByCover(controller, cover);
  44459. if (panel !== true && panel.getLinearBrushOtherExtent) {
  44460. otherExtent = panel.getLinearBrushOtherExtent(
  44461. xyIndex, controller._transform
  44462. );
  44463. }
  44464. else {
  44465. var zr = controller._zr;
  44466. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  44467. }
  44468. var rectRange = [localRange, otherExtent];
  44469. xyIndex && rectRange.reverse();
  44470. updateBaseRect(controller, cover, rectRange, brushOption);
  44471. },
  44472. updateCommon: updateCommon,
  44473. contain: mainShapeContain
  44474. };
  44475. }
  44476. function makeRectPanelClipPath(rect) {
  44477. rect = normalizeRect(rect);
  44478. return function (localPoints, transform) {
  44479. return clipPointsByRect(localPoints, rect);
  44480. };
  44481. }
  44482. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  44483. rect = normalizeRect(rect);
  44484. return function (xyIndex) {
  44485. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  44486. var brushWidth = idx ? rect.width : rect.height;
  44487. var base = idx ? rect.x : rect.y;
  44488. return [base, base + (brushWidth || 0)];
  44489. };
  44490. }
  44491. function makeRectIsTargetByCursor(rect, api, targetModel) {
  44492. rect = normalizeRect(rect);
  44493. return function (e, localCursorPoint, transform) {
  44494. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  44495. && !onIrrelevantElement(e, api, targetModel);
  44496. };
  44497. }
  44498. // Consider width/height is negative.
  44499. function normalizeRect(rect) {
  44500. return BoundingRect.create(rect);
  44501. }
  44502. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  44503. var AxisView$2 = extendComponentView({
  44504. type: 'parallelAxis',
  44505. /**
  44506. * @override
  44507. */
  44508. init: function (ecModel, api) {
  44509. AxisView$2.superApply(this, 'init', arguments);
  44510. /**
  44511. * @type {module:echarts/component/helper/BrushController}
  44512. */
  44513. (this._brushController = new BrushController(api.getZr()))
  44514. .on('brush', bind(this._onBrush, this));
  44515. },
  44516. /**
  44517. * @override
  44518. */
  44519. render: function (axisModel, ecModel, api, payload) {
  44520. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  44521. return;
  44522. }
  44523. this.axisModel = axisModel;
  44524. this.api = api;
  44525. this.group.removeAll();
  44526. var oldAxisGroup = this._axisGroup;
  44527. this._axisGroup = new Group();
  44528. this.group.add(this._axisGroup);
  44529. if (!axisModel.get('show')) {
  44530. return;
  44531. }
  44532. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  44533. var coordSys = coordSysModel.coordinateSystem;
  44534. var areaSelectStyle = axisModel.getAreaSelectStyle();
  44535. var areaWidth = areaSelectStyle.width;
  44536. var dim = axisModel.axis.dim;
  44537. var axisLayout = coordSys.getAxisLayout(dim);
  44538. var builderOpt = extend(
  44539. {strokeContainThreshold: areaWidth},
  44540. axisLayout
  44541. );
  44542. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  44543. each$1(elementList, axisBuilder.add, axisBuilder);
  44544. this._axisGroup.add(axisBuilder.getGroup());
  44545. this._refreshBrushController(
  44546. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  44547. );
  44548. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  44549. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  44550. },
  44551. // /**
  44552. // * @override
  44553. // */
  44554. // updateVisual: function (axisModel, ecModel, api, payload) {
  44555. // this._brushController && this._brushController
  44556. // .updateCovers(getCoverInfoList(axisModel));
  44557. // },
  44558. _refreshBrushController: function (
  44559. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  44560. ) {
  44561. // After filtering, axis may change, select area needs to be update.
  44562. var extent = axisModel.axis.getExtent();
  44563. var extentLen = extent[1] - extent[0];
  44564. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  44565. // width/height might be negative, which will be
  44566. // normalized in BoundingRect.
  44567. var rect = BoundingRect.create({
  44568. x: extent[0],
  44569. y: -areaWidth / 2,
  44570. width: extentLen,
  44571. height: areaWidth
  44572. });
  44573. rect.x -= extra;
  44574. rect.width += 2 * extra;
  44575. this._brushController
  44576. .mount({
  44577. enableGlobalPan: true,
  44578. rotation: builderOpt.rotation,
  44579. position: builderOpt.position
  44580. })
  44581. .setPanels([{
  44582. panelId: 'pl',
  44583. clipPath: makeRectPanelClipPath(rect),
  44584. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  44585. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  44586. }])
  44587. .enableBrush({
  44588. brushType: 'lineX',
  44589. brushStyle: areaSelectStyle,
  44590. removeOnClick: true
  44591. })
  44592. .updateCovers(getCoverInfoList(axisModel));
  44593. },
  44594. _onBrush: function (coverInfoList, opt) {
  44595. // Do not cache these object, because the mey be changed.
  44596. var axisModel = this.axisModel;
  44597. var axis = axisModel.axis;
  44598. var intervals = map(coverInfoList, function (coverInfo) {
  44599. return [
  44600. axis.coordToData(coverInfo.range[0], true),
  44601. axis.coordToData(coverInfo.range[1], true)
  44602. ];
  44603. });
  44604. // If realtime is true, action is not dispatched on drag end, because
  44605. // the drag end emits the same params with the last drag move event,
  44606. // and may have some delay when using touch pad.
  44607. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  44608. this.api.dispatchAction({
  44609. type: 'axisAreaSelect',
  44610. parallelAxisId: axisModel.id,
  44611. intervals: intervals
  44612. });
  44613. }
  44614. },
  44615. /**
  44616. * @override
  44617. */
  44618. dispose: function () {
  44619. this._brushController.dispose();
  44620. }
  44621. });
  44622. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  44623. return payload
  44624. && payload.type === 'axisAreaSelect'
  44625. && ecModel.findComponents(
  44626. {mainType: 'parallelAxis', query: payload}
  44627. )[0] === axisModel;
  44628. }
  44629. function getCoverInfoList(axisModel) {
  44630. var axis = axisModel.axis;
  44631. return map(axisModel.activeIntervals, function (interval) {
  44632. return {
  44633. brushType: 'lineX',
  44634. panelId: 'pl',
  44635. range: [
  44636. axis.dataToCoord(interval[0], true),
  44637. axis.dataToCoord(interval[1], true)
  44638. ]
  44639. };
  44640. });
  44641. }
  44642. function getCoordSysModel(axisModel, ecModel) {
  44643. return ecModel.getComponent(
  44644. 'parallel', axisModel.get('parallelIndex')
  44645. );
  44646. }
  44647. var CLICK_THRESHOLD = 5; // > 4
  44648. // Parallel view
  44649. extendComponentView({
  44650. type: 'parallel',
  44651. render: function (parallelModel, ecModel, api) {
  44652. this._model = parallelModel;
  44653. this._api = api;
  44654. if (!this._handlers) {
  44655. this._handlers = {};
  44656. each$1(handlers, function (handler, eventName) {
  44657. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  44658. }, this);
  44659. }
  44660. createOrUpdate(
  44661. this,
  44662. '_throttledDispatchExpand',
  44663. parallelModel.get('axisExpandRate'),
  44664. 'fixRate'
  44665. );
  44666. },
  44667. dispose: function (ecModel, api) {
  44668. each$1(this._handlers, function (handler, eventName) {
  44669. api.getZr().off(eventName, handler);
  44670. });
  44671. this._handlers = null;
  44672. },
  44673. /**
  44674. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  44675. */
  44676. _throttledDispatchExpand: function (opt) {
  44677. this._dispatchExpand(opt);
  44678. },
  44679. _dispatchExpand: function (opt) {
  44680. opt && this._api.dispatchAction(
  44681. extend({type: 'parallelAxisExpand'}, opt)
  44682. );
  44683. }
  44684. });
  44685. var handlers = {
  44686. mousedown: function (e) {
  44687. if (checkTrigger(this, 'click')) {
  44688. this._mouseDownPoint = [e.offsetX, e.offsetY];
  44689. }
  44690. },
  44691. mouseup: function (e) {
  44692. var mouseDownPoint = this._mouseDownPoint;
  44693. if (checkTrigger(this, 'click') && mouseDownPoint) {
  44694. var point = [e.offsetX, e.offsetY];
  44695. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  44696. + Math.pow(mouseDownPoint[1] - point[1], 2);
  44697. if (dist > CLICK_THRESHOLD) {
  44698. return;
  44699. }
  44700. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  44701. [e.offsetX, e.offsetY]
  44702. );
  44703. result.behavior !== 'none' && this._dispatchExpand({
  44704. axisExpandWindow: result.axisExpandWindow
  44705. });
  44706. }
  44707. this._mouseDownPoint = null;
  44708. },
  44709. mousemove: function (e) {
  44710. // Should do nothing when brushing.
  44711. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  44712. return;
  44713. }
  44714. var model = this._model;
  44715. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  44716. [e.offsetX, e.offsetY]
  44717. );
  44718. var behavior = result.behavior;
  44719. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  44720. this._throttledDispatchExpand(
  44721. behavior === 'none'
  44722. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  44723. : {
  44724. axisExpandWindow: result.axisExpandWindow,
  44725. // Jumping uses animation, and sliding suppresses animation.
  44726. animation: behavior === 'jump' ? null : false
  44727. }
  44728. );
  44729. }
  44730. };
  44731. function checkTrigger(view, triggerOn) {
  44732. var model = view._model;
  44733. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  44734. }
  44735. registerPreprocessor(parallelPreprocessor);
  44736. SeriesModel.extend({
  44737. type: 'series.parallel',
  44738. dependencies: ['parallel'],
  44739. visualColorAccessPath: 'lineStyle.color',
  44740. getInitialData: function (option, ecModel) {
  44741. // Anication is forbiden in progressive data mode.
  44742. if (this.option.progressive) {
  44743. this.option.animation = false;
  44744. }
  44745. var source = this.getSource();
  44746. setEncodeAndDimensions(source, this);
  44747. return createListFromArray(source, this);
  44748. },
  44749. /**
  44750. * User can get data raw indices on 'axisAreaSelected' event received.
  44751. *
  44752. * @public
  44753. * @param {string} activeState 'active' or 'inactive' or 'normal'
  44754. * @return {Array.<number>} Raw indices
  44755. */
  44756. getRawIndicesByActiveState: function (activeState) {
  44757. var coordSys = this.coordinateSystem;
  44758. var data = this.getData();
  44759. var indices = [];
  44760. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  44761. if (activeState === theActiveState) {
  44762. indices.push(data.getRawIndex(dataIndex));
  44763. }
  44764. });
  44765. return indices;
  44766. },
  44767. defaultOption: {
  44768. zlevel: 0, // 一级层叠
  44769. z: 2, // 二级层叠
  44770. coordinateSystem: 'parallel',
  44771. parallelIndex: 0,
  44772. label: {
  44773. show: false
  44774. },
  44775. inactiveOpacity: 0.05,
  44776. activeOpacity: 1,
  44777. lineStyle: {
  44778. width: 1,
  44779. opacity: 0.45,
  44780. type: 'solid'
  44781. },
  44782. emphasis: {
  44783. label: {
  44784. show: false
  44785. }
  44786. },
  44787. progressive: false, // 100
  44788. smooth: false,
  44789. animationEasing: 'linear'
  44790. }
  44791. });
  44792. function setEncodeAndDimensions(source, seriesModel) {
  44793. // The mapping of parallelAxis dimension to data dimension can
  44794. // be specified in parallelAxis.option.dim. For example, if
  44795. // parallelAxis.option.dim is 'dim3', it mapping to the third
  44796. // dimension of data. But `data.encode` has higher priority.
  44797. // Moreover, parallelModel.dimension should not be regarded as data
  44798. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  44799. if (source.encodeDefine) {
  44800. return;
  44801. }
  44802. var parallelModel = seriesModel.ecModel.getComponent(
  44803. 'parallel', seriesModel.get('parallelIndex')
  44804. );
  44805. if (!parallelModel) {
  44806. return;
  44807. }
  44808. var encodeDefine = source.encodeDefine = createHashMap();
  44809. each$1(parallelModel.dimensions, function (axisDim) {
  44810. var dataDimIndex = convertDimNameToNumber(axisDim);
  44811. encodeDefine.set(axisDim, dataDimIndex);
  44812. });
  44813. }
  44814. function convertDimNameToNumber(dimName) {
  44815. return +dimName.replace('dim', '');
  44816. }
  44817. var SMOOTH = 0.3;
  44818. var ParallelView = Chart.extend({
  44819. type: 'parallel',
  44820. init: function () {
  44821. /**
  44822. * @type {module:zrender/container/Group}
  44823. * @private
  44824. */
  44825. this._dataGroup = new Group();
  44826. this.group.add(this._dataGroup);
  44827. /**
  44828. * @type {module:echarts/data/List}
  44829. */
  44830. this._data;
  44831. },
  44832. /**
  44833. * @override
  44834. */
  44835. render: function (seriesModel, ecModel, api, payload) {
  44836. this._renderForNormal(seriesModel, payload);
  44837. // this[
  44838. // seriesModel.option.progressive
  44839. // ? '_renderForProgressive'
  44840. // : '_renderForNormal'
  44841. // ](seriesModel);
  44842. },
  44843. dispose: function () {},
  44844. /**
  44845. * @private
  44846. */
  44847. _renderForNormal: function (seriesModel, payload) {
  44848. var dataGroup = this._dataGroup;
  44849. var data = seriesModel.getData();
  44850. var oldData = this._data;
  44851. var coordSys = seriesModel.coordinateSystem;
  44852. var dimensions = coordSys.dimensions;
  44853. var option = seriesModel.option;
  44854. var smooth = option.smooth ? SMOOTH : null;
  44855. // Consider switch between progressive and not.
  44856. // oldData && oldData.__plProgressive && dataGroup.removeAll();
  44857. data.diff(oldData)
  44858. .add(add)
  44859. .update(update)
  44860. .remove(remove)
  44861. .execute();
  44862. // Update style
  44863. updateElCommon(data, smooth);
  44864. // First create
  44865. if (!this._data) {
  44866. var clipPath = createGridClipShape$1(
  44867. coordSys, seriesModel, function () {
  44868. // Callback will be invoked immediately if there is no animation
  44869. setTimeout(function () {
  44870. dataGroup.removeClipPath();
  44871. });
  44872. }
  44873. );
  44874. dataGroup.setClipPath(clipPath);
  44875. }
  44876. this._data = data;
  44877. function add(newDataIndex) {
  44878. addEl(data, dataGroup, newDataIndex, dimensions, coordSys, null, smooth);
  44879. }
  44880. function update(newDataIndex, oldDataIndex) {
  44881. var line = oldData.getItemGraphicEl(oldDataIndex);
  44882. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  44883. data.setItemGraphicEl(newDataIndex, line);
  44884. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  44885. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  44886. }
  44887. function remove(oldDataIndex) {
  44888. var line = oldData.getItemGraphicEl(oldDataIndex);
  44889. dataGroup.remove(line);
  44890. }
  44891. },
  44892. /**
  44893. * @private
  44894. */
  44895. // _renderForProgressive: function (seriesModel) {
  44896. // var dataGroup = this._dataGroup;
  44897. // var data = seriesModel.getData();
  44898. // var oldData = this._data;
  44899. // var coordSys = seriesModel.coordinateSystem;
  44900. // var dimensions = coordSys.dimensions;
  44901. // var option = seriesModel.option;
  44902. // var progressive = option.progressive;
  44903. // var smooth = option.smooth ? SMOOTH : null;
  44904. // // In progressive animation is disabled, so use simple data diff,
  44905. // // which effects performance less.
  44906. // // (Typically performance for data with length 7000+ like:
  44907. // // simpleDiff: 60ms, addEl: 184ms,
  44908. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  44909. // if (simpleDiff(oldData, data, dimensions)) {
  44910. // dataGroup.removeAll();
  44911. // data.each(function (dataIndex) {
  44912. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  44913. // });
  44914. // }
  44915. // updateElCommon(data, progressive, smooth);
  44916. // // Consider switch between progressive and not.
  44917. // data.__plProgressive = true;
  44918. // this._data = data;
  44919. // },
  44920. /**
  44921. * @override
  44922. */
  44923. remove: function () {
  44924. this._dataGroup && this._dataGroup.removeAll();
  44925. this._data = null;
  44926. }
  44927. });
  44928. function createGridClipShape$1(coordSys, seriesModel, cb) {
  44929. var parallelModel = coordSys.model;
  44930. var rect = coordSys.getRect();
  44931. var rectEl = new Rect({
  44932. shape: {
  44933. x: rect.x,
  44934. y: rect.y,
  44935. width: rect.width,
  44936. height: rect.height
  44937. }
  44938. });
  44939. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  44940. rectEl.setShape(dim, 0);
  44941. initProps(rectEl, {
  44942. shape: {
  44943. width: rect.width,
  44944. height: rect.height
  44945. }
  44946. }, seriesModel, cb);
  44947. return rectEl;
  44948. }
  44949. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  44950. var points = [];
  44951. for (var i = 0; i < dimensions.length; i++) {
  44952. var dimName = dimensions[i];
  44953. var value = data.get(data.mapDimension(dimName), dataIndex);
  44954. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  44955. points.push(coordSys.dataToPoint(value, dimName));
  44956. }
  44957. }
  44958. return points;
  44959. }
  44960. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  44961. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  44962. var line = new Polyline({
  44963. shape: {points: points},
  44964. silent: true,
  44965. z2: 10
  44966. });
  44967. dataGroup.add(line);
  44968. data.setItemGraphicEl(dataIndex, line);
  44969. }
  44970. function updateElCommon(data, smooth) {
  44971. var seriesStyleModel = data.hostModel.getModel('lineStyle');
  44972. var lineStyle = seriesStyleModel.getLineStyle();
  44973. data.eachItemGraphicEl(function (line, dataIndex) {
  44974. if (data.hasItemOption) {
  44975. var itemModel = data.getItemModel(dataIndex);
  44976. var lineStyleModel = itemModel.getModel('lineStyle', seriesStyleModel);
  44977. lineStyle = lineStyleModel.getLineStyle(['color', 'stroke']);
  44978. }
  44979. line.useStyle(extend(lineStyle, {
  44980. fill: null,
  44981. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  44982. stroke: data.getItemVisual(dataIndex, 'color'),
  44983. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  44984. opacity: data.getItemVisual(dataIndex, 'opacity')
  44985. }));
  44986. line.shape.smooth = smooth;
  44987. });
  44988. }
  44989. // function simpleDiff(oldData, newData, dimensions) {
  44990. // var oldLen;
  44991. // if (!oldData
  44992. // || !oldData.__plProgressive
  44993. // || (oldLen = oldData.count()) !== newData.count()
  44994. // ) {
  44995. // return true;
  44996. // }
  44997. // var dimLen = dimensions.length;
  44998. // for (var i = 0; i < oldLen; i++) {
  44999. // for (var j = 0; j < dimLen; j++) {
  45000. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  45001. // return true;
  45002. // }
  45003. // }
  45004. // }
  45005. // return false;
  45006. // }
  45007. // FIXME
  45008. // 公用方法?
  45009. function isEmptyValue(val, axisType) {
  45010. return axisType === 'category'
  45011. ? val == null
  45012. : (val == null || isNaN(val)); // axisType === 'value'
  45013. }
  45014. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  45015. var parallelVisual = function (ecModel) {
  45016. ecModel.eachSeriesByType('parallel', function (seriesModel) {
  45017. var itemStyleModel = seriesModel.getModel('itemStyle');
  45018. var lineStyleModel = seriesModel.getModel('lineStyle');
  45019. var globalColors = ecModel.get('color');
  45020. var color = lineStyleModel.get('color')
  45021. || itemStyleModel.get('color')
  45022. || globalColors[seriesModel.seriesIndex % globalColors.length];
  45023. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  45024. var activeOpacity = seriesModel.get('activeOpacity');
  45025. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  45026. var coordSys = seriesModel.coordinateSystem;
  45027. var data = seriesModel.getData();
  45028. var opacityMap = {
  45029. normal: lineStyle.opacity,
  45030. active: activeOpacity,
  45031. inactive: inactiveOpacity
  45032. };
  45033. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  45034. var itemModel = data.getItemModel(dataIndex);
  45035. var opacity = opacityMap[activeState];
  45036. if (activeState === 'normal') {
  45037. var itemOpacity = itemModel.get(opacityAccessPath$1, true);
  45038. itemOpacity != null && (opacity = itemOpacity);
  45039. }
  45040. data.setItemVisual(dataIndex, 'opacity', opacity);
  45041. });
  45042. data.setVisual('color', color);
  45043. });
  45044. };
  45045. registerVisual(parallelVisual);
  45046. /**
  45047. * @file Get initial data and define sankey view's series model
  45048. * @author Deqing Li(annong035@gmail.com)
  45049. */
  45050. var SankeySeries = SeriesModel.extend({
  45051. type: 'series.sankey',
  45052. layoutInfo: null,
  45053. /**
  45054. * Init a graph data structure from data in option series
  45055. *
  45056. * @param {Object} option the object used to config echarts view
  45057. * @return {module:echarts/data/List} storage initial data
  45058. */
  45059. getInitialData: function (option) {
  45060. var links = option.edges || option.links;
  45061. var nodes = option.data || option.nodes;
  45062. if (nodes && links) {
  45063. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  45064. return graph.data;
  45065. }
  45066. },
  45067. /**
  45068. * Return the graphic data structure
  45069. *
  45070. * @return {module:echarts/data/Graph} graphic data structure
  45071. */
  45072. getGraph: function () {
  45073. return this.getData().graph;
  45074. },
  45075. /**
  45076. * Get edge data of graphic data structure
  45077. *
  45078. * @return {module:echarts/data/List} data structure of list
  45079. */
  45080. getEdgeData: function () {
  45081. return this.getGraph().edgeData;
  45082. },
  45083. /**
  45084. * @override
  45085. */
  45086. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  45087. // dataType === 'node' or empty do not show tooltip by default
  45088. if (dataType === 'edge') {
  45089. var params = this.getDataParams(dataIndex, dataType);
  45090. var rawDataOpt = params.data;
  45091. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  45092. if (params.value) {
  45093. html += ' : ' + params.value;
  45094. }
  45095. return encodeHTML(html);
  45096. }
  45097. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  45098. },
  45099. defaultOption: {
  45100. zlevel: 0,
  45101. z: 2,
  45102. coordinateSystem: 'view',
  45103. layout: null,
  45104. // the position of the whole view
  45105. left: '5%',
  45106. top: '5%',
  45107. right: '20%',
  45108. bottom: '5%',
  45109. // the dx of the node
  45110. nodeWidth: 20,
  45111. // the vertical distance between two nodes
  45112. nodeGap: 8,
  45113. // the number of iterations to change the position of the node
  45114. layoutIterations: 32,
  45115. label: {
  45116. show: true,
  45117. position: 'right',
  45118. color: '#000',
  45119. fontSize: 12
  45120. },
  45121. itemStyle: {
  45122. borderWidth: 1,
  45123. borderColor: '#333'
  45124. },
  45125. lineStyle: {
  45126. color: '#314656',
  45127. opacity: 0.2,
  45128. curveness: 0.5
  45129. },
  45130. emphasis: {
  45131. label: {
  45132. show: true
  45133. },
  45134. lineStyle: {
  45135. opacity: 0.6
  45136. }
  45137. },
  45138. animationEasing: 'linear',
  45139. animationDuration: 1000
  45140. }
  45141. });
  45142. /**
  45143. * @file The file used to draw sankey view
  45144. * @author Deqing Li(annong035@gmail.com)
  45145. */
  45146. var SankeyShape = extendShape({
  45147. shape: {
  45148. x1: 0, y1: 0,
  45149. x2: 0, y2: 0,
  45150. cpx1: 0, cpy1: 0,
  45151. cpx2: 0, cpy2: 0,
  45152. extent: 0
  45153. },
  45154. buildPath: function (ctx, shape) {
  45155. var halfExtent = shape.extent / 2;
  45156. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  45157. ctx.bezierCurveTo(
  45158. shape.cpx1, shape.cpy1 - halfExtent,
  45159. shape.cpx2, shape.cpy2 - halfExtent,
  45160. shape.x2, shape.y2 - halfExtent
  45161. );
  45162. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  45163. ctx.bezierCurveTo(
  45164. shape.cpx2, shape.cpy2 + halfExtent,
  45165. shape.cpx1, shape.cpy1 + halfExtent,
  45166. shape.x1, shape.y1 + halfExtent
  45167. );
  45168. ctx.closePath();
  45169. }
  45170. });
  45171. extendChartView({
  45172. type: 'sankey',
  45173. /**
  45174. * @private
  45175. * @type {module:echarts/chart/sankey/SankeySeries}
  45176. */
  45177. _model: null,
  45178. render: function (seriesModel, ecModel, api) {
  45179. var graph = seriesModel.getGraph();
  45180. var group = this.group;
  45181. var layoutInfo = seriesModel.layoutInfo;
  45182. var nodeData = seriesModel.getData();
  45183. var edgeData = seriesModel.getData('edge');
  45184. this._model = seriesModel;
  45185. group.removeAll();
  45186. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  45187. // generate a bezire Curve for each edge
  45188. graph.eachEdge(function (edge) {
  45189. var curve = new SankeyShape();
  45190. curve.dataIndex = edge.dataIndex;
  45191. curve.seriesIndex = seriesModel.seriesIndex;
  45192. curve.dataType = 'edge';
  45193. var lineStyleModel = edge.getModel('lineStyle');
  45194. var curvature = lineStyleModel.get('curveness');
  45195. var n1Layout = edge.node1.getLayout();
  45196. var n2Layout = edge.node2.getLayout();
  45197. var edgeLayout = edge.getLayout();
  45198. curve.shape.extent = Math.max(1, edgeLayout.dy);
  45199. var x1 = n1Layout.x + n1Layout.dx;
  45200. var y1 = n1Layout.y + edgeLayout.sy + edgeLayout.dy / 2;
  45201. var x2 = n2Layout.x;
  45202. var y2 = n2Layout.y + edgeLayout.ty + edgeLayout.dy / 2;
  45203. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  45204. var cpy1 = y1;
  45205. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  45206. var cpy2 = y2;
  45207. curve.setShape({
  45208. x1: x1,
  45209. y1: y1,
  45210. x2: x2,
  45211. y2: y2,
  45212. cpx1: cpx1,
  45213. cpy1: cpy1,
  45214. cpx2: cpx2,
  45215. cpy2: cpy2
  45216. });
  45217. curve.setStyle(lineStyleModel.getItemStyle());
  45218. // Special color, use source node color or target node color
  45219. switch (curve.style.fill) {
  45220. case 'source':
  45221. curve.style.fill = edge.node1.getVisual('color');
  45222. break;
  45223. case 'target':
  45224. curve.style.fill = edge.node2.getVisual('color');
  45225. break;
  45226. }
  45227. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  45228. group.add(curve);
  45229. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  45230. });
  45231. // generate a rect for each node
  45232. graph.eachNode(function (node) {
  45233. var layout = node.getLayout();
  45234. var itemModel = node.getModel();
  45235. var labelModel = itemModel.getModel('label');
  45236. var labelHoverModel = itemModel.getModel('emphasis.label');
  45237. var rect = new Rect({
  45238. shape: {
  45239. x: layout.x,
  45240. y: layout.y,
  45241. width: node.getLayout().dx,
  45242. height: node.getLayout().dy
  45243. },
  45244. style: itemModel.getModel('itemStyle').getItemStyle()
  45245. });
  45246. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  45247. setLabelStyle(
  45248. rect.style, hoverStyle, labelModel, labelHoverModel,
  45249. {
  45250. labelFetcher: seriesModel,
  45251. labelDataIndex: node.dataIndex,
  45252. defaultText: node.id,
  45253. isRectText: true
  45254. }
  45255. );
  45256. rect.setStyle('fill', node.getVisual('color'));
  45257. setHoverStyle(rect, hoverStyle);
  45258. group.add(rect);
  45259. nodeData.setItemGraphicEl(node.dataIndex, rect);
  45260. rect.dataType = 'node';
  45261. });
  45262. if (!this._data && seriesModel.get('animation')) {
  45263. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  45264. group.removeClipPath();
  45265. }));
  45266. }
  45267. this._data = seriesModel.getData();
  45268. },
  45269. dispose: function () {}
  45270. });
  45271. // add animation to the view
  45272. function createGridClipShape$2(rect, seriesModel, cb) {
  45273. var rectEl = new Rect({
  45274. shape: {
  45275. x: rect.x - 10,
  45276. y: rect.y - 10,
  45277. width: 0,
  45278. height: rect.height + 20
  45279. }
  45280. });
  45281. initProps(rectEl, {
  45282. shape: {
  45283. width: rect.width + 20,
  45284. height: rect.height + 20
  45285. }
  45286. }, seriesModel, cb);
  45287. return rectEl;
  45288. }
  45289. /**
  45290. * nest helper used to group by the array.
  45291. * can specified the keys and sort the keys.
  45292. */
  45293. function nest() {
  45294. var keysFunction = [];
  45295. var sortKeysFunction = [];
  45296. /**
  45297. * map an Array into the mapObject.
  45298. * @param {Array} array
  45299. * @param {number} depth
  45300. */
  45301. function map$$1(array, depth) {
  45302. if (depth >= keysFunction.length) {
  45303. return array;
  45304. }
  45305. var i = -1;
  45306. var n = array.length;
  45307. var keyFunction = keysFunction[depth++];
  45308. var mapObject = {};
  45309. var valuesByKey = {};
  45310. while (++i < n) {
  45311. var keyValue = keyFunction(array[i]);
  45312. var values = valuesByKey[keyValue];
  45313. if (values) {
  45314. values.push(array[i]);
  45315. }
  45316. else {
  45317. valuesByKey[keyValue] = [array[i]];
  45318. }
  45319. }
  45320. each$1(valuesByKey, function (value, key) {
  45321. mapObject[key] = map$$1(value, depth);
  45322. });
  45323. return mapObject;
  45324. }
  45325. /**
  45326. * transform the Map Object to multidimensional Array
  45327. * @param {Object} map
  45328. * @param {number} depth
  45329. */
  45330. function entriesMap(mapObject, depth) {
  45331. if (depth >= keysFunction.length) {
  45332. return mapObject;
  45333. }
  45334. var array = [];
  45335. var sortKeyFunction = sortKeysFunction[depth++];
  45336. each$1(mapObject, function (value, key) {
  45337. array.push({
  45338. key: key, values: entriesMap(value, depth)
  45339. });
  45340. });
  45341. if (sortKeyFunction) {
  45342. return array.sort(function (a, b) {
  45343. return sortKeyFunction(a.key, b.key);
  45344. });
  45345. }
  45346. else {
  45347. return array;
  45348. }
  45349. }
  45350. return {
  45351. /**
  45352. * specified the key to groupby the arrays.
  45353. * users can specified one more keys.
  45354. * @param {Function} d
  45355. */
  45356. key: function (d) {
  45357. keysFunction.push(d);
  45358. return this;
  45359. },
  45360. /**
  45361. * specified the comparator to sort the keys
  45362. * @param {Function} order
  45363. */
  45364. sortKeys: function (order) {
  45365. sortKeysFunction[keysFunction.length - 1] = order;
  45366. return this;
  45367. },
  45368. /**
  45369. * the array to be grouped by.
  45370. * @param {Array} array
  45371. */
  45372. entries: function (array) {
  45373. return entriesMap(map$$1(array, 0), 0);
  45374. }
  45375. };
  45376. }
  45377. /**
  45378. * @file The layout algorithm of sankey view
  45379. * @author Deqing Li(annong035@gmail.com)
  45380. */
  45381. var sankeyLayout = function (ecModel, api, payload) {
  45382. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  45383. var nodeWidth = seriesModel.get('nodeWidth');
  45384. var nodeGap = seriesModel.get('nodeGap');
  45385. var layoutInfo = getViewRect$3(seriesModel, api);
  45386. seriesModel.layoutInfo = layoutInfo;
  45387. var width = layoutInfo.width;
  45388. var height = layoutInfo.height;
  45389. var graph = seriesModel.getGraph();
  45390. var nodes = graph.nodes;
  45391. var edges = graph.edges;
  45392. computeNodeValues(nodes);
  45393. var filteredNodes = filter(nodes, function (node) {
  45394. return node.getLayout().value === 0;
  45395. });
  45396. var iterations = filteredNodes.length !== 0
  45397. ? 0 : seriesModel.get('layoutIterations');
  45398. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  45399. });
  45400. };
  45401. /**
  45402. * Get the layout position of the whole view
  45403. *
  45404. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  45405. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  45406. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  45407. */
  45408. function getViewRect$3(seriesModel, api) {
  45409. return getLayoutRect(
  45410. seriesModel.getBoxLayoutParams(), {
  45411. width: api.getWidth(),
  45412. height: api.getHeight()
  45413. }
  45414. );
  45415. }
  45416. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  45417. computeNodeBreadths(nodes, nodeWidth, width);
  45418. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  45419. computeEdgeDepths(nodes);
  45420. }
  45421. /**
  45422. * Compute the value of each node by summing the associated edge's value
  45423. *
  45424. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45425. */
  45426. function computeNodeValues(nodes) {
  45427. each$1(nodes, function (node) {
  45428. var value1 = sum(node.outEdges, getEdgeValue);
  45429. var value2 = sum(node.inEdges, getEdgeValue);
  45430. var value = Math.max(value1, value2);
  45431. node.setLayout({value: value}, true);
  45432. });
  45433. }
  45434. /**
  45435. * Compute the x-position for each node
  45436. *
  45437. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45438. * @param {number} nodeWidth the dx of the node
  45439. * @param {number} width the whole width of the area to draw the view
  45440. */
  45441. function computeNodeBreadths(nodes, nodeWidth, width) {
  45442. var remainNodes = nodes;
  45443. var nextNode = null;
  45444. var x = 0;
  45445. var kx = 0;
  45446. while (remainNodes.length) {
  45447. nextNode = [];
  45448. for (var i = 0, len = remainNodes.length; i < len; i++) {
  45449. var node = remainNodes[i];
  45450. node.setLayout({x: x}, true);
  45451. node.setLayout({dx: nodeWidth}, true);
  45452. for (var j = 0, lenj = node.outEdges.length; j < lenj; j++) {
  45453. nextNode.push(node.outEdges[j].node2);
  45454. }
  45455. }
  45456. remainNodes = nextNode;
  45457. ++x;
  45458. }
  45459. moveSinksRight(nodes, x);
  45460. kx = (width - nodeWidth) / (x - 1);
  45461. scaleNodeBreadths(nodes, kx);
  45462. }
  45463. /**
  45464. * All the node without outEgdes are assigned maximum x-position and
  45465. * be aligned in the last column.
  45466. *
  45467. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45468. * @param {number} x value (x-1) use to assign to node without outEdges
  45469. * as x-position
  45470. */
  45471. function moveSinksRight(nodes, x) {
  45472. each$1(nodes, function (node) {
  45473. if (!node.outEdges.length) {
  45474. node.setLayout({x: x - 1}, true);
  45475. }
  45476. });
  45477. }
  45478. /**
  45479. * Scale node x-position to the width
  45480. *
  45481. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45482. * @param {number} kx multiple used to scale nodes
  45483. */
  45484. function scaleNodeBreadths(nodes, kx) {
  45485. each$1(nodes, function (node) {
  45486. var nodeX = node.getLayout().x * kx;
  45487. node.setLayout({x: nodeX}, true);
  45488. });
  45489. }
  45490. /**
  45491. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  45492. *
  45493. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45494. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  45495. * @param {number} height the whole height of the area to draw the view
  45496. * @param {number} nodeGap the vertical distance between two nodes
  45497. * in the same column.
  45498. * @param {number} iterations the number of iterations for the algorithm
  45499. */
  45500. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  45501. var nodesByBreadth = nest()
  45502. .key(function (d) {
  45503. return d.getLayout().x;
  45504. })
  45505. .sortKeys(ascending)
  45506. .entries(nodes)
  45507. .map(function (d) {
  45508. return d.values;
  45509. });
  45510. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  45511. resolveCollisions(nodesByBreadth, nodeGap, height);
  45512. for (var alpha = 1; iterations > 0; iterations--) {
  45513. // 0.99 is a experience parameter, ensure that each iterations of
  45514. // changes as small as possible.
  45515. alpha *= 0.99;
  45516. relaxRightToLeft(nodesByBreadth, alpha);
  45517. resolveCollisions(nodesByBreadth, nodeGap, height);
  45518. relaxLeftToRight(nodesByBreadth, alpha);
  45519. resolveCollisions(nodesByBreadth, nodeGap, height);
  45520. }
  45521. }
  45522. /**
  45523. * Compute the original y-position for each node
  45524. *
  45525. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45526. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45527. * group by the array of all sankey nodes based on the nodes x-position.
  45528. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  45529. * @param {number} height the whole height of the area to draw the view
  45530. * @param {number} nodeGap the vertical distance between two nodes
  45531. */
  45532. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  45533. var kyArray = [];
  45534. each$1(nodesByBreadth, function (nodes) {
  45535. var n = nodes.length;
  45536. var sum = 0;
  45537. each$1(nodes, function (node) {
  45538. sum += node.getLayout().value;
  45539. });
  45540. var ky = (height - (n - 1) * nodeGap) / sum;
  45541. kyArray.push(ky);
  45542. });
  45543. kyArray.sort(function (a, b) {
  45544. return a - b;
  45545. });
  45546. var ky0 = kyArray[0];
  45547. each$1(nodesByBreadth, function (nodes) {
  45548. each$1(nodes, function (node, i) {
  45549. node.setLayout({y: i}, true);
  45550. var nodeDy = node.getLayout().value * ky0;
  45551. node.setLayout({dy: nodeDy}, true);
  45552. });
  45553. });
  45554. each$1(edges, function (edge) {
  45555. var edgeDy = +edge.getValue() * ky0;
  45556. edge.setLayout({dy: edgeDy}, true);
  45557. });
  45558. }
  45559. /**
  45560. * Resolve the collision of initialized depth (y-position)
  45561. *
  45562. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45563. * group by the array of all sankey nodes based on the nodes x-position.
  45564. * @param {number} nodeGap the vertical distance between two nodes
  45565. * @param {number} height the whole height of the area to draw the view
  45566. */
  45567. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  45568. each$1(nodesByBreadth, function (nodes) {
  45569. var node;
  45570. var dy;
  45571. var y0 = 0;
  45572. var n = nodes.length;
  45573. var i;
  45574. nodes.sort(ascendingDepth);
  45575. for (i = 0; i < n; i++) {
  45576. node = nodes[i];
  45577. dy = y0 - node.getLayout().y;
  45578. if (dy > 0) {
  45579. var nodeY = node.getLayout().y + dy;
  45580. node.setLayout({y: nodeY}, true);
  45581. }
  45582. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  45583. }
  45584. // if the bottommost node goes outside the bounds, push it back up
  45585. dy = y0 - nodeGap - height;
  45586. if (dy > 0) {
  45587. var nodeY = node.getLayout().y - dy;
  45588. node.setLayout({y: nodeY}, true);
  45589. y0 = node.getLayout().y;
  45590. for (i = n - 2; i >= 0; --i) {
  45591. node = nodes[i];
  45592. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  45593. if (dy > 0) {
  45594. nodeY = node.getLayout().y - dy;
  45595. node.setLayout({y: nodeY}, true);
  45596. }
  45597. y0 = node.getLayout().y;
  45598. }
  45599. }
  45600. });
  45601. }
  45602. /**
  45603. * Change the y-position of the nodes, except most the right side nodes
  45604. *
  45605. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45606. * group by the array of all sankey nodes based on the node x-position.
  45607. * @param {number} alpha parameter used to adjust the nodes y-position
  45608. */
  45609. function relaxRightToLeft(nodesByBreadth, alpha) {
  45610. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  45611. each$1(nodes, function (node) {
  45612. if (node.outEdges.length) {
  45613. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  45614. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  45615. node.setLayout({y: nodeY}, true);
  45616. }
  45617. });
  45618. });
  45619. }
  45620. function weightedTarget(edge) {
  45621. return center$1(edge.node2) * edge.getValue();
  45622. }
  45623. /**
  45624. * Change the y-position of the nodes, except most the left side nodes
  45625. *
  45626. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45627. * group by the array of all sankey nodes based on the node x-position.
  45628. * @param {number} alpha parameter used to adjust the nodes y-position
  45629. */
  45630. function relaxLeftToRight(nodesByBreadth, alpha) {
  45631. each$1(nodesByBreadth, function (nodes) {
  45632. each$1(nodes, function (node) {
  45633. if (node.inEdges.length) {
  45634. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  45635. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  45636. node.setLayout({y: nodeY}, true);
  45637. }
  45638. });
  45639. });
  45640. }
  45641. function weightedSource(edge) {
  45642. return center$1(edge.node1) * edge.getValue();
  45643. }
  45644. /**
  45645. * Compute the depth(y-position) of each edge
  45646. *
  45647. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45648. */
  45649. function computeEdgeDepths(nodes) {
  45650. each$1(nodes, function (node) {
  45651. node.outEdges.sort(ascendingTargetDepth);
  45652. node.inEdges.sort(ascendingSourceDepth);
  45653. });
  45654. each$1(nodes, function (node) {
  45655. var sy = 0;
  45656. var ty = 0;
  45657. each$1(node.outEdges, function (edge) {
  45658. edge.setLayout({sy: sy}, true);
  45659. sy += edge.getLayout().dy;
  45660. });
  45661. each$1(node.inEdges, function (edge) {
  45662. edge.setLayout({ty: ty}, true);
  45663. ty += edge.getLayout().dy;
  45664. });
  45665. });
  45666. }
  45667. function ascendingTargetDepth(a, b) {
  45668. return a.node2.getLayout().y - b.node2.getLayout().y;
  45669. }
  45670. function ascendingSourceDepth(a, b) {
  45671. return a.node1.getLayout().y - b.node1.getLayout().y;
  45672. }
  45673. function sum(array, f) {
  45674. var sum = 0;
  45675. var len = array.length;
  45676. var i = -1;
  45677. while (++i < len) {
  45678. var value = +f.call(array, array[i], i);
  45679. if (!isNaN(value)) {
  45680. sum += value;
  45681. }
  45682. }
  45683. return sum;
  45684. }
  45685. function center$1(node) {
  45686. return node.getLayout().y + node.getLayout().dy / 2;
  45687. }
  45688. function ascendingDepth(a, b) {
  45689. return a.getLayout().y - b.getLayout().y;
  45690. }
  45691. function ascending(a, b) {
  45692. return a < b ? -1 : a > b ? 1 : a === b ? 0 : NaN;
  45693. }
  45694. function getEdgeValue(edge) {
  45695. return edge.getValue();
  45696. }
  45697. /**
  45698. * @file Visual encoding for sankey view
  45699. * @author Deqing Li(annong035@gmail.com)
  45700. */
  45701. var sankeyVisual = function (ecModel, payload) {
  45702. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  45703. var graph = seriesModel.getGraph();
  45704. var nodes = graph.nodes;
  45705. nodes.sort(function (a, b) {
  45706. return a.getLayout().value - b.getLayout().value;
  45707. });
  45708. var minValue = nodes[0].getLayout().value;
  45709. var maxValue = nodes[nodes.length - 1].getLayout().value;
  45710. each$1(nodes, function (node) {
  45711. var mapping = new VisualMapping({
  45712. type: 'color',
  45713. mappingMethod: 'linear',
  45714. dataExtent: [minValue, maxValue],
  45715. visual: seriesModel.get('color')
  45716. });
  45717. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  45718. node.setVisual('color', mapValueToColor);
  45719. // If set itemStyle.normal.color
  45720. var itemModel = node.getModel();
  45721. var customColor = itemModel.get('itemStyle.color');
  45722. if (customColor != null) {
  45723. node.setVisual('color', customColor);
  45724. }
  45725. });
  45726. });
  45727. };
  45728. registerLayout(sankeyLayout);
  45729. registerVisual(sankeyVisual);
  45730. /**
  45731. * @module echarts/chart/helper/Symbol
  45732. */
  45733. var WhiskerPath = Path.extend({
  45734. type: 'whiskerInBox',
  45735. shape: {},
  45736. buildPath: function (ctx, shape) {
  45737. for (var i in shape) {
  45738. if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
  45739. var pts = shape[i];
  45740. ctx.moveTo(pts[0][0], pts[0][1]);
  45741. ctx.lineTo(pts[1][0], pts[1][1]);
  45742. }
  45743. }
  45744. }
  45745. });
  45746. /**
  45747. * @constructor
  45748. * @alias {module:echarts/chart/helper/WhiskerBox}
  45749. * @param {module:echarts/data/List} data
  45750. * @param {number} idx
  45751. * @param {Function} styleUpdater
  45752. * @param {boolean} isInit
  45753. * @extends {module:zrender/graphic/Group}
  45754. */
  45755. function WhiskerBox(data, idx, styleUpdater, isInit) {
  45756. Group.call(this);
  45757. /**
  45758. * @type {number}
  45759. * @readOnly
  45760. */
  45761. this.bodyIndex;
  45762. /**
  45763. * @type {number}
  45764. * @readOnly
  45765. */
  45766. this.whiskerIndex;
  45767. /**
  45768. * @type {Function}
  45769. */
  45770. this.styleUpdater = styleUpdater;
  45771. this._createContent(data, idx, isInit);
  45772. this.updateData(data, idx, isInit);
  45773. /**
  45774. * Last series model.
  45775. * @type {module:echarts/model/Series}
  45776. */
  45777. this._seriesModel;
  45778. }
  45779. var whiskerBoxProto = WhiskerBox.prototype;
  45780. whiskerBoxProto._createContent = function (data, idx, isInit) {
  45781. var itemLayout = data.getItemLayout(idx);
  45782. var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
  45783. var count = 0;
  45784. // Whisker element.
  45785. this.add(new Polygon({
  45786. shape: {
  45787. points: isInit
  45788. ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
  45789. : itemLayout.bodyEnds
  45790. },
  45791. style: {strokeNoScale: true},
  45792. z2: 100
  45793. }));
  45794. this.bodyIndex = count++;
  45795. // Box element.
  45796. var whiskerEnds = map(itemLayout.whiskerEnds, function (ends) {
  45797. return isInit ? transInit(ends, constDim, itemLayout) : ends;
  45798. });
  45799. this.add(new WhiskerPath({
  45800. shape: makeWhiskerEndsShape(whiskerEnds),
  45801. style: {strokeNoScale: true},
  45802. z2: 100
  45803. }));
  45804. this.whiskerIndex = count++;
  45805. };
  45806. function transInit(points, dim, itemLayout) {
  45807. return map(points, function (point) {
  45808. point = point.slice();
  45809. point[dim] = itemLayout.initBaseline;
  45810. return point;
  45811. });
  45812. }
  45813. function makeWhiskerEndsShape(whiskerEnds) {
  45814. // zr animation only support 2-dim array.
  45815. var shape = {};
  45816. each$1(whiskerEnds, function (ends, i) {
  45817. shape['ends' + i] = ends;
  45818. });
  45819. return shape;
  45820. }
  45821. /**
  45822. * Update symbol properties
  45823. * @param {module:echarts/data/List} data
  45824. * @param {number} idx
  45825. */
  45826. whiskerBoxProto.updateData = function (data, idx, isInit) {
  45827. var seriesModel = this._seriesModel = data.hostModel;
  45828. var itemLayout = data.getItemLayout(idx);
  45829. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  45830. // this.childAt(this.bodyIndex).stopAnimation(true);
  45831. // this.childAt(this.whiskerIndex).stopAnimation(true);
  45832. updateMethod(
  45833. this.childAt(this.bodyIndex),
  45834. {shape: {points: itemLayout.bodyEnds}},
  45835. seriesModel, idx
  45836. );
  45837. updateMethod(
  45838. this.childAt(this.whiskerIndex),
  45839. {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
  45840. seriesModel, idx
  45841. );
  45842. this.styleUpdater.call(null, this, data, idx);
  45843. };
  45844. inherits(WhiskerBox, Group);
  45845. /**
  45846. * @constructor
  45847. * @alias module:echarts/chart/helper/WhiskerBoxDraw
  45848. */
  45849. function WhiskerBoxDraw(styleUpdater) {
  45850. this.group = new Group();
  45851. this.styleUpdater = styleUpdater;
  45852. }
  45853. var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;
  45854. /**
  45855. * Update symbols draw by new data
  45856. * @param {module:echarts/data/List} data
  45857. */
  45858. whiskerBoxDrawProto.updateData = function (data) {
  45859. var group = this.group;
  45860. var oldData = this._data;
  45861. var styleUpdater = this.styleUpdater;
  45862. // There is no old data only when first rendering or switching from
  45863. // stream mode to normal mode, where previous elements should be removed.
  45864. if (!this._data) {
  45865. group.removeAll();
  45866. }
  45867. data.diff(oldData)
  45868. .add(function (newIdx) {
  45869. if (data.hasValue(newIdx)) {
  45870. var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
  45871. data.setItemGraphicEl(newIdx, symbolEl);
  45872. group.add(symbolEl);
  45873. }
  45874. })
  45875. .update(function (newIdx, oldIdx) {
  45876. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45877. // Empty data
  45878. if (!data.hasValue(newIdx)) {
  45879. group.remove(symbolEl);
  45880. return;
  45881. }
  45882. if (!symbolEl) {
  45883. symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
  45884. }
  45885. else {
  45886. symbolEl.updateData(data, newIdx);
  45887. }
  45888. // Add back
  45889. group.add(symbolEl);
  45890. data.setItemGraphicEl(newIdx, symbolEl);
  45891. })
  45892. .remove(function (oldIdx) {
  45893. var el = oldData.getItemGraphicEl(oldIdx);
  45894. el && group.remove(el);
  45895. })
  45896. .execute();
  45897. this._data = data;
  45898. };
  45899. whiskerBoxDrawProto.incrementalPrepareUpdate = function (seriesModel, ecModel, api) {
  45900. this.group.removeAll();
  45901. this._data = null;
  45902. };
  45903. whiskerBoxDrawProto.incrementalUpdate = function (params, seriesModel, ecModel, api) {
  45904. var data = seriesModel.getData();
  45905. for (var idx = params.start; idx < params.end; idx++) {
  45906. var symbolEl = new WhiskerBox(data, idx, this.styleUpdater, true);
  45907. symbolEl.incremental = true;
  45908. this.group.add(symbolEl);
  45909. }
  45910. };
  45911. /**
  45912. * Remove symbols.
  45913. * @param {module:echarts/data/List} data
  45914. */
  45915. whiskerBoxDrawProto.remove = function () {
  45916. var group = this.group;
  45917. var data = this._data;
  45918. this._data = null;
  45919. data && data.eachItemGraphicEl(function (el) {
  45920. el && group.remove(el);
  45921. });
  45922. };
  45923. var seriesModelMixin = {
  45924. /**
  45925. * @private
  45926. * @type {string}
  45927. */
  45928. _baseAxisDim: null,
  45929. /**
  45930. * @override
  45931. */
  45932. getInitialData: function (option, ecModel) {
  45933. // When both types of xAxis and yAxis are 'value', layout is
  45934. // needed to be specified by user. Otherwise, layout can be
  45935. // judged by which axis is category.
  45936. var ordinalMeta;
  45937. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  45938. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  45939. var xAxisType = xAxisModel.get('type');
  45940. var yAxisType = yAxisModel.get('type');
  45941. var addOrdinal;
  45942. // FIXME
  45943. // 考虑时间轴
  45944. if (xAxisType === 'category') {
  45945. option.layout = 'horizontal';
  45946. ordinalMeta = xAxisModel.getOrdinalMeta();
  45947. addOrdinal = true;
  45948. }
  45949. else if (yAxisType === 'category') {
  45950. option.layout = 'vertical';
  45951. ordinalMeta = yAxisModel.getOrdinalMeta();
  45952. addOrdinal = true;
  45953. }
  45954. else {
  45955. option.layout = option.layout || 'horizontal';
  45956. }
  45957. var coordDims = ['x', 'y'];
  45958. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  45959. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  45960. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  45961. var axisModels = [xAxisModel, yAxisModel];
  45962. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  45963. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  45964. var data = option.data;
  45965. // ??? FIXME make a stage to perform data transfrom.
  45966. // MUST create a new data, consider setOption({}) again.
  45967. if (data && addOrdinal) {
  45968. var newOptionData = [];
  45969. each$1(data, function (item, index) {
  45970. var newItem;
  45971. if (item.value && isArray(item.value)) {
  45972. newItem = item.value.slice();
  45973. item.value.unshift(index);
  45974. }
  45975. else if (isArray(item)) {
  45976. newItem = item.slice();
  45977. item.unshift(index);
  45978. }
  45979. else {
  45980. newItem = item;
  45981. }
  45982. newOptionData.push(newItem);
  45983. });
  45984. option.data = newOptionData;
  45985. }
  45986. var defaultValueDimensions = this.defaultValueDimensions;
  45987. return createListSimply(
  45988. this,
  45989. {
  45990. coordDimensions: [{
  45991. name: baseAxisDim,
  45992. type: getDimensionTypeByAxis(baseAxisType),
  45993. ordinalMeta: ordinalMeta,
  45994. otherDims: {
  45995. tooltip: false,
  45996. itemName: 0
  45997. },
  45998. dimsDef: ['base']
  45999. }, {
  46000. name: otherAxisDim,
  46001. type: getDimensionTypeByAxis(otherAxisType),
  46002. dimsDef: defaultValueDimensions.slice()
  46003. }],
  46004. dimensionsCount: defaultValueDimensions.length + 1
  46005. }
  46006. );
  46007. },
  46008. /**
  46009. * If horizontal, base axis is x, otherwise y.
  46010. * @override
  46011. */
  46012. getBaseAxis: function () {
  46013. var dim = this._baseAxisDim;
  46014. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  46015. }
  46016. };
  46017. var viewMixin = {
  46018. init: function () {
  46019. /**
  46020. * Old data.
  46021. * @private
  46022. * @type {module:echarts/chart/helper/WhiskerBoxDraw}
  46023. */
  46024. var whiskerBoxDraw = this._whiskerBoxDraw = new WhiskerBoxDraw(
  46025. this.getStyleUpdater()
  46026. );
  46027. this.group.add(whiskerBoxDraw.group);
  46028. },
  46029. render: function (seriesModel, ecModel, api) {
  46030. this._whiskerBoxDraw.updateData(seriesModel.getData());
  46031. },
  46032. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  46033. this._whiskerBoxDraw.incrementalPrepareUpdate(seriesModel, ecModel, api);
  46034. },
  46035. incrementalRender: function (params, seriesModel, ecModel, api) {
  46036. this._whiskerBoxDraw.incrementalUpdate(params, seriesModel, ecModel, api);
  46037. },
  46038. remove: function (ecModel) {
  46039. this._whiskerBoxDraw.remove();
  46040. }
  46041. };
  46042. var BoxplotSeries = SeriesModel.extend({
  46043. type: 'series.boxplot',
  46044. dependencies: ['xAxis', 'yAxis', 'grid'],
  46045. // TODO
  46046. // box width represents group size, so dimension should have 'size'.
  46047. /**
  46048. * @see <https://en.wikipedia.org/wiki/Box_plot>
  46049. * The meanings of 'min' and 'max' depend on user,
  46050. * and echarts do not need to know it.
  46051. * @readOnly
  46052. */
  46053. defaultValueDimensions: ['min', 'Q1', 'median', 'Q3', 'max'],
  46054. /**
  46055. * @type {Array.<string>}
  46056. * @readOnly
  46057. */
  46058. dimensions: null,
  46059. /**
  46060. * @override
  46061. */
  46062. defaultOption: {
  46063. zlevel: 0, // 一级层叠
  46064. z: 2, // 二级层叠
  46065. coordinateSystem: 'cartesian2d',
  46066. legendHoverLink: true,
  46067. hoverAnimation: true,
  46068. // xAxisIndex: 0,
  46069. // yAxisIndex: 0,
  46070. layout: null, // 'horizontal' or 'vertical'
  46071. boxWidth: [7, 50], // [min, max] can be percent of band width.
  46072. itemStyle: {
  46073. color: '#fff',
  46074. borderWidth: 1
  46075. },
  46076. emphasis: {
  46077. itemStyle: {
  46078. borderWidth: 2,
  46079. shadowBlur: 5,
  46080. shadowOffsetX: 2,
  46081. shadowOffsetY: 2,
  46082. shadowColor: 'rgba(0,0,0,0.4)'
  46083. }
  46084. },
  46085. animationEasing: 'elasticOut',
  46086. animationDuration: 800
  46087. }
  46088. });
  46089. mixin(BoxplotSeries, seriesModelMixin, true);
  46090. var BoxplotView = Chart.extend({
  46091. type: 'boxplot',
  46092. getStyleUpdater: function () {
  46093. return updateStyle$1;
  46094. },
  46095. dispose: noop
  46096. });
  46097. mixin(BoxplotView, viewMixin, true);
  46098. // Update common properties
  46099. var normalStyleAccessPath$1 = ['itemStyle'];
  46100. var emphasisStyleAccessPath$1 = ['emphasis', 'itemStyle'];
  46101. function updateStyle$1(itemGroup, data, idx) {
  46102. var itemModel = data.getItemModel(idx);
  46103. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$1);
  46104. var borderColor = data.getItemVisual(idx, 'color');
  46105. // Exclude borderColor.
  46106. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  46107. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  46108. whiskerEl.style.set(itemStyle);
  46109. whiskerEl.style.stroke = borderColor;
  46110. whiskerEl.dirty();
  46111. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  46112. bodyEl.style.set(itemStyle);
  46113. bodyEl.style.stroke = borderColor;
  46114. bodyEl.dirty();
  46115. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$1).getItemStyle();
  46116. setHoverStyle(itemGroup, hoverStyle);
  46117. }
  46118. var borderColorQuery = ['itemStyle', 'borderColor'];
  46119. var boxplotVisual = function (ecModel, api) {
  46120. var globalColors = ecModel.get('color');
  46121. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  46122. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  46123. var data = seriesModel.getData();
  46124. data.setVisual({
  46125. legendSymbol: 'roundRect',
  46126. // Use name 'color' but not 'borderColor' for legend usage and
  46127. // visual coding from other component like dataRange.
  46128. color: seriesModel.get(borderColorQuery) || defaulColor
  46129. });
  46130. // Only visible series has each data be visual encoded
  46131. if (!ecModel.isSeriesFiltered(seriesModel)) {
  46132. data.each(function (idx) {
  46133. var itemModel = data.getItemModel(idx);
  46134. data.setItemVisual(
  46135. idx,
  46136. {color: itemModel.get(borderColorQuery, true)}
  46137. );
  46138. });
  46139. }
  46140. });
  46141. };
  46142. var each$14 = each$1;
  46143. var boxplotLayout = function (ecModel) {
  46144. var groupResult = groupSeriesByAxis(ecModel);
  46145. each$14(groupResult, function (groupItem) {
  46146. var seriesModels = groupItem.seriesModels;
  46147. if (!seriesModels.length) {
  46148. return;
  46149. }
  46150. calculateBase(groupItem);
  46151. each$14(seriesModels, function (seriesModel, idx) {
  46152. layoutSingleSeries(
  46153. seriesModel,
  46154. groupItem.boxOffsetList[idx],
  46155. groupItem.boxWidthList[idx]
  46156. );
  46157. });
  46158. });
  46159. };
  46160. /**
  46161. * Group series by axis.
  46162. */
  46163. function groupSeriesByAxis(ecModel) {
  46164. var result = [];
  46165. var axisList = [];
  46166. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  46167. var baseAxis = seriesModel.getBaseAxis();
  46168. var idx = indexOf(axisList, baseAxis);
  46169. if (idx < 0) {
  46170. idx = axisList.length;
  46171. axisList[idx] = baseAxis;
  46172. result[idx] = {axis: baseAxis, seriesModels: []};
  46173. }
  46174. result[idx].seriesModels.push(seriesModel);
  46175. });
  46176. return result;
  46177. }
  46178. /**
  46179. * Calculate offset and box width for each series.
  46180. */
  46181. function calculateBase(groupItem) {
  46182. var extent;
  46183. var baseAxis = groupItem.axis;
  46184. var seriesModels = groupItem.seriesModels;
  46185. var seriesCount = seriesModels.length;
  46186. var boxWidthList = groupItem.boxWidthList = [];
  46187. var boxOffsetList = groupItem.boxOffsetList = [];
  46188. var boundList = [];
  46189. var bandWidth;
  46190. if (baseAxis.type === 'category') {
  46191. bandWidth = baseAxis.getBandWidth();
  46192. }
  46193. else {
  46194. var maxDataCount = 0;
  46195. each$14(seriesModels, function (seriesModel) {
  46196. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  46197. });
  46198. extent = baseAxis.getExtent(),
  46199. Math.abs(extent[1] - extent[0]) / maxDataCount;
  46200. }
  46201. each$14(seriesModels, function (seriesModel) {
  46202. var boxWidthBound = seriesModel.get('boxWidth');
  46203. if (!isArray(boxWidthBound)) {
  46204. boxWidthBound = [boxWidthBound, boxWidthBound];
  46205. }
  46206. boundList.push([
  46207. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  46208. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  46209. ]);
  46210. });
  46211. var availableWidth = bandWidth * 0.8 - 2;
  46212. var boxGap = availableWidth / seriesCount * 0.3;
  46213. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  46214. var base = boxWidth / 2 - availableWidth / 2;
  46215. each$14(seriesModels, function (seriesModel, idx) {
  46216. boxOffsetList.push(base);
  46217. base += boxGap + boxWidth;
  46218. boxWidthList.push(
  46219. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  46220. );
  46221. });
  46222. }
  46223. /**
  46224. * Calculate points location for each series.
  46225. */
  46226. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  46227. var coordSys = seriesModel.coordinateSystem;
  46228. var data = seriesModel.getData();
  46229. var halfWidth = boxWidth / 2;
  46230. var chartLayout = seriesModel.get('layout');
  46231. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  46232. var constDim = 1 - variableDim;
  46233. var coordDims = ['x', 'y'];
  46234. var vDims = [];
  46235. var cDim;
  46236. each$1(data.dimensions, function (dimName) {
  46237. var dimInfo = data.getDimensionInfo(dimName);
  46238. var coordDim = dimInfo.coordDim;
  46239. if (coordDim === coordDims[constDim]) {
  46240. vDims.push(dimName);
  46241. }
  46242. else if (coordDim === coordDims[variableDim]) {
  46243. cDim = dimName;
  46244. }
  46245. });
  46246. if (cDim == null || vDims.length < 5) {
  46247. return;
  46248. }
  46249. data.each([cDim].concat(vDims), function () {
  46250. var args = arguments;
  46251. var axisDimVal = args[0];
  46252. var idx = args[vDims.length + 1];
  46253. var median = getPoint(args[3]);
  46254. var end1 = getPoint(args[1]);
  46255. var end5 = getPoint(args[5]);
  46256. var whiskerEnds = [
  46257. [end1, getPoint(args[2])],
  46258. [end5, getPoint(args[4])]
  46259. ];
  46260. layEndLine(end1);
  46261. layEndLine(end5);
  46262. layEndLine(median);
  46263. var bodyEnds = [];
  46264. addBodyEnd(whiskerEnds[0][1], 0);
  46265. addBodyEnd(whiskerEnds[1][1], 1);
  46266. data.setItemLayout(idx, {
  46267. chartLayout: chartLayout,
  46268. initBaseline: median[constDim],
  46269. median: median,
  46270. bodyEnds: bodyEnds,
  46271. whiskerEnds: whiskerEnds
  46272. });
  46273. function getPoint(val) {
  46274. var p = [];
  46275. p[variableDim] = axisDimVal;
  46276. p[constDim] = val;
  46277. var point;
  46278. if (isNaN(axisDimVal) || isNaN(val)) {
  46279. point = [NaN, NaN];
  46280. }
  46281. else {
  46282. point = coordSys.dataToPoint(p);
  46283. point[variableDim] += offset;
  46284. }
  46285. return point;
  46286. }
  46287. function addBodyEnd(point, start) {
  46288. var point1 = point.slice();
  46289. var point2 = point.slice();
  46290. point1[variableDim] += halfWidth;
  46291. point2[variableDim] -= halfWidth;
  46292. start
  46293. ? bodyEnds.push(point1, point2)
  46294. : bodyEnds.push(point2, point1);
  46295. }
  46296. function layEndLine(endCenter) {
  46297. var line = [endCenter.slice(), endCenter.slice()];
  46298. line[0][variableDim] -= halfWidth;
  46299. line[1][variableDim] += halfWidth;
  46300. whiskerEnds.push(line);
  46301. }
  46302. });
  46303. }
  46304. registerVisual(boxplotVisual);
  46305. registerLayout(boxplotLayout);
  46306. var CandlestickSeries = SeriesModel.extend({
  46307. type: 'series.candlestick',
  46308. dependencies: ['xAxis', 'yAxis', 'grid'],
  46309. /**
  46310. * @readOnly
  46311. */
  46312. defaultValueDimensions: ['open', 'close', 'lowest', 'highest'],
  46313. /**
  46314. * @type {Array.<string>}
  46315. * @readOnly
  46316. */
  46317. dimensions: null,
  46318. /**
  46319. * @override
  46320. */
  46321. defaultOption: {
  46322. zlevel: 0, // 一级层叠
  46323. z: 2, // 二级层叠
  46324. coordinateSystem: 'cartesian2d',
  46325. legendHoverLink: true,
  46326. hoverAnimation: true,
  46327. // xAxisIndex: 0,
  46328. // yAxisIndex: 0,
  46329. layout: null, // 'horizontal' or 'vertical'
  46330. itemStyle: {
  46331. color: '#c23531', // 阳线 positive
  46332. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  46333. borderWidth: 1,
  46334. // FIXME
  46335. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  46336. borderColor: '#c23531',
  46337. borderColor0: '#314656'
  46338. },
  46339. emphasis: {
  46340. itemStyle: {
  46341. borderWidth: 2
  46342. }
  46343. },
  46344. barMaxWidth: null,
  46345. barMinWidth: null,
  46346. barWidth: null,
  46347. animationUpdate: false,
  46348. animationEasing: 'linear',
  46349. animationDuration: 300
  46350. },
  46351. /**
  46352. * Get dimension for shadow in dataZoom
  46353. * @return {string} dimension name
  46354. */
  46355. getShadowDim: function () {
  46356. return 'open';
  46357. },
  46358. brushSelector: function (dataIndex, data, selectors) {
  46359. var itemLayout = data.getItemLayout(dataIndex);
  46360. return selectors.rect(itemLayout.brushRect);
  46361. }
  46362. });
  46363. mixin(CandlestickSeries, seriesModelMixin, true);
  46364. var CandlestickView = Chart.extend({
  46365. type: 'candlestick',
  46366. getStyleUpdater: function () {
  46367. return updateStyle$2;
  46368. },
  46369. dispose: noop
  46370. });
  46371. mixin(CandlestickView, viewMixin, true);
  46372. // Update common properties
  46373. var normalStyleAccessPath$2 = ['itemStyle'];
  46374. var emphasisStyleAccessPath$2 = ['emphasis', 'itemStyle'];
  46375. function updateStyle$2(itemGroup, data, idx) {
  46376. var itemModel = data.getItemModel(idx);
  46377. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$2);
  46378. var color = data.getItemVisual(idx, 'color');
  46379. var borderColor = data.getItemVisual(idx, 'borderColor') || color;
  46380. // Color must be excluded.
  46381. // Because symbol provide setColor individually to set fill and stroke
  46382. var itemStyle = normalItemStyleModel.getItemStyle(
  46383. ['color', 'color0', 'borderColor', 'borderColor0']
  46384. );
  46385. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  46386. whiskerEl.useStyle(itemStyle);
  46387. whiskerEl.style.stroke = borderColor;
  46388. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  46389. bodyEl.useStyle(itemStyle);
  46390. bodyEl.style.fill = color;
  46391. bodyEl.style.stroke = borderColor;
  46392. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$2).getItemStyle();
  46393. setHoverStyle(itemGroup, hoverStyle);
  46394. }
  46395. var preprocessor = function (option) {
  46396. if (!option || !isArray(option.series)) {
  46397. return;
  46398. }
  46399. // Translate 'k' to 'candlestick'.
  46400. each$1(option.series, function (seriesItem) {
  46401. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  46402. seriesItem.type = 'candlestick';
  46403. }
  46404. });
  46405. };
  46406. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  46407. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  46408. var positiveColorQuery = ['itemStyle', 'color'];
  46409. var negativeColorQuery = ['itemStyle', 'color0'];
  46410. var candlestickVisual = function (ecModel, api) {
  46411. ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
  46412. var data = seriesModel.getData();
  46413. data.setVisual({
  46414. legendSymbol: 'roundRect'
  46415. });
  46416. // Only visible series has each data be visual encoded
  46417. if (!ecModel.isSeriesFiltered(seriesModel)) {
  46418. data.each(function (idx) {
  46419. var itemModel = data.getItemModel(idx);
  46420. var sign = data.getItemLayout(idx).sign;
  46421. data.setItemVisual(
  46422. idx,
  46423. {
  46424. color: itemModel.get(
  46425. sign > 0 ? positiveColorQuery : negativeColorQuery
  46426. ),
  46427. borderColor: itemModel.get(
  46428. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  46429. )
  46430. }
  46431. );
  46432. });
  46433. }
  46434. });
  46435. };
  46436. var retrieve2$1 = retrieve2;
  46437. var candlestickLayout = function (ecModel) {
  46438. ecModel.eachSeriesByType('candlestick', function (seriesModel) {
  46439. var coordSys = seriesModel.coordinateSystem;
  46440. var data = seriesModel.getData();
  46441. var candleWidth = calculateCandleWidth(seriesModel, data);
  46442. var chartLayout = seriesModel.get('layout');
  46443. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  46444. var constDim = 1 - variableDim;
  46445. var coordDims = ['x', 'y'];
  46446. var vDims = [];
  46447. var cDim;
  46448. each$1(data.dimensions, function (dimName) {
  46449. var dimInfo = data.getDimensionInfo(dimName);
  46450. var coordDim = dimInfo.coordDim;
  46451. if (coordDim === coordDims[constDim]) {
  46452. vDims.push(dimName);
  46453. }
  46454. else if (coordDim === coordDims[variableDim]) {
  46455. cDim = dimName;
  46456. }
  46457. });
  46458. if (cDim == null || vDims.length < 4) {
  46459. return;
  46460. }
  46461. var dataIndex = 0;
  46462. data.each([cDim].concat(vDims), function () {
  46463. var args = arguments;
  46464. var axisDimVal = args[0];
  46465. var idx = args[vDims.length + 1];
  46466. var openVal = args[1];
  46467. var closeVal = args[2];
  46468. var lowestVal = args[3];
  46469. var highestVal = args[4];
  46470. var ocLow = Math.min(openVal, closeVal);
  46471. var ocHigh = Math.max(openVal, closeVal);
  46472. var ocLowPoint = getPoint(ocLow);
  46473. var ocHighPoint = getPoint(ocHigh);
  46474. var lowestPoint = getPoint(lowestVal);
  46475. var highestPoint = getPoint(highestVal);
  46476. var whiskerEnds = [
  46477. [
  46478. subPixelOptimizePoint(highestPoint),
  46479. subPixelOptimizePoint(ocHighPoint)
  46480. ],
  46481. [
  46482. subPixelOptimizePoint(lowestPoint),
  46483. subPixelOptimizePoint(ocLowPoint)
  46484. ]
  46485. ];
  46486. var bodyEnds = [];
  46487. addBodyEnd(ocHighPoint, 0);
  46488. addBodyEnd(ocLowPoint, 1);
  46489. var sign;
  46490. if (openVal > closeVal) {
  46491. sign = -1;
  46492. }
  46493. else if (openVal < closeVal) {
  46494. sign = 1;
  46495. }
  46496. else {
  46497. // If close === open, compare with close of last record
  46498. if (dataIndex > 0) {
  46499. sign = data.getItemModel(dataIndex - 1).get()[2]
  46500. <= closeVal
  46501. ? 1
  46502. : -1;
  46503. }
  46504. else {
  46505. // No record of previous, set to be positive
  46506. sign = 1;
  46507. }
  46508. }
  46509. data.setItemLayout(idx, {
  46510. chartLayout: chartLayout,
  46511. sign: sign,
  46512. initBaseline: openVal > closeVal
  46513. ? ocHighPoint[constDim] : ocLowPoint[constDim], // open point.
  46514. bodyEnds: bodyEnds,
  46515. whiskerEnds: whiskerEnds,
  46516. brushRect: makeBrushRect()
  46517. });
  46518. ++dataIndex;
  46519. function getPoint(val) {
  46520. var p = [];
  46521. p[variableDim] = axisDimVal;
  46522. p[constDim] = val;
  46523. return (isNaN(axisDimVal) || isNaN(val))
  46524. ? [NaN, NaN]
  46525. : coordSys.dataToPoint(p);
  46526. }
  46527. function addBodyEnd(point, start) {
  46528. var point1 = point.slice();
  46529. var point2 = point.slice();
  46530. point1[variableDim] = subPixelOptimize(
  46531. point1[variableDim] + candleWidth / 2, 1, false
  46532. );
  46533. point2[variableDim] = subPixelOptimize(
  46534. point2[variableDim] - candleWidth / 2, 1, true
  46535. );
  46536. start
  46537. ? bodyEnds.push(point1, point2)
  46538. : bodyEnds.push(point2, point1);
  46539. }
  46540. function makeBrushRect() {
  46541. var pmin = getPoint(Math.min(openVal, closeVal, lowestVal, highestVal));
  46542. var pmax = getPoint(Math.max(openVal, closeVal, lowestVal, highestVal));
  46543. pmin[variableDim] -= candleWidth / 2;
  46544. pmax[variableDim] -= candleWidth / 2;
  46545. return {
  46546. x: pmin[0],
  46547. y: pmin[1],
  46548. width: constDim ? candleWidth : pmax[0] - pmin[0],
  46549. height: constDim ? pmax[1] - pmin[1] : candleWidth
  46550. };
  46551. }
  46552. function subPixelOptimizePoint(point) {
  46553. point[variableDim] = subPixelOptimize(point[variableDim], 1);
  46554. return point;
  46555. }
  46556. });
  46557. });
  46558. };
  46559. function calculateCandleWidth(seriesModel, data) {
  46560. var baseAxis = seriesModel.getBaseAxis();
  46561. var extent;
  46562. var bandWidth = baseAxis.type === 'category'
  46563. ? baseAxis.getBandWidth()
  46564. : (
  46565. extent = baseAxis.getExtent(),
  46566. Math.abs(extent[1] - extent[0]) / data.count()
  46567. );
  46568. var barMaxWidth = parsePercent$1(
  46569. retrieve2$1(seriesModel.get('barMaxWidth'), bandWidth),
  46570. bandWidth
  46571. );
  46572. var barMinWidth = parsePercent$1(
  46573. retrieve2$1(seriesModel.get('barMinWidth'), 1),
  46574. bandWidth
  46575. );
  46576. var barWidth = seriesModel.get('barWidth');
  46577. return barWidth != null
  46578. ? parsePercent$1(barWidth, bandWidth)
  46579. // Put max outer to ensure bar visible in spite of overlap.
  46580. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  46581. }
  46582. registerPreprocessor(preprocessor);
  46583. registerVisual(candlestickVisual);
  46584. registerLayout(candlestickLayout);
  46585. SeriesModel.extend({
  46586. type: 'series.effectScatter',
  46587. dependencies: ['grid', 'polar'],
  46588. getInitialData: function (option, ecModel) {
  46589. return createListFromArray(this.getSource(), this);
  46590. },
  46591. brushSelector: 'point',
  46592. defaultOption: {
  46593. coordinateSystem: 'cartesian2d',
  46594. zlevel: 0,
  46595. z: 2,
  46596. legendHoverLink: true,
  46597. effectType: 'ripple',
  46598. progressive: 0,
  46599. // When to show the effect, option: 'render'|'emphasis'
  46600. showEffectOn: 'render',
  46601. // Ripple effect config
  46602. rippleEffect: {
  46603. period: 4,
  46604. // Scale of ripple
  46605. scale: 2.5,
  46606. // Brush type can be fill or stroke
  46607. brushType: 'fill'
  46608. },
  46609. // Cartesian coordinate system
  46610. // xAxisIndex: 0,
  46611. // yAxisIndex: 0,
  46612. // Polar coordinate system
  46613. // polarIndex: 0,
  46614. // Geo coordinate system
  46615. // geoIndex: 0,
  46616. // symbol: null, // 图形类型
  46617. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  46618. // symbolRotate: null, // 图形旋转控制
  46619. // large: false,
  46620. // Available when large is true
  46621. // largeThreshold: 2000,
  46622. // itemStyle: {
  46623. // opacity: 1
  46624. // }
  46625. }
  46626. });
  46627. /**
  46628. * Symbol with ripple effect
  46629. * @module echarts/chart/helper/EffectSymbol
  46630. */
  46631. var EFFECT_RIPPLE_NUMBER = 3;
  46632. function normalizeSymbolSize$1(symbolSize) {
  46633. if (!isArray(symbolSize)) {
  46634. symbolSize = [+symbolSize, +symbolSize];
  46635. }
  46636. return symbolSize;
  46637. }
  46638. function updateRipplePath(rippleGroup, effectCfg) {
  46639. rippleGroup.eachChild(function (ripplePath) {
  46640. ripplePath.attr({
  46641. z: effectCfg.z,
  46642. zlevel: effectCfg.zlevel,
  46643. style: {
  46644. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  46645. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  46646. }
  46647. });
  46648. });
  46649. }
  46650. /**
  46651. * @constructor
  46652. * @param {module:echarts/data/List} data
  46653. * @param {number} idx
  46654. * @extends {module:zrender/graphic/Group}
  46655. */
  46656. function EffectSymbol(data, idx) {
  46657. Group.call(this);
  46658. var symbol = new SymbolClz$1(data, idx);
  46659. var rippleGroup = new Group();
  46660. this.add(symbol);
  46661. this.add(rippleGroup);
  46662. rippleGroup.beforeUpdate = function () {
  46663. this.attr(symbol.getScale());
  46664. };
  46665. this.updateData(data, idx);
  46666. }
  46667. var effectSymbolProto = EffectSymbol.prototype;
  46668. effectSymbolProto.stopEffectAnimation = function () {
  46669. this.childAt(1).removeAll();
  46670. };
  46671. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  46672. var symbolType = effectCfg.symbolType;
  46673. var color = effectCfg.color;
  46674. var rippleGroup = this.childAt(1);
  46675. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  46676. // var ripplePath = createSymbol(
  46677. // symbolType, -0.5, -0.5, 1, 1, color
  46678. // );
  46679. // If width/height are set too small (e.g., set to 1) on ios10
  46680. // and macOS Sierra, a circle stroke become a rect, no matter what
  46681. // the scale is set. So we set width/height as 2. See #4136.
  46682. var ripplePath = createSymbol(
  46683. symbolType, -1, -1, 2, 2, color
  46684. );
  46685. ripplePath.attr({
  46686. style: {
  46687. strokeNoScale: true
  46688. },
  46689. z2: 99,
  46690. silent: true,
  46691. scale: [0.5, 0.5]
  46692. });
  46693. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  46694. // TODO Configurable effectCfg.period
  46695. ripplePath.animate('', true)
  46696. .when(effectCfg.period, {
  46697. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  46698. })
  46699. .delay(delay)
  46700. .start();
  46701. ripplePath.animateStyle(true)
  46702. .when(effectCfg.period, {
  46703. opacity: 0
  46704. })
  46705. .delay(delay)
  46706. .start();
  46707. rippleGroup.add(ripplePath);
  46708. }
  46709. updateRipplePath(rippleGroup, effectCfg);
  46710. };
  46711. /**
  46712. * Update effect symbol
  46713. */
  46714. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  46715. var oldEffectCfg = this._effectCfg;
  46716. var rippleGroup = this.childAt(1);
  46717. // Must reinitialize effect if following configuration changed
  46718. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  46719. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  46720. var propName = DIFFICULT_PROPS[i];
  46721. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  46722. this.stopEffectAnimation();
  46723. this.startEffectAnimation(effectCfg);
  46724. return;
  46725. }
  46726. }
  46727. updateRipplePath(rippleGroup, effectCfg);
  46728. };
  46729. /**
  46730. * Highlight symbol
  46731. */
  46732. effectSymbolProto.highlight = function () {
  46733. this.trigger('emphasis');
  46734. };
  46735. /**
  46736. * Downplay symbol
  46737. */
  46738. effectSymbolProto.downplay = function () {
  46739. this.trigger('normal');
  46740. };
  46741. /**
  46742. * Update symbol properties
  46743. * @param {module:echarts/data/List} data
  46744. * @param {number} idx
  46745. */
  46746. effectSymbolProto.updateData = function (data, idx) {
  46747. var seriesModel = data.hostModel;
  46748. this.childAt(0).updateData(data, idx);
  46749. var rippleGroup = this.childAt(1);
  46750. var itemModel = data.getItemModel(idx);
  46751. var symbolType = data.getItemVisual(idx, 'symbol');
  46752. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  46753. var color = data.getItemVisual(idx, 'color');
  46754. rippleGroup.attr('scale', symbolSize);
  46755. rippleGroup.traverse(function (ripplePath) {
  46756. ripplePath.attr({
  46757. fill: color
  46758. });
  46759. });
  46760. var symbolOffset = itemModel.getShallow('symbolOffset');
  46761. if (symbolOffset) {
  46762. var pos = rippleGroup.position;
  46763. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  46764. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  46765. }
  46766. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  46767. var effectCfg = {};
  46768. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  46769. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  46770. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  46771. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  46772. effectCfg.effectOffset = idx / data.count();
  46773. effectCfg.z = itemModel.getShallow('z') || 0;
  46774. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  46775. effectCfg.symbolType = symbolType;
  46776. effectCfg.color = color;
  46777. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  46778. if (effectCfg.showEffectOn === 'render') {
  46779. this._effectCfg
  46780. ? this.updateEffectAnimation(effectCfg)
  46781. : this.startEffectAnimation(effectCfg);
  46782. this._effectCfg = effectCfg;
  46783. }
  46784. else {
  46785. // Not keep old effect config
  46786. this._effectCfg = null;
  46787. this.stopEffectAnimation();
  46788. var symbol = this.childAt(0);
  46789. var onEmphasis = function () {
  46790. symbol.highlight();
  46791. if (effectCfg.showEffectOn !== 'render') {
  46792. this.startEffectAnimation(effectCfg);
  46793. }
  46794. };
  46795. var onNormal = function () {
  46796. symbol.downplay();
  46797. if (effectCfg.showEffectOn !== 'render') {
  46798. this.stopEffectAnimation();
  46799. }
  46800. };
  46801. this.on('mouseover', onEmphasis, this)
  46802. .on('mouseout', onNormal, this)
  46803. .on('emphasis', onEmphasis, this)
  46804. .on('normal', onNormal, this);
  46805. }
  46806. this._effectCfg = effectCfg;
  46807. };
  46808. effectSymbolProto.fadeOut = function (cb) {
  46809. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  46810. cb && cb();
  46811. };
  46812. inherits(EffectSymbol, Group);
  46813. extendChartView({
  46814. type: 'effectScatter',
  46815. init: function () {
  46816. this._symbolDraw = new SymbolDraw(EffectSymbol);
  46817. },
  46818. render: function (seriesModel, ecModel, api) {
  46819. var data = seriesModel.getData();
  46820. var effectSymbolDraw = this._symbolDraw;
  46821. effectSymbolDraw.updateData(data);
  46822. this.group.add(effectSymbolDraw.group);
  46823. },
  46824. updateTransform: function (seriesModel, ecModel, api) {
  46825. var data = seriesModel.getData();
  46826. this.group.dirty();
  46827. var res = pointsLayout().reset(seriesModel);
  46828. if (res.progress) {
  46829. res.progress({ start: 0, end: data.count() }, data);
  46830. }
  46831. this._symbolDraw.updateLayout(data);
  46832. },
  46833. _updateGroupTransform: function (seriesModel) {
  46834. var coordSys = seriesModel.coordinateSystem;
  46835. if (coordSys && coordSys.getRoamTransform) {
  46836. this.group.transform = clone$2(coordSys.getRoamTransform());
  46837. this.group.decomposeTransform();
  46838. }
  46839. },
  46840. remove: function (ecModel, api) {
  46841. this._symbolDraw && this._symbolDraw.remove(api);
  46842. },
  46843. dispose: function () {}
  46844. });
  46845. registerVisual(visualSymbol('effectScatter', 'circle'));
  46846. registerLayout(pointsLayout('effectScatter'));
  46847. var globalObj$1 = typeof window === 'undefined' ? global : window;
  46848. var Uint32Arr = globalObj$1.Uint32Array || Array;
  46849. var Float64Arr = globalObj$1.Float64Array || Array;
  46850. function compatEc2(seriesOpt) {
  46851. var data = seriesOpt.data;
  46852. if (data && data[0] && data[0][0] && data[0][0].coord) {
  46853. if (__DEV__) {
  46854. console.warn('Lines data configuration has been changed to'
  46855. + ' { coords:[[1,2],[2,3]] }');
  46856. }
  46857. seriesOpt.data = map(data, function (itemOpt) {
  46858. var coords = [
  46859. itemOpt[0].coord, itemOpt[1].coord
  46860. ];
  46861. var target = {
  46862. coords: coords
  46863. };
  46864. if (itemOpt[0].name) {
  46865. target.fromName = itemOpt[0].name;
  46866. }
  46867. if (itemOpt[1].name) {
  46868. target.toName = itemOpt[1].name;
  46869. }
  46870. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  46871. });
  46872. }
  46873. }
  46874. var LinesSeries = SeriesModel.extend({
  46875. type: 'series.lines',
  46876. dependencies: ['grid', 'polar'],
  46877. visualColorAccessPath: 'lineStyle.color',
  46878. init: function (option) {
  46879. // Not using preprocessor because mergeOption may not have series.type
  46880. compatEc2(option);
  46881. var result = this._processFlatCoordsArray(option.data);
  46882. this._flatCoords = result.flatCoords;
  46883. this._flatCoordsOffset = result.flatCoordsOffset;
  46884. if (result.flatCoords) {
  46885. option.data = new Float32Array(result.count);
  46886. }
  46887. LinesSeries.superApply(this, 'init', arguments);
  46888. },
  46889. mergeOption: function (option) {
  46890. compatEc2(option);
  46891. if (option.data) {
  46892. // Only update when have option data to merge.
  46893. var result = this._processFlatCoordsArray(option.data);
  46894. this._flatCoords = result.flatCoords;
  46895. this._flatCoordsOffset = result.flatCoordsOffset;
  46896. if (result.flatCoords) {
  46897. option.data = new Float32Array(result.count);
  46898. }
  46899. }
  46900. LinesSeries.superApply(this, 'mergeOption', arguments);
  46901. },
  46902. appendData: function (params) {
  46903. var result = this._processFlatCoordsArray(params.data);
  46904. if (result.flatCoords) {
  46905. if (!this._flatCoords) {
  46906. this._flatCoords = result.flatCoords;
  46907. this._flatCoordsOffset = result.flatCoordsOffset;
  46908. }
  46909. else {
  46910. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  46911. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  46912. }
  46913. params.data = new Float32Array(result.count);
  46914. }
  46915. this.getRawData().appendData(params.data);
  46916. },
  46917. _getCoordsFromItemModel: function (idx) {
  46918. var itemModel = this.getData().getItemModel(idx);
  46919. var coords = (itemModel.option instanceof Array)
  46920. ? itemModel.option : itemModel.getShallow('coords');
  46921. if (__DEV__) {
  46922. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  46923. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  46924. }
  46925. }
  46926. return coords;
  46927. },
  46928. getLineCoordsCount: function (idx) {
  46929. if (this._flatCoordsOffset) {
  46930. return this._flatCoordsOffset[idx * 2 + 1];
  46931. }
  46932. else {
  46933. return this._getCoordsFromItemModel(idx).length;
  46934. }
  46935. },
  46936. getLineCoords: function (idx, out) {
  46937. if (this._flatCoordsOffset) {
  46938. var offset = this._flatCoordsOffset[idx * 2];
  46939. var len = this._flatCoordsOffset[idx * 2 + 1];
  46940. for (var i = 0; i < len; i++) {
  46941. out[i] = out[i] || [];
  46942. out[i][0] = this._flatCoords[offset + i * 2];
  46943. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  46944. }
  46945. return len;
  46946. }
  46947. else {
  46948. var coords = this._getCoordsFromItemModel(idx);
  46949. for (var i = 0; i < coords.length; i++) {
  46950. out[i] = out[i] || [];
  46951. out[i][0] = coords[i][0];
  46952. out[i][1] = coords[i][1];
  46953. }
  46954. return coords.length;
  46955. }
  46956. },
  46957. _processFlatCoordsArray: function (data) {
  46958. var startOffset = 0;
  46959. if (this._flatCoords) {
  46960. startOffset = this._flatCoords.length;
  46961. }
  46962. // Stored as a typed array. In format
  46963. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  46964. if (typeof data[0] === 'number') {
  46965. var len = data.length;
  46966. // Store offset and len of each segment
  46967. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  46968. var coordsStorage = new Float64Arr(len);
  46969. var coordsCursor = 0;
  46970. var offsetCursor = 0;
  46971. var dataCount = 0;
  46972. for (var i = 0; i < len;) {
  46973. dataCount++;
  46974. var count = data[i++];
  46975. // Offset
  46976. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  46977. // Len
  46978. coordsOffsetAndLenStorage[offsetCursor++] = count;
  46979. for (var k = 0; k < count; k++) {
  46980. var x = data[i++];
  46981. var y = data[i++];
  46982. coordsStorage[coordsCursor++] = x;
  46983. coordsStorage[coordsCursor++] = y;
  46984. if (i > len) {
  46985. if (__DEV__) {
  46986. throw new Error('Invalid data format.');
  46987. }
  46988. }
  46989. }
  46990. }
  46991. return {
  46992. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  46993. flatCoords: coordsStorage,
  46994. count: dataCount
  46995. };
  46996. }
  46997. return {
  46998. flatCoordsOffset: null,
  46999. flatCoords: null,
  47000. count: data.length
  47001. };
  47002. },
  47003. getInitialData: function (option, ecModel) {
  47004. if (__DEV__) {
  47005. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  47006. if (!CoordSys) {
  47007. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  47008. }
  47009. }
  47010. var lineData = new List(['value'], this);
  47011. lineData.hasItemOption = false;
  47012. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  47013. // dataItem is simply coords
  47014. if (dataItem instanceof Array) {
  47015. return NaN;
  47016. }
  47017. else {
  47018. lineData.hasItemOption = true;
  47019. var value = dataItem.value;
  47020. if (value != null) {
  47021. return value instanceof Array ? value[dimIndex] : value;
  47022. }
  47023. }
  47024. });
  47025. return lineData;
  47026. },
  47027. formatTooltip: function (dataIndex) {
  47028. var data = this.getData();
  47029. var itemModel = data.getItemModel(dataIndex);
  47030. var name = itemModel.get('name');
  47031. if (name) {
  47032. return name;
  47033. }
  47034. var fromName = itemModel.get('fromName');
  47035. var toName = itemModel.get('toName');
  47036. var html = [];
  47037. fromName != null && html.push(fromName);
  47038. toName != null && html.push(toName);
  47039. return encodeHTML(html.join(' > '));
  47040. },
  47041. preventIncremental: function () {
  47042. return !!this.get('effect.show');
  47043. },
  47044. getProgressive: function () {
  47045. var progressive = this.option.progressive;
  47046. if (progressive == null) {
  47047. return this.option.large ? 1e4 : this.get('progressive');
  47048. }
  47049. return progressive;
  47050. },
  47051. getProgressiveThreshold: function () {
  47052. var progressiveThreshold = this.option.progressiveThreshold;
  47053. if (progressiveThreshold == null) {
  47054. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  47055. }
  47056. return progressiveThreshold;
  47057. },
  47058. defaultOption: {
  47059. coordinateSystem: 'geo',
  47060. zlevel: 0,
  47061. z: 2,
  47062. legendHoverLink: true,
  47063. hoverAnimation: true,
  47064. // Cartesian coordinate system
  47065. xAxisIndex: 0,
  47066. yAxisIndex: 0,
  47067. symbol: ['none', 'none'],
  47068. symbolSize: [10, 10],
  47069. // Geo coordinate system
  47070. geoIndex: 0,
  47071. effect: {
  47072. show: false,
  47073. period: 4,
  47074. // Animation delay. support callback
  47075. // delay: 0,
  47076. // If move with constant speed px/sec
  47077. // period will be ignored if this property is > 0,
  47078. constantSpeed: 0,
  47079. symbol: 'circle',
  47080. symbolSize: 3,
  47081. loop: true,
  47082. // Length of trail, 0 - 1
  47083. trailLength: 0.2
  47084. // Same with lineStyle.color
  47085. // color
  47086. },
  47087. large: false,
  47088. // Available when large is true
  47089. largeThreshold: 2000,
  47090. // If lines are polyline
  47091. // polyline not support curveness, label, animation
  47092. polyline: false,
  47093. label: {
  47094. show: false,
  47095. position: 'end'
  47096. // distance: 5,
  47097. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  47098. },
  47099. lineStyle: {
  47100. opacity: 0.5
  47101. }
  47102. }
  47103. });
  47104. /**
  47105. * Provide effect for line
  47106. * @module echarts/chart/helper/EffectLine
  47107. */
  47108. /**
  47109. * @constructor
  47110. * @extends {module:zrender/graphic/Group}
  47111. * @alias {module:echarts/chart/helper/Line}
  47112. */
  47113. function EffectLine(lineData, idx, seriesScope) {
  47114. Group.call(this);
  47115. this.add(this.createLine(lineData, idx, seriesScope));
  47116. this._updateEffectSymbol(lineData, idx);
  47117. }
  47118. var effectLineProto = EffectLine.prototype;
  47119. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  47120. return new Line$1(lineData, idx, seriesScope);
  47121. };
  47122. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  47123. var itemModel = lineData.getItemModel(idx);
  47124. var effectModel = itemModel.getModel('effect');
  47125. var size = effectModel.get('symbolSize');
  47126. var symbolType = effectModel.get('symbol');
  47127. if (!isArray(size)) {
  47128. size = [size, size];
  47129. }
  47130. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  47131. var symbol = this.childAt(1);
  47132. if (this._symbolType !== symbolType) {
  47133. // Remove previous
  47134. this.remove(symbol);
  47135. symbol = createSymbol(
  47136. symbolType, -0.5, -0.5, 1, 1, color
  47137. );
  47138. symbol.z2 = 100;
  47139. symbol.culling = true;
  47140. this.add(symbol);
  47141. }
  47142. // Symbol may be removed if loop is false
  47143. if (!symbol) {
  47144. return;
  47145. }
  47146. // Shadow color is same with color in default
  47147. symbol.setStyle('shadowColor', color);
  47148. symbol.setStyle(effectModel.getItemStyle(['color']));
  47149. symbol.attr('scale', size);
  47150. symbol.setColor(color);
  47151. symbol.attr('scale', size);
  47152. this._symbolType = symbolType;
  47153. this._updateEffectAnimation(lineData, effectModel, idx);
  47154. };
  47155. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  47156. var symbol = this.childAt(1);
  47157. if (!symbol) {
  47158. return;
  47159. }
  47160. var self = this;
  47161. var points = lineData.getItemLayout(idx);
  47162. var period = effectModel.get('period') * 1000;
  47163. var loop = effectModel.get('loop');
  47164. var constantSpeed = effectModel.get('constantSpeed');
  47165. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  47166. return idx / lineData.count() * period / 3;
  47167. });
  47168. var isDelayFunc = typeof delayExpr === 'function';
  47169. // Ignore when updating
  47170. symbol.ignore = true;
  47171. this.updateAnimationPoints(symbol, points);
  47172. if (constantSpeed > 0) {
  47173. period = this.getLineLength(symbol) / constantSpeed * 1000;
  47174. }
  47175. if (period !== this._period || loop !== this._loop) {
  47176. symbol.stopAnimation();
  47177. var delay = delayExpr;
  47178. if (isDelayFunc) {
  47179. delay = delayExpr(idx);
  47180. }
  47181. if (symbol.__t > 0) {
  47182. delay = -period * symbol.__t;
  47183. }
  47184. symbol.__t = 0;
  47185. var animator = symbol.animate('', loop)
  47186. .when(period, {
  47187. __t: 1
  47188. })
  47189. .delay(delay)
  47190. .during(function () {
  47191. self.updateSymbolPosition(symbol);
  47192. });
  47193. if (!loop) {
  47194. animator.done(function () {
  47195. self.remove(symbol);
  47196. });
  47197. }
  47198. animator.start();
  47199. }
  47200. this._period = period;
  47201. this._loop = loop;
  47202. };
  47203. effectLineProto.getLineLength = function (symbol) {
  47204. // Not so accurate
  47205. return (dist(symbol.__p1, symbol.__cp1)
  47206. + dist(symbol.__cp1, symbol.__p2));
  47207. };
  47208. effectLineProto.updateAnimationPoints = function (symbol, points) {
  47209. symbol.__p1 = points[0];
  47210. symbol.__p2 = points[1];
  47211. symbol.__cp1 = points[2] || [
  47212. (points[0][0] + points[1][0]) / 2,
  47213. (points[0][1] + points[1][1]) / 2
  47214. ];
  47215. };
  47216. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  47217. this.childAt(0).updateData(lineData, idx, seriesScope);
  47218. this._updateEffectSymbol(lineData, idx);
  47219. };
  47220. effectLineProto.updateSymbolPosition = function (symbol) {
  47221. var p1 = symbol.__p1;
  47222. var p2 = symbol.__p2;
  47223. var cp1 = symbol.__cp1;
  47224. var t = symbol.__t;
  47225. var pos = symbol.position;
  47226. var quadraticAt$$1 = quadraticAt;
  47227. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  47228. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  47229. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  47230. // Tangent
  47231. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  47232. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  47233. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  47234. symbol.ignore = false;
  47235. };
  47236. effectLineProto.updateLayout = function (lineData, idx) {
  47237. this.childAt(0).updateLayout(lineData, idx);
  47238. var effectModel = lineData.getItemModel(idx).getModel('effect');
  47239. this._updateEffectAnimation(lineData, effectModel, idx);
  47240. };
  47241. inherits(EffectLine, Group);
  47242. /**
  47243. * @module echarts/chart/helper/Line
  47244. */
  47245. /**
  47246. * @constructor
  47247. * @extends {module:zrender/graphic/Group}
  47248. * @alias {module:echarts/chart/helper/Polyline}
  47249. */
  47250. function Polyline$2(lineData, idx, seriesScope) {
  47251. Group.call(this);
  47252. this._createPolyline(lineData, idx, seriesScope);
  47253. }
  47254. var polylineProto = Polyline$2.prototype;
  47255. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  47256. // var seriesModel = lineData.hostModel;
  47257. var points = lineData.getItemLayout(idx);
  47258. var line = new Polyline({
  47259. shape: {
  47260. points: points
  47261. }
  47262. });
  47263. this.add(line);
  47264. this._updateCommonStl(lineData, idx, seriesScope);
  47265. };
  47266. polylineProto.updateData = function (lineData, idx, seriesScope) {
  47267. var seriesModel = lineData.hostModel;
  47268. var line = this.childAt(0);
  47269. var target = {
  47270. shape: {
  47271. points: lineData.getItemLayout(idx)
  47272. }
  47273. };
  47274. updateProps(line, target, seriesModel, idx);
  47275. this._updateCommonStl(lineData, idx, seriesScope);
  47276. };
  47277. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  47278. var line = this.childAt(0);
  47279. var itemModel = lineData.getItemModel(idx);
  47280. var visualColor = lineData.getItemVisual(idx, 'color');
  47281. var lineStyle = seriesScope && seriesScope.lineStyle;
  47282. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  47283. if (!seriesScope || lineData.hasItemOption) {
  47284. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  47285. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  47286. }
  47287. line.useStyle(defaults(
  47288. {
  47289. strokeNoScale: true,
  47290. fill: 'none',
  47291. stroke: visualColor
  47292. },
  47293. lineStyle
  47294. ));
  47295. line.hoverStyle = hoverLineStyle;
  47296. setHoverStyle(this);
  47297. };
  47298. polylineProto.updateLayout = function (lineData, idx) {
  47299. var polyline = this.childAt(0);
  47300. polyline.setShape('points', lineData.getItemLayout(idx));
  47301. };
  47302. inherits(Polyline$2, Group);
  47303. /**
  47304. * Provide effect for line
  47305. * @module echarts/chart/helper/EffectLine
  47306. */
  47307. /**
  47308. * @constructor
  47309. * @extends {module:echarts/chart/helper/EffectLine}
  47310. * @alias {module:echarts/chart/helper/Polyline}
  47311. */
  47312. function EffectPolyline(lineData, idx, seriesScope) {
  47313. EffectLine.call(this, lineData, idx, seriesScope);
  47314. this._lastFrame = 0;
  47315. this._lastFramePercent = 0;
  47316. }
  47317. var effectPolylineProto = EffectPolyline.prototype;
  47318. // Overwrite
  47319. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  47320. return new Polyline$2(lineData, idx, seriesScope);
  47321. };
  47322. // Overwrite
  47323. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  47324. this._points = points;
  47325. var accLenArr = [0];
  47326. var len$$1 = 0;
  47327. for (var i = 1; i < points.length; i++) {
  47328. var p1 = points[i - 1];
  47329. var p2 = points[i];
  47330. len$$1 += dist(p1, p2);
  47331. accLenArr.push(len$$1);
  47332. }
  47333. if (len$$1 === 0) {
  47334. return;
  47335. }
  47336. for (var i = 0; i < accLenArr.length; i++) {
  47337. accLenArr[i] /= len$$1;
  47338. }
  47339. this._offsets = accLenArr;
  47340. this._length = len$$1;
  47341. };
  47342. // Overwrite
  47343. effectPolylineProto.getLineLength = function (symbol) {
  47344. return this._length;
  47345. };
  47346. // Overwrite
  47347. effectPolylineProto.updateSymbolPosition = function (symbol) {
  47348. var t = symbol.__t;
  47349. var points = this._points;
  47350. var offsets = this._offsets;
  47351. var len$$1 = points.length;
  47352. if (!offsets) {
  47353. // Has length 0
  47354. return;
  47355. }
  47356. var lastFrame = this._lastFrame;
  47357. var frame;
  47358. if (t < this._lastFramePercent) {
  47359. // Start from the next frame
  47360. // PENDING start from lastFrame ?
  47361. var start = Math.min(lastFrame + 1, len$$1 - 1);
  47362. for (frame = start; frame >= 0; frame--) {
  47363. if (offsets[frame] <= t) {
  47364. break;
  47365. }
  47366. }
  47367. // PENDING really need to do this ?
  47368. frame = Math.min(frame, len$$1 - 2);
  47369. }
  47370. else {
  47371. for (var frame = lastFrame; frame < len$$1; frame++) {
  47372. if (offsets[frame] > t) {
  47373. break;
  47374. }
  47375. }
  47376. frame = Math.min(frame - 1, len$$1 - 2);
  47377. }
  47378. lerp(
  47379. symbol.position, points[frame], points[frame + 1],
  47380. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  47381. );
  47382. var tx = points[frame + 1][0] - points[frame][0];
  47383. var ty = points[frame + 1][1] - points[frame][1];
  47384. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  47385. this._lastFrame = frame;
  47386. this._lastFramePercent = t;
  47387. symbol.ignore = false;
  47388. };
  47389. inherits(EffectPolyline, EffectLine);
  47390. // TODO Batch by color
  47391. var LargeLineShape = extendShape({
  47392. shape: {
  47393. polyline: false,
  47394. curveness: 0,
  47395. segs: []
  47396. },
  47397. buildPath: function (path, shape) {
  47398. var segs = shape.segs;
  47399. var curveness = shape.curveness;
  47400. if (shape.polyline) {
  47401. for (var i = 0; i < segs.length;) {
  47402. var count = segs[i++];
  47403. if (count > 0) {
  47404. path.moveTo(segs[i++], segs[i++]);
  47405. for (var k = 1; k < count; k++) {
  47406. path.lineTo(segs[i++], segs[i++]);
  47407. }
  47408. }
  47409. }
  47410. }
  47411. else {
  47412. for (var i = 0; i < segs.length;) {
  47413. var x0 = segs[i++];
  47414. var y0 = segs[i++];
  47415. var x1 = segs[i++];
  47416. var y1 = segs[i++];
  47417. path.moveTo(x0, y0);
  47418. if (curveness > 0) {
  47419. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  47420. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  47421. path.quadraticCurveTo(x2, y2, x1, y1);
  47422. }
  47423. else {
  47424. path.lineTo(x1, y1);
  47425. }
  47426. }
  47427. }
  47428. },
  47429. findDataIndex: function (x, y) {
  47430. var shape = this.shape;
  47431. var segs = shape.segs;
  47432. var curveness = shape.curveness;
  47433. if (shape.polyline) {
  47434. var dataIndex = 0;
  47435. for (var i = 0; i < segs.length;) {
  47436. var count = segs[i++];
  47437. if (count > 0) {
  47438. var x0 = segs[i++];
  47439. var y0 = segs[i++];
  47440. for (var k = 1; k < count; k++) {
  47441. var x1 = segs[i++];
  47442. var y1 = segs[i++];
  47443. if (containStroke$1(x0, y0, x1, y1)) {
  47444. return dataIndex;
  47445. }
  47446. }
  47447. }
  47448. dataIndex++;
  47449. }
  47450. }
  47451. else {
  47452. var dataIndex = 0;
  47453. for (var i = 0; i < segs.length;) {
  47454. var x0 = segs[i++];
  47455. var y0 = segs[i++];
  47456. var x1 = segs[i++];
  47457. var y1 = segs[i++];
  47458. if (curveness > 0) {
  47459. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  47460. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  47461. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  47462. return dataIndex;
  47463. }
  47464. }
  47465. else {
  47466. if (containStroke$1(x0, y0, x1, y1)) {
  47467. return dataIndex;
  47468. }
  47469. }
  47470. dataIndex++;
  47471. }
  47472. }
  47473. return -1;
  47474. }
  47475. });
  47476. function LargeLineDraw() {
  47477. this.group = new Group();
  47478. }
  47479. var largeLineProto = LargeLineDraw.prototype;
  47480. largeLineProto.isPersistent = function () {
  47481. return !this._incremental;
  47482. };
  47483. /**
  47484. * Update symbols draw by new data
  47485. * @param {module:echarts/data/List} data
  47486. */
  47487. largeLineProto.updateData = function (data) {
  47488. this.group.removeAll();
  47489. var lineEl = new LargeLineShape({
  47490. rectHover: true,
  47491. cursor: 'default'
  47492. });
  47493. lineEl.setShape({
  47494. segs: data.getLayout('linesPoints')
  47495. });
  47496. this._setCommon(lineEl, data);
  47497. // Add back
  47498. this.group.add(lineEl);
  47499. this._incremental = null;
  47500. };
  47501. /**
  47502. * @override
  47503. */
  47504. largeLineProto.incrementalPrepareUpdate = function (data) {
  47505. this.group.removeAll();
  47506. this._clearIncremental();
  47507. if (data.count() > 5e5) {
  47508. if (!this._incremental) {
  47509. this._incremental = new IncrementalDisplayble({
  47510. silent: true
  47511. });
  47512. }
  47513. this.group.add(this._incremental);
  47514. }
  47515. else {
  47516. this._incremental = null;
  47517. }
  47518. };
  47519. /**
  47520. * @override
  47521. */
  47522. largeLineProto.incrementalUpdate = function (taskParams, data) {
  47523. var lineEl = new LargeLineShape();
  47524. lineEl.setShape({
  47525. segs: data.getLayout('linesPoints')
  47526. });
  47527. this._setCommon(lineEl, data, !!this._incremental);
  47528. if (!this._incremental) {
  47529. lineEl.rectHover = true;
  47530. lineEl.cursor = 'default';
  47531. lineEl.__startIndex = taskParams.start;
  47532. this.group.add(lineEl);
  47533. }
  47534. else {
  47535. this._incremental.addDisplayable(lineEl, true);
  47536. }
  47537. };
  47538. /**
  47539. * @override
  47540. */
  47541. largeLineProto.remove = function () {
  47542. this._clearIncremental();
  47543. this._incremental = null;
  47544. this.group.removeAll();
  47545. };
  47546. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  47547. var hostModel = data.hostModel;
  47548. lineEl.setShape({
  47549. polyline: hostModel.get('polyline'),
  47550. curveness: hostModel.get('lineStyle.curveness')
  47551. });
  47552. lineEl.useStyle(
  47553. hostModel.getModel('lineStyle').getLineStyle()
  47554. );
  47555. lineEl.style.strokeNoScale = true;
  47556. var visualColor = data.getVisual('color');
  47557. if (visualColor) {
  47558. lineEl.setStyle('stroke', visualColor);
  47559. }
  47560. lineEl.setStyle('fill');
  47561. if (!isIncremental) {
  47562. // Enable tooltip
  47563. // PENDING May have performance issue when path is extremely large
  47564. lineEl.seriesIndex = hostModel.seriesIndex;
  47565. lineEl.on('mousemove', function (e) {
  47566. lineEl.dataIndex = null;
  47567. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  47568. if (dataIndex > 0) {
  47569. // Provide dataIndex for tooltip
  47570. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  47571. }
  47572. });
  47573. }
  47574. };
  47575. largeLineProto._clearIncremental = function () {
  47576. var incremental = this._incremental;
  47577. if (incremental) {
  47578. incremental.clearDisplaybles();
  47579. }
  47580. };
  47581. var linesLayout = {
  47582. seriesType: 'lines',
  47583. plan: createRenderPlanner(),
  47584. reset: function (seriesModel) {
  47585. var coordSys = seriesModel.coordinateSystem;
  47586. var isPolyline = seriesModel.get('polyline');
  47587. var isLarge = seriesModel.pipelineContext.large;
  47588. function progress(params, lineData) {
  47589. var lineCoords = [];
  47590. if (isLarge) {
  47591. var points;
  47592. var segCount = params.end - params.start;
  47593. if (isPolyline) {
  47594. var totalCoordsCount = 0;
  47595. for (var i = params.start; i < params.end; i++) {
  47596. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  47597. }
  47598. points = new Float32Array(segCount + totalCoordsCount * 2);
  47599. }
  47600. else {
  47601. points = new Float32Array(segCount * 2);
  47602. }
  47603. var offset = 0;
  47604. var pt = [];
  47605. for (var i = params.start; i < params.end; i++) {
  47606. var len = seriesModel.getLineCoords(i, lineCoords);
  47607. if (isPolyline) {
  47608. points[offset++] = len;
  47609. }
  47610. for (var k = 0; k < len; k++) {
  47611. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  47612. points[offset++] = pt[0];
  47613. points[offset++] = pt[1];
  47614. }
  47615. }
  47616. lineData.setLayout('linesPoints', points);
  47617. }
  47618. else {
  47619. for (var i = params.start; i < params.end; i++) {
  47620. var itemModel = lineData.getItemModel(i);
  47621. var len = seriesModel.getLineCoords(i, lineCoords);
  47622. var pts = [];
  47623. if (isPolyline) {
  47624. for (var j = 0; j < len; j++) {
  47625. pts.push(coordSys.dataToPoint(lineCoords[j]));
  47626. }
  47627. }
  47628. else {
  47629. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  47630. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  47631. var curveness = itemModel.get('lineStyle.curveness');
  47632. if (+curveness) {
  47633. pts[2] = [
  47634. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  47635. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  47636. ];
  47637. }
  47638. }
  47639. lineData.setItemLayout(i, pts);
  47640. }
  47641. }
  47642. }
  47643. return { progress: progress };
  47644. }
  47645. };
  47646. extendChartView({
  47647. type: 'lines',
  47648. init: function () {},
  47649. render: function (seriesModel, ecModel, api) {
  47650. var data = seriesModel.getData();
  47651. var lineDraw = this._updateLineDraw(data, seriesModel);
  47652. var zlevel = seriesModel.get('zlevel');
  47653. var trailLength = seriesModel.get('effect.trailLength');
  47654. var zr = api.getZr();
  47655. // Avoid the drag cause ghost shadow
  47656. // FIXME Better way ?
  47657. // SVG doesn't support
  47658. var isSvg = zr.painter.getType() === 'svg';
  47659. if (!isSvg) {
  47660. zr.painter.getLayer(zlevel).clear(true);
  47661. }
  47662. // Config layer with motion blur
  47663. if (this._lastZlevel != null && !isSvg) {
  47664. zr.configLayer(this._lastZlevel, {
  47665. motionBlur: false
  47666. });
  47667. }
  47668. if (this._showEffect(seriesModel) && trailLength) {
  47669. if (__DEV__) {
  47670. var notInIndividual = false;
  47671. ecModel.eachSeries(function (otherSeriesModel) {
  47672. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  47673. notInIndividual = true;
  47674. }
  47675. });
  47676. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  47677. }
  47678. if (!isSvg) {
  47679. zr.configLayer(zlevel, {
  47680. motionBlur: true,
  47681. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  47682. });
  47683. }
  47684. }
  47685. lineDraw.updateData(data);
  47686. this._lastZlevel = zlevel;
  47687. this._finished = true;
  47688. },
  47689. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  47690. var data = seriesModel.getData();
  47691. var lineDraw = this._updateLineDraw(data, seriesModel);
  47692. lineDraw.incrementalPrepareUpdate(data);
  47693. this._clearLayer(api);
  47694. this._finished = false;
  47695. },
  47696. incrementalRender: function (taskParams, seriesModel, ecModel) {
  47697. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  47698. this._finished = taskParams.end === seriesModel.getData().count();
  47699. },
  47700. updateTransform: function (seriesModel, ecModel, api) {
  47701. var data = seriesModel.getData();
  47702. if (!this._finished || seriesModel.pipelineContext.large) {
  47703. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  47704. return {
  47705. update: true
  47706. };
  47707. }
  47708. else {
  47709. // TODO Use same logic with ScatterView.
  47710. // Manually update layout
  47711. var res = linesLayout.reset(seriesModel);
  47712. if (res.progress) {
  47713. res.progress({ start: 0, end: data.count() }, data);
  47714. }
  47715. this._lineDraw.updateLayout();
  47716. this._clearLayer(api);
  47717. }
  47718. },
  47719. _updateLineDraw: function (data, seriesModel) {
  47720. var lineDraw = this._lineDraw;
  47721. var hasEffect = this._showEffect(seriesModel);
  47722. var isPolyline = !!seriesModel.get('polyline');
  47723. var pipelineContext = seriesModel.pipelineContext;
  47724. var isLargeDraw = pipelineContext.large;
  47725. if (__DEV__) {
  47726. if (hasEffect && isLargeDraw) {
  47727. console.warn('Large lines not support effect');
  47728. }
  47729. }
  47730. if (!lineDraw
  47731. || hasEffect !== this._hasEffet
  47732. || isPolyline !== this._isPolyline
  47733. || isLargeDraw !== this._isLargeDraw
  47734. ) {
  47735. if (lineDraw) {
  47736. lineDraw.remove();
  47737. }
  47738. lineDraw = this._lineDraw = isLargeDraw
  47739. ? new LargeLineDraw()
  47740. : new LineDraw(
  47741. isPolyline
  47742. ? (hasEffect ? EffectPolyline : Polyline$2)
  47743. : (hasEffect ? EffectLine : Line$1)
  47744. );
  47745. this._hasEffet = hasEffect;
  47746. this._isPolyline = isPolyline;
  47747. this._isLargeDraw = isLargeDraw;
  47748. this.group.removeAll();
  47749. }
  47750. this.group.add(lineDraw.group);
  47751. return lineDraw;
  47752. },
  47753. _showEffect: function (seriesModel) {
  47754. return !!seriesModel.get('effect.show');
  47755. },
  47756. _clearLayer: function (api) {
  47757. // Not use motion when dragging or zooming
  47758. var zr = api.getZr();
  47759. var isSvg = zr.painter.getType() === 'svg';
  47760. if (!isSvg && this._lastZlevel != null) {
  47761. zr.painter.getLayer(this._lastZlevel).clear(true);
  47762. }
  47763. },
  47764. remove: function (ecModel, api) {
  47765. this._lineDraw && this._lineDraw.remove();
  47766. this._lineDraw = null;
  47767. // Clear motion when lineDraw is removed
  47768. this._clearLayer(api);
  47769. },
  47770. dispose: function () {}
  47771. });
  47772. function normalize$2(a) {
  47773. if (!(a instanceof Array)) {
  47774. a = [a, a];
  47775. }
  47776. return a;
  47777. }
  47778. var opacityQuery = 'lineStyle.opacity'.split('.');
  47779. var linesVisual = {
  47780. seriesType: 'lines',
  47781. reset: function (seriesModel, ecModel, api) {
  47782. var symbolType = normalize$2(seriesModel.get('symbol'));
  47783. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  47784. var data = seriesModel.getData();
  47785. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  47786. data.setVisual('toSymbol', symbolType && symbolType[1]);
  47787. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  47788. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  47789. data.setVisual('opacity', seriesModel.get(opacityQuery));
  47790. function dataEach(data, idx) {
  47791. var itemModel = data.getItemModel(idx);
  47792. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  47793. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  47794. var opacity = itemModel.get(opacityQuery);
  47795. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  47796. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  47797. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  47798. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  47799. data.setItemVisual(idx, 'opacity', opacity);
  47800. }
  47801. return {dataEach: data.hasItemOption ? dataEach : null};
  47802. }
  47803. };
  47804. registerLayout(linesLayout);
  47805. registerVisual(linesVisual);
  47806. SeriesModel.extend({
  47807. type: 'series.heatmap',
  47808. getInitialData: function (option, ecModel) {
  47809. return createListFromArray(this.getSource(), this, {
  47810. generateCoord: 'value'
  47811. });
  47812. },
  47813. preventIncremental: function () {
  47814. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  47815. if (coordSysCreator && coordSysCreator.dimensions) {
  47816. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  47817. }
  47818. },
  47819. defaultOption: {
  47820. // Cartesian2D or geo
  47821. coordinateSystem: 'cartesian2d',
  47822. zlevel: 0,
  47823. z: 2,
  47824. // Cartesian coordinate system
  47825. // xAxisIndex: 0,
  47826. // yAxisIndex: 0,
  47827. // Geo coordinate system
  47828. geoIndex: 0,
  47829. blurSize: 30,
  47830. pointSize: 20,
  47831. maxOpacity: 1,
  47832. minOpacity: 0
  47833. }
  47834. });
  47835. /**
  47836. * @file defines echarts Heatmap Chart
  47837. * @author Ovilia (me@zhangwenli.com)
  47838. * Inspired by https://github.com/mourner/simpleheat
  47839. *
  47840. * @module
  47841. */
  47842. var GRADIENT_LEVELS = 256;
  47843. /**
  47844. * Heatmap Chart
  47845. *
  47846. * @class
  47847. */
  47848. function Heatmap() {
  47849. var canvas = createCanvas();
  47850. this.canvas = canvas;
  47851. this.blurSize = 30;
  47852. this.pointSize = 20;
  47853. this.maxOpacity = 1;
  47854. this.minOpacity = 0;
  47855. this._gradientPixels = {};
  47856. }
  47857. Heatmap.prototype = {
  47858. /**
  47859. * Renders Heatmap and returns the rendered canvas
  47860. * @param {Array} data array of data, each has x, y, value
  47861. * @param {number} width canvas width
  47862. * @param {number} height canvas height
  47863. */
  47864. update: function(data, width, height, normalize, colorFunc, isInRange) {
  47865. var brush = this._getBrush();
  47866. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  47867. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  47868. var r = this.pointSize + this.blurSize;
  47869. var canvas = this.canvas;
  47870. var ctx = canvas.getContext('2d');
  47871. var len = data.length;
  47872. canvas.width = width;
  47873. canvas.height = height;
  47874. for (var i = 0; i < len; ++i) {
  47875. var p = data[i];
  47876. var x = p[0];
  47877. var y = p[1];
  47878. var value = p[2];
  47879. // calculate alpha using value
  47880. var alpha = normalize(value);
  47881. // draw with the circle brush with alpha
  47882. ctx.globalAlpha = alpha;
  47883. ctx.drawImage(brush, x - r, y - r);
  47884. }
  47885. if (!canvas.width || !canvas.height) {
  47886. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  47887. // 'CanvasRenderingContext2D': The source height is 0."
  47888. return canvas;
  47889. }
  47890. // colorize the canvas using alpha value and set with gradient
  47891. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  47892. var pixels = imageData.data;
  47893. var offset = 0;
  47894. var pixelLen = pixels.length;
  47895. var minOpacity = this.minOpacity;
  47896. var maxOpacity = this.maxOpacity;
  47897. var diffOpacity = maxOpacity - minOpacity;
  47898. while(offset < pixelLen) {
  47899. var alpha = pixels[offset + 3] / 256;
  47900. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  47901. // Simple optimize to ignore the empty data
  47902. if (alpha > 0) {
  47903. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  47904. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  47905. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  47906. pixels[offset++] = gradient[gradientOffset];
  47907. pixels[offset++] = gradient[gradientOffset + 1];
  47908. pixels[offset++] = gradient[gradientOffset + 2];
  47909. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  47910. }
  47911. else {
  47912. offset += 4;
  47913. }
  47914. }
  47915. ctx.putImageData(imageData, 0, 0);
  47916. return canvas;
  47917. },
  47918. /**
  47919. * get canvas of a black circle brush used for canvas to draw later
  47920. * @private
  47921. * @returns {Object} circle brush canvas
  47922. */
  47923. _getBrush: function() {
  47924. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  47925. // set brush size
  47926. var r = this.pointSize + this.blurSize;
  47927. var d = r * 2;
  47928. brushCanvas.width = d;
  47929. brushCanvas.height = d;
  47930. var ctx = brushCanvas.getContext('2d');
  47931. ctx.clearRect(0, 0, d, d);
  47932. // in order to render shadow without the distinct circle,
  47933. // draw the distinct circle in an invisible place,
  47934. // and use shadowOffset to draw shadow in the center of the canvas
  47935. ctx.shadowOffsetX = d;
  47936. ctx.shadowBlur = this.blurSize;
  47937. // draw the shadow in black, and use alpha and shadow blur to generate
  47938. // color in color map
  47939. ctx.shadowColor = '#000';
  47940. // draw circle in the left to the canvas
  47941. ctx.beginPath();
  47942. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  47943. ctx.closePath();
  47944. ctx.fill();
  47945. return brushCanvas;
  47946. },
  47947. /**
  47948. * get gradient color map
  47949. * @private
  47950. */
  47951. _getGradient: function (data, colorFunc, state) {
  47952. var gradientPixels = this._gradientPixels;
  47953. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  47954. var color = [0, 0, 0, 0];
  47955. var off = 0;
  47956. for (var i = 0; i < 256; i++) {
  47957. colorFunc[state](i / 255, true, color);
  47958. pixelsSingleState[off++] = color[0];
  47959. pixelsSingleState[off++] = color[1];
  47960. pixelsSingleState[off++] = color[2];
  47961. pixelsSingleState[off++] = color[3];
  47962. }
  47963. return pixelsSingleState;
  47964. }
  47965. };
  47966. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  47967. var dataSpan = dataExtent[1] - dataExtent[0];
  47968. pieceList = map(pieceList, function (piece) {
  47969. return {
  47970. interval: [
  47971. (piece.interval[0] - dataExtent[0]) / dataSpan,
  47972. (piece.interval[1] - dataExtent[0]) / dataSpan
  47973. ]
  47974. };
  47975. });
  47976. var len = pieceList.length;
  47977. var lastIndex = 0;
  47978. return function (val) {
  47979. // Try to find in the location of the last found
  47980. for (var i = lastIndex; i < len; i++) {
  47981. var interval = pieceList[i].interval;
  47982. if (interval[0] <= val && val <= interval[1]) {
  47983. lastIndex = i;
  47984. break;
  47985. }
  47986. }
  47987. if (i === len) { // Not found, back interation
  47988. for (var i = lastIndex - 1; i >= 0; i--) {
  47989. var interval = pieceList[i].interval;
  47990. if (interval[0] <= val && val <= interval[1]) {
  47991. lastIndex = i;
  47992. break;
  47993. }
  47994. }
  47995. }
  47996. return i >= 0 && i < len && selected[i];
  47997. };
  47998. }
  47999. function getIsInContinuousRange(dataExtent, range) {
  48000. var dataSpan = dataExtent[1] - dataExtent[0];
  48001. range = [
  48002. (range[0] - dataExtent[0]) / dataSpan,
  48003. (range[1] - dataExtent[0]) / dataSpan
  48004. ];
  48005. return function (val) {
  48006. return val >= range[0] && val <= range[1];
  48007. };
  48008. }
  48009. function isGeoCoordSys(coordSys) {
  48010. var dimensions = coordSys.dimensions;
  48011. // Not use coorSys.type === 'geo' because coordSys maybe extended
  48012. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  48013. }
  48014. extendChartView({
  48015. type: 'heatmap',
  48016. render: function (seriesModel, ecModel, api) {
  48017. var visualMapOfThisSeries;
  48018. ecModel.eachComponent('visualMap', function (visualMap) {
  48019. visualMap.eachTargetSeries(function (targetSeries) {
  48020. if (targetSeries === seriesModel) {
  48021. visualMapOfThisSeries = visualMap;
  48022. }
  48023. });
  48024. });
  48025. if (__DEV__) {
  48026. if (!visualMapOfThisSeries) {
  48027. throw new Error('Heatmap must use with visualMap');
  48028. }
  48029. }
  48030. this.group.removeAll();
  48031. this._incrementalDisplayable = null;
  48032. var coordSys = seriesModel.coordinateSystem;
  48033. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  48034. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  48035. }
  48036. else if (isGeoCoordSys(coordSys)) {
  48037. this._renderOnGeo(
  48038. coordSys, seriesModel, visualMapOfThisSeries, api
  48039. );
  48040. }
  48041. },
  48042. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  48043. this.group.removeAll();
  48044. },
  48045. incrementalRender: function (params, seriesModel, ecModel, api) {
  48046. var coordSys = seriesModel.coordinateSystem;
  48047. if (coordSys) {
  48048. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  48049. }
  48050. },
  48051. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  48052. var coordSys = seriesModel.coordinateSystem;
  48053. var width;
  48054. var height;
  48055. if (coordSys.type === 'cartesian2d') {
  48056. var xAxis = coordSys.getAxis('x');
  48057. var yAxis = coordSys.getAxis('y');
  48058. if (__DEV__) {
  48059. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  48060. throw new Error('Heatmap on cartesian must have two category axes');
  48061. }
  48062. if (!(xAxis.onBand && yAxis.onBand)) {
  48063. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  48064. }
  48065. }
  48066. width = xAxis.getBandWidth();
  48067. height = yAxis.getBandWidth();
  48068. }
  48069. var group = this.group;
  48070. var data = seriesModel.getData();
  48071. var itemStyleQuery = 'itemStyle';
  48072. var hoverItemStyleQuery = 'emphasis.itemStyle';
  48073. var labelQuery = 'label';
  48074. var hoverLabelQuery = 'emphasis.label';
  48075. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  48076. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  48077. var labelModel = seriesModel.getModel(labelQuery);
  48078. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  48079. var coordSysType = coordSys.type;
  48080. var dataDims = coordSysType === 'cartesian2d'
  48081. ? [
  48082. data.mapDimension('x'),
  48083. data.mapDimension('y'),
  48084. data.mapDimension('value')
  48085. ]
  48086. : [
  48087. data.mapDimension('time'),
  48088. data.mapDimension('value')
  48089. ];
  48090. for (var idx = start; idx < end; idx++) {
  48091. var rect;
  48092. if (coordSysType === 'cartesian2d') {
  48093. // Ignore empty data
  48094. if (isNaN(data.get(dataDims[2], idx))) {
  48095. continue;
  48096. }
  48097. var point = coordSys.dataToPoint([
  48098. data.get(dataDims[0], idx),
  48099. data.get(dataDims[1], idx)
  48100. ]);
  48101. rect = new Rect({
  48102. shape: {
  48103. x: point[0] - width / 2,
  48104. y: point[1] - height / 2,
  48105. width: width,
  48106. height: height
  48107. },
  48108. style: {
  48109. fill: data.getItemVisual(idx, 'color'),
  48110. opacity: data.getItemVisual(idx, 'opacity')
  48111. }
  48112. });
  48113. }
  48114. else {
  48115. // Ignore empty data
  48116. if (isNaN(data.get(dataDims[1], idx))) {
  48117. continue;
  48118. }
  48119. rect = new Rect({
  48120. z2: 1,
  48121. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  48122. style: {
  48123. fill: data.getItemVisual(idx, 'color'),
  48124. opacity: data.getItemVisual(idx, 'opacity')
  48125. }
  48126. });
  48127. }
  48128. var itemModel = data.getItemModel(idx);
  48129. // Optimization for large datset
  48130. if (data.hasItemOption) {
  48131. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  48132. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  48133. labelModel = itemModel.getModel(labelQuery);
  48134. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  48135. }
  48136. var rawValue = seriesModel.getRawValue(idx);
  48137. var defaultText = '-';
  48138. if (rawValue && rawValue[2] != null) {
  48139. defaultText = rawValue[2];
  48140. }
  48141. setLabelStyle(
  48142. style, hoverStl, labelModel, hoverLabelModel,
  48143. {
  48144. labelFetcher: seriesModel,
  48145. labelDataIndex: idx,
  48146. defaultText: defaultText,
  48147. isRectText: true
  48148. }
  48149. );
  48150. rect.setStyle(style);
  48151. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  48152. rect.incremental = incremental;
  48153. // PENDING
  48154. if (incremental) {
  48155. // Rect must use hover layer if it's incremental.
  48156. rect.useHoverLayer = true;
  48157. }
  48158. group.add(rect);
  48159. data.setItemGraphicEl(idx, rect);
  48160. }
  48161. },
  48162. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  48163. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  48164. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  48165. // if (!visualMapping) {
  48166. // throw new Error('Data range must have color visuals');
  48167. // }
  48168. var data = seriesModel.getData();
  48169. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  48170. hmLayer.blurSize = seriesModel.get('blurSize');
  48171. hmLayer.pointSize = seriesModel.get('pointSize');
  48172. hmLayer.minOpacity = seriesModel.get('minOpacity');
  48173. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  48174. var rect = geo.getViewRect().clone();
  48175. var roamTransform = geo.getRoamTransform();
  48176. rect.applyTransform(roamTransform);
  48177. // Clamp on viewport
  48178. var x = Math.max(rect.x, 0);
  48179. var y = Math.max(rect.y, 0);
  48180. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  48181. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  48182. var width = x2 - x;
  48183. var height = y2 - y;
  48184. var dims = [
  48185. data.mapDimension('lng'),
  48186. data.mapDimension('lat'),
  48187. data.mapDimension('value')
  48188. ];
  48189. var points = data.mapArray(dims, function (lng, lat, value) {
  48190. var pt = geo.dataToPoint([lng, lat]);
  48191. pt[0] -= x;
  48192. pt[1] -= y;
  48193. pt.push(value);
  48194. return pt;
  48195. });
  48196. var dataExtent = visualMapModel.getExtent();
  48197. var isInRange = visualMapModel.type === 'visualMap.continuous'
  48198. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  48199. : getIsInPiecewiseRange(
  48200. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  48201. );
  48202. hmLayer.update(
  48203. points, width, height,
  48204. inRangeVisuals.color.getNormalizer(),
  48205. {
  48206. inRange: inRangeVisuals.color.getColorMapper(),
  48207. outOfRange: outOfRangeVisuals.color.getColorMapper()
  48208. },
  48209. isInRange
  48210. );
  48211. var img = new ZImage({
  48212. style: {
  48213. width: width,
  48214. height: height,
  48215. x: x,
  48216. y: y,
  48217. image: hmLayer.canvas
  48218. },
  48219. silent: true
  48220. });
  48221. this.group.add(img);
  48222. },
  48223. dispose: function () {}
  48224. });
  48225. var PictorialBarSeries = BaseBarSeries.extend({
  48226. type: 'series.pictorialBar',
  48227. dependencies: ['grid'],
  48228. defaultOption: {
  48229. symbol: 'circle', // Customized bar shape
  48230. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  48231. symbolRotate: null,
  48232. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  48233. symbolOffset: null,
  48234. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  48235. // Auto margin by defualt.
  48236. symbolRepeat: false, // false/null/undefined, means no repeat.
  48237. // Can be true, means auto calculate repeat times and cut by data.
  48238. // Can be a number, specifies repeat times, and do not cut by data.
  48239. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  48240. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  48241. symbolClip: false,
  48242. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  48243. symbolPatternSize: 400, // 400 * 400 px
  48244. barGap: '-100%', // In most case, overlap is needed.
  48245. // z can be set in data item, which is z2 actually.
  48246. // Disable progressive
  48247. progressive: 0,
  48248. hoverAnimation: false // Open only when needed.
  48249. },
  48250. getInitialData: function (option) {
  48251. // Disable stack.
  48252. option.stack = null;
  48253. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  48254. }
  48255. });
  48256. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  48257. // index: +isHorizontal
  48258. var LAYOUT_ATTRS = [
  48259. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  48260. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  48261. ];
  48262. var pathForLineWidth = new Circle();
  48263. var BarView$1 = extendChartView({
  48264. type: 'pictorialBar',
  48265. render: function (seriesModel, ecModel, api) {
  48266. var group = this.group;
  48267. var data = seriesModel.getData();
  48268. var oldData = this._data;
  48269. var cartesian = seriesModel.coordinateSystem;
  48270. var baseAxis = cartesian.getBaseAxis();
  48271. var isHorizontal = !!baseAxis.isHorizontal();
  48272. var coordSysRect = cartesian.grid.getRect();
  48273. var opt = {
  48274. ecSize: {width: api.getWidth(), height: api.getHeight()},
  48275. seriesModel: seriesModel,
  48276. coordSys: cartesian,
  48277. coordSysExtent: [
  48278. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  48279. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  48280. ],
  48281. isHorizontal: isHorizontal,
  48282. valueDim: LAYOUT_ATTRS[+isHorizontal],
  48283. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  48284. };
  48285. data.diff(oldData)
  48286. .add(function (dataIndex) {
  48287. if (!data.hasValue(dataIndex)) {
  48288. return;
  48289. }
  48290. var itemModel = getItemModel(data, dataIndex);
  48291. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  48292. var bar = createBar(data, opt, symbolMeta);
  48293. data.setItemGraphicEl(dataIndex, bar);
  48294. group.add(bar);
  48295. updateCommon$1(bar, opt, symbolMeta);
  48296. })
  48297. .update(function (newIndex, oldIndex) {
  48298. var bar = oldData.getItemGraphicEl(oldIndex);
  48299. if (!data.hasValue(newIndex)) {
  48300. group.remove(bar);
  48301. return;
  48302. }
  48303. var itemModel = getItemModel(data, newIndex);
  48304. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  48305. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  48306. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  48307. group.remove(bar);
  48308. data.setItemGraphicEl(newIndex, null);
  48309. bar = null;
  48310. }
  48311. if (bar) {
  48312. updateBar(bar, opt, symbolMeta);
  48313. }
  48314. else {
  48315. bar = createBar(data, opt, symbolMeta, true);
  48316. }
  48317. data.setItemGraphicEl(newIndex, bar);
  48318. bar.__pictorialSymbolMeta = symbolMeta;
  48319. // Add back
  48320. group.add(bar);
  48321. updateCommon$1(bar, opt, symbolMeta);
  48322. })
  48323. .remove(function (dataIndex) {
  48324. var bar = oldData.getItemGraphicEl(dataIndex);
  48325. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  48326. })
  48327. .execute();
  48328. this._data = data;
  48329. return this.group;
  48330. },
  48331. dispose: noop,
  48332. remove: function (ecModel, api) {
  48333. var group = this.group;
  48334. var data = this._data;
  48335. if (ecModel.get('animation')) {
  48336. if (data) {
  48337. data.eachItemGraphicEl(function (bar) {
  48338. removeBar(data, bar.dataIndex, ecModel, bar);
  48339. });
  48340. }
  48341. }
  48342. else {
  48343. group.removeAll();
  48344. }
  48345. }
  48346. });
  48347. // Set or calculate default value about symbol, and calculate layout info.
  48348. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  48349. var layout = data.getItemLayout(dataIndex);
  48350. var symbolRepeat = itemModel.get('symbolRepeat');
  48351. var symbolClip = itemModel.get('symbolClip');
  48352. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  48353. var symbolRotate = itemModel.get('symbolRotate');
  48354. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  48355. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  48356. var isAnimationEnabled = itemModel.isAnimationEnabled();
  48357. var symbolMeta = {
  48358. dataIndex: dataIndex,
  48359. layout: layout,
  48360. itemModel: itemModel,
  48361. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  48362. color: data.getItemVisual(dataIndex, 'color'),
  48363. symbolClip: symbolClip,
  48364. symbolRepeat: symbolRepeat,
  48365. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  48366. symbolPatternSize: symbolPatternSize,
  48367. rotation: rotation,
  48368. animationModel: isAnimationEnabled ? itemModel : null,
  48369. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  48370. z2: itemModel.getShallow('z', true) || 0
  48371. };
  48372. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  48373. prepareSymbolSize(
  48374. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  48375. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  48376. );
  48377. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  48378. var symbolSize = symbolMeta.symbolSize;
  48379. var symbolOffset = itemModel.get('symbolOffset');
  48380. if (isArray(symbolOffset)) {
  48381. symbolOffset = [
  48382. parsePercent$1(symbolOffset[0], symbolSize[0]),
  48383. parsePercent$1(symbolOffset[1], symbolSize[1])
  48384. ];
  48385. }
  48386. prepareLayoutInfo(
  48387. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  48388. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  48389. opt, symbolMeta
  48390. );
  48391. return symbolMeta;
  48392. }
  48393. // bar length can be negative.
  48394. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  48395. var valueDim = opt.valueDim;
  48396. var symbolBoundingData = itemModel.get('symbolBoundingData');
  48397. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  48398. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  48399. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  48400. var boundingLength;
  48401. if (isArray(symbolBoundingData)) {
  48402. var symbolBoundingExtent = [
  48403. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  48404. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  48405. ];
  48406. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  48407. boundingLength = symbolBoundingExtent[pxSignIdx];
  48408. }
  48409. else if (symbolBoundingData != null) {
  48410. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  48411. }
  48412. else if (symbolRepeat) {
  48413. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  48414. }
  48415. else {
  48416. boundingLength = layout[valueDim.wh];
  48417. }
  48418. output.boundingLength = boundingLength;
  48419. if (symbolRepeat) {
  48420. output.repeatCutLength = layout[valueDim.wh];
  48421. }
  48422. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  48423. }
  48424. function convertToCoordOnAxis(axis, value) {
  48425. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  48426. }
  48427. // Support ['100%', '100%']
  48428. function prepareSymbolSize(
  48429. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  48430. pxSign, symbolPatternSize, opt, output
  48431. ) {
  48432. var valueDim = opt.valueDim;
  48433. var categoryDim = opt.categoryDim;
  48434. var categorySize = Math.abs(layout[categoryDim.wh]);
  48435. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  48436. if (isArray(symbolSize)) {
  48437. symbolSize = symbolSize.slice();
  48438. }
  48439. else {
  48440. if (symbolSize == null) {
  48441. symbolSize = '100%';
  48442. }
  48443. symbolSize = [symbolSize, symbolSize];
  48444. }
  48445. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  48446. // to complicated to calculate real percent value if considering scaled lineWidth.
  48447. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  48448. // which can be tolerated in pictorial chart.
  48449. symbolSize[categoryDim.index] = parsePercent$1(
  48450. symbolSize[categoryDim.index],
  48451. categorySize
  48452. );
  48453. symbolSize[valueDim.index] = parsePercent$1(
  48454. symbolSize[valueDim.index],
  48455. symbolRepeat ? categorySize : Math.abs(boundingLength)
  48456. );
  48457. output.symbolSize = symbolSize;
  48458. // If x or y is less than zero, show reversed shape.
  48459. var symbolScale = output.symbolScale = [
  48460. symbolSize[0] / symbolPatternSize,
  48461. symbolSize[1] / symbolPatternSize
  48462. ];
  48463. // Follow convention, 'right' and 'top' is the normal scale.
  48464. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  48465. }
  48466. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  48467. // In symbols are drawn with scale, so do not need to care about the case that width
  48468. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  48469. // be calculated.
  48470. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  48471. if (valueLineWidth) {
  48472. pathForLineWidth.attr({
  48473. scale: symbolScale.slice(),
  48474. rotation: rotation
  48475. });
  48476. pathForLineWidth.updateTransform();
  48477. valueLineWidth /= pathForLineWidth.getLineScale();
  48478. valueLineWidth *= symbolScale[opt.valueDim.index];
  48479. }
  48480. output.valueLineWidth = valueLineWidth;
  48481. }
  48482. function prepareLayoutInfo(
  48483. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  48484. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  48485. ) {
  48486. var categoryDim = opt.categoryDim;
  48487. var valueDim = opt.valueDim;
  48488. var pxSign = output.pxSign;
  48489. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  48490. var pathLen = unitLength;
  48491. // Note: rotation will not effect the layout of symbols, because user may
  48492. // want symbols to rotate on its center, which should not be translated
  48493. // when rotating.
  48494. if (symbolRepeat) {
  48495. var absBoundingLength = Math.abs(boundingLength);
  48496. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  48497. var hasEndGap = false;
  48498. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  48499. hasEndGap = true;
  48500. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  48501. }
  48502. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  48503. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  48504. // When symbol margin is less than 0, margin at both ends will be subtracted
  48505. // to ensure that all of the symbols will not be overflow the given area.
  48506. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  48507. // Both final repeatTimes and final symbolMargin area calculated based on
  48508. // boundingLength.
  48509. var repeatSpecified = isNumeric(symbolRepeat);
  48510. var repeatTimes = repeatSpecified
  48511. ? symbolRepeat
  48512. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  48513. // Adjust calculate margin, to ensure each symbol is displayed
  48514. // entirely in the given layout area.
  48515. var mDiff = absBoundingLength - repeatTimes * unitLength;
  48516. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  48517. uLenWithMargin = unitLength + symbolMargin * 2;
  48518. endFix = hasEndGap ? 0 : symbolMargin * 2;
  48519. // Update repeatTimes when not all symbol will be shown.
  48520. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  48521. repeatTimes = repeatCutLength
  48522. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  48523. : 0;
  48524. }
  48525. pathLen = repeatTimes * uLenWithMargin - endFix;
  48526. output.repeatTimes = repeatTimes;
  48527. output.symbolMargin = symbolMargin;
  48528. }
  48529. var sizeFix = pxSign * (pathLen / 2);
  48530. var pathPosition = output.pathPosition = [];
  48531. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  48532. pathPosition[valueDim.index] = symbolPosition === 'start'
  48533. ? sizeFix
  48534. : symbolPosition === 'end'
  48535. ? boundingLength - sizeFix
  48536. : boundingLength / 2; // 'center'
  48537. if (symbolOffset) {
  48538. pathPosition[0] += symbolOffset[0];
  48539. pathPosition[1] += symbolOffset[1];
  48540. }
  48541. var bundlePosition = output.bundlePosition = [];
  48542. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  48543. bundlePosition[valueDim.index] = layout[valueDim.xy];
  48544. var barRectShape = output.barRectShape = extend({}, layout);
  48545. barRectShape[valueDim.wh] = pxSign * Math.max(
  48546. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  48547. );
  48548. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  48549. var clipShape = output.clipShape = {};
  48550. // Consider that symbol may be overflow layout rect.
  48551. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  48552. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  48553. clipShape[valueDim.xy] = 0;
  48554. clipShape[valueDim.wh] = layout[valueDim.wh];
  48555. }
  48556. function createPath(symbolMeta) {
  48557. var symbolPatternSize = symbolMeta.symbolPatternSize;
  48558. var path = createSymbol(
  48559. // Consider texture img, make a big size.
  48560. symbolMeta.symbolType,
  48561. -symbolPatternSize / 2,
  48562. -symbolPatternSize / 2,
  48563. symbolPatternSize,
  48564. symbolPatternSize,
  48565. symbolMeta.color
  48566. );
  48567. path.attr({
  48568. culling: true
  48569. });
  48570. path.type !== 'image' && path.setStyle({
  48571. strokeNoScale: true
  48572. });
  48573. return path;
  48574. }
  48575. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  48576. var bundle = bar.__pictorialBundle;
  48577. var symbolSize = symbolMeta.symbolSize;
  48578. var valueLineWidth = symbolMeta.valueLineWidth;
  48579. var pathPosition = symbolMeta.pathPosition;
  48580. var valueDim = opt.valueDim;
  48581. var repeatTimes = symbolMeta.repeatTimes || 0;
  48582. var index = 0;
  48583. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  48584. eachPath(bar, function (path) {
  48585. path.__pictorialAnimationIndex = index;
  48586. path.__pictorialRepeatTimes = repeatTimes;
  48587. if (index < repeatTimes) {
  48588. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  48589. }
  48590. else {
  48591. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  48592. bundle.remove(path);
  48593. });
  48594. }
  48595. updateHoverAnimation(path, symbolMeta);
  48596. index++;
  48597. });
  48598. for (; index < repeatTimes; index++) {
  48599. var path = createPath(symbolMeta);
  48600. path.__pictorialAnimationIndex = index;
  48601. path.__pictorialRepeatTimes = repeatTimes;
  48602. bundle.add(path);
  48603. var target = makeTarget(index);
  48604. updateAttr(
  48605. path,
  48606. {
  48607. position: target.position,
  48608. scale: [0, 0]
  48609. },
  48610. {
  48611. scale: target.scale,
  48612. rotation: target.rotation
  48613. },
  48614. symbolMeta,
  48615. isUpdate
  48616. );
  48617. // FIXME
  48618. // If all emphasis/normal through action.
  48619. path
  48620. .on('mouseover', onMouseOver)
  48621. .on('mouseout', onMouseOut);
  48622. updateHoverAnimation(path, symbolMeta);
  48623. }
  48624. function makeTarget(index) {
  48625. var position = pathPosition.slice();
  48626. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  48627. // Otherwise: i = index;
  48628. var pxSign = symbolMeta.pxSign;
  48629. var i = index;
  48630. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  48631. i = repeatTimes - 1 - index;
  48632. }
  48633. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  48634. return {
  48635. position: position,
  48636. scale: symbolMeta.symbolScale.slice(),
  48637. rotation: symbolMeta.rotation
  48638. };
  48639. }
  48640. function onMouseOver() {
  48641. eachPath(bar, function (path) {
  48642. path.trigger('emphasis');
  48643. });
  48644. }
  48645. function onMouseOut() {
  48646. eachPath(bar, function (path) {
  48647. path.trigger('normal');
  48648. });
  48649. }
  48650. }
  48651. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  48652. var bundle = bar.__pictorialBundle;
  48653. var mainPath = bar.__pictorialMainPath;
  48654. if (!mainPath) {
  48655. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  48656. bundle.add(mainPath);
  48657. updateAttr(
  48658. mainPath,
  48659. {
  48660. position: symbolMeta.pathPosition.slice(),
  48661. scale: [0, 0],
  48662. rotation: symbolMeta.rotation
  48663. },
  48664. {
  48665. scale: symbolMeta.symbolScale.slice()
  48666. },
  48667. symbolMeta,
  48668. isUpdate
  48669. );
  48670. mainPath
  48671. .on('mouseover', onMouseOver)
  48672. .on('mouseout', onMouseOut);
  48673. }
  48674. else {
  48675. updateAttr(
  48676. mainPath,
  48677. null,
  48678. {
  48679. position: symbolMeta.pathPosition.slice(),
  48680. scale: symbolMeta.symbolScale.slice(),
  48681. rotation: symbolMeta.rotation
  48682. },
  48683. symbolMeta,
  48684. isUpdate
  48685. );
  48686. }
  48687. updateHoverAnimation(mainPath, symbolMeta);
  48688. function onMouseOver() {
  48689. this.trigger('emphasis');
  48690. }
  48691. function onMouseOut() {
  48692. this.trigger('normal');
  48693. }
  48694. }
  48695. // bar rect is used for label.
  48696. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  48697. var rectShape = extend({}, symbolMeta.barRectShape);
  48698. var barRect = bar.__pictorialBarRect;
  48699. if (!barRect) {
  48700. barRect = bar.__pictorialBarRect = new Rect({
  48701. z2: 2,
  48702. shape: rectShape,
  48703. silent: true,
  48704. style: {
  48705. stroke: 'transparent',
  48706. fill: 'transparent',
  48707. lineWidth: 0
  48708. }
  48709. });
  48710. bar.add(barRect);
  48711. }
  48712. else {
  48713. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  48714. }
  48715. }
  48716. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  48717. // If not clip, symbol will be remove and rebuilt.
  48718. if (symbolMeta.symbolClip) {
  48719. var clipPath = bar.__pictorialClipPath;
  48720. var clipShape = extend({}, symbolMeta.clipShape);
  48721. var valueDim = opt.valueDim;
  48722. var animationModel = symbolMeta.animationModel;
  48723. var dataIndex = symbolMeta.dataIndex;
  48724. if (clipPath) {
  48725. updateProps(
  48726. clipPath, {shape: clipShape}, animationModel, dataIndex
  48727. );
  48728. }
  48729. else {
  48730. clipShape[valueDim.wh] = 0;
  48731. clipPath = new Rect({shape: clipShape});
  48732. bar.__pictorialBundle.setClipPath(clipPath);
  48733. bar.__pictorialClipPath = clipPath;
  48734. var target = {};
  48735. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  48736. graphic[isUpdate ? 'updateProps' : 'initProps'](
  48737. clipPath, {shape: target}, animationModel, dataIndex
  48738. );
  48739. }
  48740. }
  48741. }
  48742. function getItemModel(data, dataIndex) {
  48743. var itemModel = data.getItemModel(dataIndex);
  48744. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  48745. itemModel.isAnimationEnabled = isAnimationEnabled;
  48746. return itemModel;
  48747. }
  48748. function getAnimationDelayParams(path) {
  48749. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  48750. return {
  48751. index: path.__pictorialAnimationIndex,
  48752. count: path.__pictorialRepeatTimes
  48753. };
  48754. }
  48755. function isAnimationEnabled() {
  48756. // `animation` prop can be set on itemModel in pictorial bar chart.
  48757. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  48758. }
  48759. function updateHoverAnimation(path, symbolMeta) {
  48760. path.off('emphasis').off('normal');
  48761. var scale = symbolMeta.symbolScale.slice();
  48762. symbolMeta.hoverAnimation && path
  48763. .on('emphasis', function() {
  48764. this.animateTo({
  48765. scale: [scale[0] * 1.1, scale[1] * 1.1]
  48766. }, 400, 'elasticOut');
  48767. })
  48768. .on('normal', function() {
  48769. this.animateTo({
  48770. scale: scale.slice()
  48771. }, 400, 'elasticOut');
  48772. });
  48773. }
  48774. function createBar(data, opt, symbolMeta, isUpdate) {
  48775. // bar is the main element for each data.
  48776. var bar = new Group();
  48777. // bundle is used for location and clip.
  48778. var bundle = new Group();
  48779. bar.add(bundle);
  48780. bar.__pictorialBundle = bundle;
  48781. bundle.attr('position', symbolMeta.bundlePosition.slice());
  48782. if (symbolMeta.symbolRepeat) {
  48783. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  48784. }
  48785. else {
  48786. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  48787. }
  48788. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  48789. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  48790. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  48791. bar.__pictorialSymbolMeta = symbolMeta;
  48792. return bar;
  48793. }
  48794. function updateBar(bar, opt, symbolMeta) {
  48795. var animationModel = symbolMeta.animationModel;
  48796. var dataIndex = symbolMeta.dataIndex;
  48797. var bundle = bar.__pictorialBundle;
  48798. updateProps(
  48799. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  48800. );
  48801. if (symbolMeta.symbolRepeat) {
  48802. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  48803. }
  48804. else {
  48805. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  48806. }
  48807. createOrUpdateBarRect(bar, symbolMeta, true);
  48808. createOrUpdateClip(bar, opt, symbolMeta, true);
  48809. }
  48810. function removeBar(data, dataIndex, animationModel, bar) {
  48811. // Not show text when animating
  48812. var labelRect = bar.__pictorialBarRect;
  48813. labelRect && (labelRect.style.text = null);
  48814. var pathes = [];
  48815. eachPath(bar, function (path) {
  48816. pathes.push(path);
  48817. });
  48818. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  48819. // I do not find proper remove animation for clip yet.
  48820. bar.__pictorialClipPath && (animationModel = null);
  48821. each$1(pathes, function (path) {
  48822. updateProps(
  48823. path, {scale: [0, 0]}, animationModel, dataIndex,
  48824. function () {
  48825. bar.parent && bar.parent.remove(bar);
  48826. }
  48827. );
  48828. });
  48829. data.setItemGraphicEl(dataIndex, null);
  48830. }
  48831. function getShapeStr(data, symbolMeta) {
  48832. return [
  48833. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  48834. !!symbolMeta.symbolRepeat,
  48835. !!symbolMeta.symbolClip
  48836. ].join(':');
  48837. }
  48838. function eachPath(bar, cb, context) {
  48839. // Do not use Group#eachChild, because it do not support remove.
  48840. each$1(bar.__pictorialBundle.children(), function (el) {
  48841. el !== bar.__pictorialBarRect && cb.call(context, el);
  48842. });
  48843. }
  48844. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  48845. immediateAttrs && el.attr(immediateAttrs);
  48846. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  48847. if (symbolMeta.symbolClip && !isUpdate) {
  48848. animationAttrs && el.attr(animationAttrs);
  48849. }
  48850. else {
  48851. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  48852. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  48853. );
  48854. }
  48855. }
  48856. function updateCommon$1(bar, opt, symbolMeta) {
  48857. var color = symbolMeta.color;
  48858. var dataIndex = symbolMeta.dataIndex;
  48859. var itemModel = symbolMeta.itemModel;
  48860. // Color must be excluded.
  48861. // Because symbol provide setColor individually to set fill and stroke
  48862. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  48863. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  48864. var cursorStyle = itemModel.getShallow('cursor');
  48865. eachPath(bar, function (path) {
  48866. // PENDING setColor should be before setStyle!!!
  48867. path.setColor(color);
  48868. path.setStyle(defaults(
  48869. {
  48870. fill: color,
  48871. opacity: symbolMeta.opacity
  48872. },
  48873. normalStyle
  48874. ));
  48875. setHoverStyle(path, hoverStyle);
  48876. cursorStyle && (path.cursor = cursorStyle);
  48877. path.z2 = symbolMeta.z2;
  48878. });
  48879. var barRectHoverStyle = {};
  48880. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  48881. var barRect = bar.__pictorialBarRect;
  48882. setLabel(
  48883. barRect.style, barRectHoverStyle, itemModel,
  48884. color, opt.seriesModel, dataIndex, barPositionOutside
  48885. );
  48886. setHoverStyle(barRect, barRectHoverStyle);
  48887. }
  48888. function toIntTimes(times) {
  48889. var roundedTimes = Math.round(times);
  48890. // Escapse accurate error
  48891. return Math.abs(times - roundedTimes) < 1e-4
  48892. ? roundedTimes
  48893. : Math.ceil(times);
  48894. }
  48895. // In case developer forget to include grid component
  48896. registerLayout(curry(
  48897. layout, 'pictorialBar'
  48898. ));
  48899. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  48900. /**
  48901. * @constructor module:echarts/coord/single/SingleAxis
  48902. * @extends {module:echarts/coord/Axis}
  48903. * @param {string} dim
  48904. * @param {*} scale
  48905. * @param {Array.<number>} coordExtent
  48906. * @param {string} axisType
  48907. * @param {string} position
  48908. */
  48909. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  48910. Axis.call(this, dim, scale, coordExtent);
  48911. /**
  48912. * Axis type
  48913. * - 'category'
  48914. * - 'value'
  48915. * - 'time'
  48916. * - 'log'
  48917. * @type {string}
  48918. */
  48919. this.type = axisType || 'value';
  48920. /**
  48921. * Axis position
  48922. * - 'top'
  48923. * - 'bottom'
  48924. * - 'left'
  48925. * - 'right'
  48926. * @type {string}
  48927. */
  48928. this.position = position || 'bottom';
  48929. /**
  48930. * Axis orient
  48931. * - 'horizontal'
  48932. * - 'vertical'
  48933. * @type {[type]}
  48934. */
  48935. this.orient = null;
  48936. /**
  48937. * @type {number}
  48938. */
  48939. this._labelInterval = null;
  48940. };
  48941. SingleAxis.prototype = {
  48942. constructor: SingleAxis,
  48943. /**
  48944. * Axis model
  48945. * @type {module:echarts/coord/single/AxisModel}
  48946. */
  48947. model: null,
  48948. /**
  48949. * Judge the orient of the axis.
  48950. * @return {boolean}
  48951. */
  48952. isHorizontal: function () {
  48953. var position = this.position;
  48954. return position === 'top' || position === 'bottom';
  48955. },
  48956. /**
  48957. * @override
  48958. */
  48959. pointToData: function (point, clamp) {
  48960. return this.coordinateSystem.pointToData(point, clamp)[0];
  48961. },
  48962. /**
  48963. * Convert the local coord(processed by dataToCoord())
  48964. * to global coord(concrete pixel coord).
  48965. * designated by module:echarts/coord/single/Single.
  48966. * @type {Function}
  48967. */
  48968. toGlobalCoord: null,
  48969. /**
  48970. * Convert the global coord to local coord.
  48971. * designated by module:echarts/coord/single/Single.
  48972. * @type {Function}
  48973. */
  48974. toLocalCoord: null
  48975. };
  48976. inherits(SingleAxis, Axis);
  48977. /**
  48978. * Single coordinates system.
  48979. */
  48980. /**
  48981. * Create a single coordinates system.
  48982. *
  48983. * @param {module:echarts/coord/single/AxisModel} axisModel
  48984. * @param {module:echarts/model/Global} ecModel
  48985. * @param {module:echarts/ExtensionAPI} api
  48986. */
  48987. function Single(axisModel, ecModel, api) {
  48988. /**
  48989. * @type {string}
  48990. * @readOnly
  48991. */
  48992. this.dimension = 'single';
  48993. /**
  48994. * Add it just for draw tooltip.
  48995. *
  48996. * @type {Array.<string>}
  48997. * @readOnly
  48998. */
  48999. this.dimensions = ['single'];
  49000. /**
  49001. * @private
  49002. * @type {module:echarts/coord/single/SingleAxis}.
  49003. */
  49004. this._axis = null;
  49005. /**
  49006. * @private
  49007. * @type {module:zrender/core/BoundingRect}
  49008. */
  49009. this._rect;
  49010. this._init(axisModel, ecModel, api);
  49011. /**
  49012. * @type {module:echarts/coord/single/AxisModel}
  49013. */
  49014. this.model = axisModel;
  49015. }
  49016. Single.prototype = {
  49017. type: 'singleAxis',
  49018. axisPointerEnabled: true,
  49019. constructor: Single,
  49020. /**
  49021. * Initialize single coordinate system.
  49022. *
  49023. * @param {module:echarts/coord/single/AxisModel} axisModel
  49024. * @param {module:echarts/model/Global} ecModel
  49025. * @param {module:echarts/ExtensionAPI} api
  49026. * @private
  49027. */
  49028. _init: function (axisModel, ecModel, api) {
  49029. var dim = this.dimension;
  49030. var axis = new SingleAxis(
  49031. dim,
  49032. createScaleByModel(axisModel),
  49033. [0, 0],
  49034. axisModel.get('type'),
  49035. axisModel.get('position')
  49036. );
  49037. var isCategory = axis.type === 'category';
  49038. axis.onBand = isCategory && axisModel.get('boundaryGap');
  49039. axis.inverse = axisModel.get('inverse');
  49040. axis.orient = axisModel.get('orient');
  49041. axisModel.axis = axis;
  49042. axis.model = axisModel;
  49043. axis.coordinateSystem = this;
  49044. this._axis = axis;
  49045. },
  49046. /**
  49047. * Update axis scale after data processed
  49048. * @param {module:echarts/model/Global} ecModel
  49049. * @param {module:echarts/ExtensionAPI} api
  49050. */
  49051. update: function (ecModel, api) {
  49052. ecModel.eachSeries(function (seriesModel) {
  49053. if (seriesModel.coordinateSystem === this) {
  49054. var data = seriesModel.getData();
  49055. each$1(data.mapDimension(this.dimension, true), function (dim) {
  49056. this._axis.scale.unionExtentFromData(data, dim);
  49057. }, this);
  49058. niceScaleExtent(this._axis.scale, this._axis.model);
  49059. }
  49060. }, this);
  49061. },
  49062. /**
  49063. * Resize the single coordinate system.
  49064. *
  49065. * @param {module:echarts/coord/single/AxisModel} axisModel
  49066. * @param {module:echarts/ExtensionAPI} api
  49067. */
  49068. resize: function (axisModel, api) {
  49069. this._rect = getLayoutRect(
  49070. {
  49071. left: axisModel.get('left'),
  49072. top: axisModel.get('top'),
  49073. right: axisModel.get('right'),
  49074. bottom: axisModel.get('bottom'),
  49075. width: axisModel.get('width'),
  49076. height: axisModel.get('height')
  49077. },
  49078. {
  49079. width: api.getWidth(),
  49080. height: api.getHeight()
  49081. }
  49082. );
  49083. this._adjustAxis();
  49084. },
  49085. /**
  49086. * @return {module:zrender/core/BoundingRect}
  49087. */
  49088. getRect: function () {
  49089. return this._rect;
  49090. },
  49091. /**
  49092. * @private
  49093. */
  49094. _adjustAxis: function () {
  49095. var rect = this._rect;
  49096. var axis = this._axis;
  49097. var isHorizontal = axis.isHorizontal();
  49098. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  49099. var idx = axis.reverse ? 1 : 0;
  49100. axis.setExtent(extent[idx], extent[1 - idx]);
  49101. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  49102. },
  49103. /**
  49104. * @param {module:echarts/coord/single/SingleAxis} axis
  49105. * @param {number} coordBase
  49106. */
  49107. _updateAxisTransform: function (axis, coordBase) {
  49108. var axisExtent = axis.getExtent();
  49109. var extentSum = axisExtent[0] + axisExtent[1];
  49110. var isHorizontal = axis.isHorizontal();
  49111. axis.toGlobalCoord = isHorizontal
  49112. ? function (coord) {
  49113. return coord + coordBase;
  49114. }
  49115. : function (coord) {
  49116. return extentSum - coord + coordBase;
  49117. };
  49118. axis.toLocalCoord = isHorizontal
  49119. ? function (coord) {
  49120. return coord - coordBase;
  49121. }
  49122. : function (coord) {
  49123. return extentSum - coord + coordBase;
  49124. };
  49125. },
  49126. /**
  49127. * Get axis.
  49128. *
  49129. * @return {module:echarts/coord/single/SingleAxis}
  49130. */
  49131. getAxis: function () {
  49132. return this._axis;
  49133. },
  49134. /**
  49135. * Get axis, add it just for draw tooltip.
  49136. *
  49137. * @return {[type]} [description]
  49138. */
  49139. getBaseAxis: function () {
  49140. return this._axis;
  49141. },
  49142. /**
  49143. * @return {Array.<module:echarts/coord/Axis>}
  49144. */
  49145. getAxes: function () {
  49146. return [this._axis];
  49147. },
  49148. /**
  49149. * @return {Object} {baseAxes: [], otherAxes: []}
  49150. */
  49151. getTooltipAxes: function () {
  49152. return {baseAxes: [this.getAxis()]};
  49153. },
  49154. /**
  49155. * If contain point.
  49156. *
  49157. * @param {Array.<number>} point
  49158. * @return {boolean}
  49159. */
  49160. containPoint: function (point) {
  49161. var rect = this.getRect();
  49162. var axis = this.getAxis();
  49163. var orient = axis.orient;
  49164. if (orient === 'horizontal') {
  49165. return axis.contain(axis.toLocalCoord(point[0]))
  49166. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  49167. }
  49168. else {
  49169. return axis.contain(axis.toLocalCoord(point[1]))
  49170. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  49171. }
  49172. },
  49173. /**
  49174. * @param {Array.<number>} point
  49175. * @return {Array.<number>}
  49176. */
  49177. pointToData: function (point) {
  49178. var axis = this.getAxis();
  49179. return [axis.coordToData(axis.toLocalCoord(
  49180. point[axis.orient === 'horizontal' ? 0 : 1]
  49181. ))];
  49182. },
  49183. /**
  49184. * Convert the series data to concrete point.
  49185. *
  49186. * @param {number|Array.<number>} val
  49187. * @return {Array.<number>}
  49188. */
  49189. dataToPoint: function (val) {
  49190. var axis = this.getAxis();
  49191. var rect = this.getRect();
  49192. var pt = [];
  49193. var idx = axis.orient === 'horizontal' ? 0 : 1;
  49194. if (val instanceof Array) {
  49195. val = val[0];
  49196. }
  49197. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  49198. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  49199. return pt;
  49200. }
  49201. };
  49202. /**
  49203. * Single coordinate system creator.
  49204. */
  49205. /**
  49206. * Create single coordinate system and inject it into seriesModel.
  49207. *
  49208. * @param {module:echarts/model/Global} ecModel
  49209. * @param {module:echarts/ExtensionAPI} api
  49210. * @return {Array.<module:echarts/coord/single/Single>}
  49211. */
  49212. function create$3(ecModel, api) {
  49213. var singles = [];
  49214. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  49215. var single = new Single(axisModel, ecModel, api);
  49216. single.name = 'single_' + idx;
  49217. single.resize(axisModel, api);
  49218. axisModel.coordinateSystem = single;
  49219. singles.push(single);
  49220. });
  49221. ecModel.eachSeries(function (seriesModel) {
  49222. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  49223. var singleAxisModel = ecModel.queryComponents({
  49224. mainType: 'singleAxis',
  49225. index: seriesModel.get('singleAxisIndex'),
  49226. id: seriesModel.get('singleAxisId')
  49227. })[0];
  49228. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  49229. }
  49230. });
  49231. return singles;
  49232. }
  49233. CoordinateSystemManager.register('single', {
  49234. create: create$3,
  49235. dimensions: Single.prototype.dimensions
  49236. });
  49237. /**
  49238. * @param {Object} opt {labelInside}
  49239. * @return {Object} {
  49240. * position, rotation, labelDirection, labelOffset,
  49241. * tickDirection, labelRotate, labelInterval, z2
  49242. * }
  49243. */
  49244. function layout$2 (axisModel, opt) {
  49245. opt = opt || {};
  49246. var single = axisModel.coordinateSystem;
  49247. var axis = axisModel.axis;
  49248. var layout = {};
  49249. var axisPosition = axis.position;
  49250. var orient = axis.orient;
  49251. var rect = single.getRect();
  49252. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  49253. var positionMap = {
  49254. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  49255. vertical: {left: rectBound[0], right: rectBound[1]}
  49256. };
  49257. layout.position = [
  49258. orient === 'vertical'
  49259. ? positionMap.vertical[axisPosition]
  49260. : rectBound[0],
  49261. orient === 'horizontal'
  49262. ? positionMap.horizontal[axisPosition]
  49263. : rectBound[3]
  49264. ];
  49265. var r = {horizontal: 0, vertical: 1};
  49266. layout.rotation = Math.PI / 2 * r[orient];
  49267. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  49268. layout.labelDirection = layout.tickDirection
  49269. = layout.nameDirection
  49270. = directionMap[axisPosition];
  49271. if (axisModel.get('axisTick.inside')) {
  49272. layout.tickDirection = -layout.tickDirection;
  49273. }
  49274. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  49275. layout.labelDirection = -layout.labelDirection;
  49276. }
  49277. var labelRotation = opt.rotate;
  49278. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  49279. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  49280. layout.labelInterval = axis.getLabelInterval();
  49281. layout.z2 = 1;
  49282. return layout;
  49283. }
  49284. var getInterval$2 = AxisBuilder.getInterval;
  49285. var ifIgnoreOnTick$2 = AxisBuilder.ifIgnoreOnTick;
  49286. var axisBuilderAttrs$2 = [
  49287. 'axisLine', 'axisTickLabel', 'axisName'
  49288. ];
  49289. var selfBuilderAttr = 'splitLine';
  49290. var SingleAxisView = AxisView.extend({
  49291. type: 'singleAxis',
  49292. axisPointerClass: 'SingleAxisPointer',
  49293. render: function (axisModel, ecModel, api, payload) {
  49294. var group = this.group;
  49295. group.removeAll();
  49296. var layout = layout$2(axisModel);
  49297. var axisBuilder = new AxisBuilder(axisModel, layout);
  49298. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  49299. group.add(axisBuilder.getGroup());
  49300. if (axisModel.get(selfBuilderAttr + '.show')) {
  49301. this['_' + selfBuilderAttr](axisModel, layout.labelInterval);
  49302. }
  49303. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  49304. },
  49305. _splitLine: function(axisModel, labelInterval) {
  49306. var axis = axisModel.axis;
  49307. if (axis.scale.isBlank()) {
  49308. return;
  49309. }
  49310. var splitLineModel = axisModel.getModel('splitLine');
  49311. var lineStyleModel = splitLineModel.getModel('lineStyle');
  49312. var lineWidth = lineStyleModel.get('width');
  49313. var lineColors = lineStyleModel.get('color');
  49314. var lineInterval = getInterval$2(splitLineModel, labelInterval);
  49315. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  49316. var gridRect = axisModel.coordinateSystem.getRect();
  49317. var isHorizontal = axis.isHorizontal();
  49318. var splitLines = [];
  49319. var lineCount = 0;
  49320. var ticksCoords = axis.getTicksCoords();
  49321. var p1 = [];
  49322. var p2 = [];
  49323. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  49324. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  49325. for (var i = 0; i < ticksCoords.length; ++i) {
  49326. if (ifIgnoreOnTick$2(
  49327. axis, i, lineInterval, ticksCoords.length,
  49328. showMinLabel, showMaxLabel
  49329. )) {
  49330. continue;
  49331. }
  49332. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  49333. if (isHorizontal) {
  49334. p1[0] = tickCoord;
  49335. p1[1] = gridRect.y;
  49336. p2[0] = tickCoord;
  49337. p2[1] = gridRect.y + gridRect.height;
  49338. }
  49339. else {
  49340. p1[0] = gridRect.x;
  49341. p1[1] = tickCoord;
  49342. p2[0] = gridRect.x + gridRect.width;
  49343. p2[1] = tickCoord;
  49344. }
  49345. var colorIndex = (lineCount++) % lineColors.length;
  49346. splitLines[colorIndex] = splitLines[colorIndex] || [];
  49347. splitLines[colorIndex].push(new Line(
  49348. subPixelOptimizeLine({
  49349. shape: {
  49350. x1: p1[0],
  49351. y1: p1[1],
  49352. x2: p2[0],
  49353. y2: p2[1]
  49354. },
  49355. style: {
  49356. lineWidth: lineWidth
  49357. },
  49358. silent: true
  49359. })));
  49360. }
  49361. for (var i = 0; i < splitLines.length; ++i) {
  49362. this.group.add(mergePath(splitLines[i], {
  49363. style: {
  49364. stroke: lineColors[i % lineColors.length],
  49365. lineDash: lineStyleModel.getLineDash(lineWidth),
  49366. lineWidth: lineWidth
  49367. },
  49368. silent: true
  49369. }));
  49370. }
  49371. }
  49372. });
  49373. var AxisModel$4 = ComponentModel.extend({
  49374. type: 'singleAxis',
  49375. layoutMode: 'box',
  49376. /**
  49377. * @type {module:echarts/coord/single/SingleAxis}
  49378. */
  49379. axis: null,
  49380. /**
  49381. * @type {module:echarts/coord/single/Single}
  49382. */
  49383. coordinateSystem: null,
  49384. /**
  49385. * @override
  49386. */
  49387. getCoordSysModel: function () {
  49388. return this;
  49389. }
  49390. });
  49391. var defaultOption$2 = {
  49392. left: '5%',
  49393. top: '5%',
  49394. right: '5%',
  49395. bottom: '5%',
  49396. type: 'value',
  49397. position: 'bottom',
  49398. orient: 'horizontal',
  49399. axisLine: {
  49400. show: true,
  49401. lineStyle: {
  49402. width: 2,
  49403. type: 'solid'
  49404. }
  49405. },
  49406. // Single coordinate system and single axis is the,
  49407. // which is used as the parent tooltip model.
  49408. // same model, so we set default tooltip show as true.
  49409. tooltip: {
  49410. show: true
  49411. },
  49412. axisTick: {
  49413. show: true,
  49414. length: 6,
  49415. lineStyle: {
  49416. width: 2
  49417. }
  49418. },
  49419. axisLabel: {
  49420. show: true,
  49421. interval: 'auto'
  49422. },
  49423. splitLine: {
  49424. show: true,
  49425. lineStyle: {
  49426. type: 'dashed',
  49427. opacity: 0.2
  49428. }
  49429. }
  49430. };
  49431. function getAxisType$2(axisName, option) {
  49432. return option.type || (option.data ? 'category' : 'value');
  49433. }
  49434. merge(AxisModel$4.prototype, axisModelCommonMixin);
  49435. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  49436. /**
  49437. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  49438. * @param {module:echarts/model/Global} ecModel
  49439. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  49440. */
  49441. var findPointFromSeries = function (finder, ecModel) {
  49442. var point = [];
  49443. var seriesIndex = finder.seriesIndex;
  49444. var seriesModel;
  49445. if (seriesIndex == null || !(
  49446. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  49447. )) {
  49448. return {point: []};
  49449. }
  49450. var data = seriesModel.getData();
  49451. var dataIndex = queryDataIndex(data, finder);
  49452. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  49453. return {point: []};
  49454. }
  49455. var el = data.getItemGraphicEl(dataIndex);
  49456. var coordSys = seriesModel.coordinateSystem;
  49457. if (seriesModel.getTooltipPosition) {
  49458. point = seriesModel.getTooltipPosition(dataIndex) || [];
  49459. }
  49460. else if (coordSys && coordSys.dataToPoint) {
  49461. point = coordSys.dataToPoint(
  49462. data.getValues(
  49463. map(coordSys.dimensions, function (dim) {
  49464. return data.mapDimension(dim);
  49465. }), dataIndex, true
  49466. )
  49467. ) || [];
  49468. }
  49469. else if (el) {
  49470. // Use graphic bounding rect
  49471. var rect = el.getBoundingRect().clone();
  49472. rect.applyTransform(el.transform);
  49473. point = [
  49474. rect.x + rect.width / 2,
  49475. rect.y + rect.height / 2
  49476. ];
  49477. }
  49478. return {point: point, el: el};
  49479. };
  49480. var each$15 = each$1;
  49481. var curry$3 = curry;
  49482. var inner$6 = makeInner();
  49483. /**
  49484. * Basic logic: check all axis, if they do not demand show/highlight,
  49485. * then hide/downplay them.
  49486. *
  49487. * @param {Object} coordSysAxesInfo
  49488. * @param {Object} payload
  49489. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  49490. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  49491. * trigger axisPointer and tooltip.
  49492. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  49493. * trigger axisPointer and tooltip.
  49494. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  49495. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  49496. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  49497. * [{
  49498. * axisDim: 'x'|'y'|'angle'|...,
  49499. * axisIndex: ...,
  49500. * value: ...
  49501. * }, ...]
  49502. * @param {Function} [payload.dispatchAction]
  49503. * @param {Object} [payload.tooltipOption]
  49504. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  49505. * which can be specified in dispatchAction
  49506. * @param {module:echarts/model/Global} ecModel
  49507. * @param {module:echarts/ExtensionAPI} api
  49508. * @return {Object} content of event obj for echarts.connect.
  49509. */
  49510. var axisTrigger = function (payload, ecModel, api) {
  49511. var currTrigger = payload.currTrigger;
  49512. var point = [payload.x, payload.y];
  49513. var finder = payload;
  49514. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  49515. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  49516. // Pending
  49517. // See #6121. But we are not able to reproduce it yet.
  49518. if (!coordSysAxesInfo) {
  49519. return;
  49520. }
  49521. if (illegalPoint(point)) {
  49522. // Used in the default behavior of `connection`: use the sample seriesIndex
  49523. // and dataIndex. And also used in the tooltipView trigger.
  49524. point = findPointFromSeries({
  49525. seriesIndex: finder.seriesIndex,
  49526. // Do not use dataIndexInside from other ec instance.
  49527. // FIXME: auto detect it?
  49528. dataIndex: finder.dataIndex
  49529. }, ecModel).point;
  49530. }
  49531. var isIllegalPoint = illegalPoint(point);
  49532. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  49533. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  49534. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  49535. // and dataIndex.
  49536. var inputAxesInfo = finder.axesInfo;
  49537. var axesInfo = coordSysAxesInfo.axesInfo;
  49538. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  49539. var outputFinder = {};
  49540. var showValueMap = {};
  49541. var dataByCoordSys = {list: [], map: {}};
  49542. var updaters = {
  49543. showPointer: curry$3(showPointer, showValueMap),
  49544. showTooltip: curry$3(showTooltip, dataByCoordSys)
  49545. };
  49546. // Process for triggered axes.
  49547. each$15(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  49548. // If a point given, it must be contained by the coordinate system.
  49549. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  49550. each$15(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  49551. var axis = axisInfo.axis;
  49552. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  49553. // If no inputAxesInfo, no axis is restricted.
  49554. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  49555. var val = inputAxisInfo && inputAxisInfo.value;
  49556. if (val == null && !isIllegalPoint) {
  49557. val = axis.pointToData(point);
  49558. }
  49559. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  49560. }
  49561. });
  49562. });
  49563. // Process for linked axes.
  49564. var linkTriggers = {};
  49565. each$15(axesInfo, function (tarAxisInfo, tarKey) {
  49566. var linkGroup = tarAxisInfo.linkGroup;
  49567. // If axis has been triggered in the previous stage, it should not be triggered by link.
  49568. if (linkGroup && !showValueMap[tarKey]) {
  49569. each$15(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  49570. var srcValItem = showValueMap[srcKey];
  49571. // If srcValItem exist, source axis is triggered, so link to target axis.
  49572. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  49573. var val = srcValItem.value;
  49574. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  49575. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  49576. )));
  49577. linkTriggers[tarAxisInfo.key] = val;
  49578. }
  49579. });
  49580. }
  49581. });
  49582. each$15(linkTriggers, function (val, tarKey) {
  49583. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  49584. });
  49585. updateModelActually(showValueMap, axesInfo, outputFinder);
  49586. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  49587. dispatchHighDownActually(axesInfo, dispatchAction, api);
  49588. return outputFinder;
  49589. };
  49590. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  49591. var axis = axisInfo.axis;
  49592. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  49593. return;
  49594. }
  49595. if (!axisInfo.involveSeries) {
  49596. updaters.showPointer(axisInfo, newValue);
  49597. return;
  49598. }
  49599. // Heavy calculation. So put it after axis.containData checking.
  49600. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  49601. var payloadBatch = payloadInfo.payloadBatch;
  49602. var snapToValue = payloadInfo.snapToValue;
  49603. // Fill content of event obj for echarts.connect.
  49604. // By defualt use the first involved series data as a sample to connect.
  49605. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  49606. extend(outputFinder, payloadBatch[0]);
  49607. }
  49608. // If no linkSource input, this process is for collecting link
  49609. // target, where snap should not be accepted.
  49610. if (!dontSnap && axisInfo.snap) {
  49611. if (axis.containData(snapToValue) && snapToValue != null) {
  49612. newValue = snapToValue;
  49613. }
  49614. }
  49615. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  49616. // Tooltip should always be snapToValue, otherwise there will be
  49617. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  49618. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  49619. }
  49620. function buildPayloadsBySeries(value, axisInfo) {
  49621. var axis = axisInfo.axis;
  49622. var dim = axis.dim;
  49623. var snapToValue = value;
  49624. var payloadBatch = [];
  49625. var minDist = Number.MAX_VALUE;
  49626. var minDiff = -1;
  49627. each$15(axisInfo.seriesModels, function (series, idx) {
  49628. var dataDim = series.getData().mapDimension(dim, true);
  49629. var seriesNestestValue;
  49630. var dataIndices;
  49631. if (series.getAxisTooltipData) {
  49632. var result = series.getAxisTooltipData(dataDim, value, axis);
  49633. dataIndices = result.dataIndices;
  49634. seriesNestestValue = result.nestestValue;
  49635. }
  49636. else {
  49637. dataIndices = series.getData().indicesOfNearest(
  49638. dataDim[0],
  49639. value,
  49640. // Add a threshold to avoid find the wrong dataIndex
  49641. // when data length is not same.
  49642. // false,
  49643. axis.type === 'category' ? 0.5 : null
  49644. );
  49645. if (!dataIndices.length) {
  49646. return;
  49647. }
  49648. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  49649. }
  49650. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  49651. return;
  49652. }
  49653. var diff = value - seriesNestestValue;
  49654. var dist = Math.abs(diff);
  49655. // Consider category case
  49656. if (dist <= minDist) {
  49657. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  49658. minDist = dist;
  49659. minDiff = diff;
  49660. snapToValue = seriesNestestValue;
  49661. payloadBatch.length = 0;
  49662. }
  49663. each$15(dataIndices, function (dataIndex) {
  49664. payloadBatch.push({
  49665. seriesIndex: series.seriesIndex,
  49666. dataIndexInside: dataIndex,
  49667. dataIndex: series.getData().getRawIndex(dataIndex)
  49668. });
  49669. });
  49670. }
  49671. });
  49672. return {
  49673. payloadBatch: payloadBatch,
  49674. snapToValue: snapToValue
  49675. };
  49676. }
  49677. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  49678. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  49679. }
  49680. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  49681. var payloadBatch = payloadInfo.payloadBatch;
  49682. var axis = axisInfo.axis;
  49683. var axisModel = axis.model;
  49684. var axisPointerModel = axisInfo.axisPointerModel;
  49685. // If no data, do not create anything in dataByCoordSys,
  49686. // whose length will be used to judge whether dispatch action.
  49687. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  49688. return;
  49689. }
  49690. var coordSysModel = axisInfo.coordSys.model;
  49691. var coordSysKey = makeKey(coordSysModel);
  49692. var coordSysItem = dataByCoordSys.map[coordSysKey];
  49693. if (!coordSysItem) {
  49694. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  49695. coordSysId: coordSysModel.id,
  49696. coordSysIndex: coordSysModel.componentIndex,
  49697. coordSysType: coordSysModel.type,
  49698. coordSysMainType: coordSysModel.mainType,
  49699. dataByAxis: []
  49700. };
  49701. dataByCoordSys.list.push(coordSysItem);
  49702. }
  49703. coordSysItem.dataByAxis.push({
  49704. axisDim: axis.dim,
  49705. axisIndex: axisModel.componentIndex,
  49706. axisType: axisModel.type,
  49707. axisId: axisModel.id,
  49708. value: value,
  49709. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  49710. // depends that all models have been updated. So it should not be performed
  49711. // here. Considering axisPointerModel used here is volatile, which is hard
  49712. // to be retrieve in TooltipView, we prepare parameters here.
  49713. valueLabelOpt: {
  49714. precision: axisPointerModel.get('label.precision'),
  49715. formatter: axisPointerModel.get('label.formatter')
  49716. },
  49717. seriesDataIndices: payloadBatch.slice()
  49718. });
  49719. }
  49720. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  49721. var outputAxesInfo = outputFinder.axesInfo = [];
  49722. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  49723. each$15(axesInfo, function (axisInfo, key) {
  49724. var option = axisInfo.axisPointerModel.option;
  49725. var valItem = showValueMap[key];
  49726. if (valItem) {
  49727. !axisInfo.useHandle && (option.status = 'show');
  49728. option.value = valItem.value;
  49729. // For label formatter param and highlight.
  49730. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  49731. }
  49732. // When always show (e.g., handle used), remain
  49733. // original value and status.
  49734. else {
  49735. // If hide, value still need to be set, consider
  49736. // click legend to toggle axis blank.
  49737. !axisInfo.useHandle && (option.status = 'hide');
  49738. }
  49739. // If status is 'hide', should be no info in payload.
  49740. option.status === 'show' && outputAxesInfo.push({
  49741. axisDim: axisInfo.axis.dim,
  49742. axisIndex: axisInfo.axis.model.componentIndex,
  49743. value: option.value
  49744. });
  49745. });
  49746. }
  49747. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  49748. // Basic logic: If no showTip required, hideTip will be dispatched.
  49749. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  49750. dispatchAction({type: 'hideTip'});
  49751. return;
  49752. }
  49753. // In most case only one axis (or event one series is used). It is
  49754. // convinient to fetch payload.seriesIndex and payload.dataIndex
  49755. // dirtectly. So put the first seriesIndex and dataIndex of the first
  49756. // axis on the payload.
  49757. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  49758. dispatchAction({
  49759. type: 'showTip',
  49760. escapeConnect: true,
  49761. x: point[0],
  49762. y: point[1],
  49763. tooltipOption: payload.tooltipOption,
  49764. position: payload.position,
  49765. dataIndexInside: sampleItem.dataIndexInside,
  49766. dataIndex: sampleItem.dataIndex,
  49767. seriesIndex: sampleItem.seriesIndex,
  49768. dataByCoordSys: dataByCoordSys.list
  49769. });
  49770. }
  49771. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  49772. // FIXME
  49773. // highlight status modification shoule be a stage of main process?
  49774. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  49775. var zr = api.getZr();
  49776. var highDownKey = 'axisPointerLastHighlights';
  49777. var lastHighlights = inner$6(zr)[highDownKey] || {};
  49778. var newHighlights = inner$6(zr)[highDownKey] = {};
  49779. // Update highlight/downplay status according to axisPointer model.
  49780. // Build hash map and remove duplicate incidentally.
  49781. each$15(axesInfo, function (axisInfo, key) {
  49782. var option = axisInfo.axisPointerModel.option;
  49783. option.status === 'show' && each$15(option.seriesDataIndices, function (batchItem) {
  49784. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  49785. newHighlights[key] = batchItem;
  49786. });
  49787. });
  49788. // Diff.
  49789. var toHighlight = [];
  49790. var toDownplay = [];
  49791. each$1(lastHighlights, function (batchItem, key) {
  49792. !newHighlights[key] && toDownplay.push(batchItem);
  49793. });
  49794. each$1(newHighlights, function (batchItem, key) {
  49795. !lastHighlights[key] && toHighlight.push(batchItem);
  49796. });
  49797. toDownplay.length && api.dispatchAction({
  49798. type: 'downplay', escapeConnect: true, batch: toDownplay
  49799. });
  49800. toHighlight.length && api.dispatchAction({
  49801. type: 'highlight', escapeConnect: true, batch: toHighlight
  49802. });
  49803. }
  49804. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  49805. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  49806. var inputAxisInfo = inputAxesInfo[i];
  49807. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  49808. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  49809. ) {
  49810. return inputAxisInfo;
  49811. }
  49812. }
  49813. }
  49814. function makeMapperParam(axisInfo) {
  49815. var axisModel = axisInfo.axis.model;
  49816. var item = {};
  49817. var dim = item.axisDim = axisInfo.axis.dim;
  49818. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  49819. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  49820. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  49821. return item;
  49822. }
  49823. function illegalPoint(point) {
  49824. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  49825. }
  49826. var AxisPointerModel = extendComponentModel({
  49827. type: 'axisPointer',
  49828. coordSysAxesInfo: null,
  49829. defaultOption: {
  49830. // 'auto' means that show when triggered by tooltip or handle.
  49831. show: 'auto',
  49832. // 'click' | 'mousemove' | 'none'
  49833. triggerOn: null, // set default in AxisPonterView.js
  49834. zlevel: 0,
  49835. z: 50,
  49836. type: 'line',
  49837. // axispointer triggered by tootip determine snap automatically,
  49838. // see `modelHelper`.
  49839. snap: false,
  49840. triggerTooltip: true,
  49841. value: null,
  49842. status: null, // Init value depends on whether handle is used.
  49843. // [group0, group1, ...]
  49844. // Each group can be: {
  49845. // mapper: function () {},
  49846. // singleTooltip: 'multiple', // 'multiple' or 'single'
  49847. // xAxisId: ...,
  49848. // yAxisName: ...,
  49849. // angleAxisIndex: ...
  49850. // }
  49851. // mapper: can be ignored.
  49852. // input: {axisInfo, value}
  49853. // output: {axisInfo, value}
  49854. link: [],
  49855. // Do not set 'auto' here, otherwise global animation: false
  49856. // will not effect at this axispointer.
  49857. animation: null,
  49858. animationDurationUpdate: 200,
  49859. lineStyle: {
  49860. color: '#aaa',
  49861. width: 1,
  49862. type: 'solid'
  49863. },
  49864. shadowStyle: {
  49865. color: 'rgba(150,150,150,0.3)'
  49866. },
  49867. label: {
  49868. show: true,
  49869. formatter: null, // string | Function
  49870. precision: 'auto', // Or a number like 0, 1, 2 ...
  49871. margin: 3,
  49872. color: '#fff',
  49873. padding: [5, 7, 5, 7],
  49874. backgroundColor: 'auto', // default: axis line color
  49875. borderColor: null,
  49876. borderWidth: 0,
  49877. shadowBlur: 3,
  49878. shadowColor: '#aaa'
  49879. // Considering applicability, common style should
  49880. // better not have shadowOffset.
  49881. // shadowOffsetX: 0,
  49882. // shadowOffsetY: 2
  49883. },
  49884. handle: {
  49885. show: false,
  49886. 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
  49887. size: 45,
  49888. // handle margin is from symbol center to axis, which is stable when circular move.
  49889. margin: 50,
  49890. // color: '#1b8bbd'
  49891. // color: '#2f4554'
  49892. color: '#333',
  49893. shadowBlur: 3,
  49894. shadowColor: '#aaa',
  49895. shadowOffsetX: 0,
  49896. shadowOffsetY: 2,
  49897. // For mobile performance
  49898. throttle: 40
  49899. }
  49900. }
  49901. });
  49902. var inner$7 = makeInner();
  49903. var each$16 = each$1;
  49904. /**
  49905. * @param {string} key
  49906. * @param {module:echarts/ExtensionAPI} api
  49907. * @param {Function} handler
  49908. * param: {string} currTrigger
  49909. * param: {Array.<number>} point
  49910. */
  49911. function register(key, api, handler) {
  49912. if (env$1.node) {
  49913. return;
  49914. }
  49915. var zr = api.getZr();
  49916. inner$7(zr).records || (inner$7(zr).records = {});
  49917. initGlobalListeners(zr, api);
  49918. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  49919. record.handler = handler;
  49920. }
  49921. function initGlobalListeners(zr, api) {
  49922. if (inner$7(zr).initialized) {
  49923. return;
  49924. }
  49925. inner$7(zr).initialized = true;
  49926. useHandler('click', curry(doEnter, 'click'));
  49927. useHandler('mousemove', curry(doEnter, 'mousemove'));
  49928. // useHandler('mouseout', onLeave);
  49929. useHandler('globalout', onLeave);
  49930. function useHandler(eventType, cb) {
  49931. zr.on(eventType, function (e) {
  49932. var dis = makeDispatchAction(api);
  49933. each$16(inner$7(zr).records, function (record) {
  49934. record && cb(record, e, dis.dispatchAction);
  49935. });
  49936. dispatchTooltipFinally(dis.pendings, api);
  49937. });
  49938. }
  49939. }
  49940. function dispatchTooltipFinally(pendings, api) {
  49941. var showLen = pendings.showTip.length;
  49942. var hideLen = pendings.hideTip.length;
  49943. var actuallyPayload;
  49944. if (showLen) {
  49945. actuallyPayload = pendings.showTip[showLen - 1];
  49946. }
  49947. else if (hideLen) {
  49948. actuallyPayload = pendings.hideTip[hideLen - 1];
  49949. }
  49950. if (actuallyPayload) {
  49951. actuallyPayload.dispatchAction = null;
  49952. api.dispatchAction(actuallyPayload);
  49953. }
  49954. }
  49955. function onLeave(record, e, dispatchAction) {
  49956. record.handler('leave', null, dispatchAction);
  49957. }
  49958. function doEnter(currTrigger, record, e, dispatchAction) {
  49959. record.handler(currTrigger, e, dispatchAction);
  49960. }
  49961. function makeDispatchAction(api) {
  49962. var pendings = {
  49963. showTip: [],
  49964. hideTip: []
  49965. };
  49966. // FIXME
  49967. // better approach?
  49968. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  49969. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  49970. // So we have to add "final stage" to merge those dispatched actions.
  49971. var dispatchAction = function (payload) {
  49972. var pendingList = pendings[payload.type];
  49973. if (pendingList) {
  49974. pendingList.push(payload);
  49975. }
  49976. else {
  49977. payload.dispatchAction = dispatchAction;
  49978. api.dispatchAction(payload);
  49979. }
  49980. };
  49981. return {
  49982. dispatchAction: dispatchAction,
  49983. pendings: pendings
  49984. };
  49985. }
  49986. /**
  49987. * @param {string} key
  49988. * @param {module:echarts/ExtensionAPI} api
  49989. */
  49990. function unregister(key, api) {
  49991. if (env$1.node) {
  49992. return;
  49993. }
  49994. var zr = api.getZr();
  49995. var record = (inner$7(zr).records || {})[key];
  49996. if (record) {
  49997. inner$7(zr).records[key] = null;
  49998. }
  49999. }
  50000. var AxisPointerView = extendComponentView({
  50001. type: 'axisPointer',
  50002. render: function (globalAxisPointerModel, ecModel, api) {
  50003. var globalTooltipModel = ecModel.getComponent('tooltip');
  50004. var triggerOn = globalAxisPointerModel.get('triggerOn')
  50005. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  50006. // Register global listener in AxisPointerView to enable
  50007. // AxisPointerView to be independent to Tooltip.
  50008. register(
  50009. 'axisPointer',
  50010. api,
  50011. function (currTrigger, e, dispatchAction) {
  50012. // If 'none', it is not controlled by mouse totally.
  50013. if (triggerOn !== 'none'
  50014. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  50015. ) {
  50016. dispatchAction({
  50017. type: 'updateAxisPointer',
  50018. currTrigger: currTrigger,
  50019. x: e && e.offsetX,
  50020. y: e && e.offsetY
  50021. });
  50022. }
  50023. }
  50024. );
  50025. },
  50026. /**
  50027. * @override
  50028. */
  50029. remove: function (ecModel, api) {
  50030. unregister(api.getZr(), 'axisPointer');
  50031. AxisPointerView.superApply(this._model, 'remove', arguments);
  50032. },
  50033. /**
  50034. * @override
  50035. */
  50036. dispose: function (ecModel, api) {
  50037. unregister('axisPointer', api);
  50038. AxisPointerView.superApply(this._model, 'dispose', arguments);
  50039. }
  50040. });
  50041. var inner$8 = makeInner();
  50042. var clone$4 = clone;
  50043. var bind$2 = bind;
  50044. /**
  50045. * Base axis pointer class in 2D.
  50046. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  50047. */
  50048. function BaseAxisPointer () {
  50049. }
  50050. BaseAxisPointer.prototype = {
  50051. /**
  50052. * @private
  50053. */
  50054. _group: null,
  50055. /**
  50056. * @private
  50057. */
  50058. _lastGraphicKey: null,
  50059. /**
  50060. * @private
  50061. */
  50062. _handle: null,
  50063. /**
  50064. * @private
  50065. */
  50066. _dragging: false,
  50067. /**
  50068. * @private
  50069. */
  50070. _lastValue: null,
  50071. /**
  50072. * @private
  50073. */
  50074. _lastStatus: null,
  50075. /**
  50076. * @private
  50077. */
  50078. _payloadInfo: null,
  50079. /**
  50080. * In px, arbitrary value. Do not set too small,
  50081. * no animation is ok for most cases.
  50082. * @protected
  50083. */
  50084. animationThreshold: 15,
  50085. /**
  50086. * @implement
  50087. */
  50088. render: function (axisModel, axisPointerModel, api, forceRender) {
  50089. var value = axisPointerModel.get('value');
  50090. var status = axisPointerModel.get('status');
  50091. // Bind them to `this`, not in closure, otherwise they will not
  50092. // be replaced when user calling setOption in not merge mode.
  50093. this._axisModel = axisModel;
  50094. this._axisPointerModel = axisPointerModel;
  50095. this._api = api;
  50096. // Optimize: `render` will be called repeatly during mouse move.
  50097. // So it is power consuming if performing `render` each time,
  50098. // especially on mobile device.
  50099. if (!forceRender
  50100. && this._lastValue === value
  50101. && this._lastStatus === status
  50102. ) {
  50103. return;
  50104. }
  50105. this._lastValue = value;
  50106. this._lastStatus = status;
  50107. var group = this._group;
  50108. var handle = this._handle;
  50109. if (!status || status === 'hide') {
  50110. // Do not clear here, for animation better.
  50111. group && group.hide();
  50112. handle && handle.hide();
  50113. return;
  50114. }
  50115. group && group.show();
  50116. handle && handle.show();
  50117. // Otherwise status is 'show'
  50118. var elOption = {};
  50119. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  50120. // Enable change axis pointer type.
  50121. var graphicKey = elOption.graphicKey;
  50122. if (graphicKey !== this._lastGraphicKey) {
  50123. this.clear(api);
  50124. }
  50125. this._lastGraphicKey = graphicKey;
  50126. var moveAnimation = this._moveAnimation =
  50127. this.determineAnimation(axisModel, axisPointerModel);
  50128. if (!group) {
  50129. group = this._group = new Group();
  50130. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  50131. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  50132. api.getZr().add(group);
  50133. }
  50134. else {
  50135. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  50136. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  50137. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  50138. }
  50139. updateMandatoryProps(group, axisPointerModel, true);
  50140. this._renderHandle(value);
  50141. },
  50142. /**
  50143. * @implement
  50144. */
  50145. remove: function (api) {
  50146. this.clear(api);
  50147. },
  50148. /**
  50149. * @implement
  50150. */
  50151. dispose: function (api) {
  50152. this.clear(api);
  50153. },
  50154. /**
  50155. * @protected
  50156. */
  50157. determineAnimation: function (axisModel, axisPointerModel) {
  50158. var animation = axisPointerModel.get('animation');
  50159. var axis = axisModel.axis;
  50160. var isCategoryAxis = axis.type === 'category';
  50161. var useSnap = axisPointerModel.get('snap');
  50162. // Value axis without snap always do not snap.
  50163. if (!useSnap && !isCategoryAxis) {
  50164. return false;
  50165. }
  50166. if (animation === 'auto' || animation == null) {
  50167. var animationThreshold = this.animationThreshold;
  50168. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  50169. return true;
  50170. }
  50171. // It is important to auto animation when snap used. Consider if there is
  50172. // a dataZoom, animation will be disabled when too many points exist, while
  50173. // it will be enabled for better visual effect when little points exist.
  50174. if (useSnap) {
  50175. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  50176. var axisExtent = axis.getExtent();
  50177. // Approximate band width
  50178. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  50179. }
  50180. return false;
  50181. }
  50182. return animation === true;
  50183. },
  50184. /**
  50185. * add {pointer, label, graphicKey} to elOption
  50186. * @protected
  50187. */
  50188. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50189. // Shoule be implemenented by sub-class.
  50190. },
  50191. /**
  50192. * @protected
  50193. */
  50194. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  50195. var pointerOption = elOption.pointer;
  50196. if (pointerOption) {
  50197. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  50198. clone$4(elOption.pointer)
  50199. );
  50200. group.add(pointerEl);
  50201. }
  50202. },
  50203. /**
  50204. * @protected
  50205. */
  50206. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  50207. if (elOption.label) {
  50208. var labelEl = inner$8(group).labelEl = new Rect(
  50209. clone$4(elOption.label)
  50210. );
  50211. group.add(labelEl);
  50212. updateLabelShowHide(labelEl, axisPointerModel);
  50213. }
  50214. },
  50215. /**
  50216. * @protected
  50217. */
  50218. updatePointerEl: function (group, elOption, updateProps$$1) {
  50219. var pointerEl = inner$8(group).pointerEl;
  50220. if (pointerEl) {
  50221. pointerEl.setStyle(elOption.pointer.style);
  50222. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  50223. }
  50224. },
  50225. /**
  50226. * @protected
  50227. */
  50228. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  50229. var labelEl = inner$8(group).labelEl;
  50230. if (labelEl) {
  50231. labelEl.setStyle(elOption.label.style);
  50232. updateProps$$1(labelEl, {
  50233. // Consider text length change in vertical axis, animation should
  50234. // be used on shape, otherwise the effect will be weird.
  50235. shape: elOption.label.shape,
  50236. position: elOption.label.position
  50237. });
  50238. updateLabelShowHide(labelEl, axisPointerModel);
  50239. }
  50240. },
  50241. /**
  50242. * @private
  50243. */
  50244. _renderHandle: function (value) {
  50245. if (this._dragging || !this.updateHandleTransform) {
  50246. return;
  50247. }
  50248. var axisPointerModel = this._axisPointerModel;
  50249. var zr = this._api.getZr();
  50250. var handle = this._handle;
  50251. var handleModel = axisPointerModel.getModel('handle');
  50252. var status = axisPointerModel.get('status');
  50253. if (!handleModel.get('show') || !status || status === 'hide') {
  50254. handle && zr.remove(handle);
  50255. this._handle = null;
  50256. return;
  50257. }
  50258. var isInit;
  50259. if (!this._handle) {
  50260. isInit = true;
  50261. handle = this._handle = createIcon(
  50262. handleModel.get('icon'),
  50263. {
  50264. cursor: 'move',
  50265. draggable: true,
  50266. onmousemove: function (e) {
  50267. // Fot mobile devicem, prevent screen slider on the button.
  50268. stop(e.event);
  50269. },
  50270. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  50271. drift: bind$2(this._onHandleDragMove, this),
  50272. ondragend: bind$2(this._onHandleDragEnd, this)
  50273. }
  50274. );
  50275. zr.add(handle);
  50276. }
  50277. updateMandatoryProps(handle, axisPointerModel, false);
  50278. // update style
  50279. var includeStyles = [
  50280. 'color', 'borderColor', 'borderWidth', 'opacity',
  50281. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  50282. ];
  50283. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  50284. // update position
  50285. var handleSize = handleModel.get('size');
  50286. if (!isArray(handleSize)) {
  50287. handleSize = [handleSize, handleSize];
  50288. }
  50289. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  50290. createOrUpdate(
  50291. this,
  50292. '_doDispatchAxisPointer',
  50293. handleModel.get('throttle') || 0,
  50294. 'fixRate'
  50295. );
  50296. this._moveHandleToValue(value, isInit);
  50297. },
  50298. /**
  50299. * @private
  50300. */
  50301. _moveHandleToValue: function (value, isInit) {
  50302. updateProps$1(
  50303. this._axisPointerModel,
  50304. !isInit && this._moveAnimation,
  50305. this._handle,
  50306. getHandleTransProps(this.getHandleTransform(
  50307. value, this._axisModel, this._axisPointerModel
  50308. ))
  50309. );
  50310. },
  50311. /**
  50312. * @private
  50313. */
  50314. _onHandleDragMove: function (dx, dy) {
  50315. var handle = this._handle;
  50316. if (!handle) {
  50317. return;
  50318. }
  50319. this._dragging = true;
  50320. // Persistent for throttle.
  50321. var trans = this.updateHandleTransform(
  50322. getHandleTransProps(handle),
  50323. [dx, dy],
  50324. this._axisModel,
  50325. this._axisPointerModel
  50326. );
  50327. this._payloadInfo = trans;
  50328. handle.stopAnimation();
  50329. handle.attr(getHandleTransProps(trans));
  50330. inner$8(handle).lastProp = null;
  50331. this._doDispatchAxisPointer();
  50332. },
  50333. /**
  50334. * Throttled method.
  50335. * @private
  50336. */
  50337. _doDispatchAxisPointer: function () {
  50338. var handle = this._handle;
  50339. if (!handle) {
  50340. return;
  50341. }
  50342. var payloadInfo = this._payloadInfo;
  50343. var axisModel = this._axisModel;
  50344. this._api.dispatchAction({
  50345. type: 'updateAxisPointer',
  50346. x: payloadInfo.cursorPoint[0],
  50347. y: payloadInfo.cursorPoint[1],
  50348. tooltipOption: payloadInfo.tooltipOption,
  50349. axesInfo: [{
  50350. axisDim: axisModel.axis.dim,
  50351. axisIndex: axisModel.componentIndex
  50352. }]
  50353. });
  50354. },
  50355. /**
  50356. * @private
  50357. */
  50358. _onHandleDragEnd: function (moveAnimation) {
  50359. this._dragging = false;
  50360. var handle = this._handle;
  50361. if (!handle) {
  50362. return;
  50363. }
  50364. var value = this._axisPointerModel.get('value');
  50365. // Consider snap or categroy axis, handle may be not consistent with
  50366. // axisPointer. So move handle to align the exact value position when
  50367. // drag ended.
  50368. this._moveHandleToValue(value);
  50369. // For the effect: tooltip will be shown when finger holding on handle
  50370. // button, and will be hidden after finger left handle button.
  50371. this._api.dispatchAction({
  50372. type: 'hideTip'
  50373. });
  50374. },
  50375. /**
  50376. * Should be implemenented by sub-class if support `handle`.
  50377. * @protected
  50378. * @param {number} value
  50379. * @param {module:echarts/model/Model} axisModel
  50380. * @param {module:echarts/model/Model} axisPointerModel
  50381. * @return {Object} {position: [x, y], rotation: 0}
  50382. */
  50383. getHandleTransform: null,
  50384. /**
  50385. * * Should be implemenented by sub-class if support `handle`.
  50386. * @protected
  50387. * @param {Object} transform {position, rotation}
  50388. * @param {Array.<number>} delta [dx, dy]
  50389. * @param {module:echarts/model/Model} axisModel
  50390. * @param {module:echarts/model/Model} axisPointerModel
  50391. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  50392. */
  50393. updateHandleTransform: null,
  50394. /**
  50395. * @private
  50396. */
  50397. clear: function (api) {
  50398. this._lastValue = null;
  50399. this._lastStatus = null;
  50400. var zr = api.getZr();
  50401. var group = this._group;
  50402. var handle = this._handle;
  50403. if (zr && group) {
  50404. this._lastGraphicKey = null;
  50405. group && zr.remove(group);
  50406. handle && zr.remove(handle);
  50407. this._group = null;
  50408. this._handle = null;
  50409. this._payloadInfo = null;
  50410. }
  50411. },
  50412. /**
  50413. * @protected
  50414. */
  50415. doClear: function () {
  50416. // Implemented by sub-class if necessary.
  50417. },
  50418. /**
  50419. * @protected
  50420. * @param {Array.<number>} xy
  50421. * @param {Array.<number>} wh
  50422. * @param {number} [xDimIndex=0] or 1
  50423. */
  50424. buildLabel: function (xy, wh, xDimIndex) {
  50425. xDimIndex = xDimIndex || 0;
  50426. return {
  50427. x: xy[xDimIndex],
  50428. y: xy[1 - xDimIndex],
  50429. width: wh[xDimIndex],
  50430. height: wh[1 - xDimIndex]
  50431. };
  50432. }
  50433. };
  50434. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  50435. function updateProps$1(animationModel, moveAnimation, el, props) {
  50436. // Animation optimize.
  50437. if (!propsEqual(inner$8(el).lastProp, props)) {
  50438. inner$8(el).lastProp = props;
  50439. moveAnimation
  50440. ? updateProps(el, props, animationModel)
  50441. : (el.stopAnimation(), el.attr(props));
  50442. }
  50443. }
  50444. function propsEqual(lastProps, newProps) {
  50445. if (isObject$1(lastProps) && isObject$1(newProps)) {
  50446. var equals = true;
  50447. each$1(newProps, function (item, key) {
  50448. equals = equals && propsEqual(lastProps[key], item);
  50449. });
  50450. return !!equals;
  50451. }
  50452. else {
  50453. return lastProps === newProps;
  50454. }
  50455. }
  50456. function updateLabelShowHide(labelEl, axisPointerModel) {
  50457. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  50458. }
  50459. function getHandleTransProps(trans) {
  50460. return {
  50461. position: trans.position.slice(),
  50462. rotation: trans.rotation || 0
  50463. };
  50464. }
  50465. function updateMandatoryProps(group, axisPointerModel, silent) {
  50466. var z = axisPointerModel.get('z');
  50467. var zlevel = axisPointerModel.get('zlevel');
  50468. group && group.traverse(function (el) {
  50469. if (el.type !== 'group') {
  50470. z != null && (el.z = z);
  50471. zlevel != null && (el.zlevel = zlevel);
  50472. el.silent = silent;
  50473. }
  50474. });
  50475. }
  50476. enableClassExtend(BaseAxisPointer);
  50477. /**
  50478. * @param {module:echarts/model/Model} axisPointerModel
  50479. */
  50480. function buildElStyle(axisPointerModel) {
  50481. var axisPointerType = axisPointerModel.get('type');
  50482. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  50483. var style;
  50484. if (axisPointerType === 'line') {
  50485. style = styleModel.getLineStyle();
  50486. style.fill = null;
  50487. }
  50488. else if (axisPointerType === 'shadow') {
  50489. style = styleModel.getAreaStyle();
  50490. style.stroke = null;
  50491. }
  50492. return style;
  50493. }
  50494. /**
  50495. * @param {Function} labelPos {align, verticalAlign, position}
  50496. */
  50497. function buildLabelElOption(
  50498. elOption, axisModel, axisPointerModel, api, labelPos
  50499. ) {
  50500. var value = axisPointerModel.get('value');
  50501. var text = getValueLabel(
  50502. value, axisModel.axis, axisModel.ecModel,
  50503. axisPointerModel.get('seriesDataIndices'),
  50504. {
  50505. precision: axisPointerModel.get('label.precision'),
  50506. formatter: axisPointerModel.get('label.formatter')
  50507. }
  50508. );
  50509. var labelModel = axisPointerModel.getModel('label');
  50510. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  50511. var font = labelModel.getFont();
  50512. var textRect = getBoundingRect(text, font);
  50513. var position = labelPos.position;
  50514. var width = textRect.width + paddings[1] + paddings[3];
  50515. var height = textRect.height + paddings[0] + paddings[2];
  50516. // Adjust by align.
  50517. var align = labelPos.align;
  50518. align === 'right' && (position[0] -= width);
  50519. align === 'center' && (position[0] -= width / 2);
  50520. var verticalAlign = labelPos.verticalAlign;
  50521. verticalAlign === 'bottom' && (position[1] -= height);
  50522. verticalAlign === 'middle' && (position[1] -= height / 2);
  50523. // Not overflow ec container
  50524. confineInContainer(position, width, height, api);
  50525. var bgColor = labelModel.get('backgroundColor');
  50526. if (!bgColor || bgColor === 'auto') {
  50527. bgColor = axisModel.get('axisLine.lineStyle.color');
  50528. }
  50529. elOption.label = {
  50530. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  50531. position: position.slice(),
  50532. // TODO: rich
  50533. style: {
  50534. text: text,
  50535. textFont: font,
  50536. textFill: labelModel.getTextColor(),
  50537. textPosition: 'inside',
  50538. fill: bgColor,
  50539. stroke: labelModel.get('borderColor') || 'transparent',
  50540. lineWidth: labelModel.get('borderWidth') || 0,
  50541. shadowBlur: labelModel.get('shadowBlur'),
  50542. shadowColor: labelModel.get('shadowColor'),
  50543. shadowOffsetX: labelModel.get('shadowOffsetX'),
  50544. shadowOffsetY: labelModel.get('shadowOffsetY')
  50545. },
  50546. // Lable should be over axisPointer.
  50547. z2: 10
  50548. };
  50549. }
  50550. // Do not overflow ec container
  50551. function confineInContainer(position, width, height, api) {
  50552. var viewWidth = api.getWidth();
  50553. var viewHeight = api.getHeight();
  50554. position[0] = Math.min(position[0] + width, viewWidth) - width;
  50555. position[1] = Math.min(position[1] + height, viewHeight) - height;
  50556. position[0] = Math.max(position[0], 0);
  50557. position[1] = Math.max(position[1], 0);
  50558. }
  50559. /**
  50560. * @param {number} value
  50561. * @param {module:echarts/coord/Axis} axis
  50562. * @param {module:echarts/model/Global} ecModel
  50563. * @param {Object} opt
  50564. * @param {Array.<Object>} seriesDataIndices
  50565. * @param {number|string} opt.precision 'auto' or a number
  50566. * @param {string|Function} opt.formatter label formatter
  50567. */
  50568. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  50569. var text = axis.scale.getLabel(
  50570. // If `precision` is set, width can be fixed (like '12.00500'), which
  50571. // helps to debounce when when moving label.
  50572. value, {precision: opt.precision}
  50573. );
  50574. var formatter = opt.formatter;
  50575. if (formatter) {
  50576. var params = {
  50577. value: getAxisRawValue(axis, value),
  50578. seriesData: []
  50579. };
  50580. each$1(seriesDataIndices, function (idxItem) {
  50581. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  50582. var dataIndex = idxItem.dataIndexInside;
  50583. var dataParams = series && series.getDataParams(dataIndex);
  50584. dataParams && params.seriesData.push(dataParams);
  50585. });
  50586. if (isString(formatter)) {
  50587. text = formatter.replace('{value}', text);
  50588. }
  50589. else if (isFunction$1(formatter)) {
  50590. text = formatter(params);
  50591. }
  50592. }
  50593. return text;
  50594. }
  50595. /**
  50596. * @param {module:echarts/coord/Axis} axis
  50597. * @param {number} value
  50598. * @param {Object} layoutInfo {
  50599. * rotation, position, labelOffset, labelDirection, labelMargin
  50600. * }
  50601. */
  50602. function getTransformedPosition (axis, value, layoutInfo) {
  50603. var transform = create$1();
  50604. rotate(transform, transform, layoutInfo.rotation);
  50605. translate(transform, transform, layoutInfo.position);
  50606. return applyTransform$1([
  50607. axis.dataToCoord(value),
  50608. (layoutInfo.labelOffset || 0)
  50609. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  50610. ], transform);
  50611. }
  50612. function buildCartesianSingleLabelElOption(
  50613. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50614. ) {
  50615. var textLayout = AxisBuilder.innerTextLayout(
  50616. layoutInfo.rotation, 0, layoutInfo.labelDirection
  50617. );
  50618. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  50619. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  50620. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50621. align: textLayout.textAlign,
  50622. verticalAlign: textLayout.textVerticalAlign
  50623. });
  50624. }
  50625. /**
  50626. * @param {Array.<number>} p1
  50627. * @param {Array.<number>} p2
  50628. * @param {number} [xDimIndex=0] or 1
  50629. */
  50630. function makeLineShape(p1, p2, xDimIndex) {
  50631. xDimIndex = xDimIndex || 0;
  50632. return {
  50633. x1: p1[xDimIndex],
  50634. y1: p1[1 - xDimIndex],
  50635. x2: p2[xDimIndex],
  50636. y2: p2[1 - xDimIndex]
  50637. };
  50638. }
  50639. /**
  50640. * @param {Array.<number>} xy
  50641. * @param {Array.<number>} wh
  50642. * @param {number} [xDimIndex=0] or 1
  50643. */
  50644. function makeRectShape(xy, wh, xDimIndex) {
  50645. xDimIndex = xDimIndex || 0;
  50646. return {
  50647. x: xy[xDimIndex],
  50648. y: xy[1 - xDimIndex],
  50649. width: wh[xDimIndex],
  50650. height: wh[1 - xDimIndex]
  50651. };
  50652. }
  50653. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  50654. return {
  50655. cx: cx,
  50656. cy: cy,
  50657. r0: r0,
  50658. r: r,
  50659. startAngle: startAngle,
  50660. endAngle: endAngle,
  50661. clockwise: true
  50662. };
  50663. }
  50664. var CartesianAxisPointer = BaseAxisPointer.extend({
  50665. /**
  50666. * @override
  50667. */
  50668. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50669. var axis = axisModel.axis;
  50670. var grid = axis.grid;
  50671. var axisPointerType = axisPointerModel.get('type');
  50672. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  50673. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  50674. if (axisPointerType && axisPointerType !== 'none') {
  50675. var elStyle = buildElStyle(axisPointerModel);
  50676. var pointerOption = pointerShapeBuilder[axisPointerType](
  50677. axis, pixelValue, otherExtent, elStyle
  50678. );
  50679. pointerOption.style = elStyle;
  50680. elOption.graphicKey = pointerOption.type;
  50681. elOption.pointer = pointerOption;
  50682. }
  50683. var layoutInfo = layout$1(grid.model, axisModel);
  50684. buildCartesianSingleLabelElOption(
  50685. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50686. );
  50687. },
  50688. /**
  50689. * @override
  50690. */
  50691. getHandleTransform: function (value, axisModel, axisPointerModel) {
  50692. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  50693. labelInside: false
  50694. });
  50695. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  50696. return {
  50697. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50698. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  50699. };
  50700. },
  50701. /**
  50702. * @override
  50703. */
  50704. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  50705. var axis = axisModel.axis;
  50706. var grid = axis.grid;
  50707. var axisExtent = axis.getGlobalExtent(true);
  50708. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  50709. var dimIndex = axis.dim === 'x' ? 0 : 1;
  50710. var currPosition = transform.position;
  50711. currPosition[dimIndex] += delta[dimIndex];
  50712. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  50713. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  50714. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  50715. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  50716. cursorPoint[dimIndex] = currPosition[dimIndex];
  50717. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  50718. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  50719. return {
  50720. position: currPosition,
  50721. rotation: transform.rotation,
  50722. cursorPoint: cursorPoint,
  50723. tooltipOption: tooltipOptions[dimIndex]
  50724. };
  50725. }
  50726. });
  50727. function getCartesian(grid, axis) {
  50728. var opt = {};
  50729. opt[axis.dim + 'AxisIndex'] = axis.index;
  50730. return grid.getCartesian(opt);
  50731. }
  50732. var pointerShapeBuilder = {
  50733. line: function (axis, pixelValue, otherExtent, elStyle) {
  50734. var targetShape = makeLineShape(
  50735. [pixelValue, otherExtent[0]],
  50736. [pixelValue, otherExtent[1]],
  50737. getAxisDimIndex(axis)
  50738. );
  50739. subPixelOptimizeLine({
  50740. shape: targetShape,
  50741. style: elStyle
  50742. });
  50743. return {
  50744. type: 'Line',
  50745. shape: targetShape
  50746. };
  50747. },
  50748. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  50749. var bandWidth = axis.getBandWidth();
  50750. var span = otherExtent[1] - otherExtent[0];
  50751. return {
  50752. type: 'Rect',
  50753. shape: makeRectShape(
  50754. [pixelValue - bandWidth / 2, otherExtent[0]],
  50755. [bandWidth, span],
  50756. getAxisDimIndex(axis)
  50757. )
  50758. };
  50759. }
  50760. };
  50761. function getAxisDimIndex(axis) {
  50762. return axis.dim === 'x' ? 0 : 1;
  50763. }
  50764. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  50765. // CartesianAxisPointer is not supposed to be required here. But consider
  50766. // echarts.simple.js and online build tooltip, which only require gridSimple,
  50767. // CartesianAxisPointer should be able to required somewhere.
  50768. registerPreprocessor(function (option) {
  50769. // Always has a global axisPointerModel for default setting.
  50770. if (option) {
  50771. (!option.axisPointer || option.axisPointer.length === 0)
  50772. && (option.axisPointer = {});
  50773. var link = option.axisPointer.link;
  50774. // Normalize to array to avoid object mergin. But if link
  50775. // is not set, remain null/undefined, otherwise it will
  50776. // override existent link setting.
  50777. if (link && !isArray(link)) {
  50778. option.axisPointer.link = [link];
  50779. }
  50780. }
  50781. });
  50782. // This process should proformed after coordinate systems created
  50783. // and series data processed. So put it on statistic processing stage.
  50784. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  50785. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  50786. // allAxesInfo should be updated when setOption performed.
  50787. ecModel.getComponent('axisPointer').coordSysAxesInfo
  50788. = collect(ecModel, api);
  50789. });
  50790. // Broadcast to all views.
  50791. registerAction({
  50792. type: 'updateAxisPointer',
  50793. event: 'updateAxisPointer',
  50794. update: ':updateAxisPointer'
  50795. }, axisTrigger);
  50796. var XY = ['x', 'y'];
  50797. var WH = ['width', 'height'];
  50798. var SingleAxisPointer = BaseAxisPointer.extend({
  50799. /**
  50800. * @override
  50801. */
  50802. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50803. var axis = axisModel.axis;
  50804. var coordSys = axis.coordinateSystem;
  50805. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  50806. var pixelValue = coordSys.dataToPoint(value)[0];
  50807. var axisPointerType = axisPointerModel.get('type');
  50808. if (axisPointerType && axisPointerType !== 'none') {
  50809. var elStyle = buildElStyle(axisPointerModel);
  50810. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  50811. axis, pixelValue, otherExtent, elStyle
  50812. );
  50813. pointerOption.style = elStyle;
  50814. elOption.graphicKey = pointerOption.type;
  50815. elOption.pointer = pointerOption;
  50816. }
  50817. var layoutInfo = layout$2(axisModel);
  50818. buildCartesianSingleLabelElOption(
  50819. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50820. );
  50821. },
  50822. /**
  50823. * @override
  50824. */
  50825. getHandleTransform: function (value, axisModel, axisPointerModel) {
  50826. var layoutInfo = layout$2(axisModel, {labelInside: false});
  50827. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  50828. return {
  50829. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50830. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  50831. };
  50832. },
  50833. /**
  50834. * @override
  50835. */
  50836. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  50837. var axis = axisModel.axis;
  50838. var coordSys = axis.coordinateSystem;
  50839. var dimIndex = getPointDimIndex(axis);
  50840. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  50841. var currPosition = transform.position;
  50842. currPosition[dimIndex] += delta[dimIndex];
  50843. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  50844. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  50845. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  50846. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  50847. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  50848. cursorPoint[dimIndex] = currPosition[dimIndex];
  50849. return {
  50850. position: currPosition,
  50851. rotation: transform.rotation,
  50852. cursorPoint: cursorPoint,
  50853. tooltipOption: {
  50854. verticalAlign: 'middle'
  50855. }
  50856. };
  50857. }
  50858. });
  50859. var pointerShapeBuilder$1 = {
  50860. line: function (axis, pixelValue, otherExtent, elStyle) {
  50861. var targetShape = makeLineShape(
  50862. [pixelValue, otherExtent[0]],
  50863. [pixelValue, otherExtent[1]],
  50864. getPointDimIndex(axis)
  50865. );
  50866. subPixelOptimizeLine({
  50867. shape: targetShape,
  50868. style: elStyle
  50869. });
  50870. return {
  50871. type: 'Line',
  50872. shape: targetShape
  50873. };
  50874. },
  50875. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  50876. var bandWidth = axis.getBandWidth();
  50877. var span = otherExtent[1] - otherExtent[0];
  50878. return {
  50879. type: 'Rect',
  50880. shape: makeRectShape(
  50881. [pixelValue - bandWidth / 2, otherExtent[0]],
  50882. [bandWidth, span],
  50883. getPointDimIndex(axis)
  50884. )
  50885. };
  50886. }
  50887. };
  50888. function getPointDimIndex(axis) {
  50889. return axis.isHorizontal() ? 0 : 1;
  50890. }
  50891. function getGlobalExtent(coordSys, dimIndex) {
  50892. var rect = coordSys.getRect();
  50893. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  50894. }
  50895. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  50896. extendComponentView({
  50897. type: 'single'
  50898. });
  50899. /**
  50900. * @file Define the themeRiver view's series model
  50901. * @author Deqing Li(annong035@gmail.com)
  50902. */
  50903. var DATA_NAME_INDEX = 2;
  50904. var ThemeRiverSeries = SeriesModel.extend({
  50905. type: 'series.themeRiver',
  50906. dependencies: ['singleAxis'],
  50907. /**
  50908. * @readOnly
  50909. * @type {module:zrender/core/util#HashMap}
  50910. */
  50911. nameMap: null,
  50912. /**
  50913. * @override
  50914. */
  50915. init: function (option) {
  50916. ThemeRiverSeries.superApply(this, 'init', arguments);
  50917. // Put this function here is for the sake of consistency of code style.
  50918. // Enable legend selection for each data item
  50919. // Use a function instead of direct access because data reference may changed
  50920. this.legendDataProvider = function () {
  50921. return this.getRawData();
  50922. };
  50923. },
  50924. /**
  50925. * If there is no value of a certain point in the time for some event,set it value to 0.
  50926. *
  50927. * @param {Array} data initial data in the option
  50928. * @return {Array}
  50929. */
  50930. fixData: function (data) {
  50931. var rawDataLength = data.length;
  50932. // grouped data by name
  50933. var dataByName = nest()
  50934. .key(function (dataItem) {
  50935. return dataItem[2];
  50936. })
  50937. .entries(data);
  50938. // data group in each layer
  50939. var layData = map(dataByName, function (d) {
  50940. return {
  50941. name: d.key,
  50942. dataList: d.values
  50943. };
  50944. });
  50945. var layerNum = layData.length;
  50946. var largestLayer = -1;
  50947. var index = -1;
  50948. for (var i = 0; i < layerNum; ++i) {
  50949. var len = layData[i].dataList.length;
  50950. if (len > largestLayer) {
  50951. largestLayer = len;
  50952. index = i;
  50953. }
  50954. }
  50955. for (var k = 0; k < layerNum; ++k) {
  50956. if (k === index) {
  50957. continue;
  50958. }
  50959. var name = layData[k].name;
  50960. for (var j = 0; j < largestLayer; ++j) {
  50961. var timeValue = layData[index].dataList[j][0];
  50962. var length = layData[k].dataList.length;
  50963. var keyIndex = -1;
  50964. for (var l = 0; l < length; ++l) {
  50965. var value = layData[k].dataList[l][0];
  50966. if (value === timeValue) {
  50967. keyIndex = l;
  50968. break;
  50969. }
  50970. }
  50971. if (keyIndex === -1) {
  50972. data[rawDataLength] = [];
  50973. data[rawDataLength][0] = timeValue;
  50974. data[rawDataLength][1] = 0;
  50975. data[rawDataLength][2] = name;
  50976. rawDataLength++;
  50977. }
  50978. }
  50979. }
  50980. return data;
  50981. },
  50982. /**
  50983. * @override
  50984. * @param {Object} option the initial option that user gived
  50985. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  50986. * @return {module:echarts/data/List}
  50987. */
  50988. getInitialData: function (option, ecModel) {
  50989. var singleAxisModel = ecModel.queryComponents({
  50990. mainType: 'singleAxis',
  50991. index: this.get('singleAxisIndex'),
  50992. id: this.get('singleAxisId')
  50993. })[0];
  50994. var axisType = singleAxisModel.get('type');
  50995. // filter the data item with the value of label is undefined
  50996. var filterData = filter(option.data, function (dataItem) {
  50997. return dataItem[2] !== undefined;
  50998. });
  50999. // ??? TODO design a stage to transfer data for themeRiver and lines?
  51000. var data = this.fixData(filterData || []);
  51001. var nameList = [];
  51002. var nameMap = this.nameMap = createHashMap();
  51003. var count = 0;
  51004. for (var i = 0; i < data.length; ++i) {
  51005. nameList.push(data[i][DATA_NAME_INDEX]);
  51006. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  51007. nameMap.set(data[i][DATA_NAME_INDEX], count);
  51008. count++;
  51009. }
  51010. }
  51011. var dimensionsInfo = createDimensions(data, {
  51012. coordDimensions: ['single'],
  51013. dimensionsDefine: [
  51014. {
  51015. name: 'time',
  51016. type: getDimensionTypeByAxis(axisType)
  51017. },
  51018. {
  51019. name: 'value',
  51020. type: 'float'
  51021. },
  51022. {
  51023. name: 'name',
  51024. type: 'ordinal'
  51025. }
  51026. ],
  51027. encodeDefine: {
  51028. single: 0,
  51029. value: 1,
  51030. itemName: 2
  51031. }
  51032. });
  51033. var list = new List(dimensionsInfo, this);
  51034. list.initData(data);
  51035. return list;
  51036. },
  51037. /**
  51038. * The raw data is divided into multiple layers and each layer
  51039. * has same name.
  51040. *
  51041. * @return {Array.<Array.<number>>}
  51042. */
  51043. getLayerSeries: function () {
  51044. var data = this.getData();
  51045. var lenCount = data.count();
  51046. var indexArr = [];
  51047. for (var i = 0; i < lenCount; ++i) {
  51048. indexArr[i] = i;
  51049. }
  51050. // data group by name
  51051. var dataByName = nest()
  51052. .key(function (index) {
  51053. return data.get('name', index);
  51054. })
  51055. .entries(indexArr);
  51056. var layerSeries = map(dataByName, function (d) {
  51057. return {
  51058. name: d.key,
  51059. indices: d.values
  51060. };
  51061. });
  51062. var timeDim = data.mapDimension('single');
  51063. for (var j = 0; j < layerSeries.length; ++j) {
  51064. layerSeries[j].indices.sort(comparer);
  51065. }
  51066. function comparer(index1, index2) {
  51067. return data.get(timeDim, index1) - data.get(timeDim, index2);
  51068. }
  51069. return layerSeries;
  51070. },
  51071. /**
  51072. * Get data indices for show tooltip content
  51073. *
  51074. * @param {Array.<string>|string} dim single coordinate dimension
  51075. * @param {number} value axis value
  51076. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  51077. * the themeRiver.
  51078. * @return {Object} {dataIndices, nestestValue}
  51079. */
  51080. getAxisTooltipData: function (dim, value, baseAxis) {
  51081. if (!isArray(dim)) {
  51082. dim = dim ? [dim] : [];
  51083. }
  51084. var data = this.getData();
  51085. var layerSeries = this.getLayerSeries();
  51086. var indices = [];
  51087. var layerNum = layerSeries.length;
  51088. var nestestValue;
  51089. for (var i = 0; i < layerNum; ++i) {
  51090. var minDist = Number.MAX_VALUE;
  51091. var nearestIdx = -1;
  51092. var pointNum = layerSeries[i].indices.length;
  51093. for (var j = 0; j < pointNum; ++j) {
  51094. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  51095. var dist = Math.abs(theValue - value);
  51096. if (dist <= minDist) {
  51097. nestestValue = theValue;
  51098. minDist = dist;
  51099. nearestIdx = layerSeries[i].indices[j];
  51100. }
  51101. }
  51102. indices.push(nearestIdx);
  51103. }
  51104. return {dataIndices: indices, nestestValue: nestestValue};
  51105. },
  51106. /**
  51107. * @override
  51108. * @param {number} dataIndex index of data
  51109. */
  51110. formatTooltip: function (dataIndex) {
  51111. var data = this.getData();
  51112. var htmlName = data.getName(dataIndex);
  51113. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  51114. if (isNaN(htmlValue) || htmlValue == null) {
  51115. htmlValue = '-';
  51116. }
  51117. return encodeHTML(htmlName + ' : ' + htmlValue);
  51118. },
  51119. defaultOption: {
  51120. zlevel: 0,
  51121. z: 2,
  51122. coordinateSystem: 'singleAxis',
  51123. // gap in axis's orthogonal orientation
  51124. boundaryGap: ['10%', '10%'],
  51125. // legendHoverLink: true,
  51126. singleAxisIndex: 0,
  51127. animationEasing: 'linear',
  51128. label: {
  51129. margin: 4,
  51130. textAlign: 'right',
  51131. show: true,
  51132. position: 'left',
  51133. color: '#000',
  51134. fontSize: 11
  51135. },
  51136. emphasis: {
  51137. label: {
  51138. show: true
  51139. }
  51140. }
  51141. }
  51142. });
  51143. /**
  51144. * @file The file used to draw themeRiver view
  51145. * @author Deqing Li(annong035@gmail.com)
  51146. */
  51147. extendChartView({
  51148. type: 'themeRiver',
  51149. init: function () {
  51150. this._layers = [];
  51151. },
  51152. render: function (seriesModel, ecModel, api) {
  51153. var data = seriesModel.getData();
  51154. var group = this.group;
  51155. var layerSeries = seriesModel.getLayerSeries();
  51156. var layoutInfo = data.getLayout('layoutInfo');
  51157. var rect = layoutInfo.rect;
  51158. var boundaryGap = layoutInfo.boundaryGap;
  51159. group.attr('position', [0, rect.y + boundaryGap[0]]);
  51160. function keyGetter(item) {
  51161. return item.name;
  51162. }
  51163. var dataDiffer = new DataDiffer(
  51164. this._layersSeries || [], layerSeries,
  51165. keyGetter, keyGetter
  51166. );
  51167. var newLayersGroups = {};
  51168. dataDiffer
  51169. .add(bind(process, this, 'add'))
  51170. .update(bind(process, this, 'update'))
  51171. .remove(bind(process, this, 'remove'))
  51172. .execute();
  51173. function process(status, idx, oldIdx) {
  51174. var oldLayersGroups = this._layers;
  51175. if (status === 'remove') {
  51176. group.remove(oldLayersGroups[idx]);
  51177. return;
  51178. }
  51179. var points0 = [];
  51180. var points1 = [];
  51181. var color;
  51182. var indices = layerSeries[idx].indices;
  51183. for (var j = 0; j < indices.length; j++) {
  51184. var layout = data.getItemLayout(indices[j]);
  51185. var x = layout.x;
  51186. var y0 = layout.y0;
  51187. var y = layout.y;
  51188. points0.push([x, y0]);
  51189. points1.push([x, y0 + y]);
  51190. color = data.getItemVisual(indices[j], 'color');
  51191. }
  51192. var polygon;
  51193. var text;
  51194. var textLayout = data.getItemLayout(indices[0]);
  51195. var itemModel = data.getItemModel(indices[j - 1]);
  51196. var labelModel = itemModel.getModel('label');
  51197. var margin = labelModel.get('margin');
  51198. if (status === 'add') {
  51199. var layerGroup = newLayersGroups[idx] = new Group();
  51200. polygon = new Polygon$1({
  51201. shape: {
  51202. points: points0,
  51203. stackedOnPoints: points1,
  51204. smooth: 0.4,
  51205. stackedOnSmooth: 0.4,
  51206. smoothConstraint: false
  51207. },
  51208. z2: 0
  51209. });
  51210. text = new Text({
  51211. style: {
  51212. x: textLayout.x - margin,
  51213. y: textLayout.y0 + textLayout.y / 2
  51214. }
  51215. });
  51216. layerGroup.add(polygon);
  51217. layerGroup.add(text);
  51218. group.add(layerGroup);
  51219. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  51220. polygon.removeClipPath();
  51221. }));
  51222. }
  51223. else {
  51224. var layerGroup = oldLayersGroups[oldIdx];
  51225. polygon = layerGroup.childAt(0);
  51226. text = layerGroup.childAt(1);
  51227. group.add(layerGroup);
  51228. newLayersGroups[idx] = layerGroup;
  51229. updateProps(polygon, {
  51230. shape: {
  51231. points: points0,
  51232. stackedOnPoints: points1
  51233. }
  51234. }, seriesModel);
  51235. updateProps(text, {
  51236. style: {
  51237. x: textLayout.x - margin,
  51238. y: textLayout.y0 + textLayout.y / 2
  51239. }
  51240. }, seriesModel);
  51241. }
  51242. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  51243. var itemStyleModel = itemModel.getModel('itemStyle');
  51244. setTextStyle(text.style, labelModel, {
  51245. text: labelModel.get('show')
  51246. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  51247. || data.getName(indices[j - 1])
  51248. : null,
  51249. textVerticalAlign: 'middle'
  51250. });
  51251. polygon.setStyle(extend({
  51252. fill: color
  51253. }, itemStyleModel.getItemStyle(['color'])));
  51254. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  51255. }
  51256. this._layersSeries = layerSeries;
  51257. this._layers = newLayersGroups;
  51258. },
  51259. dispose: function () {}
  51260. });
  51261. // add animation to the view
  51262. function createGridClipShape$3(rect, seriesModel, cb) {
  51263. var rectEl = new Rect({
  51264. shape: {
  51265. x: rect.x - 10,
  51266. y: rect.y - 10,
  51267. width: 0,
  51268. height: rect.height + 20
  51269. }
  51270. });
  51271. initProps(rectEl, {
  51272. shape: {
  51273. width: rect.width + 20,
  51274. height: rect.height + 20
  51275. }
  51276. }, seriesModel, cb);
  51277. return rectEl;
  51278. }
  51279. /**
  51280. * @file Using layout algorithm transform the raw data to layout information.
  51281. * @author Deqing Li(annong035@gmail.com)
  51282. */
  51283. var themeRiverLayout = function (ecModel, api) {
  51284. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  51285. var data = seriesModel.getData();
  51286. var single = seriesModel.coordinateSystem;
  51287. var layoutInfo = {};
  51288. // use the axis boundingRect for view
  51289. var rect = single.getRect();
  51290. layoutInfo.rect = rect;
  51291. var boundaryGap = seriesModel.get('boundaryGap');
  51292. var axis = single.getAxis();
  51293. layoutInfo.boundaryGap = boundaryGap;
  51294. if (axis.orient === 'horizontal') {
  51295. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  51296. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  51297. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  51298. themeRiverLayout$1(data, seriesModel, height);
  51299. }
  51300. else {
  51301. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  51302. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  51303. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  51304. themeRiverLayout$1(data, seriesModel, width);
  51305. }
  51306. data.setLayout('layoutInfo', layoutInfo);
  51307. });
  51308. };
  51309. /**
  51310. * The layout information about themeriver
  51311. *
  51312. * @param {module:echarts/data/List} data data in the series
  51313. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  51314. * @param {number} height value used to compute every series height
  51315. */
  51316. function themeRiverLayout$1(data, seriesModel, height) {
  51317. if (!data.count()) {
  51318. return;
  51319. }
  51320. var coordSys = seriesModel.coordinateSystem;
  51321. // the data in each layer are organized into a series.
  51322. var layerSeries = seriesModel.getLayerSeries();
  51323. // the points in each layer.
  51324. var timeDim = data.mapDimension('single');
  51325. var valueDim = data.mapDimension('value');
  51326. var layerPoints = map(layerSeries, function (singleLayer) {
  51327. return map(singleLayer.indices, function (idx) {
  51328. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  51329. pt[1] = data.get(valueDim, idx);
  51330. return pt;
  51331. });
  51332. });
  51333. var base = computeBaseline(layerPoints);
  51334. var baseLine = base.y0;
  51335. var ky = height / base.max;
  51336. // set layout information for each item.
  51337. var n = layerSeries.length;
  51338. var m = layerSeries[0].indices.length;
  51339. var baseY0;
  51340. for (var j = 0; j < m; ++j) {
  51341. baseY0 = baseLine[j] * ky;
  51342. data.setItemLayout(layerSeries[0].indices[j], {
  51343. layerIndex: 0,
  51344. x: layerPoints[0][j][0],
  51345. y0: baseY0,
  51346. y: layerPoints[0][j][1] * ky
  51347. });
  51348. for (var i = 1; i < n; ++i) {
  51349. baseY0 += layerPoints[i - 1][j][1] * ky;
  51350. data.setItemLayout(layerSeries[i].indices[j], {
  51351. layerIndex: i,
  51352. x: layerPoints[i][j][0],
  51353. y0: baseY0,
  51354. y: layerPoints[i][j][1] * ky
  51355. });
  51356. }
  51357. }
  51358. }
  51359. /**
  51360. * Compute the baseLine of the rawdata
  51361. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  51362. *
  51363. * @param {Array.<Array>} data the points in each layer
  51364. * @return {Object}
  51365. */
  51366. function computeBaseline(data) {
  51367. var layerNum = data.length;
  51368. var pointNum = data[0].length;
  51369. var sums = [];
  51370. var y0 = [];
  51371. var max = 0;
  51372. var temp;
  51373. var base = {};
  51374. for (var i = 0; i < pointNum; ++i) {
  51375. for (var j = 0, temp = 0; j < layerNum; ++j) {
  51376. temp += data[j][i][1];
  51377. }
  51378. if (temp > max) {
  51379. max = temp;
  51380. }
  51381. sums.push(temp);
  51382. }
  51383. for (var k = 0; k < pointNum; ++k) {
  51384. y0[k] = (max - sums[k]) / 2;
  51385. }
  51386. max = 0;
  51387. for (var l = 0; l < pointNum; ++l) {
  51388. var sum = sums[l] + y0[l];
  51389. if (sum > max) {
  51390. max = sum;
  51391. }
  51392. }
  51393. base.y0 = y0;
  51394. base.max = max;
  51395. return base;
  51396. }
  51397. /**
  51398. * @file Visual encoding for themeRiver view
  51399. * @author Deqing Li(annong035@gmail.com)
  51400. */
  51401. var themeRiverVisual = function (ecModel) {
  51402. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  51403. var data = seriesModel.getData();
  51404. var rawData = seriesModel.getRawData();
  51405. var colorList = seriesModel.get('color');
  51406. var idxMap = createHashMap();
  51407. data.each(function (idx) {
  51408. idxMap.set(data.getRawIndex(idx), idx);
  51409. });
  51410. rawData.each(function (rawIndex) {
  51411. var name = rawData.getName(rawIndex);
  51412. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  51413. rawData.setItemVisual(rawIndex, 'color', color);
  51414. var idx = idxMap.get(rawIndex);
  51415. if (idx != null) {
  51416. data.setItemVisual(idx, 'color', color);
  51417. }
  51418. });
  51419. });
  51420. };
  51421. registerLayout(themeRiverLayout);
  51422. registerVisual(themeRiverVisual);
  51423. registerProcessor(dataFilter('themeRiver'));
  51424. SeriesModel.extend({
  51425. type: 'series.sunburst',
  51426. /**
  51427. * @type {module:echarts/data/Tree~Node}
  51428. */
  51429. _viewRoot: null,
  51430. getInitialData: function (option, ecModel) {
  51431. // Create a virtual root.
  51432. var root = { name: option.name, children: option.data };
  51433. completeTreeValue$1(root);
  51434. var levels = option.levels || [];
  51435. // levels = option.levels = setDefault(levels, ecModel);
  51436. var treeOption = {};
  51437. treeOption.levels = levels;
  51438. // Make sure always a new tree is created when setOption,
  51439. // in TreemapView, we check whether oldTree === newTree
  51440. // to choose mappings approach among old shapes and new shapes.
  51441. return Tree.createTree(root, this, treeOption).data;
  51442. },
  51443. optionUpdated: function () {
  51444. this.resetViewRoot();
  51445. },
  51446. /*
  51447. * @override
  51448. */
  51449. getDataParams: function (dataIndex) {
  51450. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  51451. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  51452. params.treePathInfo = wrapTreePathInfo(node, this);
  51453. return params;
  51454. },
  51455. defaultOption: {
  51456. zlevel: 0,
  51457. z: 2,
  51458. // 默认全局居中
  51459. center: ['50%', '50%'],
  51460. radius: [0, '75%'],
  51461. // 默认顺时针
  51462. clockwise: true,
  51463. startAngle: 90,
  51464. // 最小角度改为0
  51465. minAngle: 0,
  51466. percentPrecision: 2,
  51467. // If still show when all data zero.
  51468. stillShowZeroSum: true,
  51469. // Policy of highlighting pieces when hover on one
  51470. // Valid values: 'none' (for not downplay others), 'descendant',
  51471. // 'ancestor', 'self'
  51472. highlightPolicy: 'descendant',
  51473. // 'rootToNode', 'link', or false
  51474. nodeClick: 'rootToNode',
  51475. renderLabelForZeroData: false,
  51476. label: {
  51477. // could be: 'radial', 'tangential', or 'none'
  51478. rotate: 'radial',
  51479. show: true,
  51480. opacity: 1,
  51481. // 'left' is for inner side of inside, and 'right' is for outter
  51482. // side for inside
  51483. align: 'center',
  51484. position: 'inside',
  51485. distance: 5,
  51486. silent: true,
  51487. emphasis: {}
  51488. },
  51489. itemStyle: {
  51490. borderWidth: 1,
  51491. borderColor: 'white',
  51492. opacity: 1,
  51493. emphasis: {},
  51494. highlight: {
  51495. opacity: 1
  51496. },
  51497. downplay: {
  51498. opacity: 0.9
  51499. }
  51500. },
  51501. // Animation type canbe expansion, scale
  51502. animationType: 'expansion',
  51503. animationDuration: 1000,
  51504. animationDurationUpdate: 500,
  51505. animationEasing: 'cubicOut',
  51506. data: [],
  51507. levels: [],
  51508. /**
  51509. * Sort order.
  51510. *
  51511. * Valid values: 'desc', 'asc', null, or callback function.
  51512. * 'desc' and 'asc' for descend and ascendant order;
  51513. * null for not sorting;
  51514. * example of callback function:
  51515. * function(nodeA, nodeB) {
  51516. * return nodeA.getValue() - nodeB.getValue();
  51517. * }
  51518. */
  51519. sort: 'desc'
  51520. },
  51521. getViewRoot: function () {
  51522. return this._viewRoot;
  51523. },
  51524. /**
  51525. * @param {module:echarts/data/Tree~Node} [viewRoot]
  51526. */
  51527. resetViewRoot: function (viewRoot) {
  51528. viewRoot
  51529. ? (this._viewRoot = viewRoot)
  51530. : (viewRoot = this._viewRoot);
  51531. var root = this.getRawData().tree.root;
  51532. if (!viewRoot
  51533. || (viewRoot !== root && !root.contains(viewRoot))
  51534. ) {
  51535. this._viewRoot = root;
  51536. }
  51537. }
  51538. });
  51539. /**
  51540. * @param {Object} dataNode
  51541. */
  51542. function completeTreeValue$1(dataNode) {
  51543. // Postorder travel tree.
  51544. // If value of none-leaf node is not set,
  51545. // calculate it by suming up the value of all children.
  51546. var sum = 0;
  51547. each$1(dataNode.children, function (child) {
  51548. completeTreeValue$1(child);
  51549. var childValue = child.value;
  51550. isArray(childValue) && (childValue = childValue[0]);
  51551. sum += childValue;
  51552. });
  51553. var thisValue = dataNode.value;
  51554. if (isArray(thisValue)) {
  51555. thisValue = thisValue[0];
  51556. }
  51557. if (thisValue == null || isNaN(thisValue)) {
  51558. thisValue = sum;
  51559. }
  51560. // Value should not less than 0.
  51561. if (thisValue < 0) {
  51562. thisValue = 0;
  51563. }
  51564. isArray(dataNode.value)
  51565. ? (dataNode.value[0] = thisValue)
  51566. : (dataNode.value = thisValue);
  51567. }
  51568. var NodeHighlightPolicy = {
  51569. NONE: 'none', // not downplay others
  51570. DESCENDANT: 'descendant',
  51571. ANCESTOR: 'ancestor',
  51572. SELF: 'self'
  51573. };
  51574. var DEFAULT_SECTOR_Z = 2;
  51575. var DEFAULT_TEXT_Z = 4;
  51576. /**
  51577. * Sunburstce of Sunburst including Sector, Label, LabelLine
  51578. * @constructor
  51579. * @extends {module:zrender/graphic/Group}
  51580. */
  51581. function SunburstPiece(node, seriesModel, ecModel) {
  51582. Group.call(this);
  51583. var sector = new Sector({
  51584. z2: DEFAULT_SECTOR_Z
  51585. });
  51586. var text = new Text({
  51587. z2: DEFAULT_TEXT_Z,
  51588. silent: node.getModel('label').get('silent')
  51589. });
  51590. this.add(sector);
  51591. this.add(text);
  51592. this.updateData(true, node, 'normal', seriesModel, ecModel);
  51593. // Hover to change label and labelLine
  51594. function onEmphasis() {
  51595. text.ignore = text.hoverIgnore;
  51596. }
  51597. function onNormal() {
  51598. text.ignore = text.normalIgnore;
  51599. }
  51600. this.on('emphasis', onEmphasis)
  51601. .on('normal', onNormal)
  51602. .on('mouseover', onEmphasis)
  51603. .on('mouseout', onNormal);
  51604. }
  51605. var SunburstPieceProto = SunburstPiece.prototype;
  51606. SunburstPieceProto.updateData = function (
  51607. firstCreate,
  51608. node,
  51609. state,
  51610. seriesModel,
  51611. ecModel
  51612. ) {
  51613. this.node = node;
  51614. node.piece = this;
  51615. seriesModel = seriesModel || this._seriesModel;
  51616. ecModel = ecModel || this._ecModel;
  51617. var sector = this.childAt(0);
  51618. sector.dataIndex = node.dataIndex;
  51619. var itemModel = node.getModel();
  51620. var layout = node.getLayout();
  51621. var sectorShape = extend({}, layout);
  51622. sectorShape.label = null;
  51623. var visualColor = getNodeColor(node, seriesModel, ecModel);
  51624. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  51625. var style;
  51626. if (state === 'normal') {
  51627. style = normalStyle;
  51628. }
  51629. else {
  51630. var stateStyle = itemModel.getModel(state + '.itemStyle')
  51631. .getItemStyle();
  51632. style = merge(stateStyle, normalStyle);
  51633. }
  51634. style = defaults(
  51635. {
  51636. lineJoin: 'bevel',
  51637. fill: style.fill || visualColor
  51638. },
  51639. style
  51640. );
  51641. if (firstCreate) {
  51642. sector.setShape(sectorShape);
  51643. sector.shape.r = layout.r0;
  51644. updateProps(
  51645. sector,
  51646. {
  51647. shape: {
  51648. r: layout.r
  51649. }
  51650. },
  51651. seriesModel,
  51652. node.dataIndex
  51653. );
  51654. sector.useStyle(style);
  51655. }
  51656. else if (typeof style.fill === 'object' && style.fill.type
  51657. || typeof sector.style.fill === 'object' && sector.style.fill.type
  51658. ) {
  51659. // Disable animation for gradient since no interpolation method
  51660. // is supported for gradient
  51661. updateProps(sector, {
  51662. shape: sectorShape
  51663. }, seriesModel);
  51664. sector.useStyle(style);
  51665. }
  51666. else {
  51667. updateProps(sector, {
  51668. shape: sectorShape,
  51669. style: style
  51670. }, seriesModel);
  51671. }
  51672. this._updateLabel(seriesModel, visualColor, state);
  51673. var cursorStyle = itemModel.getShallow('cursor');
  51674. cursorStyle && sector.attr('cursor', cursorStyle);
  51675. if (firstCreate) {
  51676. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  51677. this._initEvents(sector, node, seriesModel, highlightPolicy);
  51678. }
  51679. this._seriesModel = seriesModel || this._seriesModel;
  51680. this._ecModel = ecModel || this._ecModel;
  51681. };
  51682. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  51683. var that = this;
  51684. this.node.hostTree.root.eachNode(function (n) {
  51685. if (n.piece) {
  51686. if (that.node === n) {
  51687. n.piece.updateData(false, n, 'emphasis');
  51688. }
  51689. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  51690. n.piece.childAt(0).trigger('highlight');
  51691. }
  51692. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  51693. n.piece.childAt(0).trigger('downplay');
  51694. }
  51695. }
  51696. });
  51697. };
  51698. SunburstPieceProto.onNormal = function () {
  51699. this.node.hostTree.root.eachNode(function (n) {
  51700. if (n.piece) {
  51701. n.piece.updateData(false, n, 'normal');
  51702. }
  51703. });
  51704. };
  51705. SunburstPieceProto.onHighlight = function () {
  51706. this.updateData(false, this.node, 'highlight');
  51707. };
  51708. SunburstPieceProto.onDownplay = function () {
  51709. this.updateData(false, this.node, 'downplay');
  51710. };
  51711. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  51712. var itemModel = this.node.getModel();
  51713. var normalModel = itemModel.getModel('label');
  51714. var labelModel = state === 'normal' || state === 'emphasis'
  51715. ? normalModel
  51716. : itemModel.getModel(state + '.label');
  51717. var labelHoverModel = itemModel.getModel('emphasis.label');
  51718. var text = retrieve(
  51719. seriesModel.getFormattedLabel(
  51720. this.node.dataIndex, 'normal', null, null, 'label'
  51721. ),
  51722. this.node.name
  51723. );
  51724. if (getLabelAttr('show') === false) {
  51725. text = '';
  51726. }
  51727. var layout = this.node.getLayout();
  51728. var labelMinAngle = labelModel.get('minAngle');
  51729. if (labelMinAngle == null) {
  51730. labelMinAngle = normalModel.get('minAngle');
  51731. }
  51732. labelMinAngle = labelMinAngle / 180 * Math.PI;
  51733. var angle = layout.endAngle - layout.startAngle;
  51734. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  51735. // Not displaying text when angle is too small
  51736. text = '';
  51737. }
  51738. var label = this.childAt(1);
  51739. setLabelStyle(
  51740. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  51741. {
  51742. defaultText: labelModel.getShallow('show') ? text : null,
  51743. autoColor: visualColor,
  51744. useInsideStyle: true
  51745. }
  51746. );
  51747. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  51748. var dx = Math.cos(midAngle);
  51749. var dy = Math.sin(midAngle);
  51750. var r;
  51751. var labelPosition = getLabelAttr('position');
  51752. var labelPadding = getLabelAttr('distance') || 0;
  51753. var textAlign = getLabelAttr('align');
  51754. if (labelPosition === 'outside') {
  51755. r = layout.r + labelPadding;
  51756. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  51757. }
  51758. else {
  51759. if (!textAlign || textAlign === 'center') {
  51760. r = (layout.r + layout.r0) / 2;
  51761. textAlign = 'center';
  51762. }
  51763. else if (textAlign === 'left') {
  51764. r = layout.r0 + labelPadding;
  51765. if (midAngle > Math.PI / 2) {
  51766. textAlign = 'right';
  51767. }
  51768. }
  51769. else if (textAlign === 'right') {
  51770. r = layout.r - labelPadding;
  51771. if (midAngle > Math.PI / 2) {
  51772. textAlign = 'left';
  51773. }
  51774. }
  51775. }
  51776. label.attr('style', {
  51777. text: text,
  51778. textAlign: textAlign,
  51779. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  51780. opacity: getLabelAttr('opacity')
  51781. });
  51782. var textX = r * dx + layout.cx;
  51783. var textY = r * dy + layout.cy;
  51784. label.attr('position', [textX, textY]);
  51785. var rotateType = getLabelAttr('rotate');
  51786. var rotate = 0;
  51787. if (rotateType === 'radial') {
  51788. rotate = -midAngle;
  51789. if (rotate < -Math.PI / 2) {
  51790. rotate += Math.PI;
  51791. }
  51792. }
  51793. else if (rotateType === 'tangential') {
  51794. rotate = Math.PI / 2 - midAngle;
  51795. if (rotate > Math.PI / 2) {
  51796. rotate -= Math.PI;
  51797. }
  51798. else if (rotate < -Math.PI / 2) {
  51799. rotate += Math.PI;
  51800. }
  51801. } else if (typeof rotateType === 'number') {
  51802. rotate = rotateType * Math.PI / 180;
  51803. }
  51804. label.attr('rotation', rotate);
  51805. function getLabelAttr(name) {
  51806. var stateAttr = labelModel.get(name);
  51807. if (stateAttr == null) {
  51808. return normalModel.get(name);
  51809. }
  51810. else {
  51811. return stateAttr;
  51812. }
  51813. }
  51814. };
  51815. SunburstPieceProto._initEvents = function (
  51816. sector,
  51817. node,
  51818. seriesModel,
  51819. highlightPolicy
  51820. ) {
  51821. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  51822. var that = this;
  51823. var onEmphasis = function () {
  51824. that.onEmphasis(highlightPolicy);
  51825. };
  51826. var onNormal = function () {
  51827. that.onNormal();
  51828. };
  51829. var onDownplay = function () {
  51830. that.onDownplay();
  51831. };
  51832. var onHighlight = function () {
  51833. that.onHighlight();
  51834. };
  51835. if (seriesModel.isAnimationEnabled()) {
  51836. sector
  51837. .on('mouseover', onEmphasis)
  51838. .on('mouseout', onNormal)
  51839. .on('emphasis', onEmphasis)
  51840. .on('normal', onNormal)
  51841. .on('downplay', onDownplay)
  51842. .on('highlight', onHighlight);
  51843. }
  51844. };
  51845. inherits(SunburstPiece, Group);
  51846. /**
  51847. * Get node color
  51848. *
  51849. * @param {TreeNode} node the node to get color
  51850. * @param {module:echarts/model/Series} seriesModel series
  51851. * @param {module:echarts/model/Global} ecModel echarts defaults
  51852. */
  51853. function getNodeColor(node, seriesModel, ecModel) {
  51854. // Color from visualMap
  51855. var visualColor = node.getVisual('color');
  51856. var visualMetaList = node.getVisual('visualMeta');
  51857. if (!visualMetaList || visualMetaList.length === 0) {
  51858. // Use first-generation color if has no visualMap
  51859. visualColor = null;
  51860. }
  51861. // Self color or level color
  51862. var color = node.getModel('itemStyle').get('color');
  51863. if (color) {
  51864. return color;
  51865. }
  51866. else if (visualColor) {
  51867. // Color mapping
  51868. return visualColor;
  51869. }
  51870. else if (node.depth === 0) {
  51871. // Virtual root node
  51872. return ecModel.option.color[0];
  51873. }
  51874. else {
  51875. // First-generation color
  51876. var length = ecModel.option.color.length;
  51877. color = ecModel.option.color[getRootId(node) % length];
  51878. }
  51879. return color;
  51880. }
  51881. /**
  51882. * Get index of root in sorted order
  51883. *
  51884. * @param {TreeNode} node current node
  51885. * @return {number} index in root
  51886. */
  51887. function getRootId(node) {
  51888. var ancestor = node;
  51889. while (ancestor.depth > 1) {
  51890. ancestor = ancestor.parentNode;
  51891. }
  51892. var virtualRoot = node.getAncestors()[0];
  51893. return indexOf(virtualRoot.children, ancestor);
  51894. }
  51895. function isNodeHighlighted(node, activeNode, policy) {
  51896. if (policy === NodeHighlightPolicy.NONE) {
  51897. return false;
  51898. }
  51899. else if (policy === NodeHighlightPolicy.SELF) {
  51900. return node === activeNode;
  51901. }
  51902. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  51903. return node === activeNode || node.isAncestorOf(activeNode);
  51904. }
  51905. else {
  51906. return node === activeNode || node.isDescendantOf(activeNode);
  51907. }
  51908. }
  51909. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  51910. var SunburstView = Chart.extend({
  51911. type: 'sunburst',
  51912. init: function () {
  51913. },
  51914. render: function (seriesModel, ecModel, api, payload) {
  51915. var that = this;
  51916. this.seriesModel = seriesModel;
  51917. this.api = api;
  51918. this.ecModel = ecModel;
  51919. var data = seriesModel.getData();
  51920. var virtualRoot = data.tree.root;
  51921. var newRoot = seriesModel.getViewRoot();
  51922. var group = this.group;
  51923. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  51924. var newChildren = [];
  51925. newRoot.eachNode(function (node) {
  51926. newChildren.push(node);
  51927. });
  51928. var oldChildren = this._oldChildren || [];
  51929. dualTravel(newChildren, oldChildren);
  51930. renderRollUp(virtualRoot, newRoot);
  51931. if (payload && payload.highlight && payload.highlight.piece) {
  51932. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  51933. payload.highlight.piece.onEmphasis(highlightPolicy);
  51934. }
  51935. else if (payload && payload.unhighlight) {
  51936. var piece = virtualRoot.piece;
  51937. if (!piece && virtualRoot.children.length) {
  51938. piece = virtualRoot.children[0].piece;
  51939. }
  51940. if (piece) {
  51941. piece.onNormal();
  51942. }
  51943. }
  51944. this._initEvents();
  51945. this._oldChildren = newChildren;
  51946. function dualTravel(newChildren, oldChildren) {
  51947. if (newChildren.length === 0 && oldChildren.length === 0) {
  51948. return;
  51949. }
  51950. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  51951. .add(processNode)
  51952. .update(processNode)
  51953. .remove(curry(processNode, null))
  51954. .execute();
  51955. function getKey(node) {
  51956. return node.getId();
  51957. }
  51958. function processNode(newId, oldId) {
  51959. var newNode = newId == null ? null : newChildren[newId];
  51960. var oldNode = oldId == null ? null : oldChildren[oldId];
  51961. doRenderNode(newNode, oldNode);
  51962. }
  51963. }
  51964. function doRenderNode(newNode, oldNode) {
  51965. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  51966. // Not render data with value 0
  51967. newNode = null;
  51968. }
  51969. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  51970. if (oldNode && oldNode.piece) {
  51971. if (newNode) {
  51972. // Update
  51973. oldNode.piece.updateData(
  51974. false, newNode, 'normal', seriesModel, ecModel);
  51975. // For tooltip
  51976. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  51977. }
  51978. else {
  51979. // Remove
  51980. removeNode(oldNode);
  51981. }
  51982. }
  51983. else if (newNode) {
  51984. // Add
  51985. var piece = new SunburstPiece(
  51986. newNode,
  51987. seriesModel,
  51988. ecModel
  51989. );
  51990. group.add(piece);
  51991. // For tooltip
  51992. data.setItemGraphicEl(newNode.dataIndex, piece);
  51993. }
  51994. }
  51995. }
  51996. function removeNode(node) {
  51997. if (!node) {
  51998. return;
  51999. }
  52000. if (node.piece) {
  52001. group.remove(node.piece);
  52002. node.piece = null;
  52003. }
  52004. }
  52005. function renderRollUp(virtualRoot, viewRoot) {
  52006. if (viewRoot.depth > 0) {
  52007. // Render
  52008. if (virtualRoot.piece) {
  52009. // Update
  52010. virtualRoot.piece.updateData(
  52011. false, virtualRoot, 'normal', seriesModel, ecModel);
  52012. }
  52013. else {
  52014. // Add
  52015. virtualRoot.piece = new SunburstPiece(
  52016. virtualRoot,
  52017. seriesModel,
  52018. ecModel
  52019. );
  52020. group.add(virtualRoot.piece);
  52021. }
  52022. if (viewRoot.piece._onclickEvent) {
  52023. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  52024. }
  52025. var event = function (e) {
  52026. that._rootToNode(viewRoot.parentNode);
  52027. };
  52028. viewRoot.piece._onclickEvent = event;
  52029. virtualRoot.piece.on('click', event);
  52030. }
  52031. else if (virtualRoot.piece) {
  52032. // Remove
  52033. group.remove(virtualRoot.piece);
  52034. virtualRoot.piece = null;
  52035. }
  52036. }
  52037. },
  52038. dispose: function () {
  52039. },
  52040. /**
  52041. * @private
  52042. */
  52043. _initEvents: function () {
  52044. var that = this;
  52045. var event = function (e) {
  52046. var targetFound = false;
  52047. var viewRoot = that.seriesModel.getViewRoot();
  52048. viewRoot.eachNode(function (node) {
  52049. if (!targetFound
  52050. && node.piece && node.piece.childAt(0) === e.target
  52051. ) {
  52052. var nodeClick = node.getModel().get('nodeClick');
  52053. if (nodeClick === 'rootToNode') {
  52054. that._rootToNode(node);
  52055. }
  52056. else if (nodeClick === 'link') {
  52057. var itemModel = node.getModel();
  52058. var link = itemModel.get('link');
  52059. if (link) {
  52060. var linkTarget = itemModel.get('target', true)
  52061. || '_blank';
  52062. window.open(link, linkTarget);
  52063. }
  52064. }
  52065. targetFound = true;
  52066. }
  52067. });
  52068. };
  52069. if (this.group._onclickEvent) {
  52070. this.group.off('click', this.group._onclickEvent);
  52071. }
  52072. this.group.on('click', event);
  52073. this.group._onclickEvent = event;
  52074. },
  52075. /**
  52076. * @private
  52077. */
  52078. _rootToNode: function (node) {
  52079. if (node !== this.seriesModel.getViewRoot()) {
  52080. this.api.dispatchAction({
  52081. type: ROOT_TO_NODE_ACTION,
  52082. from: this.uid,
  52083. seriesId: this.seriesModel.id,
  52084. targetNode: node
  52085. });
  52086. }
  52087. },
  52088. /**
  52089. * @implement
  52090. */
  52091. containPoint: function (point, seriesModel) {
  52092. var treeRoot = seriesModel.getData();
  52093. var itemLayout = treeRoot.getItemLayout(0);
  52094. if (itemLayout) {
  52095. var dx = point[0] - itemLayout.cx;
  52096. var dy = point[1] - itemLayout.cy;
  52097. var radius = Math.sqrt(dx * dx + dy * dy);
  52098. return radius <= itemLayout.r && radius >= itemLayout.r0;
  52099. }
  52100. }
  52101. });
  52102. /**
  52103. * @file Sunburst action
  52104. */
  52105. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  52106. registerAction(
  52107. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  52108. function (payload, ecModel) {
  52109. ecModel.eachComponent(
  52110. {mainType: 'series', subType: 'sunburst', query: payload},
  52111. handleRootToNode
  52112. );
  52113. function handleRootToNode(model, index) {
  52114. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  52115. if (targetInfo) {
  52116. var originViewRoot = model.getViewRoot();
  52117. if (originViewRoot) {
  52118. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  52119. ? 'rollUp' : 'drillDown';
  52120. }
  52121. model.resetViewRoot(targetInfo.node);
  52122. }
  52123. }
  52124. }
  52125. );
  52126. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  52127. registerAction(
  52128. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  52129. function (payload, ecModel) {
  52130. ecModel.eachComponent(
  52131. {mainType: 'series', subType: 'sunburst', query: payload},
  52132. handleHighlight
  52133. );
  52134. function handleHighlight(model, index) {
  52135. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  52136. if (targetInfo) {
  52137. payload.highlight = targetInfo.node;
  52138. }
  52139. }
  52140. }
  52141. );
  52142. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  52143. registerAction(
  52144. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  52145. function (payload, ecModel) {
  52146. ecModel.eachComponent(
  52147. {mainType: 'series', subType: 'sunburst', query: payload},
  52148. handleUnhighlight
  52149. );
  52150. function handleUnhighlight(model, index) {
  52151. payload.unhighlight = true;
  52152. }
  52153. }
  52154. );
  52155. var RADIAN$1 = Math.PI / 180;
  52156. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  52157. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  52158. var center = seriesModel.get('center');
  52159. var radius = seriesModel.get('radius');
  52160. if (!isArray(radius)) {
  52161. radius = [0, radius];
  52162. }
  52163. if (!isArray(center)) {
  52164. center = [center, center];
  52165. }
  52166. var width = api.getWidth();
  52167. var height = api.getHeight();
  52168. var size = Math.min(width, height);
  52169. var cx = parsePercent$1(center[0], width);
  52170. var cy = parsePercent$1(center[1], height);
  52171. var r0 = parsePercent$1(radius[0], size / 2);
  52172. var r = parsePercent$1(radius[1], size / 2);
  52173. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  52174. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  52175. var virtualRoot = seriesModel.getData().tree.root;
  52176. var treeRoot = seriesModel.getViewRoot();
  52177. var rootDepth = treeRoot.depth;
  52178. var sort = seriesModel.get('sort');
  52179. if (sort != null) {
  52180. initChildren$1(treeRoot, sort);
  52181. }
  52182. var validDataCount = 0;
  52183. each$1(treeRoot.children, function (child) {
  52184. !isNaN(child.getValue()) && validDataCount++;
  52185. });
  52186. var sum = treeRoot.getValue();
  52187. // Sum may be 0
  52188. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  52189. var renderRollupNode = treeRoot.depth > 0;
  52190. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  52191. var rPerLevel = (r - r0) / (levels || 1);
  52192. var clockwise = seriesModel.get('clockwise');
  52193. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  52194. // In the case some sector angle is smaller than minAngle
  52195. var dir = clockwise ? 1 : -1;
  52196. /**
  52197. * Render a tree
  52198. * @return increased angle
  52199. */
  52200. var renderNode = function (node, startAngle) {
  52201. if (!node) {
  52202. return;
  52203. }
  52204. var endAngle = startAngle;
  52205. // Render self
  52206. if (node !== virtualRoot) {
  52207. // Tree node is virtual, so it doesn't need to be drawn
  52208. var value = node.getValue();
  52209. var angle = (sum === 0 && stillShowZeroSum)
  52210. ? unitRadian : (value * unitRadian);
  52211. if (angle < minAngle) {
  52212. angle = minAngle;
  52213. }
  52214. else {
  52215. }
  52216. endAngle = startAngle + dir * angle;
  52217. var depth = node.depth - rootDepth
  52218. - (renderRollupNode ? -1 : 1);
  52219. var rStart = r0 + rPerLevel * depth;
  52220. var rEnd = r0 + rPerLevel * (depth + 1);
  52221. var itemModel = node.getModel();
  52222. if (itemModel.get('r0') != null) {
  52223. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  52224. }
  52225. if (itemModel.get('r') != null) {
  52226. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  52227. }
  52228. node.setLayout({
  52229. angle: angle,
  52230. startAngle: startAngle,
  52231. endAngle: endAngle,
  52232. clockwise: clockwise,
  52233. cx: cx,
  52234. cy: cy,
  52235. r0: rStart,
  52236. r: rEnd
  52237. });
  52238. }
  52239. // Render children
  52240. if (node.children && node.children.length) {
  52241. // currentAngle = startAngle;
  52242. var siblingAngle = 0;
  52243. each$1(node.children, function (node) {
  52244. siblingAngle += renderNode(node, startAngle + siblingAngle);
  52245. });
  52246. }
  52247. return endAngle - startAngle;
  52248. };
  52249. // Virtual root node for roll up
  52250. if (renderRollupNode) {
  52251. var rStart = r0;
  52252. var rEnd = r0 + rPerLevel;
  52253. var angle = Math.PI * 2;
  52254. virtualRoot.setLayout({
  52255. angle: angle,
  52256. startAngle: startAngle,
  52257. endAngle: startAngle + angle,
  52258. clockwise: clockwise,
  52259. cx: cx,
  52260. cy: cy,
  52261. r0: rStart,
  52262. r: rEnd
  52263. });
  52264. }
  52265. renderNode(treeRoot, startAngle);
  52266. });
  52267. };
  52268. /**
  52269. * Init node children by order and update visual
  52270. *
  52271. * @param {TreeNode} node root node
  52272. * @param {boolean} isAsc if is in ascendant order
  52273. */
  52274. function initChildren$1(node, isAsc) {
  52275. var children = node.children || [];
  52276. node.children = sort$2(children, isAsc);
  52277. // Init children recursively
  52278. if (children.length) {
  52279. each$1(node.children, function (child) {
  52280. initChildren$1(child, isAsc);
  52281. });
  52282. }
  52283. }
  52284. /**
  52285. * Sort children nodes
  52286. *
  52287. * @param {TreeNode[]} children children of node to be sorted
  52288. * @param {string | function | null} sort sort method
  52289. * See SunburstSeries.js for details.
  52290. */
  52291. function sort$2(children, sortOrder) {
  52292. if (typeof sortOrder === 'function') {
  52293. return children.sort(sortOrder);
  52294. }
  52295. else {
  52296. var isAsc = sortOrder === 'asc';
  52297. return children.sort(function (a, b) {
  52298. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  52299. return diff === 0
  52300. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  52301. : diff;
  52302. });
  52303. }
  52304. }
  52305. registerVisual(curry(dataColor, 'sunburst'));
  52306. registerLayout(curry(sunburstLayout, 'sunburst'));
  52307. registerProcessor(curry(dataFilter, 'sunburst'));
  52308. function dataToCoordSize(dataSize, dataItem) {
  52309. // dataItem is necessary in log axis.
  52310. dataItem = dataItem || [0, 0];
  52311. return map(['x', 'y'], function (dim, dimIdx) {
  52312. var axis = this.getAxis(dim);
  52313. var val = dataItem[dimIdx];
  52314. var halfSize = dataSize[dimIdx] / 2;
  52315. return axis.type === 'category'
  52316. ? axis.getBandWidth()
  52317. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  52318. }, this);
  52319. }
  52320. var prepareCartesian2d = function (coordSys) {
  52321. var rect = coordSys.grid.getRect();
  52322. return {
  52323. coordSys: {
  52324. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  52325. type: 'cartesian2d',
  52326. x: rect.x,
  52327. y: rect.y,
  52328. width: rect.width,
  52329. height: rect.height
  52330. },
  52331. api: {
  52332. coord: function (data) {
  52333. // do not provide "out" param
  52334. return coordSys.dataToPoint(data);
  52335. },
  52336. size: bind(dataToCoordSize, coordSys)
  52337. }
  52338. };
  52339. };
  52340. function dataToCoordSize$1(dataSize, dataItem) {
  52341. dataItem = dataItem || [0, 0];
  52342. return map([0, 1], function (dimIdx) {
  52343. var val = dataItem[dimIdx];
  52344. var halfSize = dataSize[dimIdx] / 2;
  52345. var p1 = [];
  52346. var p2 = [];
  52347. p1[dimIdx] = val - halfSize;
  52348. p2[dimIdx] = val + halfSize;
  52349. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  52350. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  52351. }, this);
  52352. }
  52353. var prepareGeo = function (coordSys) {
  52354. var rect = coordSys.getBoundingRect();
  52355. return {
  52356. coordSys: {
  52357. type: 'geo',
  52358. x: rect.x,
  52359. y: rect.y,
  52360. width: rect.width,
  52361. height: rect.height
  52362. },
  52363. api: {
  52364. coord: function (data) {
  52365. // do not provide "out" and noRoam param,
  52366. // Compatible with this usage:
  52367. // echarts.util.map(item.points, api.coord)
  52368. return coordSys.dataToPoint(data);
  52369. },
  52370. size: bind(dataToCoordSize$1, coordSys)
  52371. }
  52372. };
  52373. };
  52374. function dataToCoordSize$2(dataSize, dataItem) {
  52375. // dataItem is necessary in log axis.
  52376. var axis = this.getAxis();
  52377. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  52378. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  52379. return axis.type === 'category'
  52380. ? axis.getBandWidth()
  52381. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  52382. }
  52383. var prepareSingleAxis = function (coordSys) {
  52384. var rect = coordSys.getRect();
  52385. return {
  52386. coordSys: {
  52387. type: 'singleAxis',
  52388. x: rect.x,
  52389. y: rect.y,
  52390. width: rect.width,
  52391. height: rect.height
  52392. },
  52393. api: {
  52394. coord: function (val) {
  52395. // do not provide "out" param
  52396. return coordSys.dataToPoint(val);
  52397. },
  52398. size: bind(dataToCoordSize$2, coordSys)
  52399. }
  52400. };
  52401. };
  52402. function dataToCoordSize$3(dataSize, dataItem) {
  52403. // dataItem is necessary in log axis.
  52404. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  52405. var axis = this['get' + dim + 'Axis']();
  52406. var val = dataItem[dimIdx];
  52407. var halfSize = dataSize[dimIdx] / 2;
  52408. var method = 'dataTo' + dim;
  52409. var result = axis.type === 'category'
  52410. ? axis.getBandWidth()
  52411. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  52412. if (dim === 'Angle') {
  52413. result = result * Math.PI / 180;
  52414. }
  52415. return result;
  52416. }, this);
  52417. }
  52418. var preparePolar = function (coordSys) {
  52419. var radiusAxis = coordSys.getRadiusAxis();
  52420. var angleAxis = coordSys.getAngleAxis();
  52421. var radius = radiusAxis.getExtent();
  52422. radius[0] > radius[1] && radius.reverse();
  52423. return {
  52424. coordSys: {
  52425. type: 'polar',
  52426. cx: coordSys.cx,
  52427. cy: coordSys.cy,
  52428. r: radius[1],
  52429. r0: radius[0]
  52430. },
  52431. api: {
  52432. coord: bind(function (data) {
  52433. var radius = radiusAxis.dataToRadius(data[0]);
  52434. var angle = angleAxis.dataToAngle(data[1]);
  52435. var coord = coordSys.coordToPoint([radius, angle]);
  52436. coord.push(radius, angle * Math.PI / 180);
  52437. return coord;
  52438. }),
  52439. size: bind(dataToCoordSize$3, coordSys)
  52440. }
  52441. };
  52442. };
  52443. var prepareCalendar = function (coordSys) {
  52444. var rect = coordSys.getRect();
  52445. var rangeInfo = coordSys.getRangeInfo();
  52446. return {
  52447. coordSys: {
  52448. type: 'calendar',
  52449. x: rect.x,
  52450. y: rect.y,
  52451. width: rect.width,
  52452. height: rect.height,
  52453. cellWidth: coordSys.getCellWidth(),
  52454. cellHeight: coordSys.getCellHeight(),
  52455. rangeInfo: {
  52456. start: rangeInfo.start,
  52457. end: rangeInfo.end,
  52458. weeks: rangeInfo.weeks,
  52459. dayCount: rangeInfo.allDay
  52460. }
  52461. },
  52462. api: {
  52463. coord: function (data, clamp) {
  52464. return coordSys.dataToPoint(data, clamp);
  52465. }
  52466. }
  52467. };
  52468. };
  52469. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  52470. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  52471. var LABEL_NORMAL = ['label'];
  52472. var LABEL_EMPHASIS = ['emphasis', 'label'];
  52473. // Use prefix to avoid index to be the same as el.name,
  52474. // which will cause weird udpate animation.
  52475. var GROUP_DIFF_PREFIX = 'e\0\0';
  52476. /**
  52477. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  52478. * of each coordinate systems are not required by each coordinate systems directly, but
  52479. * required by the module `custom`.
  52480. *
  52481. * prepareInfoForCustomSeries {Function}: optional
  52482. * @return {Object} {coordSys: {...}, api: {
  52483. * coord: function (data, clamp) {}, // return point in global.
  52484. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  52485. * }}
  52486. */
  52487. var prepareCustoms = {
  52488. cartesian2d: prepareCartesian2d,
  52489. geo: prepareGeo,
  52490. singleAxis: prepareSingleAxis,
  52491. polar: preparePolar,
  52492. calendar: prepareCalendar
  52493. };
  52494. // ------
  52495. // Model
  52496. // ------
  52497. extendSeriesModel({
  52498. type: 'series.custom',
  52499. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  52500. defaultOption: {
  52501. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  52502. zlevel: 0,
  52503. z: 2,
  52504. legendHoverLink: true
  52505. // Cartesian coordinate system
  52506. // xAxisIndex: 0,
  52507. // yAxisIndex: 0,
  52508. // Polar coordinate system
  52509. // polarIndex: 0,
  52510. // Geo coordinate system
  52511. // geoIndex: 0,
  52512. // label: {}
  52513. // itemStyle: {}
  52514. },
  52515. getInitialData: function (option, ecModel) {
  52516. return createListFromArray(this.getSource(), this);
  52517. }
  52518. });
  52519. // -----
  52520. // View
  52521. // -----
  52522. extendChartView({
  52523. type: 'custom',
  52524. /**
  52525. * @private
  52526. * @type {module:echarts/data/List}
  52527. */
  52528. _data: null,
  52529. /**
  52530. * @override
  52531. */
  52532. render: function (customSeries, ecModel, api) {
  52533. var oldData = this._data;
  52534. var data = customSeries.getData();
  52535. var group = this.group;
  52536. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  52537. this.group.removeAll();
  52538. data.diff(oldData)
  52539. .add(function (newIdx) {
  52540. createOrUpdate$1(
  52541. null, newIdx, renderItem(newIdx), customSeries, group, data
  52542. );
  52543. })
  52544. .update(function (newIdx, oldIdx) {
  52545. var el = oldData.getItemGraphicEl(oldIdx);
  52546. createOrUpdate$1(
  52547. el, newIdx, renderItem(newIdx), customSeries, group, data
  52548. );
  52549. })
  52550. .remove(function (oldIdx) {
  52551. var el = oldData.getItemGraphicEl(oldIdx);
  52552. el && group.remove(el);
  52553. })
  52554. .execute();
  52555. this._data = data;
  52556. },
  52557. incrementalPrepareRender: function (customSeries, ecModel, api) {
  52558. this.group.removeAll();
  52559. this._data = null;
  52560. },
  52561. incrementalRender: function (params, customSeries, ecModel, api) {
  52562. var data = customSeries.getData();
  52563. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  52564. function setIncrementalAndHoverLayer(el) {
  52565. if (!el.isGroup) {
  52566. el.incremental = true;
  52567. el.useHoverLayer = true;
  52568. }
  52569. }
  52570. for (var idx = params.start; idx < params.end; idx++) {
  52571. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  52572. el.traverse(setIncrementalAndHoverLayer);
  52573. }
  52574. },
  52575. /**
  52576. * @override
  52577. */
  52578. dispose: noop
  52579. });
  52580. function createEl(elOption) {
  52581. var graphicType = elOption.type;
  52582. var el;
  52583. if (graphicType === 'path') {
  52584. var shape = elOption.shape;
  52585. el = makePath(
  52586. shape.pathData,
  52587. null,
  52588. {
  52589. x: shape.x || 0,
  52590. y: shape.y || 0,
  52591. width: shape.width || 0,
  52592. height: shape.height || 0
  52593. },
  52594. 'center'
  52595. );
  52596. el.__customPathData = elOption.pathData;
  52597. }
  52598. else if (graphicType === 'image') {
  52599. el = new ZImage({
  52600. });
  52601. el.__customImagePath = elOption.style.image;
  52602. }
  52603. else if (graphicType === 'text') {
  52604. el = new Text({
  52605. });
  52606. el.__customText = elOption.style.text;
  52607. }
  52608. else {
  52609. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  52610. if (__DEV__) {
  52611. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  52612. }
  52613. el = new Clz();
  52614. }
  52615. el.__customGraphicType = graphicType;
  52616. el.name = elOption.name;
  52617. return el;
  52618. }
  52619. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  52620. var targetProps = {};
  52621. var elOptionStyle = elOption.style || {};
  52622. elOption.shape && (targetProps.shape = clone(elOption.shape));
  52623. elOption.position && (targetProps.position = elOption.position.slice());
  52624. elOption.scale && (targetProps.scale = elOption.scale.slice());
  52625. elOption.origin && (targetProps.origin = elOption.origin.slice());
  52626. elOption.rotation && (targetProps.rotation = elOption.rotation);
  52627. if (el.type === 'image' && elOption.style) {
  52628. var targetStyle = targetProps.style = {};
  52629. each$1(['x', 'y', 'width', 'height'], function (prop) {
  52630. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  52631. });
  52632. }
  52633. if (el.type === 'text' && elOption.style) {
  52634. var targetStyle = targetProps.style = {};
  52635. each$1(['x', 'y'], function (prop) {
  52636. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  52637. });
  52638. // Compatible with previous: both support
  52639. // textFill and fill, textStroke and stroke in 'text' element.
  52640. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  52641. elOptionStyle.textFill = elOptionStyle.fill
  52642. );
  52643. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  52644. elOptionStyle.textStroke = elOptionStyle.stroke
  52645. );
  52646. }
  52647. if (el.type !== 'group') {
  52648. el.useStyle(elOptionStyle);
  52649. // Init animation.
  52650. if (isInit) {
  52651. el.style.opacity = 0;
  52652. var targetOpacity = elOptionStyle.opacity;
  52653. targetOpacity == null && (targetOpacity = 1);
  52654. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  52655. }
  52656. }
  52657. if (isInit) {
  52658. el.attr(targetProps);
  52659. }
  52660. else {
  52661. updateProps(el, targetProps, animatableModel, dataIndex);
  52662. }
  52663. // z2 must not be null/undefined, otherwise sort error may occur.
  52664. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  52665. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  52666. }
  52667. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  52668. if (elOptionStyle[prop] != null && !isInit) {
  52669. targetStyle[prop] = elOptionStyle[prop];
  52670. elOptionStyle[prop] = oldElStyle[prop];
  52671. }
  52672. }
  52673. function makeRenderItem(customSeries, data, ecModel, api) {
  52674. var renderItem = customSeries.get('renderItem');
  52675. var coordSys = customSeries.coordinateSystem;
  52676. var prepareResult = {};
  52677. if (coordSys) {
  52678. if (__DEV__) {
  52679. assert$1(renderItem, 'series.render is required.');
  52680. assert$1(
  52681. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  52682. 'This coordSys does not support custom series.'
  52683. );
  52684. }
  52685. prepareResult = coordSys.prepareCustoms
  52686. ? coordSys.prepareCustoms()
  52687. : prepareCustoms[coordSys.type](coordSys);
  52688. }
  52689. var userAPI = defaults({
  52690. getWidth: api.getWidth,
  52691. getHeight: api.getHeight,
  52692. getZr: api.getZr,
  52693. getDevicePixelRatio: api.getDevicePixelRatio,
  52694. value: value,
  52695. style: style,
  52696. styleEmphasis: styleEmphasis,
  52697. visual: visual,
  52698. barLayout: barLayout,
  52699. currentSeriesIndices: currentSeriesIndices,
  52700. font: font
  52701. }, prepareResult.api || {});
  52702. var userParams = {
  52703. context: {},
  52704. seriesId: customSeries.id,
  52705. seriesName: customSeries.name,
  52706. seriesIndex: customSeries.seriesIndex,
  52707. coordSys: prepareResult.coordSys,
  52708. dataInsideLength: data.count(),
  52709. encode: wrapEncodeDef(customSeries.getData())
  52710. };
  52711. // Do not support call `api` asynchronously without dataIndexInside input.
  52712. var currDataIndexInside;
  52713. var currDirty = true;
  52714. var currItemModel;
  52715. var currLabelNormalModel;
  52716. var currLabelEmphasisModel;
  52717. var currVisualColor;
  52718. return function (dataIndexInside) {
  52719. currDataIndexInside = dataIndexInside;
  52720. currDirty = true;
  52721. return renderItem && renderItem(
  52722. defaults({
  52723. dataIndexInside: dataIndexInside,
  52724. dataIndex: data.getRawIndex(dataIndexInside)
  52725. }, userParams),
  52726. userAPI
  52727. ) || {};
  52728. };
  52729. // Do not update cache until api called.
  52730. function updateCache(dataIndexInside) {
  52731. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52732. if (currDirty) {
  52733. currItemModel = data.getItemModel(dataIndexInside);
  52734. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  52735. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  52736. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  52737. currDirty = false;
  52738. }
  52739. }
  52740. /**
  52741. * @public
  52742. * @param {number|string} dim
  52743. * @param {number} [dataIndexInside=currDataIndexInside]
  52744. * @return {number|string} value
  52745. */
  52746. function value(dim, dataIndexInside) {
  52747. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52748. return data.get(data.getDimension(dim || 0), dataIndexInside);
  52749. }
  52750. /**
  52751. * By default, `visual` is applied to style (to support visualMap).
  52752. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  52753. * it can be implemented as:
  52754. * `api.style({stroke: api.visual('color'), fill: null})`;
  52755. * @public
  52756. * @param {Object} [extra]
  52757. * @param {number} [dataIndexInside=currDataIndexInside]
  52758. */
  52759. function style(extra, dataIndexInside) {
  52760. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52761. updateCache(dataIndexInside);
  52762. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  52763. currVisualColor != null && (itemStyle.fill = currVisualColor);
  52764. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  52765. opacity != null && (itemStyle.opacity = opacity);
  52766. setTextStyle(itemStyle, currLabelNormalModel, null, {
  52767. autoColor: currVisualColor,
  52768. isRectText: true
  52769. });
  52770. itemStyle.text = currLabelNormalModel.getShallow('show')
  52771. ? retrieve2(
  52772. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  52773. getDefaultLabel(data, dataIndexInside)
  52774. )
  52775. : null;
  52776. extra && extend(itemStyle, extra);
  52777. return itemStyle;
  52778. }
  52779. /**
  52780. * @public
  52781. * @param {Object} [extra]
  52782. * @param {number} [dataIndexInside=currDataIndexInside]
  52783. */
  52784. function styleEmphasis(extra, dataIndexInside) {
  52785. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52786. updateCache(dataIndexInside);
  52787. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  52788. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  52789. isRectText: true
  52790. }, true);
  52791. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  52792. ? retrieve3(
  52793. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  52794. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  52795. getDefaultLabel(data, dataIndexInside)
  52796. )
  52797. : null;
  52798. extra && extend(itemStyle, extra);
  52799. return itemStyle;
  52800. }
  52801. /**
  52802. * @public
  52803. * @param {string} visualType
  52804. * @param {number} [dataIndexInside=currDataIndexInside]
  52805. */
  52806. function visual(visualType, dataIndexInside) {
  52807. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52808. return data.getItemVisual(dataIndexInside, visualType);
  52809. }
  52810. /**
  52811. * @public
  52812. * @param {number} opt.count Positive interger.
  52813. * @param {number} [opt.barWidth]
  52814. * @param {number} [opt.barMaxWidth]
  52815. * @param {number} [opt.barGap]
  52816. * @param {number} [opt.barCategoryGap]
  52817. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  52818. */
  52819. function barLayout(opt) {
  52820. if (coordSys.getBaseAxis) {
  52821. var baseAxis = coordSys.getBaseAxis();
  52822. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  52823. }
  52824. }
  52825. /**
  52826. * @public
  52827. * @return {Array.<number>}
  52828. */
  52829. function currentSeriesIndices() {
  52830. return ecModel.getCurrentSeriesIndices();
  52831. }
  52832. /**
  52833. * @public
  52834. * @param {Object} opt
  52835. * @param {string} [opt.fontStyle]
  52836. * @param {number} [opt.fontWeight]
  52837. * @param {number} [opt.fontSize]
  52838. * @param {string} [opt.fontFamily]
  52839. * @return {string} font string
  52840. */
  52841. function font(opt) {
  52842. return getFont(opt, ecModel);
  52843. }
  52844. }
  52845. function wrapEncodeDef(data) {
  52846. var encodeDef = {};
  52847. each$1(data.dimensions, function (dimName, dataDimIndex) {
  52848. var dimInfo = data.getDimensionInfo(dimName);
  52849. if (!dimInfo.isExtraCoord) {
  52850. var coordDim = dimInfo.coordDim;
  52851. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  52852. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  52853. }
  52854. });
  52855. return encodeDef;
  52856. }
  52857. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  52858. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  52859. el && data.setItemGraphicEl(dataIndex, el);
  52860. return el;
  52861. }
  52862. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  52863. var elOptionType = elOption.type;
  52864. if (el
  52865. && elOptionType !== el.__customGraphicType
  52866. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  52867. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  52868. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  52869. ) {
  52870. group.remove(el);
  52871. el = null;
  52872. }
  52873. // `elOption.type` is undefined when `renderItem` returns nothing.
  52874. if (elOptionType == null) {
  52875. return;
  52876. }
  52877. var isInit = !el;
  52878. !el && (el = createEl(elOption));
  52879. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  52880. if (elOptionType === 'group') {
  52881. var oldChildren = el.children() || [];
  52882. var newChildren = elOption.children || [];
  52883. if (elOption.diffChildrenByName) {
  52884. // lower performance.
  52885. diffGroupChildren({
  52886. oldChildren: oldChildren,
  52887. newChildren: newChildren,
  52888. dataIndex: dataIndex,
  52889. animatableModel: animatableModel,
  52890. group: el,
  52891. data: data
  52892. });
  52893. }
  52894. else {
  52895. // better performance.
  52896. var index = 0;
  52897. for (; index < newChildren.length; index++) {
  52898. doCreateOrUpdate(
  52899. el.childAt(index),
  52900. dataIndex,
  52901. newChildren[index],
  52902. animatableModel,
  52903. el,
  52904. data
  52905. );
  52906. }
  52907. for (; index < oldChildren.length; index++) {
  52908. oldChildren[index] && el.remove(oldChildren[index]);
  52909. }
  52910. }
  52911. }
  52912. group.add(el);
  52913. return el;
  52914. }
  52915. function diffGroupChildren(context) {
  52916. (new DataDiffer(
  52917. context.oldChildren,
  52918. context.newChildren,
  52919. getKey,
  52920. getKey,
  52921. context
  52922. ))
  52923. .add(processAddUpdate)
  52924. .update(processAddUpdate)
  52925. .remove(processRemove)
  52926. .execute();
  52927. }
  52928. function getKey(item, idx) {
  52929. var name = item && item.name;
  52930. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  52931. }
  52932. function processAddUpdate(newIndex, oldIndex) {
  52933. var context = this.context;
  52934. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  52935. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  52936. doCreateOrUpdate(
  52937. child,
  52938. context.dataIndex,
  52939. childOption,
  52940. context.animatableModel,
  52941. context.group,
  52942. context.data
  52943. );
  52944. }
  52945. function processRemove(oldIndex) {
  52946. var context = this.context;
  52947. var child = context.oldChildren[oldIndex];
  52948. child && context.group.remove(child);
  52949. }
  52950. // -------------
  52951. // Preprocessor
  52952. // -------------
  52953. registerPreprocessor(function (option) {
  52954. var graphicOption = option.graphic;
  52955. // Convert
  52956. // {graphic: [{left: 10, type: 'circle'}, ...]}
  52957. // or
  52958. // {graphic: {left: 10, type: 'circle'}}
  52959. // to
  52960. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  52961. if (isArray(graphicOption)) {
  52962. if (!graphicOption[0] || !graphicOption[0].elements) {
  52963. option.graphic = [{elements: graphicOption}];
  52964. }
  52965. else {
  52966. // Only one graphic instance can be instantiated. (We dont
  52967. // want that too many views are created in echarts._viewMap)
  52968. option.graphic = [option.graphic[0]];
  52969. }
  52970. }
  52971. else if (graphicOption && !graphicOption.elements) {
  52972. option.graphic = [{elements: [graphicOption]}];
  52973. }
  52974. });
  52975. // ------
  52976. // Model
  52977. // ------
  52978. var GraphicModel = extendComponentModel({
  52979. type: 'graphic',
  52980. defaultOption: {
  52981. // Extra properties for each elements:
  52982. //
  52983. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  52984. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  52985. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  52986. // This mechanism is useful when you want to position a group/element
  52987. // against the right side or the center of this container.
  52988. //
  52989. // width/height: (can only be pixel value, default 0)
  52990. // Only be used to specify contianer(group) size, if needed. And
  52991. // can not be percentage value (like '33%'). See the reason in the
  52992. // layout algorithm below.
  52993. //
  52994. // bounding: (enum: 'all' (default) | 'raw')
  52995. // Specify how to calculate boundingRect when locating.
  52996. // 'all': Get uioned and transformed boundingRect
  52997. // from both itself and its descendants.
  52998. // This mode simplies confining a group of elements in the bounding
  52999. // of their ancester container (e.g., using 'right: 0').
  53000. // 'raw': Only use the boundingRect of itself and before transformed.
  53001. // This mode is similar to css behavior, which is useful when you
  53002. // want an element to be able to overflow its container. (Consider
  53003. // a rotated circle needs to be located in a corner.)
  53004. // Note: elements is always behind its ancestors in this elements array.
  53005. elements: [],
  53006. parentId: null
  53007. },
  53008. /**
  53009. * Save el options for the sake of the performance (only update modified graphics).
  53010. * The order is the same as those in option. (ancesters -> descendants)
  53011. *
  53012. * @private
  53013. * @type {Array.<Object>}
  53014. */
  53015. _elOptionsToUpdate: null,
  53016. /**
  53017. * @override
  53018. */
  53019. mergeOption: function (option) {
  53020. // Prevent default merge to elements
  53021. var elements = this.option.elements;
  53022. this.option.elements = null;
  53023. GraphicModel.superApply(this, 'mergeOption', arguments);
  53024. this.option.elements = elements;
  53025. },
  53026. /**
  53027. * @override
  53028. */
  53029. optionUpdated: function (newOption, isInit) {
  53030. var thisOption = this.option;
  53031. var newList = (isInit ? thisOption : newOption).elements;
  53032. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  53033. var flattenedList = [];
  53034. this._flatten(newList, flattenedList);
  53035. var mappingResult = mappingToExists(existList, flattenedList);
  53036. makeIdAndName(mappingResult);
  53037. // Clear elOptionsToUpdate
  53038. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  53039. each$1(mappingResult, function (resultItem, index) {
  53040. var newElOption = resultItem.option;
  53041. if (__DEV__) {
  53042. assert$1(
  53043. isObject$1(newElOption) || resultItem.exist,
  53044. 'Empty graphic option definition'
  53045. );
  53046. }
  53047. if (!newElOption) {
  53048. return;
  53049. }
  53050. elOptionsToUpdate.push(newElOption);
  53051. setKeyInfoToNewElOption(resultItem, newElOption);
  53052. mergeNewElOptionToExist(existList, index, newElOption);
  53053. setLayoutInfoToExist(existList[index], newElOption);
  53054. }, this);
  53055. // Clean
  53056. for (var i = existList.length - 1; i >= 0; i--) {
  53057. if (existList[i] == null) {
  53058. existList.splice(i, 1);
  53059. }
  53060. else {
  53061. // $action should be volatile, otherwise option gotten from
  53062. // `getOption` will contain unexpected $action.
  53063. delete existList[i].$action;
  53064. }
  53065. }
  53066. },
  53067. /**
  53068. * Convert
  53069. * [{
  53070. * type: 'group',
  53071. * id: 'xx',
  53072. * children: [{type: 'circle'}, {type: 'polygon'}]
  53073. * }]
  53074. * to
  53075. * [
  53076. * {type: 'group', id: 'xx'},
  53077. * {type: 'circle', parentId: 'xx'},
  53078. * {type: 'polygon', parentId: 'xx'}
  53079. * ]
  53080. *
  53081. * @private
  53082. * @param {Array.<Object>} optionList option list
  53083. * @param {Array.<Object>} result result of flatten
  53084. * @param {Object} parentOption parent option
  53085. */
  53086. _flatten: function (optionList, result, parentOption) {
  53087. each$1(optionList, function (option) {
  53088. if (!option) {
  53089. return;
  53090. }
  53091. if (parentOption) {
  53092. option.parentOption = parentOption;
  53093. }
  53094. result.push(option);
  53095. var children = option.children;
  53096. if (option.type === 'group' && children) {
  53097. this._flatten(children, result, option);
  53098. }
  53099. // Deleting for JSON output, and for not affecting group creation.
  53100. delete option.children;
  53101. }, this);
  53102. },
  53103. // FIXME
  53104. // Pass to view using payload? setOption has a payload?
  53105. useElOptionsToUpdate: function () {
  53106. var els = this._elOptionsToUpdate;
  53107. // Clear to avoid render duplicately when zooming.
  53108. this._elOptionsToUpdate = null;
  53109. return els;
  53110. }
  53111. });
  53112. // -----
  53113. // View
  53114. // -----
  53115. extendComponentView({
  53116. type: 'graphic',
  53117. /**
  53118. * @override
  53119. */
  53120. init: function (ecModel, api) {
  53121. /**
  53122. * @private
  53123. * @type {module:zrender/core/util.HashMap}
  53124. */
  53125. this._elMap = createHashMap();
  53126. /**
  53127. * @private
  53128. * @type {module:echarts/graphic/GraphicModel}
  53129. */
  53130. this._lastGraphicModel;
  53131. },
  53132. /**
  53133. * @override
  53134. */
  53135. render: function (graphicModel, ecModel, api) {
  53136. // Having leveraged between use cases and algorithm complexity, a very
  53137. // simple layout mechanism is used:
  53138. // The size(width/height) can be determined by itself or its parent (not
  53139. // implemented yet), but can not by its children. (Top-down travel)
  53140. // The location(x/y) can be determined by the bounding rect of itself
  53141. // (can including its descendants or not) and the size of its parent.
  53142. // (Bottom-up travel)
  53143. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  53144. // view will be reused.
  53145. if (graphicModel !== this._lastGraphicModel) {
  53146. this._clear();
  53147. }
  53148. this._lastGraphicModel = graphicModel;
  53149. this._updateElements(graphicModel, api);
  53150. this._relocate(graphicModel, api);
  53151. },
  53152. /**
  53153. * Update graphic elements.
  53154. *
  53155. * @private
  53156. * @param {Object} graphicModel graphic model
  53157. * @param {module:echarts/ExtensionAPI} api extension API
  53158. */
  53159. _updateElements: function (graphicModel, api) {
  53160. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  53161. if (!elOptionsToUpdate) {
  53162. return;
  53163. }
  53164. var elMap = this._elMap;
  53165. var rootGroup = this.group;
  53166. // Top-down tranverse to assign graphic settings to each elements.
  53167. each$1(elOptionsToUpdate, function (elOption) {
  53168. var $action = elOption.$action;
  53169. var id = elOption.id;
  53170. var existEl = elMap.get(id);
  53171. var parentId = elOption.parentId;
  53172. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  53173. if (elOption.type === 'text') {
  53174. var elOptionStyle = elOption.style;
  53175. // In top/bottom mode, textVerticalAlign should not be used, which cause
  53176. // inaccurately locating.
  53177. if (elOption.hv && elOption.hv[1]) {
  53178. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  53179. }
  53180. // Compatible with previous setting: both support fill and textFill,
  53181. // stroke and textStroke.
  53182. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  53183. elOptionStyle.textFill = elOptionStyle.fill
  53184. );
  53185. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  53186. elOptionStyle.textStroke = elOptionStyle.stroke
  53187. );
  53188. }
  53189. // Remove unnecessary props to avoid potential problems.
  53190. var elOptionCleaned = getCleanedElOption(elOption);
  53191. // For simple, do not support parent change, otherwise reorder is needed.
  53192. if (__DEV__) {
  53193. existEl && assert$1(
  53194. targetElParent === existEl.parent,
  53195. 'Changing parent is not supported.'
  53196. );
  53197. }
  53198. if (!$action || $action === 'merge') {
  53199. existEl
  53200. ? existEl.attr(elOptionCleaned)
  53201. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  53202. }
  53203. else if ($action === 'replace') {
  53204. removeEl(existEl, elMap);
  53205. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  53206. }
  53207. else if ($action === 'remove') {
  53208. removeEl(existEl, elMap);
  53209. }
  53210. var el = elMap.get(id);
  53211. if (el) {
  53212. el.__ecGraphicWidth = elOption.width;
  53213. el.__ecGraphicHeight = elOption.height;
  53214. }
  53215. });
  53216. },
  53217. /**
  53218. * Locate graphic elements.
  53219. *
  53220. * @private
  53221. * @param {Object} graphicModel graphic model
  53222. * @param {module:echarts/ExtensionAPI} api extension API
  53223. */
  53224. _relocate: function (graphicModel, api) {
  53225. var elOptions = graphicModel.option.elements;
  53226. var rootGroup = this.group;
  53227. var elMap = this._elMap;
  53228. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  53229. for (var i = elOptions.length - 1; i >= 0; i--) {
  53230. var elOption = elOptions[i];
  53231. var el = elMap.get(elOption.id);
  53232. if (!el) {
  53233. continue;
  53234. }
  53235. var parentEl = el.parent;
  53236. var containerInfo = parentEl === rootGroup
  53237. ? {
  53238. width: api.getWidth(),
  53239. height: api.getHeight()
  53240. }
  53241. : { // Like 'position:absolut' in css, default 0.
  53242. width: parentEl.__ecGraphicWidth || 0,
  53243. height: parentEl.__ecGraphicHeight || 0
  53244. };
  53245. positionElement(
  53246. el, elOption, containerInfo, null,
  53247. {hv: elOption.hv, boundingMode: elOption.bounding}
  53248. );
  53249. }
  53250. },
  53251. /**
  53252. * Clear all elements.
  53253. *
  53254. * @private
  53255. */
  53256. _clear: function () {
  53257. var elMap = this._elMap;
  53258. elMap.each(function (el) {
  53259. removeEl(el, elMap);
  53260. });
  53261. this._elMap = createHashMap();
  53262. },
  53263. /**
  53264. * @override
  53265. */
  53266. dispose: function () {
  53267. this._clear();
  53268. }
  53269. });
  53270. function createEl$1(id, targetElParent, elOption, elMap) {
  53271. var graphicType = elOption.type;
  53272. if (__DEV__) {
  53273. assert$1(graphicType, 'graphic type MUST be set');
  53274. }
  53275. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  53276. if (__DEV__) {
  53277. assert$1(Clz, 'graphic type can not be found');
  53278. }
  53279. var el = new Clz(elOption);
  53280. targetElParent.add(el);
  53281. elMap.set(id, el);
  53282. el.__ecGraphicId = id;
  53283. }
  53284. function removeEl(existEl, elMap) {
  53285. var existElParent = existEl && existEl.parent;
  53286. if (existElParent) {
  53287. existEl.type === 'group' && existEl.traverse(function (el) {
  53288. removeEl(el, elMap);
  53289. });
  53290. elMap.removeKey(existEl.__ecGraphicId);
  53291. existElParent.remove(existEl);
  53292. }
  53293. }
  53294. // Remove unnecessary props to avoid potential problems.
  53295. function getCleanedElOption(elOption) {
  53296. elOption = extend({}, elOption);
  53297. each$1(
  53298. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  53299. function (name) {
  53300. delete elOption[name];
  53301. }
  53302. );
  53303. return elOption;
  53304. }
  53305. function isSetLoc(obj, props) {
  53306. var isSet;
  53307. each$1(props, function (prop) {
  53308. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  53309. });
  53310. return isSet;
  53311. }
  53312. function setKeyInfoToNewElOption(resultItem, newElOption) {
  53313. var existElOption = resultItem.exist;
  53314. // Set id and type after id assigned.
  53315. newElOption.id = resultItem.keyInfo.id;
  53316. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  53317. // Set parent id if not specified
  53318. if (newElOption.parentId == null) {
  53319. var newElParentOption = newElOption.parentOption;
  53320. if (newElParentOption) {
  53321. newElOption.parentId = newElParentOption.id;
  53322. }
  53323. else if (existElOption) {
  53324. newElOption.parentId = existElOption.parentId;
  53325. }
  53326. }
  53327. // Clear
  53328. newElOption.parentOption = null;
  53329. }
  53330. function mergeNewElOptionToExist(existList, index, newElOption) {
  53331. // Update existing options, for `getOption` feature.
  53332. var newElOptCopy = extend({}, newElOption);
  53333. var existElOption = existList[index];
  53334. var $action = newElOption.$action || 'merge';
  53335. if ($action === 'merge') {
  53336. if (existElOption) {
  53337. if (__DEV__) {
  53338. var newType = newElOption.type;
  53339. assert$1(
  53340. !newType || existElOption.type === newType,
  53341. 'Please set $action: "replace" to change `type`'
  53342. );
  53343. }
  53344. // We can ensure that newElOptCopy and existElOption are not
  53345. // the same object, so `merge` will not change newElOptCopy.
  53346. merge(existElOption, newElOptCopy, true);
  53347. // Rigid body, use ignoreSize.
  53348. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  53349. // Will be used in render.
  53350. copyLayoutParams(newElOption, existElOption);
  53351. }
  53352. else {
  53353. existList[index] = newElOptCopy;
  53354. }
  53355. }
  53356. else if ($action === 'replace') {
  53357. existList[index] = newElOptCopy;
  53358. }
  53359. else if ($action === 'remove') {
  53360. // null will be cleaned later.
  53361. existElOption && (existList[index] = null);
  53362. }
  53363. }
  53364. function setLayoutInfoToExist(existItem, newElOption) {
  53365. if (!existItem) {
  53366. return;
  53367. }
  53368. existItem.hv = newElOption.hv = [
  53369. // Rigid body, dont care `width`.
  53370. isSetLoc(newElOption, ['left', 'right']),
  53371. // Rigid body, dont care `height`.
  53372. isSetLoc(newElOption, ['top', 'bottom'])
  53373. ];
  53374. // Give default group size. Otherwise layout error may occur.
  53375. if (existItem.type === 'group') {
  53376. existItem.width == null && (existItem.width = newElOption.width = 0);
  53377. existItem.height == null && (existItem.height = newElOption.height = 0);
  53378. }
  53379. }
  53380. var LegendModel = extendComponentModel({
  53381. type: 'legend.plain',
  53382. dependencies: ['series'],
  53383. layoutMode: {
  53384. type: 'box',
  53385. // legend.width/height are maxWidth/maxHeight actually,
  53386. // whereas realy width/height is calculated by its content.
  53387. // (Setting {left: 10, right: 10} does not make sense).
  53388. // So consider the case:
  53389. // `setOption({legend: {left: 10});`
  53390. // then `setOption({legend: {right: 10});`
  53391. // The previous `left` should be cleared by setting `ignoreSize`.
  53392. ignoreSize: true
  53393. },
  53394. init: function (option, parentModel, ecModel) {
  53395. this.mergeDefaultAndTheme(option, ecModel);
  53396. option.selected = option.selected || {};
  53397. },
  53398. mergeOption: function (option) {
  53399. LegendModel.superCall(this, 'mergeOption', option);
  53400. },
  53401. optionUpdated: function () {
  53402. this._updateData(this.ecModel);
  53403. var legendData = this._data;
  53404. // If selectedMode is single, try to select one
  53405. if (legendData[0] && this.get('selectedMode') === 'single') {
  53406. var hasSelected = false;
  53407. // If has any selected in option.selected
  53408. for (var i = 0; i < legendData.length; i++) {
  53409. var name = legendData[i].get('name');
  53410. if (this.isSelected(name)) {
  53411. // Force to unselect others
  53412. this.select(name);
  53413. hasSelected = true;
  53414. break;
  53415. }
  53416. }
  53417. // Try select the first if selectedMode is single
  53418. !hasSelected && this.select(legendData[0].get('name'));
  53419. }
  53420. },
  53421. _updateData: function (ecModel) {
  53422. var potentialData = [];
  53423. var availableNames = [];
  53424. ecModel.eachRawSeries(function (seriesModel) {
  53425. var seriesName = seriesModel.name;
  53426. availableNames.push(seriesName);
  53427. var isPotential;
  53428. if (seriesModel.legendDataProvider) {
  53429. var data = seriesModel.legendDataProvider();
  53430. var names = data.mapArray(data.getName);
  53431. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53432. availableNames = availableNames.concat(names);
  53433. }
  53434. if (names.length) {
  53435. potentialData = potentialData.concat(names);
  53436. }
  53437. else {
  53438. isPotential = true;
  53439. }
  53440. }
  53441. else {
  53442. isPotential = true;
  53443. }
  53444. if (isPotential && isNameSpecified(seriesModel)) {
  53445. potentialData.push(seriesModel.name);
  53446. }
  53447. });
  53448. /**
  53449. * @type {Array.<string>}
  53450. * @private
  53451. */
  53452. this._availableNames = availableNames;
  53453. // If legend.data not specified in option, use availableNames as data,
  53454. // which is convinient for user preparing option.
  53455. var rawData = this.get('data') || potentialData;
  53456. var legendData = map(rawData, function (dataItem) {
  53457. // Can be string or number
  53458. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  53459. dataItem = {
  53460. name: dataItem
  53461. };
  53462. }
  53463. return new Model(dataItem, this, this.ecModel);
  53464. }, this);
  53465. /**
  53466. * @type {Array.<module:echarts/model/Model>}
  53467. * @private
  53468. */
  53469. this._data = legendData;
  53470. },
  53471. /**
  53472. * @return {Array.<module:echarts/model/Model>}
  53473. */
  53474. getData: function () {
  53475. return this._data;
  53476. },
  53477. /**
  53478. * @param {string} name
  53479. */
  53480. select: function (name) {
  53481. var selected = this.option.selected;
  53482. var selectedMode = this.get('selectedMode');
  53483. if (selectedMode === 'single') {
  53484. var data = this._data;
  53485. each$1(data, function (dataItem) {
  53486. selected[dataItem.get('name')] = false;
  53487. });
  53488. }
  53489. selected[name] = true;
  53490. },
  53491. /**
  53492. * @param {string} name
  53493. */
  53494. unSelect: function (name) {
  53495. if (this.get('selectedMode') !== 'single') {
  53496. this.option.selected[name] = false;
  53497. }
  53498. },
  53499. /**
  53500. * @param {string} name
  53501. */
  53502. toggleSelected: function (name) {
  53503. var selected = this.option.selected;
  53504. // Default is true
  53505. if (!selected.hasOwnProperty(name)) {
  53506. selected[name] = true;
  53507. }
  53508. this[selected[name] ? 'unSelect' : 'select'](name);
  53509. },
  53510. /**
  53511. * @param {string} name
  53512. */
  53513. isSelected: function (name) {
  53514. var selected = this.option.selected;
  53515. return !(selected.hasOwnProperty(name) && !selected[name])
  53516. && indexOf(this._availableNames, name) >= 0;
  53517. },
  53518. defaultOption: {
  53519. // 一级层叠
  53520. zlevel: 0,
  53521. // 二级层叠
  53522. z: 4,
  53523. show: true,
  53524. // 布局方式,默认为水平布局,可选为:
  53525. // 'horizontal' | 'vertical'
  53526. orient: 'horizontal',
  53527. left: 'center',
  53528. // right: 'center',
  53529. top: 0,
  53530. // bottom: null,
  53531. // 水平对齐
  53532. // 'auto' | 'left' | 'right'
  53533. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  53534. align: 'auto',
  53535. backgroundColor: 'rgba(0,0,0,0)',
  53536. // 图例边框颜色
  53537. borderColor: '#ccc',
  53538. borderRadius: 0,
  53539. // 图例边框线宽,单位px,默认为0(无边框)
  53540. borderWidth: 0,
  53541. // 图例内边距,单位px,默认各方向内边距为5,
  53542. // 接受数组分别设定上右下左边距,同css
  53543. padding: 5,
  53544. // 各个item之间的间隔,单位px,默认为10,
  53545. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  53546. itemGap: 10,
  53547. // 图例图形宽度
  53548. itemWidth: 25,
  53549. // 图例图形高度
  53550. itemHeight: 14,
  53551. // 图例关闭时候的颜色
  53552. inactiveColor: '#ccc',
  53553. textStyle: {
  53554. // 图例文字颜色
  53555. color: '#333'
  53556. },
  53557. // formatter: '',
  53558. // 选择模式,默认开启图例开关
  53559. selectedMode: true,
  53560. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  53561. // selected: null,
  53562. // 图例内容(详见legend.data,数组中每一项代表一个item
  53563. // data: [],
  53564. // Tooltip 相关配置
  53565. tooltip: {
  53566. show: false
  53567. }
  53568. }
  53569. });
  53570. function legendSelectActionHandler(methodName, payload, ecModel) {
  53571. var selectedMap = {};
  53572. var isToggleSelect = methodName === 'toggleSelected';
  53573. var isSelected;
  53574. // Update all legend components
  53575. ecModel.eachComponent('legend', function (legendModel) {
  53576. if (isToggleSelect && isSelected != null) {
  53577. // Force other legend has same selected status
  53578. // Or the first is toggled to true and other are toggled to false
  53579. // In the case one legend has some item unSelected in option. And if other legend
  53580. // doesn't has the item, they will assume it is selected.
  53581. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  53582. }
  53583. else {
  53584. legendModel[methodName](payload.name);
  53585. isSelected = legendModel.isSelected(payload.name);
  53586. }
  53587. var legendData = legendModel.getData();
  53588. each$1(legendData, function (model) {
  53589. var name = model.get('name');
  53590. // Wrap element
  53591. if (name === '\n' || name === '') {
  53592. return;
  53593. }
  53594. var isItemSelected = legendModel.isSelected(name);
  53595. if (selectedMap.hasOwnProperty(name)) {
  53596. // Unselected if any legend is unselected
  53597. selectedMap[name] = selectedMap[name] && isItemSelected;
  53598. }
  53599. else {
  53600. selectedMap[name] = isItemSelected;
  53601. }
  53602. });
  53603. });
  53604. // Return the event explicitly
  53605. return {
  53606. name: payload.name,
  53607. selected: selectedMap
  53608. };
  53609. }
  53610. /**
  53611. * @event legendToggleSelect
  53612. * @type {Object}
  53613. * @property {string} type 'legendToggleSelect'
  53614. * @property {string} [from]
  53615. * @property {string} name Series name or data item name
  53616. */
  53617. registerAction(
  53618. 'legendToggleSelect', 'legendselectchanged',
  53619. curry(legendSelectActionHandler, 'toggleSelected')
  53620. );
  53621. /**
  53622. * @event legendSelect
  53623. * @type {Object}
  53624. * @property {string} type 'legendSelect'
  53625. * @property {string} name Series name or data item name
  53626. */
  53627. registerAction(
  53628. 'legendSelect', 'legendselected',
  53629. curry(legendSelectActionHandler, 'select')
  53630. );
  53631. /**
  53632. * @event legendUnSelect
  53633. * @type {Object}
  53634. * @property {string} type 'legendUnSelect'
  53635. * @property {string} name Series name or data item name
  53636. */
  53637. registerAction(
  53638. 'legendUnSelect', 'legendunselected',
  53639. curry(legendSelectActionHandler, 'unSelect')
  53640. );
  53641. /**
  53642. * Layout list like component.
  53643. * It will box layout each items in group of component and then position the whole group in the viewport
  53644. * @param {module:zrender/group/Group} group
  53645. * @param {module:echarts/model/Component} componentModel
  53646. * @param {module:echarts/ExtensionAPI}
  53647. */
  53648. function layout$3(group, componentModel, api) {
  53649. var boxLayoutParams = componentModel.getBoxLayoutParams();
  53650. var padding = componentModel.get('padding');
  53651. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  53652. var rect = getLayoutRect(
  53653. boxLayoutParams,
  53654. viewportSize,
  53655. padding
  53656. );
  53657. box(
  53658. componentModel.get('orient'),
  53659. group,
  53660. componentModel.get('itemGap'),
  53661. rect.width,
  53662. rect.height
  53663. );
  53664. positionElement(
  53665. group,
  53666. boxLayoutParams,
  53667. viewportSize,
  53668. padding
  53669. );
  53670. }
  53671. function makeBackground(rect, componentModel) {
  53672. var padding = normalizeCssArray$1(
  53673. componentModel.get('padding')
  53674. );
  53675. var style = componentModel.getItemStyle(['color', 'opacity']);
  53676. style.fill = componentModel.get('backgroundColor');
  53677. var rect = new Rect({
  53678. shape: {
  53679. x: rect.x - padding[3],
  53680. y: rect.y - padding[0],
  53681. width: rect.width + padding[1] + padding[3],
  53682. height: rect.height + padding[0] + padding[2],
  53683. r: componentModel.get('borderRadius')
  53684. },
  53685. style: style,
  53686. silent: true,
  53687. z2: -1
  53688. });
  53689. // FIXME
  53690. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  53691. // and background rect when setting like `left: 0`, `top: 0`.
  53692. // graphic.subPixelOptimizeRect(rect);
  53693. return rect;
  53694. }
  53695. var curry$4 = curry;
  53696. var each$17 = each$1;
  53697. var Group$3 = Group;
  53698. var LegendView = extendComponentView({
  53699. type: 'legend.plain',
  53700. newlineDisabled: false,
  53701. /**
  53702. * @override
  53703. */
  53704. init: function () {
  53705. /**
  53706. * @private
  53707. * @type {module:zrender/container/Group}
  53708. */
  53709. this.group.add(this._contentGroup = new Group$3());
  53710. /**
  53711. * @private
  53712. * @type {module:zrender/Element}
  53713. */
  53714. this._backgroundEl;
  53715. },
  53716. /**
  53717. * @protected
  53718. */
  53719. getContentGroup: function () {
  53720. return this._contentGroup;
  53721. },
  53722. /**
  53723. * @override
  53724. */
  53725. render: function (legendModel, ecModel, api) {
  53726. this.resetInner();
  53727. if (!legendModel.get('show', true)) {
  53728. return;
  53729. }
  53730. var itemAlign = legendModel.get('align');
  53731. if (!itemAlign || itemAlign === 'auto') {
  53732. itemAlign = (
  53733. legendModel.get('left') === 'right'
  53734. && legendModel.get('orient') === 'vertical'
  53735. ) ? 'right' : 'left';
  53736. }
  53737. this.renderInner(itemAlign, legendModel, ecModel, api);
  53738. // Perform layout.
  53739. var positionInfo = legendModel.getBoxLayoutParams();
  53740. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  53741. var padding = legendModel.get('padding');
  53742. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  53743. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  53744. // Place mainGroup, based on the calculated `mainRect`.
  53745. var layoutRect = getLayoutRect(
  53746. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  53747. viewportSize,
  53748. padding
  53749. );
  53750. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  53751. // Render background after group is layout.
  53752. this.group.add(
  53753. this._backgroundEl = makeBackground(mainRect, legendModel)
  53754. );
  53755. },
  53756. /**
  53757. * @protected
  53758. */
  53759. resetInner: function () {
  53760. this.getContentGroup().removeAll();
  53761. this._backgroundEl && this.group.remove(this._backgroundEl);
  53762. },
  53763. /**
  53764. * @protected
  53765. */
  53766. renderInner: function (itemAlign, legendModel, ecModel, api) {
  53767. var contentGroup = this.getContentGroup();
  53768. var legendDrawnMap = createHashMap();
  53769. var selectMode = legendModel.get('selectedMode');
  53770. each$17(legendModel.getData(), function (itemModel, dataIndex) {
  53771. var name = itemModel.get('name');
  53772. // Use empty string or \n as a newline string
  53773. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  53774. contentGroup.add(new Group$3({
  53775. newline: true
  53776. }));
  53777. return;
  53778. }
  53779. var seriesModel = ecModel.getSeriesByName(name)[0];
  53780. if (legendDrawnMap.get(name)) {
  53781. // Have been drawed
  53782. return;
  53783. }
  53784. // Series legend
  53785. if (seriesModel) {
  53786. var data = seriesModel.getData();
  53787. var color = data.getVisual('color');
  53788. // If color is a callback function
  53789. if (typeof color === 'function') {
  53790. // Use the first data
  53791. color = color(seriesModel.getDataParams(0));
  53792. }
  53793. // Using rect symbol defaultly
  53794. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  53795. var symbolType = data.getVisual('symbol');
  53796. var itemGroup = this._createItem(
  53797. name, dataIndex, itemModel, legendModel,
  53798. legendSymbolType, symbolType,
  53799. itemAlign, color,
  53800. selectMode
  53801. );
  53802. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  53803. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api))
  53804. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api));
  53805. legendDrawnMap.set(name, true);
  53806. }
  53807. else {
  53808. // Data legend of pie, funnel
  53809. ecModel.eachRawSeries(function (seriesModel) {
  53810. // In case multiple series has same data name
  53811. if (legendDrawnMap.get(name)) {
  53812. return;
  53813. }
  53814. if (seriesModel.legendDataProvider) {
  53815. var data = seriesModel.legendDataProvider();
  53816. var idx = data.indexOfName(name);
  53817. if (idx < 0) {
  53818. return;
  53819. }
  53820. var color = data.getItemVisual(idx, 'color');
  53821. var legendSymbolType = 'roundRect';
  53822. var itemGroup = this._createItem(
  53823. name, dataIndex, itemModel, legendModel,
  53824. legendSymbolType, null,
  53825. itemAlign, color,
  53826. selectMode
  53827. );
  53828. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  53829. // FIXME Should not specify the series name
  53830. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api))
  53831. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api));
  53832. legendDrawnMap.set(name, true);
  53833. }
  53834. }, this);
  53835. }
  53836. if (__DEV__) {
  53837. if (!legendDrawnMap.get(name)) {
  53838. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  53839. }
  53840. }
  53841. }, this);
  53842. },
  53843. _createItem: function (
  53844. name, dataIndex, itemModel, legendModel,
  53845. legendSymbolType, symbolType,
  53846. itemAlign, color, selectMode
  53847. ) {
  53848. var itemWidth = legendModel.get('itemWidth');
  53849. var itemHeight = legendModel.get('itemHeight');
  53850. var inactiveColor = legendModel.get('inactiveColor');
  53851. var isSelected = legendModel.isSelected(name);
  53852. var itemGroup = new Group$3();
  53853. var textStyleModel = itemModel.getModel('textStyle');
  53854. var itemIcon = itemModel.get('icon');
  53855. var tooltipModel = itemModel.getModel('tooltip');
  53856. var legendGlobalTooltipModel = tooltipModel.parentModel;
  53857. // Use user given icon first
  53858. legendSymbolType = itemIcon || legendSymbolType;
  53859. itemGroup.add(createSymbol(
  53860. legendSymbolType,
  53861. 0,
  53862. 0,
  53863. itemWidth,
  53864. itemHeight,
  53865. isSelected ? color : inactiveColor,
  53866. true
  53867. ));
  53868. // Compose symbols
  53869. // PENDING
  53870. if (!itemIcon && symbolType
  53871. // At least show one symbol, can't be all none
  53872. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  53873. ) {
  53874. var size = itemHeight * 0.8;
  53875. if (symbolType === 'none') {
  53876. symbolType = 'circle';
  53877. }
  53878. // Put symbol in the center
  53879. itemGroup.add(createSymbol(
  53880. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  53881. isSelected ? color : inactiveColor
  53882. ));
  53883. }
  53884. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  53885. var textAlign = itemAlign;
  53886. var formatter = legendModel.get('formatter');
  53887. var content = name;
  53888. if (typeof formatter === 'string' && formatter) {
  53889. content = formatter.replace('{name}', name != null ? name : '');
  53890. }
  53891. else if (typeof formatter === 'function') {
  53892. content = formatter(name);
  53893. }
  53894. itemGroup.add(new Text({
  53895. style: setTextStyle({}, textStyleModel, {
  53896. text: content,
  53897. x: textX,
  53898. y: itemHeight / 2,
  53899. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  53900. textAlign: textAlign,
  53901. textVerticalAlign: 'middle'
  53902. })
  53903. }));
  53904. // Add a invisible rect to increase the area of mouse hover
  53905. var hitRect = new Rect({
  53906. shape: itemGroup.getBoundingRect(),
  53907. invisible: true,
  53908. tooltip: tooltipModel.get('show') ? extend({
  53909. content: name,
  53910. // Defaul formatter
  53911. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  53912. return name;
  53913. },
  53914. formatterParams: {
  53915. componentType: 'legend',
  53916. legendIndex: legendModel.componentIndex,
  53917. name: name,
  53918. $vars: ['name']
  53919. }
  53920. }, tooltipModel.option) : null
  53921. });
  53922. itemGroup.add(hitRect);
  53923. itemGroup.eachChild(function (child) {
  53924. child.silent = true;
  53925. });
  53926. hitRect.silent = !selectMode;
  53927. this.getContentGroup().add(itemGroup);
  53928. setHoverStyle(itemGroup);
  53929. itemGroup.__legendDataIndex = dataIndex;
  53930. return itemGroup;
  53931. },
  53932. /**
  53933. * @protected
  53934. */
  53935. layoutInner: function (legendModel, itemAlign, maxSize) {
  53936. var contentGroup = this.getContentGroup();
  53937. // Place items in contentGroup.
  53938. box(
  53939. legendModel.get('orient'),
  53940. contentGroup,
  53941. legendModel.get('itemGap'),
  53942. maxSize.width,
  53943. maxSize.height
  53944. );
  53945. var contentRect = contentGroup.getBoundingRect();
  53946. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  53947. return this.group.getBoundingRect();
  53948. }
  53949. });
  53950. function dispatchSelectAction(name, api) {
  53951. api.dispatchAction({
  53952. type: 'legendToggleSelect',
  53953. name: name
  53954. });
  53955. }
  53956. function dispatchHighlightAction(seriesModel, dataName, api) {
  53957. // If element hover will move to a hoverLayer.
  53958. var el = api.getZr().storage.getDisplayList()[0];
  53959. if (!(el && el.useHoverLayer)) {
  53960. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53961. type: 'highlight',
  53962. seriesName: seriesModel.name,
  53963. name: dataName
  53964. });
  53965. }
  53966. }
  53967. function dispatchDownplayAction(seriesModel, dataName, api) {
  53968. // If element hover will move to a hoverLayer.
  53969. var el = api.getZr().storage.getDisplayList()[0];
  53970. if (!(el && el.useHoverLayer)) {
  53971. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53972. type: 'downplay',
  53973. seriesName: seriesModel.name,
  53974. name: dataName
  53975. });
  53976. }
  53977. }
  53978. var legendFilter = function (ecModel) {
  53979. var legendModels = ecModel.findComponents({
  53980. mainType: 'legend'
  53981. });
  53982. if (legendModels && legendModels.length) {
  53983. ecModel.filterSeries(function (series) {
  53984. // If in any legend component the status is not selected.
  53985. // Because in legend series is assumed selected when it is not in the legend data.
  53986. for (var i = 0; i < legendModels.length; i++) {
  53987. if (!legendModels[i].isSelected(series.name)) {
  53988. return false;
  53989. }
  53990. }
  53991. return true;
  53992. });
  53993. }
  53994. };
  53995. // Do not contain scrollable legend, for sake of file size.
  53996. // Series Filter
  53997. registerProcessor(legendFilter);
  53998. ComponentModel.registerSubTypeDefaulter('legend', function () {
  53999. // Default 'plain' when no type specified.
  54000. return 'plain';
  54001. });
  54002. var ScrollableLegendModel = LegendModel.extend({
  54003. type: 'legend.scroll',
  54004. /**
  54005. * @param {number} scrollDataIndex
  54006. */
  54007. setScrollDataIndex: function (scrollDataIndex) {
  54008. this.option.scrollDataIndex = scrollDataIndex;
  54009. },
  54010. defaultOption: {
  54011. scrollDataIndex: 0,
  54012. pageButtonItemGap: 5,
  54013. pageButtonGap: null,
  54014. pageButtonPosition: 'end', // 'start' or 'end'
  54015. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  54016. pageIcons: {
  54017. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  54018. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  54019. },
  54020. pageIconColor: '#2f4554',
  54021. pageIconInactiveColor: '#aaa',
  54022. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  54023. pageTextStyle: {
  54024. color: '#333'
  54025. },
  54026. animationDurationUpdate: 800
  54027. },
  54028. /**
  54029. * @override
  54030. */
  54031. init: function (option, parentModel, ecModel, extraOpt) {
  54032. var inputPositionParams = getLayoutParams(option);
  54033. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  54034. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  54035. },
  54036. /**
  54037. * @override
  54038. */
  54039. mergeOption: function (option, extraOpt) {
  54040. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  54041. mergeAndNormalizeLayoutParams(this, this.option, option);
  54042. },
  54043. getOrient: function () {
  54044. return this.get('orient') === 'vertical'
  54045. ? {index: 1, name: 'vertical'}
  54046. : {index: 0, name: 'horizontal'};
  54047. }
  54048. });
  54049. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  54050. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  54051. var orient = legendModel.getOrient();
  54052. var ignoreSize = [1, 1];
  54053. ignoreSize[orient.index] = 0;
  54054. mergeLayoutParam(target, raw, {
  54055. type: 'box', ignoreSize: ignoreSize
  54056. });
  54057. }
  54058. /**
  54059. * Separate legend and scrollable legend to reduce package size.
  54060. */
  54061. var Group$4 = Group;
  54062. var WH$1 = ['width', 'height'];
  54063. var XY$1 = ['x', 'y'];
  54064. var ScrollableLegendView = LegendView.extend({
  54065. type: 'legend.scroll',
  54066. newlineDisabled: true,
  54067. init: function () {
  54068. ScrollableLegendView.superCall(this, 'init');
  54069. /**
  54070. * @private
  54071. * @type {number} For `scroll`.
  54072. */
  54073. this._currentIndex = 0;
  54074. /**
  54075. * @private
  54076. * @type {module:zrender/container/Group}
  54077. */
  54078. this.group.add(this._containerGroup = new Group$4());
  54079. this._containerGroup.add(this.getContentGroup());
  54080. /**
  54081. * @private
  54082. * @type {module:zrender/container/Group}
  54083. */
  54084. this.group.add(this._controllerGroup = new Group$4());
  54085. /**
  54086. *
  54087. * @private
  54088. */
  54089. this._showController;
  54090. },
  54091. /**
  54092. * @override
  54093. */
  54094. resetInner: function () {
  54095. ScrollableLegendView.superCall(this, 'resetInner');
  54096. this._controllerGroup.removeAll();
  54097. this._containerGroup.removeClipPath();
  54098. this._containerGroup.__rectSize = null;
  54099. },
  54100. /**
  54101. * @override
  54102. */
  54103. renderInner: function (itemAlign, legendModel, ecModel, api) {
  54104. var me = this;
  54105. // Render content items.
  54106. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  54107. var controllerGroup = this._controllerGroup;
  54108. var pageIconSize = legendModel.get('pageIconSize', true);
  54109. if (!isArray(pageIconSize)) {
  54110. pageIconSize = [pageIconSize, pageIconSize];
  54111. }
  54112. createPageButton('pagePrev', 0);
  54113. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  54114. controllerGroup.add(new Text({
  54115. name: 'pageText',
  54116. style: {
  54117. textFill: pageTextStyleModel.getTextColor(),
  54118. font: pageTextStyleModel.getFont(),
  54119. textVerticalAlign: 'middle',
  54120. textAlign: 'center'
  54121. },
  54122. silent: true
  54123. }));
  54124. createPageButton('pageNext', 1);
  54125. function createPageButton(name, iconIdx) {
  54126. var pageDataIndexName = name + 'DataIndex';
  54127. var icon = createIcon(
  54128. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  54129. {
  54130. // Buttons will be created in each render, so we do not need
  54131. // to worry about avoiding using legendModel kept in scope.
  54132. onclick: bind(
  54133. me._pageGo, me, pageDataIndexName, legendModel, api
  54134. )
  54135. },
  54136. {
  54137. x: -pageIconSize[0] / 2,
  54138. y: -pageIconSize[1] / 2,
  54139. width: pageIconSize[0],
  54140. height: pageIconSize[1]
  54141. }
  54142. );
  54143. icon.name = name;
  54144. controllerGroup.add(icon);
  54145. }
  54146. },
  54147. /**
  54148. * @override
  54149. */
  54150. layoutInner: function (legendModel, itemAlign, maxSize) {
  54151. var contentGroup = this.getContentGroup();
  54152. var containerGroup = this._containerGroup;
  54153. var controllerGroup = this._controllerGroup;
  54154. var orientIdx = legendModel.getOrient().index;
  54155. var wh = WH$1[orientIdx];
  54156. var hw = WH$1[1 - orientIdx];
  54157. var yx = XY$1[1 - orientIdx];
  54158. // Place items in contentGroup.
  54159. box(
  54160. legendModel.get('orient'),
  54161. contentGroup,
  54162. legendModel.get('itemGap'),
  54163. !orientIdx ? null : maxSize.width,
  54164. orientIdx ? null : maxSize.height
  54165. );
  54166. box(
  54167. // Buttons in controller are layout always horizontally.
  54168. 'horizontal',
  54169. controllerGroup,
  54170. legendModel.get('pageButtonItemGap', true)
  54171. );
  54172. var contentRect = contentGroup.getBoundingRect();
  54173. var controllerRect = controllerGroup.getBoundingRect();
  54174. var showController = this._showController = contentRect[wh] > maxSize[wh];
  54175. var contentPos = [-contentRect.x, -contentRect.y];
  54176. // Remain contentPos when scroll animation perfroming.
  54177. contentPos[orientIdx] = contentGroup.position[orientIdx];
  54178. // Layout container group based on 0.
  54179. var containerPos = [0, 0];
  54180. var controllerPos = [-controllerRect.x, -controllerRect.y];
  54181. var pageButtonGap = retrieve2(
  54182. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  54183. );
  54184. // Place containerGroup and controllerGroup and contentGroup.
  54185. if (showController) {
  54186. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  54187. // controller is on the right / bottom.
  54188. if (pageButtonPosition === 'end') {
  54189. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  54190. }
  54191. // controller is on the left / top.
  54192. else {
  54193. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  54194. }
  54195. }
  54196. // Always align controller to content as 'middle'.
  54197. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  54198. contentGroup.attr('position', contentPos);
  54199. containerGroup.attr('position', containerPos);
  54200. controllerGroup.attr('position', controllerPos);
  54201. // Calculate `mainRect` and set `clipPath`.
  54202. // mainRect should not be calculated by `this.group.getBoundingRect()`
  54203. // for sake of the overflow.
  54204. var mainRect = this.group.getBoundingRect();
  54205. var mainRect = {x: 0, y: 0};
  54206. // Consider content may be overflow (should be clipped).
  54207. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  54208. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  54209. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  54210. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  54211. containerGroup.__rectSize = maxSize[wh];
  54212. if (showController) {
  54213. var clipShape = {x: 0, y: 0};
  54214. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  54215. clipShape[hw] = mainRect[hw];
  54216. containerGroup.setClipPath(new Rect({shape: clipShape}));
  54217. // Consider content may be larger than container, container rect
  54218. // can not be obtained from `containerGroup.getBoundingRect()`.
  54219. containerGroup.__rectSize = clipShape[wh];
  54220. }
  54221. else {
  54222. // Do not remove or ignore controller. Keep them set as place holders.
  54223. controllerGroup.eachChild(function (child) {
  54224. child.attr({invisible: true, silent: true});
  54225. });
  54226. }
  54227. // Content translate animation.
  54228. var pageInfo = this._getPageInfo(legendModel);
  54229. pageInfo.pageIndex != null && updateProps(
  54230. contentGroup,
  54231. {position: pageInfo.contentPosition},
  54232. // When switch from "show controller" to "not show controller", view should be
  54233. // updated immediately without animation, otherwise causes weird efffect.
  54234. showController ? legendModel : false
  54235. );
  54236. this._updatePageInfoView(legendModel, pageInfo);
  54237. return mainRect;
  54238. },
  54239. _pageGo: function (to, legendModel, api) {
  54240. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  54241. scrollDataIndex != null && api.dispatchAction({
  54242. type: 'legendScroll',
  54243. scrollDataIndex: scrollDataIndex,
  54244. legendId: legendModel.id
  54245. });
  54246. },
  54247. _updatePageInfoView: function (legendModel, pageInfo) {
  54248. var controllerGroup = this._controllerGroup;
  54249. each$1(['pagePrev', 'pageNext'], function (name) {
  54250. var canJump = pageInfo[name + 'DataIndex'] != null;
  54251. var icon = controllerGroup.childOfName(name);
  54252. if (icon) {
  54253. icon.setStyle(
  54254. 'fill',
  54255. canJump
  54256. ? legendModel.get('pageIconColor', true)
  54257. : legendModel.get('pageIconInactiveColor', true)
  54258. );
  54259. icon.cursor = canJump ? 'pointer' : 'default';
  54260. }
  54261. });
  54262. var pageText = controllerGroup.childOfName('pageText');
  54263. var pageFormatter = legendModel.get('pageFormatter');
  54264. var pageIndex = pageInfo.pageIndex;
  54265. var current = pageIndex != null ? pageIndex + 1 : 0;
  54266. var total = pageInfo.pageCount;
  54267. pageText && pageFormatter && pageText.setStyle(
  54268. 'text',
  54269. isString(pageFormatter)
  54270. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  54271. : pageFormatter({current: current, total: total})
  54272. );
  54273. },
  54274. /**
  54275. * @param {module:echarts/model/Model} legendModel
  54276. * @return {Object} {
  54277. * contentPosition: Array.<number>, null when data item not found.
  54278. * pageIndex: number, null when data item not found.
  54279. * pageCount: number, always be a number, can be 0.
  54280. * pagePrevDataIndex: number, null when no next page.
  54281. * pageNextDataIndex: number, null when no previous page.
  54282. * }
  54283. */
  54284. _getPageInfo: function (legendModel) {
  54285. // Align left or top by the current dataIndex.
  54286. var currDataIndex = legendModel.get('scrollDataIndex', true);
  54287. var contentGroup = this.getContentGroup();
  54288. var contentRect = contentGroup.getBoundingRect();
  54289. var containerRectSize = this._containerGroup.__rectSize;
  54290. var orientIdx = legendModel.getOrient().index;
  54291. var wh = WH$1[orientIdx];
  54292. var hw = WH$1[1 - orientIdx];
  54293. var xy = XY$1[orientIdx];
  54294. var contentPos = contentGroup.position.slice();
  54295. var pageIndex;
  54296. var pagePrevDataIndex;
  54297. var pageNextDataIndex;
  54298. var targetItemGroup;
  54299. if (this._showController) {
  54300. contentGroup.eachChild(function (child) {
  54301. if (child.__legendDataIndex === currDataIndex) {
  54302. targetItemGroup = child;
  54303. }
  54304. });
  54305. }
  54306. else {
  54307. targetItemGroup = contentGroup.childAt(0);
  54308. }
  54309. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  54310. if (targetItemGroup) {
  54311. var itemRect = targetItemGroup.getBoundingRect();
  54312. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  54313. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  54314. pageIndex = Math.floor(
  54315. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  54316. );
  54317. pageIndex = (contentRect[wh] && pageCount)
  54318. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  54319. : -1;
  54320. var winRect = {x: 0, y: 0};
  54321. winRect[wh] = containerRectSize;
  54322. winRect[hw] = contentRect[hw];
  54323. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  54324. var startIdx;
  54325. var children = contentGroup.children();
  54326. contentGroup.eachChild(function (child, index) {
  54327. var itemRect = getItemRect(child);
  54328. if (itemRect.intersect(winRect)) {
  54329. startIdx == null && (startIdx = index);
  54330. // It is user-friendly that the last item shown in the
  54331. // current window is shown at the begining of next window.
  54332. pageNextDataIndex = child.__legendDataIndex;
  54333. }
  54334. // If the last item is shown entirely, no next page.
  54335. if (index === children.length - 1
  54336. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  54337. ) {
  54338. pageNextDataIndex = null;
  54339. }
  54340. });
  54341. // Always align based on the left/top most item, so the left/top most
  54342. // item in the previous window is needed to be found here.
  54343. if (startIdx != null) {
  54344. var startItem = children[startIdx];
  54345. var startRect = getItemRect(startItem);
  54346. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  54347. // If the first item is shown entirely, no previous page.
  54348. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  54349. pagePrevDataIndex = null;
  54350. }
  54351. else {
  54352. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  54353. startIdx--;
  54354. }
  54355. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  54356. }
  54357. }
  54358. }
  54359. return {
  54360. contentPosition: contentPos,
  54361. pageIndex: pageIndex,
  54362. pageCount: pageCount,
  54363. pagePrevDataIndex: pagePrevDataIndex,
  54364. pageNextDataIndex: pageNextDataIndex
  54365. };
  54366. function getItemRect(el) {
  54367. var itemRect = el.getBoundingRect().clone();
  54368. itemRect[xy] += el.position[orientIdx];
  54369. return itemRect;
  54370. }
  54371. }
  54372. });
  54373. /**
  54374. * @event legendScroll
  54375. * @type {Object}
  54376. * @property {string} type 'legendScroll'
  54377. * @property {string} scrollDataIndex
  54378. */
  54379. registerAction(
  54380. 'legendScroll', 'legendscroll',
  54381. function (payload, ecModel) {
  54382. var scrollDataIndex = payload.scrollDataIndex;
  54383. scrollDataIndex != null && ecModel.eachComponent(
  54384. {mainType: 'legend', subType: 'scroll', query: payload},
  54385. function (legendModel) {
  54386. legendModel.setScrollDataIndex(scrollDataIndex);
  54387. }
  54388. );
  54389. }
  54390. );
  54391. /**
  54392. * Legend component entry file8
  54393. */
  54394. extendComponentModel({
  54395. type: 'tooltip',
  54396. dependencies: ['axisPointer'],
  54397. defaultOption: {
  54398. zlevel: 0,
  54399. z: 8,
  54400. show: true,
  54401. // tooltip主体内容
  54402. showContent: true,
  54403. // 'trigger' only works on coordinate system.
  54404. // 'item' | 'axis' | 'none'
  54405. trigger: 'item',
  54406. // 'click' | 'mousemove' | 'none'
  54407. triggerOn: 'mousemove|click',
  54408. alwaysShowContent: false,
  54409. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  54410. // 位置 {Array} | {Function}
  54411. // position: null
  54412. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  54413. // align: null,
  54414. // verticalAlign: null,
  54415. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  54416. confine: false,
  54417. // 内容格式器:{string}(Template) ¦ {Function}
  54418. // formatter: null
  54419. showDelay: 0,
  54420. // 隐藏延迟,单位ms
  54421. hideDelay: 100,
  54422. // 动画变换时间,单位s
  54423. transitionDuration: 0.4,
  54424. enterable: false,
  54425. // 提示背景颜色,默认为透明度为0.7的黑色
  54426. backgroundColor: 'rgba(50,50,50,0.7)',
  54427. // 提示边框颜色
  54428. borderColor: '#333',
  54429. // 提示边框圆角,单位px,默认为4
  54430. borderRadius: 4,
  54431. // 提示边框线宽,单位px,默认为0(无边框)
  54432. borderWidth: 0,
  54433. // 提示内边距,单位px,默认各方向内边距为5,
  54434. // 接受数组分别设定上右下左边距,同css
  54435. padding: 5,
  54436. // Extra css text
  54437. extraCssText: '',
  54438. // 坐标轴指示器,坐标轴触发有效
  54439. axisPointer: {
  54440. // 默认为直线
  54441. // 可选为:'line' | 'shadow' | 'cross'
  54442. type: 'line',
  54443. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  54444. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  54445. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  54446. // 极坐标系会默认选择 angle 轴
  54447. axis: 'auto',
  54448. animation: 'auto',
  54449. animationDurationUpdate: 200,
  54450. animationEasingUpdate: 'exponentialOut',
  54451. crossStyle: {
  54452. color: '#999',
  54453. width: 1,
  54454. type: 'dashed',
  54455. // TODO formatter
  54456. textStyle: {}
  54457. }
  54458. // lineStyle and shadowStyle should not be specified here,
  54459. // otherwise it will always override those styles on option.axisPointer.
  54460. },
  54461. textStyle: {
  54462. color: '#fff',
  54463. fontSize: 14
  54464. }
  54465. }
  54466. });
  54467. var each$19 = each$1;
  54468. var toCamelCase$1 = toCamelCase;
  54469. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  54470. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  54471. /**
  54472. * @param {number} duration
  54473. * @return {string}
  54474. * @inner
  54475. */
  54476. function assembleTransition(duration) {
  54477. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  54478. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  54479. + 'top ' + duration + 's ' + transitionCurve;
  54480. return map(vendors, function (vendorPrefix) {
  54481. return vendorPrefix + 'transition:' + transitionText;
  54482. }).join(';');
  54483. }
  54484. /**
  54485. * @param {Object} textStyle
  54486. * @return {string}
  54487. * @inner
  54488. */
  54489. function assembleFont(textStyleModel) {
  54490. var cssText = [];
  54491. var fontSize = textStyleModel.get('fontSize');
  54492. var color = textStyleModel.getTextColor();
  54493. color && cssText.push('color:' + color);
  54494. cssText.push('font:' + textStyleModel.getFont());
  54495. fontSize &&
  54496. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  54497. each$19(['decoration', 'align'], function (name) {
  54498. var val = textStyleModel.get(name);
  54499. val && cssText.push('text-' + name + ':' + val);
  54500. });
  54501. return cssText.join(';');
  54502. }
  54503. /**
  54504. * @param {Object} tooltipModel
  54505. * @return {string}
  54506. * @inner
  54507. */
  54508. function assembleCssText(tooltipModel) {
  54509. var cssText = [];
  54510. var transitionDuration = tooltipModel.get('transitionDuration');
  54511. var backgroundColor = tooltipModel.get('backgroundColor');
  54512. var textStyleModel = tooltipModel.getModel('textStyle');
  54513. var padding = tooltipModel.get('padding');
  54514. // Animation transition. Do not animate when transitionDuration is 0.
  54515. transitionDuration &&
  54516. cssText.push(assembleTransition(transitionDuration));
  54517. if (backgroundColor) {
  54518. if (env$1.canvasSupported) {
  54519. cssText.push('background-Color:' + backgroundColor);
  54520. }
  54521. else {
  54522. // for ie
  54523. cssText.push(
  54524. 'background-Color:#' + toHex(backgroundColor)
  54525. );
  54526. cssText.push('filter:alpha(opacity=70)');
  54527. }
  54528. }
  54529. // Border style
  54530. each$19(['width', 'color', 'radius'], function (name) {
  54531. var borderName = 'border-' + name;
  54532. var camelCase = toCamelCase$1(borderName);
  54533. var val = tooltipModel.get(camelCase);
  54534. val != null &&
  54535. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  54536. });
  54537. // Text style
  54538. cssText.push(assembleFont(textStyleModel));
  54539. // Padding
  54540. if (padding != null) {
  54541. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  54542. }
  54543. return cssText.join(';') + ';';
  54544. }
  54545. /**
  54546. * @alias module:echarts/component/tooltip/TooltipContent
  54547. * @constructor
  54548. */
  54549. function TooltipContent(container, api) {
  54550. if (env$1.wxa) {
  54551. return null;
  54552. }
  54553. var el = document.createElement('div');
  54554. var zr = this._zr = api.getZr();
  54555. this.el = el;
  54556. this._x = api.getWidth() / 2;
  54557. this._y = api.getHeight() / 2;
  54558. container.appendChild(el);
  54559. this._container = container;
  54560. this._show = false;
  54561. /**
  54562. * @private
  54563. */
  54564. this._hideTimeout;
  54565. var self = this;
  54566. el.onmouseenter = function () {
  54567. // clear the timeout in hideLater and keep showing tooltip
  54568. if (self._enterable) {
  54569. clearTimeout(self._hideTimeout);
  54570. self._show = true;
  54571. }
  54572. self._inContent = true;
  54573. };
  54574. el.onmousemove = function (e) {
  54575. e = e || window.event;
  54576. if (!self._enterable) {
  54577. // Try trigger zrender event to avoid mouse
  54578. // in and out shape too frequently
  54579. var handler = zr.handler;
  54580. normalizeEvent(container, e, true);
  54581. handler.dispatch('mousemove', e);
  54582. }
  54583. };
  54584. el.onmouseleave = function () {
  54585. if (self._enterable) {
  54586. if (self._show) {
  54587. self.hideLater(self._hideDelay);
  54588. }
  54589. }
  54590. self._inContent = false;
  54591. };
  54592. }
  54593. TooltipContent.prototype = {
  54594. constructor: TooltipContent,
  54595. /**
  54596. * @private
  54597. * @type {boolean}
  54598. */
  54599. _enterable: true,
  54600. /**
  54601. * Update when tooltip is rendered
  54602. */
  54603. update: function () {
  54604. // FIXME
  54605. // Move this logic to ec main?
  54606. var container = this._container;
  54607. var stl = container.currentStyle
  54608. || document.defaultView.getComputedStyle(container);
  54609. var domStyle = container.style;
  54610. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  54611. domStyle.position = 'relative';
  54612. }
  54613. // Hide the tooltip
  54614. // PENDING
  54615. // this.hide();
  54616. },
  54617. show: function (tooltipModel) {
  54618. clearTimeout(this._hideTimeout);
  54619. var el = this.el;
  54620. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  54621. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  54622. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  54623. + (tooltipModel.get('extraCssText') || '');
  54624. el.style.display = el.innerHTML ? 'block' : 'none';
  54625. this._show = true;
  54626. },
  54627. setContent: function (content) {
  54628. this.el.innerHTML = content == null ? '' : content;
  54629. },
  54630. setEnterable: function (enterable) {
  54631. this._enterable = enterable;
  54632. },
  54633. getSize: function () {
  54634. var el = this.el;
  54635. return [el.clientWidth, el.clientHeight];
  54636. },
  54637. moveTo: function (x, y) {
  54638. // xy should be based on canvas root. But tooltipContent is
  54639. // the sibling of canvas root. So padding of ec container
  54640. // should be considered here.
  54641. var zr = this._zr;
  54642. var viewportRootOffset;
  54643. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  54644. x += viewportRootOffset.offsetLeft;
  54645. y += viewportRootOffset.offsetTop;
  54646. }
  54647. var style = this.el.style;
  54648. style.left = x + 'px';
  54649. style.top = y + 'px';
  54650. this._x = x;
  54651. this._y = y;
  54652. },
  54653. hide: function () {
  54654. this.el.style.display = 'none';
  54655. this._show = false;
  54656. },
  54657. hideLater: function (time) {
  54658. if (this._show && !(this._inContent && this._enterable)) {
  54659. if (time) {
  54660. this._hideDelay = time;
  54661. // Set show false to avoid invoke hideLater mutiple times
  54662. this._show = false;
  54663. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  54664. }
  54665. else {
  54666. this.hide();
  54667. }
  54668. }
  54669. },
  54670. isShow: function () {
  54671. return this._show;
  54672. }
  54673. };
  54674. var bind$3 = bind;
  54675. var each$18 = each$1;
  54676. var parsePercent$2 = parsePercent$1;
  54677. var proxyRect = new Rect({
  54678. shape: {x: -1, y: -1, width: 2, height: 2}
  54679. });
  54680. extendComponentView({
  54681. type: 'tooltip',
  54682. init: function (ecModel, api) {
  54683. if (env$1.node) {
  54684. return;
  54685. }
  54686. var tooltipContent = new TooltipContent(api.getDom(), api);
  54687. this._tooltipContent = tooltipContent;
  54688. },
  54689. render: function (tooltipModel, ecModel, api) {
  54690. if (env$1.node || env$1.wxa) {
  54691. return;
  54692. }
  54693. // Reset
  54694. this.group.removeAll();
  54695. /**
  54696. * @private
  54697. * @type {module:echarts/component/tooltip/TooltipModel}
  54698. */
  54699. this._tooltipModel = tooltipModel;
  54700. /**
  54701. * @private
  54702. * @type {module:echarts/model/Global}
  54703. */
  54704. this._ecModel = ecModel;
  54705. /**
  54706. * @private
  54707. * @type {module:echarts/ExtensionAPI}
  54708. */
  54709. this._api = api;
  54710. /**
  54711. * Should be cleaned when render.
  54712. * @private
  54713. * @type {Array.<Array.<Object>>}
  54714. */
  54715. this._lastDataByCoordSys = null;
  54716. /**
  54717. * @private
  54718. * @type {boolean}
  54719. */
  54720. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  54721. var tooltipContent = this._tooltipContent;
  54722. tooltipContent.update();
  54723. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  54724. this._initGlobalListener();
  54725. this._keepShow();
  54726. },
  54727. _initGlobalListener: function () {
  54728. var tooltipModel = this._tooltipModel;
  54729. var triggerOn = tooltipModel.get('triggerOn');
  54730. register(
  54731. 'itemTooltip',
  54732. this._api,
  54733. bind$3(function (currTrigger, e, dispatchAction) {
  54734. // If 'none', it is not controlled by mouse totally.
  54735. if (triggerOn !== 'none') {
  54736. if (triggerOn.indexOf(currTrigger) >= 0) {
  54737. this._tryShow(e, dispatchAction);
  54738. }
  54739. else if (currTrigger === 'leave') {
  54740. this._hide(dispatchAction);
  54741. }
  54742. }
  54743. }, this)
  54744. );
  54745. },
  54746. _keepShow: function () {
  54747. var tooltipModel = this._tooltipModel;
  54748. var ecModel = this._ecModel;
  54749. var api = this._api;
  54750. // Try to keep the tooltip show when refreshing
  54751. if (this._lastX != null
  54752. && this._lastY != null
  54753. // When user is willing to control tooltip totally using API,
  54754. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  54755. // which is not expected.
  54756. && tooltipModel.get('triggerOn') !== 'none'
  54757. ) {
  54758. var self = this;
  54759. clearTimeout(this._refreshUpdateTimeout);
  54760. this._refreshUpdateTimeout = setTimeout(function () {
  54761. // Show tip next tick after other charts are rendered
  54762. // In case highlight action has wrong result
  54763. // FIXME
  54764. self.manuallyShowTip(tooltipModel, ecModel, api, {
  54765. x: self._lastX,
  54766. y: self._lastY
  54767. });
  54768. });
  54769. }
  54770. },
  54771. /**
  54772. * Show tip manually by
  54773. * dispatchAction({
  54774. * type: 'showTip',
  54775. * x: 10,
  54776. * y: 10
  54777. * });
  54778. * Or
  54779. * dispatchAction({
  54780. * type: 'showTip',
  54781. * seriesIndex: 0,
  54782. * dataIndex or dataIndexInside or name
  54783. * });
  54784. *
  54785. * TODO Batch
  54786. */
  54787. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  54788. if (payload.from === this.uid || env$1.node) {
  54789. return;
  54790. }
  54791. var dispatchAction = makeDispatchAction$1(payload, api);
  54792. // Reset ticket
  54793. this._ticket = '';
  54794. // When triggered from axisPointer.
  54795. var dataByCoordSys = payload.dataByCoordSys;
  54796. if (payload.tooltip && payload.x != null && payload.y != null) {
  54797. var el = proxyRect;
  54798. el.position = [payload.x, payload.y];
  54799. el.update();
  54800. el.tooltip = payload.tooltip;
  54801. // Manually show tooltip while view is not using zrender elements.
  54802. this._tryShow({
  54803. offsetX: payload.x,
  54804. offsetY: payload.y,
  54805. target: el
  54806. }, dispatchAction);
  54807. }
  54808. else if (dataByCoordSys) {
  54809. this._tryShow({
  54810. offsetX: payload.x,
  54811. offsetY: payload.y,
  54812. position: payload.position,
  54813. event: {},
  54814. dataByCoordSys: payload.dataByCoordSys,
  54815. tooltipOption: payload.tooltipOption
  54816. }, dispatchAction);
  54817. }
  54818. else if (payload.seriesIndex != null) {
  54819. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  54820. return;
  54821. }
  54822. var pointInfo = findPointFromSeries(payload, ecModel);
  54823. var cx = pointInfo.point[0];
  54824. var cy = pointInfo.point[1];
  54825. if (cx != null && cy != null) {
  54826. this._tryShow({
  54827. offsetX: cx,
  54828. offsetY: cy,
  54829. position: payload.position,
  54830. target: pointInfo.el,
  54831. event: {}
  54832. }, dispatchAction);
  54833. }
  54834. }
  54835. else if (payload.x != null && payload.y != null) {
  54836. // FIXME
  54837. // should wrap dispatchAction like `axisPointer/globalListener` ?
  54838. api.dispatchAction({
  54839. type: 'updateAxisPointer',
  54840. x: payload.x,
  54841. y: payload.y
  54842. });
  54843. this._tryShow({
  54844. offsetX: payload.x,
  54845. offsetY: payload.y,
  54846. position: payload.position,
  54847. target: api.getZr().findHover(payload.x, payload.y).target,
  54848. event: {}
  54849. }, dispatchAction);
  54850. }
  54851. },
  54852. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  54853. var tooltipContent = this._tooltipContent;
  54854. if (!this._alwaysShowContent && this._tooltipModel) {
  54855. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  54856. }
  54857. this._lastX = this._lastY = null;
  54858. if (payload.from !== this.uid) {
  54859. this._hide(makeDispatchAction$1(payload, api));
  54860. }
  54861. },
  54862. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  54863. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  54864. // and tooltip.
  54865. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  54866. var seriesIndex = payload.seriesIndex;
  54867. var dataIndex = payload.dataIndex;
  54868. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  54869. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  54870. return;
  54871. }
  54872. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  54873. if (!seriesModel) {
  54874. return;
  54875. }
  54876. var data = seriesModel.getData();
  54877. var tooltipModel = buildTooltipModel([
  54878. data.getItemModel(dataIndex),
  54879. seriesModel,
  54880. (seriesModel.coordinateSystem || {}).model,
  54881. tooltipModel
  54882. ]);
  54883. if (tooltipModel.get('trigger') !== 'axis') {
  54884. return;
  54885. }
  54886. api.dispatchAction({
  54887. type: 'updateAxisPointer',
  54888. seriesIndex: seriesIndex,
  54889. dataIndex: dataIndex,
  54890. position: payload.position
  54891. });
  54892. return true;
  54893. },
  54894. _tryShow: function (e, dispatchAction) {
  54895. var el = e.target;
  54896. var tooltipModel = this._tooltipModel;
  54897. if (!tooltipModel) {
  54898. return;
  54899. }
  54900. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  54901. this._lastX = e.offsetX;
  54902. this._lastY = e.offsetY;
  54903. var dataByCoordSys = e.dataByCoordSys;
  54904. if (dataByCoordSys && dataByCoordSys.length) {
  54905. this._showAxisTooltip(dataByCoordSys, e);
  54906. }
  54907. // Always show item tooltip if mouse is on the element with dataIndex
  54908. else if (el && el.dataIndex != null) {
  54909. this._lastDataByCoordSys = null;
  54910. this._showSeriesItemTooltip(e, el, dispatchAction);
  54911. }
  54912. // Tooltip provided directly. Like legend.
  54913. else if (el && el.tooltip) {
  54914. this._lastDataByCoordSys = null;
  54915. this._showComponentItemTooltip(e, el, dispatchAction);
  54916. }
  54917. else {
  54918. this._lastDataByCoordSys = null;
  54919. this._hide(dispatchAction);
  54920. }
  54921. },
  54922. _showOrMove: function (tooltipModel, cb) {
  54923. // showDelay is used in this case: tooltip.enterable is set
  54924. // as true. User intent to move mouse into tooltip and click
  54925. // something. `showDelay` makes it easyer to enter the content
  54926. // but tooltip do not move immediately.
  54927. var delay = tooltipModel.get('showDelay');
  54928. cb = bind(cb, this);
  54929. clearTimeout(this._showTimout);
  54930. delay > 0
  54931. ? (this._showTimout = setTimeout(cb, delay))
  54932. : cb();
  54933. },
  54934. _showAxisTooltip: function (dataByCoordSys, e) {
  54935. var ecModel = this._ecModel;
  54936. var globalTooltipModel = this._tooltipModel;
  54937. var point = [e.offsetX, e.offsetY];
  54938. var singleDefaultHTML = [];
  54939. var singleParamsList = [];
  54940. var singleTooltipModel = buildTooltipModel([
  54941. e.tooltipOption,
  54942. globalTooltipModel
  54943. ]);
  54944. each$18(dataByCoordSys, function (itemCoordSys) {
  54945. // var coordParamList = [];
  54946. // var coordDefaultHTML = [];
  54947. // var coordTooltipModel = buildTooltipModel([
  54948. // e.tooltipOption,
  54949. // itemCoordSys.tooltipOption,
  54950. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  54951. // globalTooltipModel
  54952. // ]);
  54953. // var displayMode = coordTooltipModel.get('displayMode');
  54954. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  54955. each$18(itemCoordSys.dataByAxis, function (item) {
  54956. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  54957. var axisValue = item.value;
  54958. var seriesDefaultHTML = [];
  54959. if (!axisModel || axisValue == null) {
  54960. return;
  54961. }
  54962. var valueLabel = getValueLabel(
  54963. axisValue, axisModel.axis, ecModel,
  54964. item.seriesDataIndices,
  54965. item.valueLabelOpt
  54966. );
  54967. each$1(item.seriesDataIndices, function (idxItem) {
  54968. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  54969. var dataIndex = idxItem.dataIndexInside;
  54970. var dataParams = series && series.getDataParams(dataIndex);
  54971. dataParams.axisDim = item.axisDim;
  54972. dataParams.axisIndex = item.axisIndex;
  54973. dataParams.axisType = item.axisType;
  54974. dataParams.axisId = item.axisId;
  54975. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  54976. dataParams.axisValueLabel = valueLabel;
  54977. if (dataParams) {
  54978. singleParamsList.push(dataParams);
  54979. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  54980. }
  54981. });
  54982. // Default tooltip content
  54983. // FIXME
  54984. // (1) shold be the first data which has name?
  54985. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  54986. var firstLine = valueLabel;
  54987. singleDefaultHTML.push(
  54988. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  54989. + seriesDefaultHTML.join('<br />')
  54990. );
  54991. });
  54992. }, this);
  54993. // In most case, the second axis is shown upper than the first one.
  54994. singleDefaultHTML.reverse();
  54995. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  54996. var positionExpr = e.position;
  54997. this._showOrMove(singleTooltipModel, function () {
  54998. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  54999. this._updatePosition(
  55000. singleTooltipModel,
  55001. positionExpr,
  55002. point[0], point[1],
  55003. this._tooltipContent,
  55004. singleParamsList
  55005. );
  55006. }
  55007. else {
  55008. this._showTooltipContent(
  55009. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  55010. point[0], point[1], positionExpr
  55011. );
  55012. }
  55013. });
  55014. // Do not trigger events here, because this branch only be entered
  55015. // from dispatchAction.
  55016. },
  55017. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  55018. var ecModel = this._ecModel;
  55019. // Use dataModel in element if possible
  55020. // Used when mouseover on a element like markPoint or edge
  55021. // In which case, the data is not main data in series.
  55022. var seriesIndex = el.seriesIndex;
  55023. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  55024. // For example, graph link.
  55025. var dataModel = el.dataModel || seriesModel;
  55026. var dataIndex = el.dataIndex;
  55027. var dataType = el.dataType;
  55028. var data = dataModel.getData();
  55029. var tooltipModel = buildTooltipModel([
  55030. data.getItemModel(dataIndex),
  55031. dataModel,
  55032. seriesModel && (seriesModel.coordinateSystem || {}).model,
  55033. this._tooltipModel
  55034. ]);
  55035. var tooltipTrigger = tooltipModel.get('trigger');
  55036. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  55037. return;
  55038. }
  55039. var params = dataModel.getDataParams(dataIndex, dataType);
  55040. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  55041. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  55042. this._showOrMove(tooltipModel, function () {
  55043. this._showTooltipContent(
  55044. tooltipModel, defaultHtml, params, asyncTicket,
  55045. e.offsetX, e.offsetY, e.position, e.target
  55046. );
  55047. });
  55048. // FIXME
  55049. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  55050. dispatchAction({
  55051. type: 'showTip',
  55052. dataIndexInside: dataIndex,
  55053. dataIndex: data.getRawIndex(dataIndex),
  55054. seriesIndex: seriesIndex,
  55055. from: this.uid
  55056. });
  55057. },
  55058. _showComponentItemTooltip: function (e, el, dispatchAction) {
  55059. var tooltipOpt = el.tooltip;
  55060. if (typeof tooltipOpt === 'string') {
  55061. var content = tooltipOpt;
  55062. tooltipOpt = {
  55063. content: content,
  55064. // Fixed formatter
  55065. formatter: content
  55066. };
  55067. }
  55068. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  55069. var defaultHtml = subTooltipModel.get('content');
  55070. var asyncTicket = Math.random();
  55071. // Do not check whether `trigger` is 'none' here, because `trigger`
  55072. // only works on cooridinate system. In fact, we have not found case
  55073. // that requires setting `trigger` nothing on component yet.
  55074. this._showOrMove(subTooltipModel, function () {
  55075. this._showTooltipContent(
  55076. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  55077. asyncTicket, e.offsetX, e.offsetY, e.position, el
  55078. );
  55079. });
  55080. // If not dispatch showTip, tip may be hide triggered by axis.
  55081. dispatchAction({
  55082. type: 'showTip',
  55083. from: this.uid
  55084. });
  55085. },
  55086. _showTooltipContent: function (
  55087. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  55088. ) {
  55089. // Reset ticket
  55090. this._ticket = '';
  55091. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  55092. return;
  55093. }
  55094. var tooltipContent = this._tooltipContent;
  55095. var formatter = tooltipModel.get('formatter');
  55096. positionExpr = positionExpr || tooltipModel.get('position');
  55097. var html = defaultHtml;
  55098. if (formatter && typeof formatter === 'string') {
  55099. html = formatTpl(formatter, params, true);
  55100. }
  55101. else if (typeof formatter === 'function') {
  55102. var callback = bind$3(function (cbTicket, html) {
  55103. if (cbTicket === this._ticket) {
  55104. tooltipContent.setContent(html);
  55105. this._updatePosition(
  55106. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  55107. );
  55108. }
  55109. }, this);
  55110. this._ticket = asyncTicket;
  55111. html = formatter(params, asyncTicket, callback);
  55112. }
  55113. tooltipContent.setContent(html);
  55114. tooltipContent.show(tooltipModel);
  55115. this._updatePosition(
  55116. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  55117. );
  55118. },
  55119. /**
  55120. * @param {string|Function|Array.<number>|Object} positionExpr
  55121. * @param {number} x Mouse x
  55122. * @param {number} y Mouse y
  55123. * @param {boolean} confine Whether confine tooltip content in view rect.
  55124. * @param {Object|<Array.<Object>} params
  55125. * @param {module:zrender/Element} el target element
  55126. * @param {module:echarts/ExtensionAPI} api
  55127. * @return {Array.<number>}
  55128. */
  55129. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  55130. var viewWidth = this._api.getWidth();
  55131. var viewHeight = this._api.getHeight();
  55132. positionExpr = positionExpr || tooltipModel.get('position');
  55133. var contentSize = content.getSize();
  55134. var align = tooltipModel.get('align');
  55135. var vAlign = tooltipModel.get('verticalAlign');
  55136. var rect = el && el.getBoundingRect().clone();
  55137. el && rect.applyTransform(el.transform);
  55138. if (typeof positionExpr === 'function') {
  55139. // Callback of position can be an array or a string specify the position
  55140. positionExpr = positionExpr([x, y], params, content.el, rect, {
  55141. viewSize: [viewWidth, viewHeight],
  55142. contentSize: contentSize.slice()
  55143. });
  55144. }
  55145. if (isArray(positionExpr)) {
  55146. x = parsePercent$2(positionExpr[0], viewWidth);
  55147. y = parsePercent$2(positionExpr[1], viewHeight);
  55148. }
  55149. else if (isObject$1(positionExpr)) {
  55150. positionExpr.width = contentSize[0];
  55151. positionExpr.height = contentSize[1];
  55152. var layoutRect = getLayoutRect(
  55153. positionExpr, {width: viewWidth, height: viewHeight}
  55154. );
  55155. x = layoutRect.x;
  55156. y = layoutRect.y;
  55157. align = null;
  55158. // When positionExpr is left/top/right/bottom,
  55159. // align and verticalAlign will not work.
  55160. vAlign = null;
  55161. }
  55162. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  55163. else if (typeof positionExpr === 'string' && el) {
  55164. var pos = calcTooltipPosition(
  55165. positionExpr, rect, contentSize
  55166. );
  55167. x = pos[0];
  55168. y = pos[1];
  55169. }
  55170. else {
  55171. var pos = refixTooltipPosition(
  55172. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  55173. );
  55174. x = pos[0];
  55175. y = pos[1];
  55176. }
  55177. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  55178. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  55179. if (tooltipModel.get('confine')) {
  55180. var pos = confineTooltipPosition(
  55181. x, y, content.el, viewWidth, viewHeight
  55182. );
  55183. x = pos[0];
  55184. y = pos[1];
  55185. }
  55186. content.moveTo(x, y);
  55187. },
  55188. // FIXME
  55189. // Should we remove this but leave this to user?
  55190. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  55191. var lastCoordSys = this._lastDataByCoordSys;
  55192. var contentNotChanged = !!lastCoordSys
  55193. && lastCoordSys.length === dataByCoordSys.length;
  55194. contentNotChanged && each$18(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  55195. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  55196. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  55197. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  55198. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  55199. contentNotChanged && each$18(lastDataByAxis, function (lastItem, indexAxis) {
  55200. var thisItem = thisDataByAxis[indexAxis] || {};
  55201. var lastIndices = lastItem.seriesDataIndices || [];
  55202. var newIndices = thisItem.seriesDataIndices || [];
  55203. contentNotChanged &=
  55204. lastItem.value === thisItem.value
  55205. && lastItem.axisType === thisItem.axisType
  55206. && lastItem.axisId === thisItem.axisId
  55207. && lastIndices.length === newIndices.length;
  55208. contentNotChanged && each$18(lastIndices, function (lastIdxItem, j) {
  55209. var newIdxItem = newIndices[j];
  55210. contentNotChanged &=
  55211. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  55212. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  55213. });
  55214. });
  55215. });
  55216. this._lastDataByCoordSys = dataByCoordSys;
  55217. return !!contentNotChanged;
  55218. },
  55219. _hide: function (dispatchAction) {
  55220. // Do not directly hideLater here, because this behavior may be prevented
  55221. // in dispatchAction when showTip is dispatched.
  55222. // FIXME
  55223. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  55224. this._lastDataByCoordSys = null;
  55225. dispatchAction({
  55226. type: 'hideTip',
  55227. from: this.uid
  55228. });
  55229. },
  55230. dispose: function (ecModel, api) {
  55231. if (env$1.node) {
  55232. return;
  55233. }
  55234. this._tooltipContent.hide();
  55235. unregister('itemTooltip', api);
  55236. }
  55237. });
  55238. /**
  55239. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  55240. * From top to bottom. (the last one should be globalTooltipModel);
  55241. */
  55242. function buildTooltipModel(modelCascade) {
  55243. var resultModel = modelCascade.pop();
  55244. while (modelCascade.length) {
  55245. var tooltipOpt = modelCascade.pop();
  55246. if (tooltipOpt) {
  55247. if (Model.isInstance(tooltipOpt)) {
  55248. tooltipOpt = tooltipOpt.get('tooltip', true);
  55249. }
  55250. // In each data item tooltip can be simply write:
  55251. // {
  55252. // value: 10,
  55253. // tooltip: 'Something you need to know'
  55254. // }
  55255. if (typeof tooltipOpt === 'string') {
  55256. tooltipOpt = {formatter: tooltipOpt};
  55257. }
  55258. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  55259. }
  55260. }
  55261. return resultModel;
  55262. }
  55263. function makeDispatchAction$1(payload, api) {
  55264. return payload.dispatchAction || bind(api.dispatchAction, api);
  55265. }
  55266. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  55267. var size = getOuterSize(el);
  55268. var width = size.width;
  55269. var height = size.height;
  55270. if (gapH != null) {
  55271. if (x + width + gapH > viewWidth) {
  55272. x -= width + gapH;
  55273. }
  55274. else {
  55275. x += gapH;
  55276. }
  55277. }
  55278. if (gapV != null) {
  55279. if (y + height + gapV > viewHeight) {
  55280. y -= height + gapV;
  55281. }
  55282. else {
  55283. y += gapV;
  55284. }
  55285. }
  55286. return [x, y];
  55287. }
  55288. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  55289. var size = getOuterSize(el);
  55290. var width = size.width;
  55291. var height = size.height;
  55292. x = Math.min(x + width, viewWidth) - width;
  55293. y = Math.min(y + height, viewHeight) - height;
  55294. x = Math.max(x, 0);
  55295. y = Math.max(y, 0);
  55296. return [x, y];
  55297. }
  55298. function getOuterSize(el) {
  55299. var width = el.clientWidth;
  55300. var height = el.clientHeight;
  55301. // Consider browser compatibility.
  55302. // IE8 does not support getComputedStyle.
  55303. if (document.defaultView && document.defaultView.getComputedStyle) {
  55304. var stl = document.defaultView.getComputedStyle(el);
  55305. if (stl) {
  55306. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  55307. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  55308. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  55309. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  55310. }
  55311. }
  55312. return {width: width, height: height};
  55313. }
  55314. function calcTooltipPosition(position, rect, contentSize) {
  55315. var domWidth = contentSize[0];
  55316. var domHeight = contentSize[1];
  55317. var gap = 5;
  55318. var x = 0;
  55319. var y = 0;
  55320. var rectWidth = rect.width;
  55321. var rectHeight = rect.height;
  55322. switch (position) {
  55323. case 'inside':
  55324. x = rect.x + rectWidth / 2 - domWidth / 2;
  55325. y = rect.y + rectHeight / 2 - domHeight / 2;
  55326. break;
  55327. case 'top':
  55328. x = rect.x + rectWidth / 2 - domWidth / 2;
  55329. y = rect.y - domHeight - gap;
  55330. break;
  55331. case 'bottom':
  55332. x = rect.x + rectWidth / 2 - domWidth / 2;
  55333. y = rect.y + rectHeight + gap;
  55334. break;
  55335. case 'left':
  55336. x = rect.x - domWidth - gap;
  55337. y = rect.y + rectHeight / 2 - domHeight / 2;
  55338. break;
  55339. case 'right':
  55340. x = rect.x + rectWidth + gap;
  55341. y = rect.y + rectHeight / 2 - domHeight / 2;
  55342. }
  55343. return [x, y];
  55344. }
  55345. function isCenterAlign(align) {
  55346. return align === 'center' || align === 'middle';
  55347. }
  55348. // FIXME Better way to pack data in graphic element
  55349. /**
  55350. * @action
  55351. * @property {string} type
  55352. * @property {number} seriesIndex
  55353. * @property {number} dataIndex
  55354. * @property {number} [x]
  55355. * @property {number} [y]
  55356. */
  55357. registerAction(
  55358. {
  55359. type: 'showTip',
  55360. event: 'showTip',
  55361. update: 'tooltip:manuallyShowTip'
  55362. },
  55363. // noop
  55364. function () {}
  55365. );
  55366. registerAction(
  55367. {
  55368. type: 'hideTip',
  55369. event: 'hideTip',
  55370. update: 'tooltip:manuallyHideTip'
  55371. },
  55372. // noop
  55373. function () {}
  55374. );
  55375. function getSeriesStackId$1(seriesModel) {
  55376. return seriesModel.get('stack')
  55377. || '__ec_stack_' + seriesModel.seriesIndex;
  55378. }
  55379. function getAxisKey$1(axis) {
  55380. return axis.dim;
  55381. }
  55382. /**
  55383. * @param {string} seriesType
  55384. * @param {module:echarts/model/Global} ecModel
  55385. * @param {module:echarts/ExtensionAPI} api
  55386. */
  55387. function barLayoutPolar(seriesType, ecModel, api) {
  55388. var width = api.getWidth();
  55389. var height = api.getHeight();
  55390. var lastStackCoords = {};
  55391. var barWidthAndOffset = calRadialBar(
  55392. filter(
  55393. ecModel.getSeriesByType(seriesType),
  55394. function (seriesModel) {
  55395. return !ecModel.isSeriesFiltered(seriesModel)
  55396. && seriesModel.coordinateSystem
  55397. && seriesModel.coordinateSystem.type === 'polar';
  55398. }
  55399. )
  55400. );
  55401. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  55402. // Check series coordinate, do layout for polar only
  55403. if (seriesModel.coordinateSystem.type !== 'polar') {
  55404. return;
  55405. }
  55406. var data = seriesModel.getData();
  55407. var polar = seriesModel.coordinateSystem;
  55408. var baseAxis = polar.getBaseAxis();
  55409. var stackId = getSeriesStackId$1(seriesModel);
  55410. var columnLayoutInfo
  55411. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  55412. var columnOffset = columnLayoutInfo.offset;
  55413. var columnWidth = columnLayoutInfo.width;
  55414. var valueAxis = polar.getOtherAxis(baseAxis);
  55415. var center = seriesModel.get('center') || ['50%', '50%'];
  55416. var cx = parsePercent$1(center[0], width);
  55417. var cy = parsePercent$1(center[1], height);
  55418. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  55419. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  55420. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  55421. var valueDim = data.mapDimension(valueAxis.dim);
  55422. var baseDim = data.mapDimension(baseAxis.dim);
  55423. var stacked = isDimensionStacked(data, valueDim, baseDim);
  55424. var valueAxisStart = valueAxis.getExtent()[0];
  55425. for (var idx = 0, len = data.count(); idx < len; idx++) {
  55426. var value = data.get(valueDim, idx);
  55427. var baseValue = data.get(baseDim, idx);
  55428. if (isNaN(value)) {
  55429. continue;
  55430. }
  55431. var sign = value >= 0 ? 'p' : 'n';
  55432. var baseCoord = valueAxisStart;
  55433. // Because of the barMinHeight, we can not use the value in
  55434. // stackResultDimension directly.
  55435. // Only ordinal axis can be stacked.
  55436. if (stacked) {
  55437. if (!lastStackCoords[stackId][baseValue]) {
  55438. lastStackCoords[stackId][baseValue] = {
  55439. p: valueAxisStart, // Positive stack
  55440. n: valueAxisStart // Negative stack
  55441. };
  55442. }
  55443. // Should also consider #4243
  55444. baseCoord = lastStackCoords[stackId][baseValue][sign];
  55445. }
  55446. var r0;
  55447. var r;
  55448. var startAngle;
  55449. var endAngle;
  55450. // radial sector
  55451. if (valueAxis.dim === 'radius') {
  55452. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  55453. var angle = baseAxis.dataToAngle(baseValue);
  55454. if (Math.abs(radiusSpan) < barMinHeight) {
  55455. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  55456. }
  55457. r0 = baseCoord;
  55458. r = baseCoord + radiusSpan;
  55459. startAngle = angle - columnOffset;
  55460. endAngle = startAngle - columnWidth;
  55461. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  55462. }
  55463. // tangential sector
  55464. else {
  55465. // angleAxis must be clamped.
  55466. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  55467. var radius = baseAxis.dataToRadius(baseValue);
  55468. if (Math.abs(angleSpan) < barMinAngle) {
  55469. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  55470. }
  55471. r0 = radius + columnOffset;
  55472. r = r0 + columnWidth;
  55473. startAngle = baseCoord;
  55474. endAngle = baseCoord + angleSpan;
  55475. // if the previous stack is at the end of the ring,
  55476. // add a round to differentiate it from origin
  55477. // var extent = angleAxis.getExtent();
  55478. // var stackCoord = angle;
  55479. // if (stackCoord === extent[0] && value > 0) {
  55480. // stackCoord = extent[1];
  55481. // }
  55482. // else if (stackCoord === extent[1] && value < 0) {
  55483. // stackCoord = extent[0];
  55484. // }
  55485. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  55486. }
  55487. data.setItemLayout(idx, {
  55488. cx: cx,
  55489. cy: cy,
  55490. r0: r0,
  55491. r: r,
  55492. // Consider that positive angle is anti-clockwise,
  55493. // while positive radian of sector is clockwise
  55494. startAngle: -startAngle * Math.PI / 180,
  55495. endAngle: -endAngle * Math.PI / 180
  55496. });
  55497. }
  55498. }, this);
  55499. }
  55500. /**
  55501. * Calculate bar width and offset for radial bar charts
  55502. */
  55503. function calRadialBar(barSeries, api) {
  55504. // Columns info on each category axis. Key is polar name
  55505. var columnsMap = {};
  55506. each$1(barSeries, function (seriesModel, idx) {
  55507. var data = seriesModel.getData();
  55508. var polar = seriesModel.coordinateSystem;
  55509. var baseAxis = polar.getBaseAxis();
  55510. var axisExtent = baseAxis.getExtent();
  55511. var bandWidth = baseAxis.type === 'category'
  55512. ? baseAxis.getBandWidth()
  55513. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  55514. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  55515. bandWidth: bandWidth,
  55516. remainedWidth: bandWidth,
  55517. autoWidthCount: 0,
  55518. categoryGap: '20%',
  55519. gap: '30%',
  55520. stacks: {}
  55521. };
  55522. var stacks = columnsOnAxis.stacks;
  55523. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  55524. var stackId = getSeriesStackId$1(seriesModel);
  55525. if (!stacks[stackId]) {
  55526. columnsOnAxis.autoWidthCount++;
  55527. }
  55528. stacks[stackId] = stacks[stackId] || {
  55529. width: 0,
  55530. maxWidth: 0
  55531. };
  55532. var barWidth = parsePercent$1(
  55533. seriesModel.get('barWidth'),
  55534. bandWidth
  55535. );
  55536. var barMaxWidth = parsePercent$1(
  55537. seriesModel.get('barMaxWidth'),
  55538. bandWidth
  55539. );
  55540. var barGap = seriesModel.get('barGap');
  55541. var barCategoryGap = seriesModel.get('barCategoryGap');
  55542. if (barWidth && !stacks[stackId].width) {
  55543. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  55544. stacks[stackId].width = barWidth;
  55545. columnsOnAxis.remainedWidth -= barWidth;
  55546. }
  55547. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  55548. (barGap != null) && (columnsOnAxis.gap = barGap);
  55549. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  55550. });
  55551. var result = {};
  55552. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  55553. result[coordSysName] = {};
  55554. var stacks = columnsOnAxis.stacks;
  55555. var bandWidth = columnsOnAxis.bandWidth;
  55556. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  55557. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  55558. var remainedWidth = columnsOnAxis.remainedWidth;
  55559. var autoWidthCount = columnsOnAxis.autoWidthCount;
  55560. var autoWidth = (remainedWidth - categoryGap)
  55561. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  55562. autoWidth = Math.max(autoWidth, 0);
  55563. // Find if any auto calculated bar exceeded maxBarWidth
  55564. each$1(stacks, function (column, stack) {
  55565. var maxWidth = column.maxWidth;
  55566. if (maxWidth && maxWidth < autoWidth) {
  55567. maxWidth = Math.min(maxWidth, remainedWidth);
  55568. if (column.width) {
  55569. maxWidth = Math.min(maxWidth, column.width);
  55570. }
  55571. remainedWidth -= maxWidth;
  55572. column.width = maxWidth;
  55573. autoWidthCount--;
  55574. }
  55575. });
  55576. // Recalculate width again
  55577. autoWidth = (remainedWidth - categoryGap)
  55578. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  55579. autoWidth = Math.max(autoWidth, 0);
  55580. var widthSum = 0;
  55581. var lastColumn;
  55582. each$1(stacks, function (column, idx) {
  55583. if (!column.width) {
  55584. column.width = autoWidth;
  55585. }
  55586. lastColumn = column;
  55587. widthSum += column.width * (1 + barGapPercent);
  55588. });
  55589. if (lastColumn) {
  55590. widthSum -= lastColumn.width * barGapPercent;
  55591. }
  55592. var offset = -widthSum / 2;
  55593. each$1(stacks, function (column, stackId) {
  55594. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  55595. offset: offset,
  55596. width: column.width
  55597. };
  55598. offset += column.width * (1 + barGapPercent);
  55599. });
  55600. });
  55601. return result;
  55602. }
  55603. function RadiusAxis(scale, radiusExtent) {
  55604. Axis.call(this, 'radius', scale, radiusExtent);
  55605. /**
  55606. * Axis type
  55607. * - 'category'
  55608. * - 'value'
  55609. * - 'time'
  55610. * - 'log'
  55611. * @type {string}
  55612. */
  55613. this.type = 'category';
  55614. }
  55615. RadiusAxis.prototype = {
  55616. constructor: RadiusAxis,
  55617. /**
  55618. * @override
  55619. */
  55620. pointToData: function (point, clamp) {
  55621. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  55622. },
  55623. dataToRadius: Axis.prototype.dataToCoord,
  55624. radiusToData: Axis.prototype.coordToData
  55625. };
  55626. inherits(RadiusAxis, Axis);
  55627. function AngleAxis(scale, angleExtent) {
  55628. angleExtent = angleExtent || [0, 360];
  55629. Axis.call(this, 'angle', scale, angleExtent);
  55630. /**
  55631. * Axis type
  55632. * - 'category'
  55633. * - 'value'
  55634. * - 'time'
  55635. * - 'log'
  55636. * @type {string}
  55637. */
  55638. this.type = 'category';
  55639. }
  55640. AngleAxis.prototype = {
  55641. constructor: AngleAxis,
  55642. /**
  55643. * @override
  55644. */
  55645. pointToData: function (point, clamp) {
  55646. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  55647. },
  55648. dataToAngle: Axis.prototype.dataToCoord,
  55649. angleToData: Axis.prototype.coordToData
  55650. };
  55651. inherits(AngleAxis, Axis);
  55652. /**
  55653. * @module echarts/coord/polar/Polar
  55654. */
  55655. /**
  55656. * @alias {module:echarts/coord/polar/Polar}
  55657. * @constructor
  55658. * @param {string} name
  55659. */
  55660. var Polar = function (name) {
  55661. /**
  55662. * @type {string}
  55663. */
  55664. this.name = name || '';
  55665. /**
  55666. * x of polar center
  55667. * @type {number}
  55668. */
  55669. this.cx = 0;
  55670. /**
  55671. * y of polar center
  55672. * @type {number}
  55673. */
  55674. this.cy = 0;
  55675. /**
  55676. * @type {module:echarts/coord/polar/RadiusAxis}
  55677. * @private
  55678. */
  55679. this._radiusAxis = new RadiusAxis();
  55680. /**
  55681. * @type {module:echarts/coord/polar/AngleAxis}
  55682. * @private
  55683. */
  55684. this._angleAxis = new AngleAxis();
  55685. this._radiusAxis.polar = this._angleAxis.polar = this;
  55686. };
  55687. Polar.prototype = {
  55688. type: 'polar',
  55689. axisPointerEnabled: true,
  55690. constructor: Polar,
  55691. /**
  55692. * @param {Array.<string>}
  55693. * @readOnly
  55694. */
  55695. dimensions: ['radius', 'angle'],
  55696. /**
  55697. * @type {module:echarts/coord/PolarModel}
  55698. */
  55699. model: null,
  55700. /**
  55701. * If contain coord
  55702. * @param {Array.<number>} point
  55703. * @return {boolean}
  55704. */
  55705. containPoint: function (point) {
  55706. var coord = this.pointToCoord(point);
  55707. return this._radiusAxis.contain(coord[0])
  55708. && this._angleAxis.contain(coord[1]);
  55709. },
  55710. /**
  55711. * If contain data
  55712. * @param {Array.<number>} data
  55713. * @return {boolean}
  55714. */
  55715. containData: function (data) {
  55716. return this._radiusAxis.containData(data[0])
  55717. && this._angleAxis.containData(data[1]);
  55718. },
  55719. /**
  55720. * @param {string} dim
  55721. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55722. */
  55723. getAxis: function (dim) {
  55724. return this['_' + dim + 'Axis'];
  55725. },
  55726. /**
  55727. * @return {Array.<module:echarts/coord/Axis>}
  55728. */
  55729. getAxes: function () {
  55730. return [this._radiusAxis, this._angleAxis];
  55731. },
  55732. /**
  55733. * Get axes by type of scale
  55734. * @param {string} scaleType
  55735. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55736. */
  55737. getAxesByScale: function (scaleType) {
  55738. var axes = [];
  55739. var angleAxis = this._angleAxis;
  55740. var radiusAxis = this._radiusAxis;
  55741. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  55742. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  55743. return axes;
  55744. },
  55745. /**
  55746. * @return {module:echarts/coord/polar/AngleAxis}
  55747. */
  55748. getAngleAxis: function () {
  55749. return this._angleAxis;
  55750. },
  55751. /**
  55752. * @return {module:echarts/coord/polar/RadiusAxis}
  55753. */
  55754. getRadiusAxis: function () {
  55755. return this._radiusAxis;
  55756. },
  55757. /**
  55758. * @param {module:echarts/coord/polar/Axis}
  55759. * @return {module:echarts/coord/polar/Axis}
  55760. */
  55761. getOtherAxis: function (axis) {
  55762. var angleAxis = this._angleAxis;
  55763. return axis === angleAxis ? this._radiusAxis : angleAxis;
  55764. },
  55765. /**
  55766. * Base axis will be used on stacking.
  55767. *
  55768. * @return {module:echarts/coord/polar/Axis}
  55769. */
  55770. getBaseAxis: function () {
  55771. return this.getAxesByScale('ordinal')[0]
  55772. || this.getAxesByScale('time')[0]
  55773. || this.getAngleAxis();
  55774. },
  55775. /**
  55776. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  55777. * @return {Object} {baseAxes: [], otherAxes: []}
  55778. */
  55779. getTooltipAxes: function (dim) {
  55780. var baseAxis = (dim != null && dim !== 'auto')
  55781. ? this.getAxis(dim) : this.getBaseAxis();
  55782. return {
  55783. baseAxes: [baseAxis],
  55784. otherAxes: [this.getOtherAxis(baseAxis)]
  55785. };
  55786. },
  55787. /**
  55788. * Convert a single data item to (x, y) point.
  55789. * Parameter data is an array which the first element is radius and the second is angle
  55790. * @param {Array.<number>} data
  55791. * @param {boolean} [clamp=false]
  55792. * @return {Array.<number>}
  55793. */
  55794. dataToPoint: function (data, clamp) {
  55795. return this.coordToPoint([
  55796. this._radiusAxis.dataToRadius(data[0], clamp),
  55797. this._angleAxis.dataToAngle(data[1], clamp)
  55798. ]);
  55799. },
  55800. /**
  55801. * Convert a (x, y) point to data
  55802. * @param {Array.<number>} point
  55803. * @param {boolean} [clamp=false]
  55804. * @return {Array.<number>}
  55805. */
  55806. pointToData: function (point, clamp) {
  55807. var coord = this.pointToCoord(point);
  55808. return [
  55809. this._radiusAxis.radiusToData(coord[0], clamp),
  55810. this._angleAxis.angleToData(coord[1], clamp)
  55811. ];
  55812. },
  55813. /**
  55814. * Convert a (x, y) point to (radius, angle) coord
  55815. * @param {Array.<number>} point
  55816. * @return {Array.<number>}
  55817. */
  55818. pointToCoord: function (point) {
  55819. var dx = point[0] - this.cx;
  55820. var dy = point[1] - this.cy;
  55821. var angleAxis = this.getAngleAxis();
  55822. var extent = angleAxis.getExtent();
  55823. var minAngle = Math.min(extent[0], extent[1]);
  55824. var maxAngle = Math.max(extent[0], extent[1]);
  55825. // Fix fixed extent in polarCreator
  55826. // FIXME
  55827. angleAxis.inverse
  55828. ? (minAngle = maxAngle - 360)
  55829. : (maxAngle = minAngle + 360);
  55830. var radius = Math.sqrt(dx * dx + dy * dy);
  55831. dx /= radius;
  55832. dy /= radius;
  55833. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  55834. // move to angleExtent
  55835. var dir = radian < minAngle ? 1 : -1;
  55836. while (radian < minAngle || radian > maxAngle) {
  55837. radian += dir * 360;
  55838. }
  55839. return [radius, radian];
  55840. },
  55841. /**
  55842. * Convert a (radius, angle) coord to (x, y) point
  55843. * @param {Array.<number>} coord
  55844. * @return {Array.<number>}
  55845. */
  55846. coordToPoint: function (coord) {
  55847. var radius = coord[0];
  55848. var radian = coord[1] / 180 * Math.PI;
  55849. var x = Math.cos(radian) * radius + this.cx;
  55850. // Inverse the y
  55851. var y = -Math.sin(radian) * radius + this.cy;
  55852. return [x, y];
  55853. }
  55854. };
  55855. var PolarAxisModel = ComponentModel.extend({
  55856. type: 'polarAxis',
  55857. /**
  55858. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55859. */
  55860. axis: null,
  55861. /**
  55862. * @override
  55863. */
  55864. getCoordSysModel: function () {
  55865. return this.ecModel.queryComponents({
  55866. mainType: 'polar',
  55867. index: this.option.polarIndex,
  55868. id: this.option.polarId
  55869. })[0];
  55870. }
  55871. });
  55872. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  55873. var polarAxisDefaultExtendedOption = {
  55874. angle: {
  55875. // polarIndex: 0,
  55876. // polarId: '',
  55877. startAngle: 90,
  55878. clockwise: true,
  55879. splitNumber: 12,
  55880. axisLabel: {
  55881. rotate: false
  55882. }
  55883. },
  55884. radius: {
  55885. // polarIndex: 0,
  55886. // polarId: '',
  55887. splitNumber: 5
  55888. }
  55889. };
  55890. function getAxisType$3(axisDim, option) {
  55891. // Default axis with data is category axis
  55892. return option.type || (option.data ? 'category' : 'value');
  55893. }
  55894. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  55895. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  55896. extendComponentModel({
  55897. type: 'polar',
  55898. dependencies: ['polarAxis', 'angleAxis'],
  55899. /**
  55900. * @type {module:echarts/coord/polar/Polar}
  55901. */
  55902. coordinateSystem: null,
  55903. /**
  55904. * @param {string} axisType
  55905. * @return {module:echarts/coord/polar/AxisModel}
  55906. */
  55907. findAxisModel: function (axisType) {
  55908. var foundAxisModel;
  55909. var ecModel = this.ecModel;
  55910. ecModel.eachComponent(axisType, function (axisModel) {
  55911. if (axisModel.getCoordSysModel() === this) {
  55912. foundAxisModel = axisModel;
  55913. }
  55914. }, this);
  55915. return foundAxisModel;
  55916. },
  55917. defaultOption: {
  55918. zlevel: 0,
  55919. z: 0,
  55920. center: ['50%', '50%'],
  55921. radius: '80%'
  55922. }
  55923. });
  55924. // TODO Axis scale
  55925. // 依赖 PolarModel 做预处理
  55926. /**
  55927. * Resize method bound to the polar
  55928. * @param {module:echarts/coord/polar/PolarModel} polarModel
  55929. * @param {module:echarts/ExtensionAPI} api
  55930. */
  55931. function resizePolar(polar, polarModel, api) {
  55932. var center = polarModel.get('center');
  55933. var width = api.getWidth();
  55934. var height = api.getHeight();
  55935. polar.cx = parsePercent$1(center[0], width);
  55936. polar.cy = parsePercent$1(center[1], height);
  55937. var radiusAxis = polar.getRadiusAxis();
  55938. var size = Math.min(width, height) / 2;
  55939. var radius = parsePercent$1(polarModel.get('radius'), size);
  55940. radiusAxis.inverse
  55941. ? radiusAxis.setExtent(radius, 0)
  55942. : radiusAxis.setExtent(0, radius);
  55943. }
  55944. /**
  55945. * Update polar
  55946. */
  55947. function updatePolarScale(ecModel, api) {
  55948. var polar = this;
  55949. var angleAxis = polar.getAngleAxis();
  55950. var radiusAxis = polar.getRadiusAxis();
  55951. // Reset scale
  55952. angleAxis.scale.setExtent(Infinity, -Infinity);
  55953. radiusAxis.scale.setExtent(Infinity, -Infinity);
  55954. ecModel.eachSeries(function (seriesModel) {
  55955. if (seriesModel.coordinateSystem === polar) {
  55956. var data = seriesModel.getData();
  55957. each$1(data.mapDimension('radius', true), function (dim) {
  55958. radiusAxis.scale.unionExtentFromData(data, dim);
  55959. });
  55960. each$1(data.mapDimension('angle', true), function (dim) {
  55961. angleAxis.scale.unionExtentFromData(data, dim);
  55962. });
  55963. }
  55964. });
  55965. niceScaleExtent(angleAxis.scale, angleAxis.model);
  55966. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  55967. // Fix extent of category angle axis
  55968. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  55969. var extent = angleAxis.getExtent();
  55970. var diff = 360 / angleAxis.scale.count();
  55971. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  55972. angleAxis.setExtent(extent[0], extent[1]);
  55973. }
  55974. }
  55975. /**
  55976. * Set common axis properties
  55977. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55978. * @param {module:echarts/coord/polar/AxisModel}
  55979. * @inner
  55980. */
  55981. function setAxis(axis, axisModel) {
  55982. axis.type = axisModel.get('type');
  55983. axis.scale = createScaleByModel(axisModel);
  55984. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  55985. axis.inverse = axisModel.get('inverse');
  55986. if (axisModel.mainType === 'angleAxis') {
  55987. axis.inverse ^= axisModel.get('clockwise');
  55988. var startAngle = axisModel.get('startAngle');
  55989. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  55990. }
  55991. // Inject axis instance
  55992. axisModel.axis = axis;
  55993. axis.model = axisModel;
  55994. }
  55995. var polarCreator = {
  55996. dimensions: Polar.prototype.dimensions,
  55997. create: function (ecModel, api) {
  55998. var polarList = [];
  55999. ecModel.eachComponent('polar', function (polarModel, idx) {
  56000. var polar = new Polar(idx);
  56001. // Inject resize and update method
  56002. polar.update = updatePolarScale;
  56003. var radiusAxis = polar.getRadiusAxis();
  56004. var angleAxis = polar.getAngleAxis();
  56005. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  56006. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  56007. setAxis(radiusAxis, radiusAxisModel);
  56008. setAxis(angleAxis, angleAxisModel);
  56009. resizePolar(polar, polarModel, api);
  56010. polarList.push(polar);
  56011. polarModel.coordinateSystem = polar;
  56012. polar.model = polarModel;
  56013. });
  56014. // Inject coordinateSystem to series
  56015. ecModel.eachSeries(function (seriesModel) {
  56016. if (seriesModel.get('coordinateSystem') === 'polar') {
  56017. var polarModel = ecModel.queryComponents({
  56018. mainType: 'polar',
  56019. index: seriesModel.get('polarIndex'),
  56020. id: seriesModel.get('polarId')
  56021. })[0];
  56022. if (__DEV__) {
  56023. if (!polarModel) {
  56024. throw new Error(
  56025. 'Polar "' + retrieve(
  56026. seriesModel.get('polarIndex'),
  56027. seriesModel.get('polarId'),
  56028. 0
  56029. ) + '" not found'
  56030. );
  56031. }
  56032. }
  56033. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  56034. }
  56035. });
  56036. return polarList;
  56037. }
  56038. };
  56039. CoordinateSystemManager.register('polar', polarCreator);
  56040. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  56041. function getAxisLineShape(polar, rExtent, angle) {
  56042. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  56043. var start = polar.coordToPoint([rExtent[0], angle]);
  56044. var end = polar.coordToPoint([rExtent[1], angle]);
  56045. return {
  56046. x1: start[0],
  56047. y1: start[1],
  56048. x2: end[0],
  56049. y2: end[1]
  56050. };
  56051. }
  56052. function getRadiusIdx(polar) {
  56053. var radiusAxis = polar.getRadiusAxis();
  56054. return radiusAxis.inverse ? 0 : 1;
  56055. }
  56056. AxisView.extend({
  56057. type: 'angleAxis',
  56058. axisPointerClass: 'PolarAxisPointer',
  56059. render: function (angleAxisModel, ecModel) {
  56060. this.group.removeAll();
  56061. if (!angleAxisModel.get('show')) {
  56062. return;
  56063. }
  56064. var angleAxis = angleAxisModel.axis;
  56065. var polar = angleAxis.polar;
  56066. var radiusExtent = polar.getRadiusAxis().getExtent();
  56067. var ticksAngles = angleAxis.getTicksCoords();
  56068. if (angleAxis.type !== 'category') {
  56069. // Remove the last tick which will overlap the first tick
  56070. ticksAngles.pop();
  56071. }
  56072. each$1(elementList$1, function (name) {
  56073. if (angleAxisModel.get(name +'.show')
  56074. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  56075. ) {
  56076. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent);
  56077. }
  56078. }, this);
  56079. },
  56080. /**
  56081. * @private
  56082. */
  56083. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56084. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  56085. var circle = new Circle({
  56086. shape: {
  56087. cx: polar.cx,
  56088. cy: polar.cy,
  56089. r: radiusExtent[getRadiusIdx(polar)]
  56090. },
  56091. style: lineStyleModel.getLineStyle(),
  56092. z2: 1,
  56093. silent: true
  56094. });
  56095. circle.style.fill = null;
  56096. this.group.add(circle);
  56097. },
  56098. /**
  56099. * @private
  56100. */
  56101. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56102. var tickModel = angleAxisModel.getModel('axisTick');
  56103. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  56104. var radius = radiusExtent[getRadiusIdx(polar)];
  56105. var lines = map(ticksAngles, function (tickAngle) {
  56106. return new Line({
  56107. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngle)
  56108. });
  56109. });
  56110. this.group.add(mergePath(
  56111. lines, {
  56112. style: defaults(
  56113. tickModel.getModel('lineStyle').getLineStyle(),
  56114. {
  56115. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  56116. }
  56117. )
  56118. }
  56119. ));
  56120. },
  56121. /**
  56122. * @private
  56123. */
  56124. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56125. var axis = angleAxisModel.axis;
  56126. var categoryData = angleAxisModel.getCategories();
  56127. var labelModel = angleAxisModel.getModel('axisLabel');
  56128. var labels = angleAxisModel.getFormattedLabels();
  56129. var labelMargin = labelModel.get('margin');
  56130. var labelsAngles = axis.getLabelsCoords();
  56131. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  56132. for (var i = 0; i < ticksAngles.length; i++) {
  56133. var r = radiusExtent[getRadiusIdx(polar)];
  56134. var p = polar.coordToPoint([r + labelMargin, labelsAngles[i]]);
  56135. var cx = polar.cx;
  56136. var cy = polar.cy;
  56137. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  56138. ? 'center' : (p[0] > cx ? 'left' : 'right');
  56139. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  56140. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  56141. if (categoryData && categoryData[i] && categoryData[i].textStyle) {
  56142. labelModel = new Model(categoryData[i].textStyle, labelModel, labelModel.ecModel);
  56143. }
  56144. var textEl = new Text({silent: true});
  56145. this.group.add(textEl);
  56146. setTextStyle(textEl.style, labelModel, {
  56147. x: p[0],
  56148. y: p[1],
  56149. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  56150. text: labels[i],
  56151. textAlign: labelTextAlign,
  56152. textVerticalAlign: labelTextVerticalAlign
  56153. });
  56154. }
  56155. },
  56156. /**
  56157. * @private
  56158. */
  56159. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56160. var splitLineModel = angleAxisModel.getModel('splitLine');
  56161. var lineStyleModel = splitLineModel.getModel('lineStyle');
  56162. var lineColors = lineStyleModel.get('color');
  56163. var lineCount = 0;
  56164. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  56165. var splitLines = [];
  56166. for (var i = 0; i < ticksAngles.length; i++) {
  56167. var colorIndex = (lineCount++) % lineColors.length;
  56168. splitLines[colorIndex] = splitLines[colorIndex] || [];
  56169. splitLines[colorIndex].push(new Line({
  56170. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i])
  56171. }));
  56172. }
  56173. // Simple optimization
  56174. // Batching the lines if color are the same
  56175. for (var i = 0; i < splitLines.length; i++) {
  56176. this.group.add(mergePath(splitLines[i], {
  56177. style: defaults({
  56178. stroke: lineColors[i % lineColors.length]
  56179. }, lineStyleModel.getLineStyle()),
  56180. silent: true,
  56181. z: angleAxisModel.get('z')
  56182. }));
  56183. }
  56184. },
  56185. /**
  56186. * @private
  56187. */
  56188. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56189. var splitAreaModel = angleAxisModel.getModel('splitArea');
  56190. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  56191. var areaColors = areaStyleModel.get('color');
  56192. var lineCount = 0;
  56193. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  56194. var splitAreas = [];
  56195. var RADIAN = Math.PI / 180;
  56196. var prevAngle = -ticksAngles[0] * RADIAN;
  56197. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  56198. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  56199. var clockwise = angleAxisModel.get('clockwise');
  56200. for (var i = 1; i < ticksAngles.length; i++) {
  56201. var colorIndex = (lineCount++) % areaColors.length;
  56202. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  56203. splitAreas[colorIndex].push(new Sector({
  56204. shape: {
  56205. cx: polar.cx,
  56206. cy: polar.cy,
  56207. r0: r0,
  56208. r: r1,
  56209. startAngle: prevAngle,
  56210. endAngle: -ticksAngles[i] * RADIAN,
  56211. clockwise: clockwise
  56212. },
  56213. silent: true
  56214. }));
  56215. prevAngle = -ticksAngles[i] * RADIAN;
  56216. }
  56217. // Simple optimization
  56218. // Batching the lines if color are the same
  56219. for (var i = 0; i < splitAreas.length; i++) {
  56220. this.group.add(mergePath(splitAreas[i], {
  56221. style: defaults({
  56222. fill: areaColors[i % areaColors.length]
  56223. }, areaStyleModel.getAreaStyle()),
  56224. silent: true
  56225. }));
  56226. }
  56227. }
  56228. });
  56229. var axisBuilderAttrs$3 = [
  56230. 'axisLine', 'axisTickLabel', 'axisName'
  56231. ];
  56232. var selfBuilderAttrs$1 = [
  56233. 'splitLine', 'splitArea'
  56234. ];
  56235. AxisView.extend({
  56236. type: 'radiusAxis',
  56237. axisPointerClass: 'PolarAxisPointer',
  56238. render: function (radiusAxisModel, ecModel) {
  56239. this.group.removeAll();
  56240. if (!radiusAxisModel.get('show')) {
  56241. return;
  56242. }
  56243. var radiusAxis = radiusAxisModel.axis;
  56244. var polar = radiusAxis.polar;
  56245. var angleAxis = polar.getAngleAxis();
  56246. var ticksCoords = radiusAxis.getTicksCoords();
  56247. var axisAngle = angleAxis.getExtent()[0];
  56248. var radiusExtent = radiusAxis.getExtent();
  56249. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  56250. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  56251. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  56252. this.group.add(axisBuilder.getGroup());
  56253. each$1(selfBuilderAttrs$1, function (name) {
  56254. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  56255. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  56256. }
  56257. }, this);
  56258. },
  56259. /**
  56260. * @private
  56261. */
  56262. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  56263. var splitLineModel = radiusAxisModel.getModel('splitLine');
  56264. var lineStyleModel = splitLineModel.getModel('lineStyle');
  56265. var lineColors = lineStyleModel.get('color');
  56266. var lineCount = 0;
  56267. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  56268. var splitLines = [];
  56269. for (var i = 0; i < ticksCoords.length; i++) {
  56270. var colorIndex = (lineCount++) % lineColors.length;
  56271. splitLines[colorIndex] = splitLines[colorIndex] || [];
  56272. splitLines[colorIndex].push(new Circle({
  56273. shape: {
  56274. cx: polar.cx,
  56275. cy: polar.cy,
  56276. r: ticksCoords[i]
  56277. },
  56278. silent: true
  56279. }));
  56280. }
  56281. // Simple optimization
  56282. // Batching the lines if color are the same
  56283. for (var i = 0; i < splitLines.length; i++) {
  56284. this.group.add(mergePath(splitLines[i], {
  56285. style: defaults({
  56286. stroke: lineColors[i % lineColors.length],
  56287. fill: null
  56288. }, lineStyleModel.getLineStyle()),
  56289. silent: true
  56290. }));
  56291. }
  56292. },
  56293. /**
  56294. * @private
  56295. */
  56296. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  56297. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  56298. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  56299. var areaColors = areaStyleModel.get('color');
  56300. var lineCount = 0;
  56301. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  56302. var splitAreas = [];
  56303. var prevRadius = ticksCoords[0];
  56304. for (var i = 1; i < ticksCoords.length; i++) {
  56305. var colorIndex = (lineCount++) % areaColors.length;
  56306. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  56307. splitAreas[colorIndex].push(new Sector({
  56308. shape: {
  56309. cx: polar.cx,
  56310. cy: polar.cy,
  56311. r0: prevRadius,
  56312. r: ticksCoords[i],
  56313. startAngle: 0,
  56314. endAngle: Math.PI * 2
  56315. },
  56316. silent: true
  56317. }));
  56318. prevRadius = ticksCoords[i];
  56319. }
  56320. // Simple optimization
  56321. // Batching the lines if color are the same
  56322. for (var i = 0; i < splitAreas.length; i++) {
  56323. this.group.add(mergePath(splitAreas[i], {
  56324. style: defaults({
  56325. fill: areaColors[i % areaColors.length]
  56326. }, areaStyleModel.getAreaStyle()),
  56327. silent: true
  56328. }));
  56329. }
  56330. }
  56331. });
  56332. /**
  56333. * @inner
  56334. */
  56335. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  56336. return {
  56337. position: [polar.cx, polar.cy],
  56338. rotation: axisAngle / 180 * Math.PI,
  56339. labelDirection: -1,
  56340. tickDirection: -1,
  56341. nameDirection: 1,
  56342. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  56343. // Over splitLine and splitArea
  56344. z2: 1
  56345. };
  56346. }
  56347. var PolarAxisPointer = BaseAxisPointer.extend({
  56348. /**
  56349. * @override
  56350. */
  56351. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56352. var axis = axisModel.axis;
  56353. if (axis.dim === 'angle') {
  56354. this.animationThreshold = Math.PI / 18;
  56355. }
  56356. var polar = axis.polar;
  56357. var otherAxis = polar.getOtherAxis(axis);
  56358. var otherExtent = otherAxis.getExtent();
  56359. var coordValue;
  56360. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  56361. var axisPointerType = axisPointerModel.get('type');
  56362. if (axisPointerType && axisPointerType !== 'none') {
  56363. var elStyle = buildElStyle(axisPointerModel);
  56364. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  56365. axis, polar, coordValue, otherExtent, elStyle
  56366. );
  56367. pointerOption.style = elStyle;
  56368. elOption.graphicKey = pointerOption.type;
  56369. elOption.pointer = pointerOption;
  56370. }
  56371. var labelMargin = axisPointerModel.get('label.margin');
  56372. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  56373. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  56374. }
  56375. // Do not support handle, utill any user requires it.
  56376. });
  56377. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  56378. var axis = axisModel.axis;
  56379. var coord = axis.dataToCoord(value);
  56380. var axisAngle = polar.getAngleAxis().getExtent()[0];
  56381. axisAngle = axisAngle / 180 * Math.PI;
  56382. var radiusExtent = polar.getRadiusAxis().getExtent();
  56383. var position;
  56384. var align;
  56385. var verticalAlign;
  56386. if (axis.dim === 'radius') {
  56387. var transform = create$1();
  56388. rotate(transform, transform, axisAngle);
  56389. translate(transform, transform, [polar.cx, polar.cy]);
  56390. position = applyTransform$1([coord, -labelMargin], transform);
  56391. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  56392. var labelLayout = AxisBuilder.innerTextLayout(
  56393. axisAngle, labelRotation * Math.PI / 180, -1
  56394. );
  56395. align = labelLayout.textAlign;
  56396. verticalAlign = labelLayout.textVerticalAlign;
  56397. }
  56398. else { // angle axis
  56399. var r = radiusExtent[1];
  56400. position = polar.coordToPoint([r + labelMargin, coord]);
  56401. var cx = polar.cx;
  56402. var cy = polar.cy;
  56403. align = Math.abs(position[0] - cx) / r < 0.3
  56404. ? 'center' : (position[0] > cx ? 'left' : 'right');
  56405. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  56406. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  56407. }
  56408. return {
  56409. position: position,
  56410. align: align,
  56411. verticalAlign: verticalAlign
  56412. };
  56413. }
  56414. var pointerShapeBuilder$2 = {
  56415. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  56416. return axis.dim === 'angle'
  56417. ? {
  56418. type: 'Line',
  56419. shape: makeLineShape(
  56420. polar.coordToPoint([otherExtent[0], coordValue]),
  56421. polar.coordToPoint([otherExtent[1], coordValue])
  56422. )
  56423. }
  56424. : {
  56425. type: 'Circle',
  56426. shape: {
  56427. cx: polar.cx,
  56428. cy: polar.cy,
  56429. r: coordValue
  56430. }
  56431. };
  56432. },
  56433. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  56434. var bandWidth = axis.getBandWidth();
  56435. var radian = Math.PI / 180;
  56436. return axis.dim === 'angle'
  56437. ? {
  56438. type: 'Sector',
  56439. shape: makeSectorShape(
  56440. polar.cx, polar.cy,
  56441. otherExtent[0], otherExtent[1],
  56442. // In ECharts y is negative if angle is positive
  56443. (-coordValue - bandWidth / 2) * radian,
  56444. (-coordValue + bandWidth / 2) * radian
  56445. )
  56446. }
  56447. : {
  56448. type: 'Sector',
  56449. shape: makeSectorShape(
  56450. polar.cx, polar.cy,
  56451. coordValue - bandWidth / 2,
  56452. coordValue + bandWidth / 2,
  56453. 0, Math.PI * 2
  56454. )
  56455. };
  56456. }
  56457. };
  56458. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  56459. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  56460. registerLayout(curry(barLayoutPolar, 'bar'));
  56461. // Polar view
  56462. extendComponentView({
  56463. type: 'polar'
  56464. });
  56465. var GeoModel = ComponentModel.extend({
  56466. type: 'geo',
  56467. /**
  56468. * @type {module:echarts/coord/geo/Geo}
  56469. */
  56470. coordinateSystem: null,
  56471. layoutMode: 'box',
  56472. init: function (option) {
  56473. ComponentModel.prototype.init.apply(this, arguments);
  56474. // Default label emphasis `show`
  56475. defaultEmphasis(option, 'label', ['show']);
  56476. },
  56477. optionUpdated: function () {
  56478. var option = this.option;
  56479. var self = this;
  56480. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  56481. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  56482. if (regionOpt.name) {
  56483. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  56484. }
  56485. return optionModelMap;
  56486. }, createHashMap());
  56487. this.updateSelectedMap(option.regions);
  56488. },
  56489. defaultOption: {
  56490. zlevel: 0,
  56491. z: 0,
  56492. show: true,
  56493. left: 'center',
  56494. top: 'center',
  56495. // width:,
  56496. // height:,
  56497. // right
  56498. // bottom
  56499. // Aspect is width / height. Inited to be geoJson bbox aspect
  56500. // This parameter is used for scale this aspect
  56501. aspectScale: 0.75,
  56502. ///// Layout with center and size
  56503. // If you wan't to put map in a fixed size box with right aspect ratio
  56504. // This two properties may more conveninet
  56505. // layoutCenter: [50%, 50%]
  56506. // layoutSize: 100
  56507. silent: false,
  56508. // Map type
  56509. map: '',
  56510. // Define left-top, right-bottom coords to control view
  56511. // For example, [ [180, 90], [-180, -90] ]
  56512. boundingCoords: null,
  56513. // Default on center of map
  56514. center: null,
  56515. zoom: 1,
  56516. scaleLimit: null,
  56517. // selectedMode: false
  56518. label: {
  56519. show: false,
  56520. color: '#000'
  56521. },
  56522. itemStyle: {
  56523. // color: 各异,
  56524. borderWidth: 0.5,
  56525. borderColor: '#444',
  56526. color: '#eee'
  56527. },
  56528. emphasis: {
  56529. label: {
  56530. show: true,
  56531. color: 'rgb(100,0,0)'
  56532. },
  56533. itemStyle: {
  56534. color: 'rgba(255,215,0,0.8)'
  56535. }
  56536. },
  56537. regions: []
  56538. },
  56539. /**
  56540. * Get model of region
  56541. * @param {string} name
  56542. * @return {module:echarts/model/Model}
  56543. */
  56544. getRegionModel: function (name) {
  56545. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  56546. },
  56547. /**
  56548. * Format label
  56549. * @param {string} name Region name
  56550. * @param {string} [status='normal'] 'normal' or 'emphasis'
  56551. * @return {string}
  56552. */
  56553. getFormattedLabel: function (name, status) {
  56554. var regionModel = this.getRegionModel(name);
  56555. var formatter = regionModel.get('label.' + status + '.formatter');
  56556. var params = {
  56557. name: name
  56558. };
  56559. if (typeof formatter === 'function') {
  56560. params.status = status;
  56561. return formatter(params);
  56562. }
  56563. else if (typeof formatter === 'string') {
  56564. return formatter.replace('{a}', name != null ? name : '');
  56565. }
  56566. },
  56567. setZoom: function (zoom) {
  56568. this.option.zoom = zoom;
  56569. },
  56570. setCenter: function (center) {
  56571. this.option.center = center;
  56572. }
  56573. });
  56574. mixin(GeoModel, selectableMixin);
  56575. extendComponentView({
  56576. type: 'geo',
  56577. init: function (ecModel, api) {
  56578. var mapDraw = new MapDraw(api, true);
  56579. this._mapDraw = mapDraw;
  56580. this.group.add(mapDraw.group);
  56581. },
  56582. render: function (geoModel, ecModel, api, payload) {
  56583. // Not render if it is an toggleSelect action from self
  56584. if (payload && payload.type === 'geoToggleSelect'
  56585. && payload.from === this.uid
  56586. ) {
  56587. return;
  56588. }
  56589. var mapDraw = this._mapDraw;
  56590. if (geoModel.get('show')) {
  56591. mapDraw.draw(geoModel, ecModel, api, this, payload);
  56592. }
  56593. else {
  56594. this._mapDraw.group.removeAll();
  56595. }
  56596. this.group.silent = geoModel.get('silent');
  56597. },
  56598. dispose: function () {
  56599. this._mapDraw && this._mapDraw.remove();
  56600. }
  56601. });
  56602. function makeAction(method, actionInfo) {
  56603. actionInfo.update = 'updateView';
  56604. registerAction(actionInfo, function (payload, ecModel) {
  56605. var selected = {};
  56606. ecModel.eachComponent(
  56607. { mainType: 'geo', query: payload},
  56608. function (geoModel) {
  56609. geoModel[method](payload.name);
  56610. var geo = geoModel.coordinateSystem;
  56611. each$1(geo.regions, function (region) {
  56612. selected[region.name] = geoModel.isSelected(region.name) || false;
  56613. });
  56614. }
  56615. );
  56616. return {
  56617. selected: selected,
  56618. name: payload.name
  56619. };
  56620. });
  56621. }
  56622. makeAction('toggleSelected', {
  56623. type: 'geoToggleSelect',
  56624. event: 'geoselectchanged'
  56625. });
  56626. makeAction('select', {
  56627. type: 'geoSelect',
  56628. event: 'geoselected'
  56629. });
  56630. makeAction('unSelect', {
  56631. type: 'geoUnSelect',
  56632. event: 'geounselected'
  56633. });
  56634. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  56635. var preprocessor$1 = function (option, isNew) {
  56636. var brushComponents = option && option.brush;
  56637. if (!isArray(brushComponents)) {
  56638. brushComponents = brushComponents ? [brushComponents] : [];
  56639. }
  56640. if (!brushComponents.length) {
  56641. return;
  56642. }
  56643. var brushComponentSpecifiedBtns = [];
  56644. each$1(brushComponents, function (brushOpt) {
  56645. var tbs = brushOpt.hasOwnProperty('toolbox')
  56646. ? brushOpt.toolbox : [];
  56647. if (tbs instanceof Array) {
  56648. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  56649. }
  56650. });
  56651. var toolbox = option && option.toolbox;
  56652. if (isArray(toolbox)) {
  56653. toolbox = toolbox[0];
  56654. }
  56655. if (!toolbox) {
  56656. toolbox = {feature: {}};
  56657. option.toolbox = [toolbox];
  56658. }
  56659. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  56660. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  56661. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  56662. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  56663. removeDuplicate(brushTypes);
  56664. if (isNew && !brushTypes.length) {
  56665. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  56666. }
  56667. };
  56668. function removeDuplicate(arr) {
  56669. var map$$1 = {};
  56670. each$1(arr, function (val) {
  56671. map$$1[val] = 1;
  56672. });
  56673. arr.length = 0;
  56674. each$1(map$$1, function (flag, val) {
  56675. arr.push(val);
  56676. });
  56677. }
  56678. /**
  56679. * @file Visual solution, for consistent option specification.
  56680. */
  56681. var each$20 = each$1;
  56682. function hasKeys(obj) {
  56683. if (obj) {
  56684. for (var name in obj){
  56685. if (obj.hasOwnProperty(name)) {
  56686. return true;
  56687. }
  56688. }
  56689. }
  56690. }
  56691. /**
  56692. * @param {Object} option
  56693. * @param {Array.<string>} stateList
  56694. * @param {Function} [supplementVisualOption]
  56695. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  56696. */
  56697. function createVisualMappings(option, stateList, supplementVisualOption) {
  56698. var visualMappings = {};
  56699. each$20(stateList, function (state) {
  56700. var mappings = visualMappings[state] = createMappings();
  56701. each$20(option[state], function (visualData, visualType) {
  56702. if (!VisualMapping.isValidType(visualType)) {
  56703. return;
  56704. }
  56705. var mappingOption = {
  56706. type: visualType,
  56707. visual: visualData
  56708. };
  56709. supplementVisualOption && supplementVisualOption(mappingOption, state);
  56710. mappings[visualType] = new VisualMapping(mappingOption);
  56711. // Prepare a alpha for opacity, for some case that opacity
  56712. // is not supported, such as rendering using gradient color.
  56713. if (visualType === 'opacity') {
  56714. mappingOption = clone(mappingOption);
  56715. mappingOption.type = 'colorAlpha';
  56716. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  56717. }
  56718. });
  56719. });
  56720. return visualMappings;
  56721. function createMappings() {
  56722. var Creater = function () {};
  56723. // Make sure hidden fields will not be visited by
  56724. // object iteration (with hasOwnProperty checking).
  56725. Creater.prototype.__hidden = Creater.prototype;
  56726. var obj = new Creater();
  56727. return obj;
  56728. }
  56729. }
  56730. /**
  56731. * @param {Object} thisOption
  56732. * @param {Object} newOption
  56733. * @param {Array.<string>} keys
  56734. */
  56735. function replaceVisualOption(thisOption, newOption, keys) {
  56736. // Visual attributes merge is not supported, otherwise it
  56737. // brings overcomplicated merge logic. See #2853. So if
  56738. // newOption has anyone of these keys, all of these keys
  56739. // will be reset. Otherwise, all keys remain.
  56740. var has;
  56741. each$1(keys, function (key) {
  56742. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  56743. has = true;
  56744. }
  56745. });
  56746. has && each$1(keys, function (key) {
  56747. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  56748. thisOption[key] = clone(newOption[key]);
  56749. }
  56750. else {
  56751. delete thisOption[key];
  56752. }
  56753. });
  56754. }
  56755. /**
  56756. * @param {Array.<string>} stateList
  56757. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  56758. * @param {module:echarts/data/List} list
  56759. * @param {Function} getValueState param: valueOrIndex, return: state.
  56760. * @param {object} [scope] Scope for getValueState
  56761. * @param {string} [dimension] Concrete dimension, if used.
  56762. */
  56763. // ???! handle brush?
  56764. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  56765. var visualTypesMap = {};
  56766. each$1(stateList, function (state) {
  56767. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  56768. visualTypesMap[state] = visualTypes;
  56769. });
  56770. var dataIndex;
  56771. function getVisual(key) {
  56772. return data.getItemVisual(dataIndex, key);
  56773. }
  56774. function setVisual(key, value) {
  56775. data.setItemVisual(dataIndex, key, value);
  56776. }
  56777. if (dimension == null) {
  56778. data.each(eachItem);
  56779. }
  56780. else {
  56781. data.each([dimension], eachItem);
  56782. }
  56783. function eachItem(valueOrIndex, index) {
  56784. dataIndex = dimension == null ? valueOrIndex : index;
  56785. var rawDataItem = data.getRawDataItem(dataIndex);
  56786. // Consider performance
  56787. if (rawDataItem && rawDataItem.visualMap === false) {
  56788. return;
  56789. }
  56790. var valueState = getValueState.call(scope, valueOrIndex);
  56791. var mappings = visualMappings[valueState];
  56792. var visualTypes = visualTypesMap[valueState];
  56793. for (var i = 0, len = visualTypes.length; i < len; i++) {
  56794. var type = visualTypes[i];
  56795. mappings[type] && mappings[type].applyVisual(
  56796. valueOrIndex, getVisual, setVisual
  56797. );
  56798. }
  56799. }
  56800. }
  56801. /**
  56802. * @param {module:echarts/data/List} data
  56803. * @param {Array.<string>} stateList
  56804. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  56805. * @param {Function} getValueState param: valueOrIndex, return: state.
  56806. * @param {number} [dim] dimension or dimension index.
  56807. */
  56808. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  56809. var visualTypesMap = {};
  56810. each$1(stateList, function (state) {
  56811. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  56812. visualTypesMap[state] = visualTypes;
  56813. });
  56814. function progress(params, data) {
  56815. if (dim != null) {
  56816. dim = data.getDimension(dim);
  56817. }
  56818. function getVisual(key) {
  56819. return data.getItemVisual(dataIndex, key);
  56820. }
  56821. function setVisual(key, value) {
  56822. data.setItemVisual(dataIndex, key, value);
  56823. }
  56824. for (var dataIndex = params.start; dataIndex < params.end; dataIndex++) {
  56825. var rawDataItem = data.getRawDataItem(dataIndex);
  56826. // Consider performance
  56827. if (rawDataItem && rawDataItem.visualMap === false) {
  56828. return;
  56829. }
  56830. var value = dim != null
  56831. ? data.get(dim, dataIndex, true)
  56832. : dataIndex;
  56833. var valueState = getValueState(value);
  56834. var mappings = visualMappings[valueState];
  56835. var visualTypes = visualTypesMap[valueState];
  56836. for (var i = 0, len = visualTypes.length; i < len; i++) {
  56837. var type = visualTypes[i];
  56838. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  56839. }
  56840. }
  56841. }
  56842. return {progress: progress};
  56843. }
  56844. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  56845. // Key of the second level is chart element type: `point`, `rect`.
  56846. // See moudule:echarts/component/helper/BrushController
  56847. // function param:
  56848. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  56849. // {Object} selectors {point: selector, rect: selector, ...}
  56850. // {Object} area {range: [[], [], ..], boudingRect}
  56851. // function return:
  56852. // {boolean} Whether in the given brush.
  56853. var selector = {
  56854. lineX: getLineSelectors(0),
  56855. lineY: getLineSelectors(1),
  56856. rect: {
  56857. point: function (itemLayout, selectors, area) {
  56858. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  56859. },
  56860. rect: function (itemLayout, selectors, area) {
  56861. return itemLayout && area.boundingRect.intersect(itemLayout);
  56862. }
  56863. },
  56864. polygon: {
  56865. point: function (itemLayout, selectors, area) {
  56866. return itemLayout
  56867. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  56868. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  56869. },
  56870. rect: function (itemLayout, selectors, area) {
  56871. var points = area.range;
  56872. if (!itemLayout || points.length <= 1) {
  56873. return false;
  56874. }
  56875. var x = itemLayout.x;
  56876. var y = itemLayout.y;
  56877. var width = itemLayout.width;
  56878. var height = itemLayout.height;
  56879. var p = points[0];
  56880. if (contain$1(points, x, y)
  56881. || contain$1(points, x + width, y)
  56882. || contain$1(points, x, y + height)
  56883. || contain$1(points, x + width, y + height)
  56884. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  56885. || lineIntersectPolygon(x, y, x + width, y, points)
  56886. || lineIntersectPolygon(x, y, x, y + height, points)
  56887. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  56888. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  56889. ) {
  56890. return true;
  56891. }
  56892. }
  56893. }
  56894. };
  56895. function getLineSelectors(xyIndex) {
  56896. var xy = ['x', 'y'];
  56897. var wh = ['width', 'height'];
  56898. return {
  56899. point: function (itemLayout, selectors, area) {
  56900. if (itemLayout) {
  56901. var range = area.range;
  56902. var p = itemLayout[xyIndex];
  56903. return inLineRange(p, range);
  56904. }
  56905. },
  56906. rect: function (itemLayout, selectors, area) {
  56907. if (itemLayout) {
  56908. var range = area.range;
  56909. var layoutRange = [
  56910. itemLayout[xy[xyIndex]],
  56911. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  56912. ];
  56913. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  56914. return inLineRange(layoutRange[0], range)
  56915. || inLineRange(layoutRange[1], range)
  56916. || inLineRange(range[0], layoutRange)
  56917. || inLineRange(range[1], layoutRange);
  56918. }
  56919. }
  56920. };
  56921. }
  56922. function inLineRange(p, range) {
  56923. return range[0] <= p && p <= range[1];
  56924. }
  56925. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  56926. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  56927. var p = points[i];
  56928. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  56929. return true;
  56930. }
  56931. p2 = p;
  56932. }
  56933. }
  56934. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  56935. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  56936. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  56937. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  56938. if (nearZero(delta)) { // parallel
  56939. return false;
  56940. }
  56941. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  56942. if (namenda < 0 || namenda > 1) {
  56943. return false;
  56944. }
  56945. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  56946. if (miu < 0 || miu > 1) {
  56947. return false;
  56948. }
  56949. return true;
  56950. }
  56951. function nearZero(val) {
  56952. return val <= (1e-6) && val >= -(1e-6);
  56953. }
  56954. function determinant(v1, v2, v3, v4) {
  56955. return v1 * v4 - v2 * v3;
  56956. }
  56957. var each$21 = each$1;
  56958. var indexOf$1 = indexOf;
  56959. var curry$5 = curry;
  56960. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  56961. // FIXME
  56962. // how to genarialize to more coordinate systems.
  56963. var INCLUDE_FINDER_MAIN_TYPES = [
  56964. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  56965. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  56966. ];
  56967. /**
  56968. * [option in constructor]:
  56969. * {
  56970. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  56971. * }
  56972. *
  56973. *
  56974. * [targetInfo]:
  56975. *
  56976. * There can be multiple axes in a single targetInfo. Consider the case
  56977. * of `grid` component, a targetInfo represents a grid which contains one or more
  56978. * cartesian and one or more axes. And consider the case of parallel system,
  56979. * which has multiple axes in a coordinate system.
  56980. * Can be {
  56981. * panelId: ...,
  56982. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  56983. * coordSyses: all cartesians.
  56984. * gridModel: <grid component>
  56985. * xAxes: correspond to coordSyses on index
  56986. * yAxes: correspond to coordSyses on index
  56987. * }
  56988. * or {
  56989. * panelId: ...,
  56990. * coordSys: <geo coord sys>
  56991. * coordSyses: [<geo coord sys>]
  56992. * geoModel: <geo component>
  56993. * }
  56994. *
  56995. *
  56996. * [panelOpt]:
  56997. *
  56998. * Make from targetInfo. Input to BrushController.
  56999. * {
  57000. * panelId: ...,
  57001. * rect: ...
  57002. * }
  57003. *
  57004. *
  57005. * [area]:
  57006. *
  57007. * Generated by BrushController or user input.
  57008. * {
  57009. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  57010. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  57011. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  57012. * range: pixel range.
  57013. * coordRange: representitive coord range (the first one of coordRanges).
  57014. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  57015. * }
  57016. */
  57017. /**
  57018. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  57019. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  57020. * @param {module:echarts/model/Global} ecModel
  57021. * @param {Object} [opt]
  57022. * @param {Array.<string>} [opt.include] include coordinate system types.
  57023. */
  57024. function BrushTargetManager(option, ecModel, opt) {
  57025. /**
  57026. * @private
  57027. * @type {Array.<Object>}
  57028. */
  57029. var targetInfoList = this._targetInfoList = [];
  57030. var info = {};
  57031. var foundCpts = parseFinder$1(ecModel, option);
  57032. each$21(targetInfoBuilders, function (builder, type) {
  57033. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  57034. builder(foundCpts, targetInfoList, info);
  57035. }
  57036. });
  57037. }
  57038. var proto$2 = BrushTargetManager.prototype;
  57039. proto$2.setOutputRanges = function (areas, ecModel) {
  57040. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  57041. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  57042. // area.coordRange is the first of area.coordRanges
  57043. if (!area.coordRange) {
  57044. area.coordRange = coordRange;
  57045. // In 'category' axis, coord to pixel is not reversible, so we can not
  57046. // rebuild range by coordRange accrately, which may bring trouble when
  57047. // brushing only one item. So we use __rangeOffset to rebuilding range
  57048. // by coordRange. And this it only used in brush component so it is no
  57049. // need to be adapted to coordRanges.
  57050. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  57051. area.__rangeOffset = {
  57052. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  57053. xyMinMax: result.xyMinMax
  57054. };
  57055. }
  57056. });
  57057. };
  57058. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  57059. each$21(areas, function (area) {
  57060. var targetInfo = this.findTargetInfo(area, ecModel);
  57061. if (targetInfo && targetInfo !== true) {
  57062. each$1(
  57063. targetInfo.coordSyses,
  57064. function (coordSys) {
  57065. var result = coordConvert[area.brushType](1, coordSys, area.range);
  57066. cb(area, result.values, coordSys, ecModel);
  57067. }
  57068. );
  57069. }
  57070. }, this);
  57071. };
  57072. proto$2.setInputRanges = function (areas, ecModel) {
  57073. each$21(areas, function (area) {
  57074. var targetInfo = this.findTargetInfo(area, ecModel);
  57075. if (__DEV__) {
  57076. assert$1(
  57077. !targetInfo || targetInfo === true || area.coordRange,
  57078. 'coordRange must be specified when coord index specified.'
  57079. );
  57080. assert$1(
  57081. !targetInfo || targetInfo !== true || area.range,
  57082. 'range must be specified in global brush.'
  57083. );
  57084. }
  57085. area.range = area.range || [];
  57086. // convert coordRange to global range and set panelId.
  57087. if (targetInfo && targetInfo !== true) {
  57088. area.panelId = targetInfo.panelId;
  57089. // (1) area.range shoule always be calculate from coordRange but does
  57090. // not keep its original value, for the sake of the dataZoom scenario,
  57091. // where area.coordRange remains unchanged but area.range may be changed.
  57092. // (2) Only support converting one coordRange to pixel range in brush
  57093. // component. So do not consider `coordRanges`.
  57094. // (3) About __rangeOffset, see comment above.
  57095. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  57096. var rangeOffset = area.__rangeOffset;
  57097. area.range = rangeOffset
  57098. ? diffProcessor[area.brushType](
  57099. result.values,
  57100. rangeOffset.offset,
  57101. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  57102. )
  57103. : result.values;
  57104. }
  57105. }, this);
  57106. };
  57107. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  57108. return map(this._targetInfoList, function (targetInfo) {
  57109. var rect = targetInfo.getPanelRect();
  57110. return {
  57111. panelId: targetInfo.panelId,
  57112. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  57113. clipPath: makeRectPanelClipPath(rect),
  57114. isTargetByCursor: makeRectIsTargetByCursor(
  57115. rect, api, targetInfo.coordSysModel
  57116. ),
  57117. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  57118. };
  57119. });
  57120. };
  57121. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  57122. // Check whether area is bound in coord, and series do not belong to that coord.
  57123. // If do not do this check, some brush (like lineX) will controll all axes.
  57124. var targetInfo = this.findTargetInfo(area, ecModel);
  57125. return targetInfo === true || (
  57126. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  57127. );
  57128. };
  57129. /**
  57130. * If return Object, a coord found.
  57131. * If reutrn true, global found.
  57132. * Otherwise nothing found.
  57133. *
  57134. * @param {Object} area
  57135. * @param {Array} targetInfoList
  57136. * @return {Object|boolean}
  57137. */
  57138. proto$2.findTargetInfo = function (area, ecModel) {
  57139. var targetInfoList = this._targetInfoList;
  57140. var foundCpts = parseFinder$1(ecModel, area);
  57141. for (var i = 0; i < targetInfoList.length; i++) {
  57142. var targetInfo = targetInfoList[i];
  57143. var areaPanelId = area.panelId;
  57144. if (areaPanelId) {
  57145. if (targetInfo.panelId === areaPanelId) {
  57146. return targetInfo;
  57147. }
  57148. }
  57149. else {
  57150. for (var i = 0; i < targetInfoMatchers.length; i++) {
  57151. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  57152. return targetInfo;
  57153. }
  57154. }
  57155. }
  57156. }
  57157. return true;
  57158. };
  57159. function formatMinMax(minMax) {
  57160. minMax[0] > minMax[1] && minMax.reverse();
  57161. return minMax;
  57162. }
  57163. function parseFinder$1(ecModel, option) {
  57164. return parseFinder(
  57165. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  57166. );
  57167. }
  57168. var targetInfoBuilders = {
  57169. grid: function (foundCpts, targetInfoList) {
  57170. var xAxisModels = foundCpts.xAxisModels;
  57171. var yAxisModels = foundCpts.yAxisModels;
  57172. var gridModels = foundCpts.gridModels;
  57173. // Remove duplicated.
  57174. var gridModelMap = createHashMap();
  57175. var xAxesHas = {};
  57176. var yAxesHas = {};
  57177. if (!xAxisModels && !yAxisModels && !gridModels) {
  57178. return;
  57179. }
  57180. each$21(xAxisModels, function (axisModel) {
  57181. var gridModel = axisModel.axis.grid.model;
  57182. gridModelMap.set(gridModel.id, gridModel);
  57183. xAxesHas[gridModel.id] = true;
  57184. });
  57185. each$21(yAxisModels, function (axisModel) {
  57186. var gridModel = axisModel.axis.grid.model;
  57187. gridModelMap.set(gridModel.id, gridModel);
  57188. yAxesHas[gridModel.id] = true;
  57189. });
  57190. each$21(gridModels, function (gridModel) {
  57191. gridModelMap.set(gridModel.id, gridModel);
  57192. xAxesHas[gridModel.id] = true;
  57193. yAxesHas[gridModel.id] = true;
  57194. });
  57195. gridModelMap.each(function (gridModel) {
  57196. var grid = gridModel.coordinateSystem;
  57197. var cartesians = [];
  57198. each$21(grid.getCartesians(), function (cartesian, index) {
  57199. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  57200. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  57201. ) {
  57202. cartesians.push(cartesian);
  57203. }
  57204. });
  57205. targetInfoList.push({
  57206. panelId: 'grid--' + gridModel.id,
  57207. gridModel: gridModel,
  57208. coordSysModel: gridModel,
  57209. // Use the first one as the representitive coordSys.
  57210. coordSys: cartesians[0],
  57211. coordSyses: cartesians,
  57212. getPanelRect: panelRectBuilder.grid,
  57213. xAxisDeclared: xAxesHas[gridModel.id],
  57214. yAxisDeclared: yAxesHas[gridModel.id]
  57215. });
  57216. });
  57217. },
  57218. geo: function (foundCpts, targetInfoList) {
  57219. each$21(foundCpts.geoModels, function (geoModel) {
  57220. var coordSys = geoModel.coordinateSystem;
  57221. targetInfoList.push({
  57222. panelId: 'geo--' + geoModel.id,
  57223. geoModel: geoModel,
  57224. coordSysModel: geoModel,
  57225. coordSys: coordSys,
  57226. coordSyses: [coordSys],
  57227. getPanelRect: panelRectBuilder.geo
  57228. });
  57229. });
  57230. }
  57231. };
  57232. var targetInfoMatchers = [
  57233. // grid
  57234. function (foundCpts, targetInfo) {
  57235. var xAxisModel = foundCpts.xAxisModel;
  57236. var yAxisModel = foundCpts.yAxisModel;
  57237. var gridModel = foundCpts.gridModel;
  57238. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  57239. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  57240. return gridModel && gridModel === targetInfo.gridModel;
  57241. },
  57242. // geo
  57243. function (foundCpts, targetInfo) {
  57244. var geoModel = foundCpts.geoModel;
  57245. return geoModel && geoModel === targetInfo.geoModel;
  57246. }
  57247. ];
  57248. var panelRectBuilder = {
  57249. grid: function () {
  57250. // grid is not Transformable.
  57251. return this.coordSys.grid.getRect().clone();
  57252. },
  57253. geo: function () {
  57254. var coordSys = this.coordSys;
  57255. var rect = coordSys.getBoundingRect().clone();
  57256. // geo roam and zoom transform
  57257. rect.applyTransform(getTransform(coordSys));
  57258. return rect;
  57259. }
  57260. };
  57261. var coordConvert = {
  57262. lineX: curry$5(axisConvert, 0),
  57263. lineY: curry$5(axisConvert, 1),
  57264. rect: function (to, coordSys, rangeOrCoordRange) {
  57265. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  57266. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  57267. var values = [
  57268. formatMinMax([xminymin[0], xmaxymax[0]]),
  57269. formatMinMax([xminymin[1], xmaxymax[1]])
  57270. ];
  57271. return {values: values, xyMinMax: values};
  57272. },
  57273. polygon: function (to, coordSys, rangeOrCoordRange) {
  57274. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  57275. var values = map(rangeOrCoordRange, function (item) {
  57276. var p = coordSys[COORD_CONVERTS[to]](item);
  57277. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  57278. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  57279. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  57280. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  57281. return p;
  57282. });
  57283. return {values: values, xyMinMax: xyMinMax};
  57284. }
  57285. };
  57286. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  57287. if (__DEV__) {
  57288. assert$1(
  57289. coordSys.type === 'cartesian2d',
  57290. 'lineX/lineY brush is available only in cartesian2d.'
  57291. );
  57292. }
  57293. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  57294. var values = formatMinMax(map([0, 1], function (i) {
  57295. return to
  57296. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  57297. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  57298. }));
  57299. var xyMinMax = [];
  57300. xyMinMax[axisNameIndex] = values;
  57301. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  57302. return {values: values, xyMinMax: xyMinMax};
  57303. }
  57304. var diffProcessor = {
  57305. lineX: curry$5(axisDiffProcessor, 0),
  57306. lineY: curry$5(axisDiffProcessor, 1),
  57307. rect: function (values, refer, scales) {
  57308. return [
  57309. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  57310. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  57311. ];
  57312. },
  57313. polygon: function (values, refer, scales) {
  57314. return map(values, function (item, idx) {
  57315. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  57316. });
  57317. }
  57318. };
  57319. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  57320. return [
  57321. values[0] - scales[axisNameIndex] * refer[0],
  57322. values[1] - scales[axisNameIndex] * refer[1]
  57323. ];
  57324. }
  57325. // We have to process scale caused by dataZoom manually,
  57326. // although it might be not accurate.
  57327. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  57328. var sizeCurr = getSize(xyMinMaxCurr);
  57329. var sizeOrigin = getSize(xyMinMaxOrigin);
  57330. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  57331. isNaN(scales[0]) && (scales[0] = 1);
  57332. isNaN(scales[1]) && (scales[1] = 1);
  57333. return scales;
  57334. }
  57335. function getSize(xyMinMax) {
  57336. return xyMinMax
  57337. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  57338. : [NaN, NaN];
  57339. }
  57340. var STATE_LIST = ['inBrush', 'outOfBrush'];
  57341. var DISPATCH_METHOD = '__ecBrushSelect';
  57342. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  57343. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  57344. /**
  57345. * Layout for visual, the priority higher than other layout, and before brush visual.
  57346. */
  57347. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  57348. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  57349. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  57350. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  57351. );
  57352. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  57353. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  57354. });
  57355. });
  57356. /**
  57357. * Register the visual encoding if this modules required.
  57358. */
  57359. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  57360. var brushSelected = [];
  57361. var throttleType;
  57362. var throttleDelay;
  57363. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  57364. var thisBrushSelected = {
  57365. brushId: brushModel.id,
  57366. brushIndex: brushIndex,
  57367. brushName: brushModel.name,
  57368. areas: clone(brushModel.areas),
  57369. selected: []
  57370. };
  57371. // Every brush component exists in event params, convenient
  57372. // for user to find by index.
  57373. brushSelected.push(thisBrushSelected);
  57374. var brushOption = brushModel.option;
  57375. var brushLink = brushOption.brushLink;
  57376. var linkedSeriesMap = [];
  57377. var selectedDataIndexForLink = [];
  57378. var rangeInfoBySeries = [];
  57379. var hasBrushExists = 0;
  57380. if (!brushIndex) { // Only the first throttle setting works.
  57381. throttleType = brushOption.throttleType;
  57382. throttleDelay = brushOption.throttleDelay;
  57383. }
  57384. // Add boundingRect and selectors to range.
  57385. var areas = map(brushModel.areas, function (area) {
  57386. return bindSelector(
  57387. defaults(
  57388. {boundingRect: boundingRectBuilders[area.brushType](area)},
  57389. area
  57390. )
  57391. );
  57392. });
  57393. var visualMappings = createVisualMappings(
  57394. brushModel.option, STATE_LIST, function (mappingOption) {
  57395. mappingOption.mappingMethod = 'fixed';
  57396. }
  57397. );
  57398. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  57399. linkedSeriesMap[seriesIndex] = 1;
  57400. });
  57401. function linkOthers(seriesIndex) {
  57402. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  57403. }
  57404. // If no supported brush or no brush on the series,
  57405. // all visuals should be in original state.
  57406. function brushed(rangeInfoList) {
  57407. return !!rangeInfoList.length;
  57408. }
  57409. /**
  57410. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  57411. *
  57412. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  57413. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  57414. * └!hasBrushExist┘ └nothing.
  57415. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  57416. * └!hasBrushExist┘ └nothing.
  57417. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  57418. * !brushed┘ └nothing.
  57419. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  57420. */
  57421. // Step A
  57422. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  57423. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  57424. seriesModel.subType === 'parallel'
  57425. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  57426. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  57427. });
  57428. function stepAParallel(seriesModel, seriesIndex) {
  57429. var coordSys = seriesModel.coordinateSystem;
  57430. hasBrushExists |= coordSys.hasAxisBrushed();
  57431. linkOthers(seriesIndex) && coordSys.eachActiveState(
  57432. seriesModel.getData(),
  57433. function (activeState, dataIndex) {
  57434. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  57435. }
  57436. );
  57437. }
  57438. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  57439. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  57440. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  57441. return;
  57442. }
  57443. each$1(areas, function (area) {
  57444. selectorsByBrushType[area.brushType]
  57445. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  57446. && rangeInfoList.push(area);
  57447. hasBrushExists |= brushed(rangeInfoList);
  57448. });
  57449. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  57450. var data = seriesModel.getData();
  57451. data.each(function (dataIndex) {
  57452. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  57453. selectedDataIndexForLink[dataIndex] = 1;
  57454. }
  57455. });
  57456. }
  57457. }
  57458. // Step B
  57459. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  57460. var seriesBrushSelected = {
  57461. seriesId: seriesModel.id,
  57462. seriesIndex: seriesIndex,
  57463. seriesName: seriesModel.name,
  57464. dataIndex: []
  57465. };
  57466. // Every series exists in event params, convenient
  57467. // for user to find series by seriesIndex.
  57468. thisBrushSelected.selected.push(seriesBrushSelected);
  57469. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  57470. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  57471. var data = seriesModel.getData();
  57472. var getValueState = linkOthers(seriesIndex)
  57473. ? function (dataIndex) {
  57474. return selectedDataIndexForLink[dataIndex]
  57475. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  57476. : 'outOfBrush';
  57477. }
  57478. : function (dataIndex) {
  57479. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  57480. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  57481. : 'outOfBrush';
  57482. };
  57483. // If no supported brush or no brush, all visuals are in original state.
  57484. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  57485. && applyVisual(
  57486. STATE_LIST, visualMappings, data, getValueState
  57487. );
  57488. });
  57489. });
  57490. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  57491. });
  57492. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  57493. // This event will not be triggered when `setOpion`, otherwise dead lock may
  57494. // triggered when do `setOption` in event listener, which we do not find
  57495. // satisfactory way to solve yet. Some considered resolutions:
  57496. // (a) Diff with prevoius selected data ant only trigger event when changed.
  57497. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  57498. // also detect value changes in selected data) might bring complexity or fragility.
  57499. // (b) Use spectial param like `silent` to suppress event triggering.
  57500. // But such kind of volatile param may be weird in `setOption`.
  57501. if (!payload) {
  57502. return;
  57503. }
  57504. var zr = api.getZr();
  57505. if (zr[DISPATCH_FLAG]) {
  57506. return;
  57507. }
  57508. if (!zr[DISPATCH_METHOD]) {
  57509. zr[DISPATCH_METHOD] = doDispatch;
  57510. }
  57511. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  57512. fn(api, brushSelected);
  57513. }
  57514. function doDispatch(api, brushSelected) {
  57515. if (!api.isDisposed()) {
  57516. var zr = api.getZr();
  57517. zr[DISPATCH_FLAG] = true;
  57518. api.dispatchAction({
  57519. type: 'brushSelect',
  57520. batch: brushSelected
  57521. });
  57522. zr[DISPATCH_FLAG] = false;
  57523. }
  57524. }
  57525. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  57526. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  57527. var area = rangeInfoList[i];
  57528. if (selectorsByBrushType[area.brushType](
  57529. dataIndex, data, area.selectors, area
  57530. )) {
  57531. return true;
  57532. }
  57533. }
  57534. }
  57535. function getSelectorsByBrushType(seriesModel) {
  57536. var brushSelector = seriesModel.brushSelector;
  57537. if (isString(brushSelector)) {
  57538. var sels = [];
  57539. each$1(selector, function (selectorsByElementType, brushType) {
  57540. sels[brushType] = function (dataIndex, data, selectors, area) {
  57541. var itemLayout = data.getItemLayout(dataIndex);
  57542. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  57543. };
  57544. });
  57545. return sels;
  57546. }
  57547. else if (isFunction$1(brushSelector)) {
  57548. var bSelector = {};
  57549. each$1(selector, function (sel, brushType) {
  57550. bSelector[brushType] = brushSelector;
  57551. });
  57552. return bSelector;
  57553. }
  57554. return brushSelector;
  57555. }
  57556. function brushModelNotControll(brushModel, seriesIndex) {
  57557. var seriesIndices = brushModel.option.seriesIndex;
  57558. return seriesIndices != null
  57559. && seriesIndices !== 'all'
  57560. && (
  57561. isArray(seriesIndices)
  57562. ? indexOf(seriesIndices, seriesIndex) < 0
  57563. : seriesIndex !== seriesIndices
  57564. );
  57565. }
  57566. function bindSelector(area) {
  57567. var selectors = area.selectors = {};
  57568. each$1(selector[area.brushType], function (selFn, elType) {
  57569. // Do not use function binding or curry for performance.
  57570. selectors[elType] = function (itemLayout) {
  57571. return selFn(itemLayout, selectors, area);
  57572. };
  57573. });
  57574. return area;
  57575. }
  57576. var boundingRectBuilders = {
  57577. lineX: noop,
  57578. lineY: noop,
  57579. rect: function (area) {
  57580. return getBoundingRectFromMinMax(area.range);
  57581. },
  57582. polygon: function (area) {
  57583. var minMax;
  57584. var range = area.range;
  57585. for (var i = 0, len = range.length; i < len; i++) {
  57586. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  57587. var rg = range[i];
  57588. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  57589. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  57590. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  57591. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  57592. }
  57593. return minMax && getBoundingRectFromMinMax(minMax);
  57594. }
  57595. };
  57596. function getBoundingRectFromMinMax(minMax) {
  57597. return new BoundingRect(
  57598. minMax[0][0],
  57599. minMax[1][0],
  57600. minMax[0][1] - minMax[0][0],
  57601. minMax[1][1] - minMax[1][0]
  57602. );
  57603. }
  57604. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  57605. var BrushModel = extendComponentModel({
  57606. type: 'brush',
  57607. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  57608. /**
  57609. * @protected
  57610. */
  57611. defaultOption: {
  57612. // inBrush: null,
  57613. // outOfBrush: null,
  57614. toolbox: null, // Default value see preprocessor.
  57615. brushLink: null, // Series indices array, broadcast using dataIndex.
  57616. // or 'all', which means all series. 'none' or null means no series.
  57617. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  57618. geoIndex: null, //
  57619. xAxisIndex: null,
  57620. yAxisIndex: null,
  57621. brushType: 'rect', // Default brushType, see BrushController.
  57622. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  57623. transformable: true, // Default transformable.
  57624. brushStyle: { // Default brushStyle
  57625. borderWidth: 1,
  57626. color: 'rgba(120,140,180,0.3)',
  57627. borderColor: 'rgba(120,140,180,0.8)'
  57628. },
  57629. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  57630. // If null, no throttle. Valid only in the first brush component
  57631. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  57632. // FIXME
  57633. // 试验效果
  57634. removeOnClick: true,
  57635. z: 10000
  57636. },
  57637. /**
  57638. * @readOnly
  57639. * @type {Array.<Object>}
  57640. */
  57641. areas: [],
  57642. /**
  57643. * Current activated brush type.
  57644. * If null, brush is inactived.
  57645. * see module:echarts/component/helper/BrushController
  57646. * @readOnly
  57647. * @type {string}
  57648. */
  57649. brushType: null,
  57650. /**
  57651. * Current brush opt.
  57652. * see module:echarts/component/helper/BrushController
  57653. * @readOnly
  57654. * @type {Object}
  57655. */
  57656. brushOption: {},
  57657. /**
  57658. * @readOnly
  57659. * @type {Array.<Object>}
  57660. */
  57661. coordInfoList: [],
  57662. optionUpdated: function (newOption, isInit) {
  57663. var thisOption = this.option;
  57664. !isInit && replaceVisualOption(
  57665. thisOption, newOption, ['inBrush', 'outOfBrush']
  57666. );
  57667. thisOption.inBrush = thisOption.inBrush || {};
  57668. // Always give default visual, consider setOption at the second time.
  57669. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  57670. },
  57671. /**
  57672. * If ranges is null/undefined, range state remain.
  57673. *
  57674. * @param {Array.<Object>} [ranges]
  57675. */
  57676. setAreas: function (areas) {
  57677. if (__DEV__) {
  57678. assert$1(isArray(areas));
  57679. each$1(areas, function (area) {
  57680. assert$1(area.brushType, 'Illegal areas');
  57681. });
  57682. }
  57683. // If ranges is null/undefined, range state remain.
  57684. // This helps user to dispatchAction({type: 'brush'}) with no areas
  57685. // set but just want to get the current brush select info from a `brush` event.
  57686. if (!areas) {
  57687. return;
  57688. }
  57689. this.areas = map(areas, function (area) {
  57690. return generateBrushOption(this.option, area);
  57691. }, this);
  57692. },
  57693. /**
  57694. * see module:echarts/component/helper/BrushController
  57695. * @param {Object} brushOption
  57696. */
  57697. setBrushOption: function (brushOption) {
  57698. this.brushOption = generateBrushOption(this.option, brushOption);
  57699. this.brushType = this.brushOption.brushType;
  57700. }
  57701. });
  57702. function generateBrushOption(option, brushOption) {
  57703. return merge(
  57704. {
  57705. brushType: option.brushType,
  57706. brushMode: option.brushMode,
  57707. transformable: option.transformable,
  57708. brushStyle: new Model(option.brushStyle).getItemStyle(),
  57709. removeOnClick: option.removeOnClick,
  57710. z: option.z
  57711. },
  57712. brushOption,
  57713. true
  57714. );
  57715. }
  57716. extendComponentView({
  57717. type: 'brush',
  57718. init: function (ecModel, api) {
  57719. /**
  57720. * @readOnly
  57721. * @type {module:echarts/model/Global}
  57722. */
  57723. this.ecModel = ecModel;
  57724. /**
  57725. * @readOnly
  57726. * @type {module:echarts/ExtensionAPI}
  57727. */
  57728. this.api = api;
  57729. /**
  57730. * @readOnly
  57731. * @type {module:echarts/component/brush/BrushModel}
  57732. */
  57733. this.model;
  57734. /**
  57735. * @private
  57736. * @type {module:echarts/component/helper/BrushController}
  57737. */
  57738. (this._brushController = new BrushController(api.getZr()))
  57739. .on('brush', bind(this._onBrush, this))
  57740. .mount();
  57741. },
  57742. /**
  57743. * @override
  57744. */
  57745. render: function (brushModel) {
  57746. this.model = brushModel;
  57747. return updateController.apply(this, arguments);
  57748. },
  57749. /**
  57750. * @override
  57751. */
  57752. updateTransform: updateController,
  57753. /**
  57754. * @override
  57755. */
  57756. updateView: updateController,
  57757. // /**
  57758. // * @override
  57759. // */
  57760. // updateLayout: updateController,
  57761. // /**
  57762. // * @override
  57763. // */
  57764. // updateVisual: updateController,
  57765. /**
  57766. * @override
  57767. */
  57768. dispose: function () {
  57769. this._brushController.dispose();
  57770. },
  57771. /**
  57772. * @private
  57773. */
  57774. _onBrush: function (areas, opt) {
  57775. var modelId = this.model.id;
  57776. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  57777. // Action is not dispatched on drag end, because the drag end
  57778. // emits the same params with the last drag move event, and
  57779. // may have some delay when using touch pad, which makes
  57780. // animation not smooth (when using debounce).
  57781. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  57782. type: 'brush',
  57783. brushId: modelId,
  57784. areas: clone(areas),
  57785. $from: modelId
  57786. });
  57787. }
  57788. });
  57789. function updateController(brushModel, ecModel, api, payload) {
  57790. // Do not update controller when drawing.
  57791. (!payload || payload.$from !== brushModel.id) && this._brushController
  57792. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  57793. .enableBrush(brushModel.brushOption)
  57794. .updateCovers(brushModel.areas.slice());
  57795. }
  57796. /**
  57797. * payload: {
  57798. * brushIndex: number, or,
  57799. * brushId: string, or,
  57800. * brushName: string,
  57801. * globalRanges: Array
  57802. * }
  57803. */
  57804. registerAction(
  57805. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  57806. function (payload, ecModel) {
  57807. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  57808. brushModel.setAreas(payload.areas);
  57809. });
  57810. }
  57811. );
  57812. /**
  57813. * payload: {
  57814. * brushComponents: [
  57815. * {
  57816. * brushId,
  57817. * brushIndex,
  57818. * brushName,
  57819. * series: [
  57820. * {
  57821. * seriesId,
  57822. * seriesIndex,
  57823. * seriesName,
  57824. * rawIndices: [21, 34, ...]
  57825. * },
  57826. * ...
  57827. * ]
  57828. * },
  57829. * ...
  57830. * ]
  57831. * }
  57832. */
  57833. registerAction(
  57834. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  57835. function () {}
  57836. );
  57837. var features = {};
  57838. function register$1(name, ctor) {
  57839. features[name] = ctor;
  57840. }
  57841. function get$1(name) {
  57842. return features[name];
  57843. }
  57844. var brushLang = lang.toolbox.brush;
  57845. function Brush(model, ecModel, api) {
  57846. this.model = model;
  57847. this.ecModel = ecModel;
  57848. this.api = api;
  57849. /**
  57850. * @private
  57851. * @type {string}
  57852. */
  57853. this._brushType;
  57854. /**
  57855. * @private
  57856. * @type {string}
  57857. */
  57858. this._brushMode;
  57859. }
  57860. Brush.defaultOption = {
  57861. show: true,
  57862. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  57863. icon: {
  57864. 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
  57865. 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
  57866. 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
  57867. 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
  57868. 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
  57869. 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
  57870. },
  57871. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  57872. title: clone(brushLang.title)
  57873. };
  57874. var proto$3 = Brush.prototype;
  57875. // proto.updateLayout = function (featureModel, ecModel, api) {
  57876. proto$3.render =
  57877. proto$3.updateView = function (featureModel, ecModel, api) {
  57878. var brushType;
  57879. var brushMode;
  57880. var isBrushed;
  57881. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  57882. brushType = brushModel.brushType;
  57883. brushMode = brushModel.brushOption.brushMode || 'single';
  57884. isBrushed |= brushModel.areas.length;
  57885. });
  57886. this._brushType = brushType;
  57887. this._brushMode = brushMode;
  57888. each$1(featureModel.get('type', true), function (type) {
  57889. featureModel.setIconStatus(
  57890. type,
  57891. (
  57892. type === 'keep'
  57893. ? brushMode === 'multiple'
  57894. : type === 'clear'
  57895. ? isBrushed
  57896. : type === brushType
  57897. ) ? 'emphasis' : 'normal'
  57898. );
  57899. });
  57900. };
  57901. proto$3.getIcons = function () {
  57902. var model = this.model;
  57903. var availableIcons = model.get('icon', true);
  57904. var icons = {};
  57905. each$1(model.get('type', true), function (type) {
  57906. if (availableIcons[type]) {
  57907. icons[type] = availableIcons[type];
  57908. }
  57909. });
  57910. return icons;
  57911. };
  57912. proto$3.onclick = function (ecModel, api, type) {
  57913. var brushType = this._brushType;
  57914. var brushMode = this._brushMode;
  57915. if (type === 'clear') {
  57916. // Trigger parallel action firstly
  57917. api.dispatchAction({
  57918. type: 'axisAreaSelect',
  57919. intervals: []
  57920. });
  57921. api.dispatchAction({
  57922. type: 'brush',
  57923. command: 'clear',
  57924. // Clear all areas of all brush components.
  57925. areas: []
  57926. });
  57927. }
  57928. else {
  57929. api.dispatchAction({
  57930. type: 'takeGlobalCursor',
  57931. key: 'brush',
  57932. brushOption: {
  57933. brushType: type === 'keep'
  57934. ? brushType
  57935. : (brushType === type ? false : type),
  57936. brushMode: type === 'keep'
  57937. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  57938. : brushMode
  57939. }
  57940. });
  57941. }
  57942. };
  57943. register$1('brush', Brush);
  57944. /**
  57945. * Brush component entry
  57946. */
  57947. registerPreprocessor(preprocessor$1);
  57948. // (24*60*60*1000)
  57949. var PROXIMATE_ONE_DAY = 86400000;
  57950. /**
  57951. * Calendar
  57952. *
  57953. * @constructor
  57954. *
  57955. * @param {Object} calendarModel calendarModel
  57956. * @param {Object} ecModel ecModel
  57957. * @param {Object} api api
  57958. */
  57959. function Calendar(calendarModel, ecModel, api) {
  57960. this._model = calendarModel;
  57961. }
  57962. Calendar.prototype = {
  57963. constructor: Calendar,
  57964. type: 'calendar',
  57965. dimensions: ['time', 'value'],
  57966. // Required in createListFromData
  57967. getDimensionsInfo: function () {
  57968. return [{name: 'time', type: 'time'}, 'value'];
  57969. },
  57970. getRangeInfo: function () {
  57971. return this._rangeInfo;
  57972. },
  57973. getModel: function () {
  57974. return this._model;
  57975. },
  57976. getRect: function () {
  57977. return this._rect;
  57978. },
  57979. getCellWidth: function () {
  57980. return this._sw;
  57981. },
  57982. getCellHeight: function () {
  57983. return this._sh;
  57984. },
  57985. getOrient: function () {
  57986. return this._orient;
  57987. },
  57988. /**
  57989. * getFirstDayOfWeek
  57990. *
  57991. * @example
  57992. * 0 : start at Sunday
  57993. * 1 : start at Monday
  57994. *
  57995. * @return {number}
  57996. */
  57997. getFirstDayOfWeek: function () {
  57998. return this._firstDayOfWeek;
  57999. },
  58000. /**
  58001. * get date info
  58002. *
  58003. * @param {string|number} date date
  58004. * @return {Object}
  58005. * {
  58006. * y: string, local full year, eg., '1940',
  58007. * m: string, local month, from '01' ot '12',
  58008. * d: string, local date, from '01' to '31' (if exists),
  58009. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  58010. * time: timestamp,
  58011. * formatedDate: string, yyyy-MM-dd,
  58012. * date: original date object.
  58013. * }
  58014. */
  58015. getDateInfo: function (date) {
  58016. date = parseDate(date);
  58017. var y = date.getFullYear();
  58018. var m = date.getMonth() + 1;
  58019. m = m < 10 ? '0' + m : m;
  58020. var d = date.getDate();
  58021. d = d < 10 ? '0' + d : d;
  58022. var day = date.getDay();
  58023. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  58024. return {
  58025. y: y,
  58026. m: m,
  58027. d: d,
  58028. day: day,
  58029. time: date.getTime(),
  58030. formatedDate: y + '-' + m + '-' + d,
  58031. date: date
  58032. };
  58033. },
  58034. getNextNDay: function (date, n) {
  58035. n = n || 0;
  58036. if (n === 0) {
  58037. return this.getDateInfo(date);
  58038. }
  58039. date = new Date(this.getDateInfo(date).time);
  58040. date.setDate(date.getDate() + n);
  58041. return this.getDateInfo(date);
  58042. },
  58043. update: function (ecModel, api) {
  58044. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  58045. this._orient = this._model.get('orient');
  58046. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  58047. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  58048. var weeks = this._rangeInfo.weeks || 1;
  58049. var whNames = ['width', 'height'];
  58050. var cellSize = this._model.get('cellSize').slice();
  58051. var layoutParams = this._model.getBoxLayoutParams();
  58052. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  58053. each$1([0, 1], function (idx) {
  58054. if (cellSizeSpecified(cellSize, idx)) {
  58055. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  58056. }
  58057. });
  58058. var whGlobal = {
  58059. width: api.getWidth(),
  58060. height: api.getHeight()
  58061. };
  58062. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  58063. each$1([0, 1], function (idx) {
  58064. if (!cellSizeSpecified(cellSize, idx)) {
  58065. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  58066. }
  58067. });
  58068. function cellSizeSpecified(cellSize, idx) {
  58069. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  58070. }
  58071. this._sw = cellSize[0];
  58072. this._sh = cellSize[1];
  58073. },
  58074. /**
  58075. * Convert a time data(time, value) item to (x, y) point.
  58076. *
  58077. * @override
  58078. * @param {Array|number} data data
  58079. * @param {boolean} [clamp=true] out of range
  58080. * @return {Array} point
  58081. */
  58082. dataToPoint: function (data, clamp) {
  58083. isArray(data) && (data = data[0]);
  58084. clamp == null && (clamp = true);
  58085. var dayInfo = this.getDateInfo(data);
  58086. var range = this._rangeInfo;
  58087. var date = dayInfo.formatedDate;
  58088. // if not in range return [NaN, NaN]
  58089. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) {
  58090. return [NaN, NaN];
  58091. }
  58092. var week = dayInfo.day;
  58093. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  58094. if (this._orient === 'vertical') {
  58095. return [
  58096. this._rect.x + week * this._sw + this._sw / 2,
  58097. this._rect.y + nthWeek * this._sh + this._sh / 2
  58098. ];
  58099. }
  58100. return [
  58101. this._rect.x + nthWeek * this._sw + this._sw / 2,
  58102. this._rect.y + week * this._sh + this._sh / 2
  58103. ];
  58104. },
  58105. /**
  58106. * Convert a (x, y) point to time data
  58107. *
  58108. * @override
  58109. * @param {string} point point
  58110. * @return {string} data
  58111. */
  58112. pointToData: function (point) {
  58113. var date = this.pointToDate(point);
  58114. return date && date.time;
  58115. },
  58116. /**
  58117. * Convert a time date item to (x, y) four point.
  58118. *
  58119. * @param {Array} data date[0] is date
  58120. * @param {boolean} [clamp=true] out of range
  58121. * @return {Object} point
  58122. */
  58123. dataToRect: function (data, clamp) {
  58124. var point = this.dataToPoint(data, clamp);
  58125. return {
  58126. contentShape: {
  58127. x: point[0] - (this._sw - this._lineWidth) / 2,
  58128. y: point[1] - (this._sh - this._lineWidth) / 2,
  58129. width: this._sw - this._lineWidth,
  58130. height: this._sh - this._lineWidth
  58131. },
  58132. center: point,
  58133. tl: [
  58134. point[0] - this._sw / 2,
  58135. point[1] - this._sh / 2
  58136. ],
  58137. tr: [
  58138. point[0] + this._sw / 2,
  58139. point[1] - this._sh / 2
  58140. ],
  58141. br: [
  58142. point[0] + this._sw / 2,
  58143. point[1] + this._sh / 2
  58144. ],
  58145. bl: [
  58146. point[0] - this._sw / 2,
  58147. point[1] + this._sh / 2
  58148. ]
  58149. };
  58150. },
  58151. /**
  58152. * Convert a (x, y) point to time date
  58153. *
  58154. * @param {Array} point point
  58155. * @return {Object} date
  58156. */
  58157. pointToDate: function (point) {
  58158. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  58159. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  58160. var range = this._rangeInfo.range;
  58161. if (this._orient === 'vertical') {
  58162. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  58163. }
  58164. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  58165. },
  58166. /**
  58167. * @inheritDoc
  58168. */
  58169. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  58170. /**
  58171. * @inheritDoc
  58172. */
  58173. convertFromPixel: curry(doConvert$2, 'pointToData'),
  58174. /**
  58175. * initRange
  58176. *
  58177. * @private
  58178. * @return {Array} [start, end]
  58179. */
  58180. _initRangeOption: function () {
  58181. var range = this._model.get('range');
  58182. var rg = range;
  58183. if (isArray(rg) && rg.length === 1) {
  58184. rg = rg[0];
  58185. }
  58186. if (/^\d{4}$/.test(rg)) {
  58187. range = [rg + '-01-01', rg + '-12-31'];
  58188. }
  58189. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  58190. var start = this.getDateInfo(rg);
  58191. var firstDay = start.date;
  58192. firstDay.setMonth(firstDay.getMonth() + 1);
  58193. var end = this.getNextNDay(firstDay, -1);
  58194. range = [start.formatedDate, end.formatedDate];
  58195. }
  58196. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  58197. range = [rg, rg];
  58198. }
  58199. var tmp = this._getRangeInfo(range);
  58200. if (tmp.start.time > tmp.end.time) {
  58201. range.reverse();
  58202. }
  58203. return range;
  58204. },
  58205. /**
  58206. * range info
  58207. *
  58208. * @private
  58209. * @param {Array} range range ['2017-01-01', '2017-07-08']
  58210. * If range[0] > range[1], they will not be reversed.
  58211. * @return {Object} obj
  58212. */
  58213. _getRangeInfo: function (range) {
  58214. range = [
  58215. this.getDateInfo(range[0]),
  58216. this.getDateInfo(range[1])
  58217. ];
  58218. var reversed;
  58219. if (range[0].time > range[1].time) {
  58220. reversed = true;
  58221. range.reverse();
  58222. }
  58223. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  58224. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  58225. // Consider case:
  58226. // Firstly set system timezone as "Time Zone: America/Toronto",
  58227. // ```
  58228. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  58229. // var second = new Date(1478412000000);
  58230. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  58231. // ```
  58232. // will get wrong result because of DST. So we should fix it.
  58233. var date = new Date(range[0].time);
  58234. var startDateNum = date.getDate();
  58235. var endDateNum = range[1].date.getDate();
  58236. date.setDate(startDateNum + allDay - 1);
  58237. // The bias can not over a month, so just compare date.
  58238. if (date.getDate() !== endDateNum) {
  58239. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  58240. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  58241. allDay -= sign;
  58242. date.setDate(startDateNum + allDay - 1);
  58243. }
  58244. }
  58245. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  58246. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  58247. reversed && range.reverse();
  58248. return {
  58249. range: [range[0].formatedDate, range[1].formatedDate],
  58250. start: range[0],
  58251. end: range[1],
  58252. allDay: allDay,
  58253. weeks: weeks,
  58254. // From 0.
  58255. nthWeek: nthWeek,
  58256. fweek: range[0].day,
  58257. lweek: range[1].day
  58258. };
  58259. },
  58260. /**
  58261. * get date by nthWeeks and week day in range
  58262. *
  58263. * @private
  58264. * @param {number} nthWeek the week
  58265. * @param {number} day the week day
  58266. * @param {Array} range [d1, d2]
  58267. * @return {Object}
  58268. */
  58269. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  58270. var rangeInfo = this._getRangeInfo(range);
  58271. if (nthWeek > rangeInfo.weeks
  58272. || (nthWeek === 0 && day < rangeInfo.fweek)
  58273. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  58274. ) {
  58275. return false;
  58276. }
  58277. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  58278. var date = new Date(rangeInfo.start.time);
  58279. date.setDate(rangeInfo.start.d + nthDay);
  58280. return this.getDateInfo(date);
  58281. }
  58282. };
  58283. Calendar.dimensions = Calendar.prototype.dimensions;
  58284. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  58285. Calendar.create = function (ecModel, api) {
  58286. var calendarList = [];
  58287. ecModel.eachComponent('calendar', function (calendarModel) {
  58288. var calendar = new Calendar(calendarModel, ecModel, api);
  58289. calendarList.push(calendar);
  58290. calendarModel.coordinateSystem = calendar;
  58291. });
  58292. ecModel.eachSeries(function (calendarSeries) {
  58293. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  58294. // Inject coordinate system
  58295. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  58296. }
  58297. });
  58298. return calendarList;
  58299. };
  58300. function doConvert$2(methodName, ecModel, finder, value) {
  58301. var calendarModel = finder.calendarModel;
  58302. var seriesModel = finder.seriesModel;
  58303. var coordSys = calendarModel
  58304. ? calendarModel.coordinateSystem
  58305. : seriesModel
  58306. ? seriesModel.coordinateSystem
  58307. : null;
  58308. return coordSys === this ? coordSys[methodName](value) : null;
  58309. }
  58310. CoordinateSystemManager.register('calendar', Calendar);
  58311. var CalendarModel = ComponentModel.extend({
  58312. type: 'calendar',
  58313. /**
  58314. * @type {module:echarts/coord/calendar/Calendar}
  58315. */
  58316. coordinateSystem: null,
  58317. defaultOption: {
  58318. zlevel: 0,
  58319. z: 2,
  58320. left: 80,
  58321. top: 60,
  58322. cellSize: 20,
  58323. // horizontal vertical
  58324. orient: 'horizontal',
  58325. // month separate line style
  58326. splitLine: {
  58327. show: true,
  58328. lineStyle: {
  58329. color: '#000',
  58330. width: 1,
  58331. type: 'solid'
  58332. }
  58333. },
  58334. // rect style temporarily unused emphasis
  58335. itemStyle: {
  58336. color: '#fff',
  58337. borderWidth: 1,
  58338. borderColor: '#ccc'
  58339. },
  58340. // week text style
  58341. dayLabel: {
  58342. show: true,
  58343. // a week first day
  58344. firstDay: 0,
  58345. // start end
  58346. position: 'start',
  58347. margin: '50%', // 50% of cellSize
  58348. nameMap: 'en',
  58349. color: '#000'
  58350. },
  58351. // month text style
  58352. monthLabel: {
  58353. show: true,
  58354. // start end
  58355. position: 'start',
  58356. margin: 5,
  58357. // center or left
  58358. align: 'center',
  58359. // cn en []
  58360. nameMap: 'en',
  58361. formatter: null,
  58362. color: '#000'
  58363. },
  58364. // year text style
  58365. yearLabel: {
  58366. show: true,
  58367. // top bottom left right
  58368. position: null,
  58369. margin: 30,
  58370. formatter: null,
  58371. color: '#ccc',
  58372. fontFamily: 'sans-serif',
  58373. fontWeight: 'bolder',
  58374. fontSize: 20
  58375. }
  58376. },
  58377. /**
  58378. * @override
  58379. */
  58380. init: function (option, parentModel, ecModel, extraOpt) {
  58381. var inputPositionParams = getLayoutParams(option);
  58382. CalendarModel.superApply(this, 'init', arguments);
  58383. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  58384. },
  58385. /**
  58386. * @override
  58387. */
  58388. mergeOption: function (option, extraOpt) {
  58389. CalendarModel.superApply(this, 'mergeOption', arguments);
  58390. mergeAndNormalizeLayoutParams$1(this.option, option);
  58391. }
  58392. });
  58393. function mergeAndNormalizeLayoutParams$1(target, raw) {
  58394. // Normalize cellSize
  58395. var cellSize = target.cellSize;
  58396. if (!isArray(cellSize)) {
  58397. cellSize = target.cellSize = [cellSize, cellSize];
  58398. }
  58399. else if (cellSize.length === 1) {
  58400. cellSize[1] = cellSize[0];
  58401. }
  58402. var ignoreSize = map([0, 1], function (hvIdx) {
  58403. // If user have set `width` or both `left` and `right`, cellSize
  58404. // will be automatically set to 'auto', otherwise the default
  58405. // setting of cellSize will make `width` setting not work.
  58406. if (sizeCalculable(raw, hvIdx)) {
  58407. cellSize[hvIdx] = 'auto';
  58408. }
  58409. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  58410. });
  58411. mergeLayoutParam(target, raw, {
  58412. type: 'box', ignoreSize: ignoreSize
  58413. });
  58414. }
  58415. var MONTH_TEXT = {
  58416. EN: [
  58417. 'Jan', 'Feb', 'Mar',
  58418. 'Apr', 'May', 'Jun',
  58419. 'Jul', 'Aug', 'Sep',
  58420. 'Oct', 'Nov', 'Dec'
  58421. ],
  58422. CN: [
  58423. '一月', '二月', '三月',
  58424. '四月', '五月', '六月',
  58425. '七月', '八月', '九月',
  58426. '十月', '十一月', '十二月'
  58427. ]
  58428. };
  58429. var WEEK_TEXT = {
  58430. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  58431. CN: ['日', '一', '二', '三', '四', '五', '六']
  58432. };
  58433. extendComponentView({
  58434. type: 'calendar',
  58435. /**
  58436. * top/left line points
  58437. * @private
  58438. */
  58439. _tlpoints: null,
  58440. /**
  58441. * bottom/right line points
  58442. * @private
  58443. */
  58444. _blpoints: null,
  58445. /**
  58446. * first day of month
  58447. * @private
  58448. */
  58449. _firstDayOfMonth: null,
  58450. /**
  58451. * first day point of month
  58452. * @private
  58453. */
  58454. _firstDayPoints: null,
  58455. render: function (calendarModel, ecModel, api) {
  58456. var group = this.group;
  58457. group.removeAll();
  58458. var coordSys = calendarModel.coordinateSystem;
  58459. // range info
  58460. var rangeData = coordSys.getRangeInfo();
  58461. var orient = coordSys.getOrient();
  58462. this._renderDayRect(calendarModel, rangeData, group);
  58463. // _renderLines must be called prior to following function
  58464. this._renderLines(calendarModel, rangeData, orient, group);
  58465. this._renderYearText(calendarModel, rangeData, orient, group);
  58466. this._renderMonthText(calendarModel, orient, group);
  58467. this._renderWeekText(calendarModel, rangeData, orient, group);
  58468. },
  58469. // render day rect
  58470. _renderDayRect: function (calendarModel, rangeData, group) {
  58471. var coordSys = calendarModel.coordinateSystem;
  58472. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  58473. var sw = coordSys.getCellWidth();
  58474. var sh = coordSys.getCellHeight();
  58475. for (var i = rangeData.start.time;
  58476. i <= rangeData.end.time;
  58477. i = coordSys.getNextNDay(i, 1).time
  58478. ) {
  58479. var point = coordSys.dataToRect([i], false).tl;
  58480. // every rect
  58481. var rect = new Rect({
  58482. shape: {
  58483. x: point[0],
  58484. y: point[1],
  58485. width: sw,
  58486. height: sh
  58487. },
  58488. cursor: 'default',
  58489. style: itemRectStyleModel
  58490. });
  58491. group.add(rect);
  58492. }
  58493. },
  58494. // render separate line
  58495. _renderLines: function (calendarModel, rangeData, orient, group) {
  58496. var self = this;
  58497. var coordSys = calendarModel.coordinateSystem;
  58498. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  58499. var show = calendarModel.get('splitLine.show');
  58500. var lineWidth = lineStyleModel.lineWidth;
  58501. this._tlpoints = [];
  58502. this._blpoints = [];
  58503. this._firstDayOfMonth = [];
  58504. this._firstDayPoints = [];
  58505. var firstDay = rangeData.start;
  58506. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  58507. addPoints(firstDay.formatedDate);
  58508. if (i === 0) {
  58509. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  58510. }
  58511. var date = firstDay.date;
  58512. date.setMonth(date.getMonth() + 1);
  58513. firstDay = coordSys.getDateInfo(date);
  58514. }
  58515. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  58516. function addPoints(date) {
  58517. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  58518. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  58519. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  58520. self._tlpoints.push(points[0]);
  58521. self._blpoints.push(points[points.length - 1]);
  58522. show && self._drawSplitline(points, lineStyleModel, group);
  58523. }
  58524. // render top/left line
  58525. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  58526. // render bottom/right line
  58527. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  58528. },
  58529. // get points at both ends
  58530. _getEdgesPoints: function (points, lineWidth, orient) {
  58531. var rs = [points[0].slice(), points[points.length - 1].slice()];
  58532. var idx = orient === 'horizontal' ? 0 : 1;
  58533. // both ends of the line are extend half lineWidth
  58534. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  58535. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  58536. return rs;
  58537. },
  58538. // render split line
  58539. _drawSplitline: function (points, lineStyleModel, group) {
  58540. var poyline = new Polyline({
  58541. z2: 20,
  58542. shape: {
  58543. points: points
  58544. },
  58545. style: lineStyleModel
  58546. });
  58547. group.add(poyline);
  58548. },
  58549. // render month line of one week points
  58550. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  58551. var coordSys = calendarModel.coordinateSystem;
  58552. date = coordSys.getDateInfo(date);
  58553. var points = [];
  58554. for (var i = 0; i < 7; i++) {
  58555. var tmpD = coordSys.getNextNDay(date.time, i);
  58556. var point = coordSys.dataToRect([tmpD.time], false);
  58557. points[2 * tmpD.day] = point.tl;
  58558. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  58559. }
  58560. return points;
  58561. },
  58562. _formatterLabel: function (formatter, params) {
  58563. if (typeof formatter === 'string' && formatter) {
  58564. return formatTplSimple(formatter, params);
  58565. }
  58566. if (typeof formatter === 'function') {
  58567. return formatter(params);
  58568. }
  58569. return params.nameMap;
  58570. },
  58571. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  58572. point = point.slice();
  58573. var aligns = ['center', 'bottom'];
  58574. if (position === 'bottom') {
  58575. point[1] += margin;
  58576. aligns = ['center', 'top'];
  58577. }
  58578. else if (position === 'left') {
  58579. point[0] -= margin;
  58580. }
  58581. else if (position === 'right') {
  58582. point[0] += margin;
  58583. aligns = ['center', 'top'];
  58584. }
  58585. else { // top
  58586. point[1] -= margin;
  58587. }
  58588. var rotate = 0;
  58589. if (position === 'left' || position === 'right') {
  58590. rotate = Math.PI / 2;
  58591. }
  58592. return {
  58593. rotation: rotate,
  58594. position: point,
  58595. style: {
  58596. textAlign: aligns[0],
  58597. textVerticalAlign: aligns[1]
  58598. }
  58599. };
  58600. },
  58601. // render year
  58602. _renderYearText: function (calendarModel, rangeData, orient, group) {
  58603. var yearLabel = calendarModel.getModel('yearLabel');
  58604. if (!yearLabel.get('show')) {
  58605. return;
  58606. }
  58607. var margin = yearLabel.get('margin');
  58608. var pos = yearLabel.get('position');
  58609. if (!pos) {
  58610. pos = orient !== 'horizontal' ? 'top' : 'left';
  58611. }
  58612. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  58613. var xc = (points[0][0] + points[1][0]) / 2;
  58614. var yc = (points[0][1] + points[1][1]) / 2;
  58615. var idx = orient === 'horizontal' ? 0 : 1;
  58616. var posPoints = {
  58617. top: [xc, points[idx][1]],
  58618. bottom: [xc, points[1 - idx][1]],
  58619. left: [points[1 - idx][0], yc],
  58620. right: [points[idx][0], yc]
  58621. };
  58622. var name = rangeData.start.y;
  58623. if (+rangeData.end.y > +rangeData.start.y) {
  58624. name = name + '-' + rangeData.end.y;
  58625. }
  58626. var formatter = yearLabel.get('formatter');
  58627. var params = {
  58628. start: rangeData.start.y,
  58629. end: rangeData.end.y,
  58630. nameMap: name
  58631. };
  58632. var content = this._formatterLabel(formatter, params);
  58633. var yearText = new Text({z2: 30});
  58634. setTextStyle(yearText.style, yearLabel, {text: content}),
  58635. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  58636. group.add(yearText);
  58637. },
  58638. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  58639. var align = 'left';
  58640. var vAlign = 'top';
  58641. var x = point[0];
  58642. var y = point[1];
  58643. if (orient === 'horizontal') {
  58644. y = y + margin;
  58645. if (isCenter) {
  58646. align = 'center';
  58647. }
  58648. if (position === 'start') {
  58649. vAlign = 'bottom';
  58650. }
  58651. }
  58652. else {
  58653. x = x + margin;
  58654. if (isCenter) {
  58655. vAlign = 'middle';
  58656. }
  58657. if (position === 'start') {
  58658. align = 'right';
  58659. }
  58660. }
  58661. return {
  58662. x: x,
  58663. y: y,
  58664. textAlign: align,
  58665. textVerticalAlign: vAlign
  58666. };
  58667. },
  58668. // render month and year text
  58669. _renderMonthText: function (calendarModel, orient, group) {
  58670. var monthLabel = calendarModel.getModel('monthLabel');
  58671. if (!monthLabel.get('show')) {
  58672. return;
  58673. }
  58674. var nameMap = monthLabel.get('nameMap');
  58675. var margin = monthLabel.get('margin');
  58676. var pos = monthLabel.get('position');
  58677. var align = monthLabel.get('align');
  58678. var termPoints = [this._tlpoints, this._blpoints];
  58679. if (isString(nameMap)) {
  58680. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  58681. }
  58682. var idx = pos === 'start' ? 0 : 1;
  58683. var axis = orient === 'horizontal' ? 0 : 1;
  58684. margin = pos === 'start' ? -margin : margin;
  58685. var isCenter = (align === 'center');
  58686. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  58687. var tmp = termPoints[idx][i].slice();
  58688. var firstDay = this._firstDayOfMonth[i];
  58689. if (isCenter) {
  58690. var firstDayPoints = this._firstDayPoints[i];
  58691. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  58692. }
  58693. var formatter = monthLabel.get('formatter');
  58694. var name = nameMap[+firstDay.m - 1];
  58695. var params = {
  58696. yyyy: firstDay.y,
  58697. yy: (firstDay.y + '').slice(2),
  58698. MM: firstDay.m,
  58699. M: +firstDay.m,
  58700. nameMap: name
  58701. };
  58702. var content = this._formatterLabel(formatter, params);
  58703. var monthText = new Text({z2: 30});
  58704. extend(
  58705. setTextStyle(monthText.style, monthLabel, {text: content}),
  58706. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  58707. );
  58708. group.add(monthText);
  58709. }
  58710. },
  58711. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  58712. var align = 'center';
  58713. var vAlign = 'middle';
  58714. var x = point[0];
  58715. var y = point[1];
  58716. var isStart = position === 'start';
  58717. if (orient === 'horizontal') {
  58718. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  58719. align = isStart ? 'right' : 'left';
  58720. }
  58721. else {
  58722. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  58723. vAlign = isStart ? 'bottom' : 'top';
  58724. }
  58725. return {
  58726. x: x,
  58727. y: y,
  58728. textAlign: align,
  58729. textVerticalAlign: vAlign
  58730. };
  58731. },
  58732. // render weeks
  58733. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  58734. var dayLabel = calendarModel.getModel('dayLabel');
  58735. if (!dayLabel.get('show')) {
  58736. return;
  58737. }
  58738. var coordSys = calendarModel.coordinateSystem;
  58739. var pos = dayLabel.get('position');
  58740. var nameMap = dayLabel.get('nameMap');
  58741. var margin = dayLabel.get('margin');
  58742. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  58743. if (isString(nameMap)) {
  58744. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  58745. }
  58746. var start = coordSys.getNextNDay(
  58747. rangeData.end.time, (7 - rangeData.lweek)
  58748. ).time;
  58749. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  58750. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  58751. if (pos === 'start') {
  58752. start = coordSys.getNextNDay(
  58753. rangeData.start.time, -(7 + rangeData.fweek)
  58754. ).time;
  58755. margin = -margin;
  58756. }
  58757. for (var i = 0; i < 7; i++) {
  58758. var tmpD = coordSys.getNextNDay(start, i);
  58759. var point = coordSys.dataToRect([tmpD.time], false).center;
  58760. var day = i;
  58761. day = Math.abs((i + firstDayOfWeek) % 7);
  58762. var weekText = new Text({z2: 30});
  58763. extend(
  58764. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  58765. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  58766. );
  58767. group.add(weekText);
  58768. }
  58769. }
  58770. });
  58771. /**
  58772. * @file calendar.js
  58773. * @author dxh
  58774. */
  58775. // Model
  58776. extendComponentModel({
  58777. type: 'title',
  58778. layoutMode: {type: 'box', ignoreSize: true},
  58779. defaultOption: {
  58780. // 一级层叠
  58781. zlevel: 0,
  58782. // 二级层叠
  58783. z: 6,
  58784. show: true,
  58785. text: '',
  58786. // 超链接跳转
  58787. // link: null,
  58788. // 仅支持self | blank
  58789. target: 'blank',
  58790. subtext: '',
  58791. // 超链接跳转
  58792. // sublink: null,
  58793. // 仅支持self | blank
  58794. subtarget: 'blank',
  58795. // 'center' ¦ 'left' ¦ 'right'
  58796. // ¦ {number}(x坐标,单位px)
  58797. left: 0,
  58798. // 'top' ¦ 'bottom' ¦ 'center'
  58799. // ¦ {number}(y坐标,单位px)
  58800. top: 0,
  58801. // 水平对齐
  58802. // 'auto' | 'left' | 'right' | 'center'
  58803. // 默认根据 left 的位置判断是左对齐还是右对齐
  58804. // textAlign: null
  58805. //
  58806. // 垂直对齐
  58807. // 'auto' | 'top' | 'bottom' | 'middle'
  58808. // 默认根据 top 位置判断是上对齐还是下对齐
  58809. // textBaseline: null
  58810. backgroundColor: 'rgba(0,0,0,0)',
  58811. // 标题边框颜色
  58812. borderColor: '#ccc',
  58813. // 标题边框线宽,单位px,默认为0(无边框)
  58814. borderWidth: 0,
  58815. // 标题内边距,单位px,默认各方向内边距为5,
  58816. // 接受数组分别设定上右下左边距,同css
  58817. padding: 5,
  58818. // 主副标题纵向间隔,单位px,默认为10,
  58819. itemGap: 10,
  58820. textStyle: {
  58821. fontSize: 18,
  58822. fontWeight: 'bolder',
  58823. color: '#333'
  58824. },
  58825. subtextStyle: {
  58826. color: '#aaa'
  58827. }
  58828. }
  58829. });
  58830. // View
  58831. extendComponentView({
  58832. type: 'title',
  58833. render: function (titleModel, ecModel, api) {
  58834. this.group.removeAll();
  58835. if (!titleModel.get('show')) {
  58836. return;
  58837. }
  58838. var group = this.group;
  58839. var textStyleModel = titleModel.getModel('textStyle');
  58840. var subtextStyleModel = titleModel.getModel('subtextStyle');
  58841. var textAlign = titleModel.get('textAlign');
  58842. var textBaseline = titleModel.get('textBaseline');
  58843. var textEl = new Text({
  58844. style: setTextStyle({}, textStyleModel, {
  58845. text: titleModel.get('text'),
  58846. textFill: textStyleModel.getTextColor()
  58847. }, {disableBox: true}),
  58848. z2: 10
  58849. });
  58850. var textRect = textEl.getBoundingRect();
  58851. var subText = titleModel.get('subtext');
  58852. var subTextEl = new Text({
  58853. style: setTextStyle({}, subtextStyleModel, {
  58854. text: subText,
  58855. textFill: subtextStyleModel.getTextColor(),
  58856. y: textRect.height + titleModel.get('itemGap'),
  58857. textVerticalAlign: 'top'
  58858. }, {disableBox: true}),
  58859. z2: 10
  58860. });
  58861. var link = titleModel.get('link');
  58862. var sublink = titleModel.get('sublink');
  58863. textEl.silent = !link;
  58864. subTextEl.silent = !sublink;
  58865. if (link) {
  58866. textEl.on('click', function () {
  58867. window.open(link, '_' + titleModel.get('target'));
  58868. });
  58869. }
  58870. if (sublink) {
  58871. subTextEl.on('click', function () {
  58872. window.open(sublink, '_' + titleModel.get('subtarget'));
  58873. });
  58874. }
  58875. group.add(textEl);
  58876. subText && group.add(subTextEl);
  58877. // If no subText, but add subTextEl, there will be an empty line.
  58878. var groupRect = group.getBoundingRect();
  58879. var layoutOption = titleModel.getBoxLayoutParams();
  58880. layoutOption.width = groupRect.width;
  58881. layoutOption.height = groupRect.height;
  58882. var layoutRect = getLayoutRect(
  58883. layoutOption, {
  58884. width: api.getWidth(),
  58885. height: api.getHeight()
  58886. }, titleModel.get('padding')
  58887. );
  58888. // Adjust text align based on position
  58889. if (!textAlign) {
  58890. // Align left if title is on the left. center and right is same
  58891. textAlign = titleModel.get('left') || titleModel.get('right');
  58892. if (textAlign === 'middle') {
  58893. textAlign = 'center';
  58894. }
  58895. // Adjust layout by text align
  58896. if (textAlign === 'right') {
  58897. layoutRect.x += layoutRect.width;
  58898. }
  58899. else if (textAlign === 'center') {
  58900. layoutRect.x += layoutRect.width / 2;
  58901. }
  58902. }
  58903. if (!textBaseline) {
  58904. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  58905. if (textBaseline === 'center') {
  58906. textBaseline = 'middle';
  58907. }
  58908. if (textBaseline === 'bottom') {
  58909. layoutRect.y += layoutRect.height;
  58910. }
  58911. else if (textBaseline === 'middle') {
  58912. layoutRect.y += layoutRect.height / 2;
  58913. }
  58914. textBaseline = textBaseline || 'top';
  58915. }
  58916. group.attr('position', [layoutRect.x, layoutRect.y]);
  58917. var alignStyle = {
  58918. textAlign: textAlign,
  58919. textVerticalAlign: textBaseline
  58920. };
  58921. textEl.setStyle(alignStyle);
  58922. subTextEl.setStyle(alignStyle);
  58923. // Render background
  58924. // Get groupRect again because textAlign has been changed
  58925. groupRect = group.getBoundingRect();
  58926. var padding = layoutRect.margin;
  58927. var style = titleModel.getItemStyle(['color', 'opacity']);
  58928. style.fill = titleModel.get('backgroundColor');
  58929. var rect = new Rect({
  58930. shape: {
  58931. x: groupRect.x - padding[3],
  58932. y: groupRect.y - padding[0],
  58933. width: groupRect.width + padding[1] + padding[3],
  58934. height: groupRect.height + padding[0] + padding[2],
  58935. r: titleModel.get('borderRadius')
  58936. },
  58937. style: style,
  58938. silent: true
  58939. });
  58940. subPixelOptimizeRect(rect);
  58941. group.add(rect);
  58942. }
  58943. });
  58944. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  58945. // Default 'slider' when no type specified.
  58946. return 'slider';
  58947. });
  58948. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  58949. // Supported coords.
  58950. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  58951. /**
  58952. * @param {string} coordType
  58953. * @return {boolean}
  58954. */
  58955. function isCoordSupported(coordType) {
  58956. return indexOf(COORDS, coordType) >= 0;
  58957. }
  58958. /**
  58959. * Create "each" method to iterate names.
  58960. *
  58961. * @pubilc
  58962. * @param {Array.<string>} names
  58963. * @param {Array.<string>=} attrs
  58964. * @return {Function}
  58965. */
  58966. function createNameEach(names, attrs) {
  58967. names = names.slice();
  58968. var capitalNames = map(names, capitalFirst);
  58969. attrs = (attrs || []).slice();
  58970. var capitalAttrs = map(attrs, capitalFirst);
  58971. return function (callback, context) {
  58972. each$1(names, function (name, index) {
  58973. var nameObj = {name: name, capital: capitalNames[index]};
  58974. for (var j = 0; j < attrs.length; j++) {
  58975. nameObj[attrs[j]] = name + capitalAttrs[j];
  58976. }
  58977. callback.call(context, nameObj);
  58978. });
  58979. };
  58980. }
  58981. /**
  58982. * Iterate each dimension name.
  58983. *
  58984. * @public
  58985. * @param {Function} callback The parameter is like:
  58986. * {
  58987. * name: 'angle',
  58988. * capital: 'Angle',
  58989. * axis: 'angleAxis',
  58990. * axisIndex: 'angleAixs',
  58991. * index: 'angleIndex'
  58992. * }
  58993. * @param {Object} context
  58994. */
  58995. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  58996. /**
  58997. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  58998. * dataZoomModels and 'links' make up one or more graphics.
  58999. * This function finds the graphic where the source dataZoomModel is in.
  59000. *
  59001. * @public
  59002. * @param {Function} forEachNode Node iterator.
  59003. * @param {Function} forEachEdgeType edgeType iterator
  59004. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  59005. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  59006. */
  59007. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  59008. return function (sourceNode) {
  59009. var result = {
  59010. nodes: [],
  59011. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  59012. };
  59013. forEachEdgeType(function (edgeType) {
  59014. result.records[edgeType.name] = {};
  59015. });
  59016. if (!sourceNode) {
  59017. return result;
  59018. }
  59019. absorb(sourceNode, result);
  59020. var existsLink;
  59021. do {
  59022. existsLink = false;
  59023. forEachNode(processSingleNode);
  59024. }
  59025. while (existsLink);
  59026. function processSingleNode(node) {
  59027. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  59028. absorb(node, result);
  59029. existsLink = true;
  59030. }
  59031. }
  59032. return result;
  59033. };
  59034. function isNodeAbsorded(node, result) {
  59035. return indexOf(result.nodes, node) >= 0;
  59036. }
  59037. function isLinked(node, result) {
  59038. var hasLink = false;
  59039. forEachEdgeType(function (edgeType) {
  59040. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  59041. result.records[edgeType.name][edgeId] && (hasLink = true);
  59042. });
  59043. });
  59044. return hasLink;
  59045. }
  59046. function absorb(node, result) {
  59047. result.nodes.push(node);
  59048. forEachEdgeType(function (edgeType) {
  59049. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  59050. result.records[edgeType.name][edgeId] = true;
  59051. });
  59052. });
  59053. }
  59054. }
  59055. var each$23 = each$1;
  59056. var asc$1 = asc;
  59057. /**
  59058. * Operate single axis.
  59059. * One axis can only operated by one axis operator.
  59060. * Different dataZoomModels may be defined to operate the same axis.
  59061. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  59062. * So dataZoomModels share one axisProxy in that case.
  59063. *
  59064. * @class
  59065. */
  59066. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  59067. /**
  59068. * @private
  59069. * @type {string}
  59070. */
  59071. this._dimName = dimName;
  59072. /**
  59073. * @private
  59074. */
  59075. this._axisIndex = axisIndex;
  59076. /**
  59077. * @private
  59078. * @type {Array.<number>}
  59079. */
  59080. this._valueWindow;
  59081. /**
  59082. * @private
  59083. * @type {Array.<number>}
  59084. */
  59085. this._percentWindow;
  59086. /**
  59087. * @private
  59088. * @type {Array.<number>}
  59089. */
  59090. this._dataExtent;
  59091. /**
  59092. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  59093. * @private
  59094. * @type {Object}
  59095. */
  59096. this._minMaxSpan;
  59097. /**
  59098. * @readOnly
  59099. * @type {module: echarts/model/Global}
  59100. */
  59101. this.ecModel = ecModel;
  59102. /**
  59103. * @private
  59104. * @type {module: echarts/component/dataZoom/DataZoomModel}
  59105. */
  59106. this._dataZoomModel = dataZoomModel;
  59107. // /**
  59108. // * @readOnly
  59109. // * @private
  59110. // */
  59111. // this.hasSeriesStacked;
  59112. };
  59113. AxisProxy.prototype = {
  59114. constructor: AxisProxy,
  59115. /**
  59116. * Whether the axisProxy is hosted by dataZoomModel.
  59117. *
  59118. * @public
  59119. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59120. * @return {boolean}
  59121. */
  59122. hostedBy: function (dataZoomModel) {
  59123. return this._dataZoomModel === dataZoomModel;
  59124. },
  59125. /**
  59126. * @return {Array.<number>} Value can only be NaN or finite value.
  59127. */
  59128. getDataValueWindow: function () {
  59129. return this._valueWindow.slice();
  59130. },
  59131. /**
  59132. * @return {Array.<number>}
  59133. */
  59134. getDataPercentWindow: function () {
  59135. return this._percentWindow.slice();
  59136. },
  59137. /**
  59138. * @public
  59139. * @param {number} axisIndex
  59140. * @return {Array} seriesModels
  59141. */
  59142. getTargetSeriesModels: function () {
  59143. var seriesModels = [];
  59144. var ecModel = this.ecModel;
  59145. ecModel.eachSeries(function (seriesModel) {
  59146. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  59147. var dimName = this._dimName;
  59148. var axisModel = ecModel.queryComponents({
  59149. mainType: dimName + 'Axis',
  59150. index: seriesModel.get(dimName + 'AxisIndex'),
  59151. id: seriesModel.get(dimName + 'AxisId')
  59152. })[0];
  59153. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  59154. seriesModels.push(seriesModel);
  59155. }
  59156. }
  59157. }, this);
  59158. return seriesModels;
  59159. },
  59160. getAxisModel: function () {
  59161. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  59162. },
  59163. getOtherAxisModel: function () {
  59164. var axisDim = this._dimName;
  59165. var ecModel = this.ecModel;
  59166. var axisModel = this.getAxisModel();
  59167. var isCartesian = axisDim === 'x' || axisDim === 'y';
  59168. var otherAxisDim;
  59169. var coordSysIndexName;
  59170. if (isCartesian) {
  59171. coordSysIndexName = 'gridIndex';
  59172. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  59173. }
  59174. else {
  59175. coordSysIndexName = 'polarIndex';
  59176. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  59177. }
  59178. var foundOtherAxisModel;
  59179. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  59180. if ((otherAxisModel.get(coordSysIndexName) || 0)
  59181. === (axisModel.get(coordSysIndexName) || 0)
  59182. ) {
  59183. foundOtherAxisModel = otherAxisModel;
  59184. }
  59185. });
  59186. return foundOtherAxisModel;
  59187. },
  59188. getMinMaxSpan: function () {
  59189. return clone(this._minMaxSpan);
  59190. },
  59191. /**
  59192. * Only calculate by given range and this._dataExtent, do not change anything.
  59193. *
  59194. * @param {Object} opt
  59195. * @param {number} [opt.start]
  59196. * @param {number} [opt.end]
  59197. * @param {number} [opt.startValue]
  59198. * @param {number} [opt.endValue]
  59199. */
  59200. calculateDataWindow: function (opt) {
  59201. var dataExtent = this._dataExtent;
  59202. var axisModel = this.getAxisModel();
  59203. var scale = axisModel.axis.scale;
  59204. var rangePropMode = this._dataZoomModel.getRangePropMode();
  59205. var percentExtent = [0, 100];
  59206. var percentWindow = [
  59207. opt.start,
  59208. opt.end
  59209. ];
  59210. var valueWindow = [];
  59211. each$23(['startValue', 'endValue'], function (prop) {
  59212. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  59213. });
  59214. // Normalize bound.
  59215. each$23([0, 1], function (idx) {
  59216. var boundValue = valueWindow[idx];
  59217. var boundPercent = percentWindow[idx];
  59218. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  59219. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  59220. // for cases that a dataZoom component controls multiple axes with different
  59221. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  59222. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  59223. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  59224. // accurately (because all of values that are overflow the `dataExtent` will
  59225. // be calculated to percent '100%'). So we have to use
  59226. // `dataZoom.getRangePropMode()` to mark which prop is used.
  59227. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  59228. // it remains its original value.
  59229. if (rangePropMode[idx] === 'percent') {
  59230. if (boundPercent == null) {
  59231. boundPercent = percentExtent[idx];
  59232. }
  59233. // Use scale.parse to math round for category or time axis.
  59234. boundValue = scale.parse(linearMap(
  59235. boundPercent, percentExtent, dataExtent, true
  59236. ));
  59237. }
  59238. else {
  59239. // Calculating `percent` from `value` may be not accurate, because
  59240. // This calculation can not be inversed, because all of values that
  59241. // are overflow the `dataExtent` will be calculated to percent '100%'
  59242. boundPercent = linearMap(
  59243. boundValue, dataExtent, percentExtent, true
  59244. );
  59245. }
  59246. // valueWindow[idx] = round(boundValue);
  59247. // percentWindow[idx] = round(boundPercent);
  59248. valueWindow[idx] = boundValue;
  59249. percentWindow[idx] = boundPercent;
  59250. });
  59251. return {
  59252. valueWindow: asc$1(valueWindow),
  59253. percentWindow: asc$1(percentWindow)
  59254. };
  59255. },
  59256. /**
  59257. * Notice: reset should not be called before series.restoreData() called,
  59258. * so it is recommanded to be called in "process stage" but not "model init
  59259. * stage".
  59260. *
  59261. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59262. */
  59263. reset: function (dataZoomModel) {
  59264. if (dataZoomModel !== this._dataZoomModel) {
  59265. return;
  59266. }
  59267. var targetSeries = this.getTargetSeriesModels();
  59268. // Culculate data window and data extent, and record them.
  59269. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  59270. // this.hasSeriesStacked = false;
  59271. // each(targetSeries, function (series) {
  59272. // var data = series.getData();
  59273. // var dataDim = data.mapDimension(this._dimName);
  59274. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  59275. // if (stackedDimension && stackedDimension === dataDim) {
  59276. // this.hasSeriesStacked = true;
  59277. // }
  59278. // }, this);
  59279. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  59280. this._valueWindow = dataWindow.valueWindow;
  59281. this._percentWindow = dataWindow.percentWindow;
  59282. setMinMaxSpan(this);
  59283. // Update axis setting then.
  59284. setAxisModel(this);
  59285. },
  59286. /**
  59287. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59288. */
  59289. restore: function (dataZoomModel) {
  59290. if (dataZoomModel !== this._dataZoomModel) {
  59291. return;
  59292. }
  59293. this._valueWindow = this._percentWindow = null;
  59294. setAxisModel(this, true);
  59295. },
  59296. /**
  59297. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59298. */
  59299. filterData: function (dataZoomModel, api) {
  59300. if (dataZoomModel !== this._dataZoomModel) {
  59301. return;
  59302. }
  59303. var axisDim = this._dimName;
  59304. var seriesModels = this.getTargetSeriesModels();
  59305. var filterMode = dataZoomModel.get('filterMode');
  59306. var valueWindow = this._valueWindow;
  59307. if (filterMode === 'none') {
  59308. return;
  59309. }
  59310. // FIXME
  59311. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  59312. // with NaN data, NaN will be filtered and stack will be wrong.
  59313. // So we need to force the mode to be set empty.
  59314. // In fect, it is not a big deal that do not support filterMode-'filter'
  59315. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  59316. // selection" some day, which might need "adapt to data extent on the
  59317. // otherAxis", which is disabled by filterMode-'empty'.
  59318. // But currently, stack has been fixed to based on value but not index,
  59319. // so this is not an issue any more.
  59320. // var otherAxisModel = this.getOtherAxisModel();
  59321. // if (dataZoomModel.get('$fromToolbox')
  59322. // && otherAxisModel
  59323. // && otherAxisModel.hasSeriesStacked
  59324. // ) {
  59325. // filterMode = 'empty';
  59326. // }
  59327. // TODO
  59328. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  59329. // Process series data
  59330. each$23(seriesModels, function (seriesModel) {
  59331. var seriesData = seriesModel.getData();
  59332. var dataDims = seriesData.mapDimension(axisDim, true);
  59333. if (filterMode === 'weakFilter') {
  59334. seriesData.filterSelf(function (dataIndex) {
  59335. var leftOut;
  59336. var rightOut;
  59337. var hasValue;
  59338. for (var i = 0; i < dataDims.length; i++) {
  59339. var value = seriesData.get(dataDims[i], dataIndex);
  59340. var thisHasValue = !isNaN(value);
  59341. var thisLeftOut = value < valueWindow[0];
  59342. var thisRightOut = value > valueWindow[1];
  59343. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  59344. return true;
  59345. }
  59346. thisHasValue && (hasValue = true);
  59347. thisLeftOut && (leftOut = true);
  59348. thisRightOut && (rightOut = true);
  59349. }
  59350. // If both left out and right out, do not filter.
  59351. return hasValue && leftOut && rightOut;
  59352. });
  59353. }
  59354. else {
  59355. each$23(dataDims, function (dim) {
  59356. if (filterMode === 'empty') {
  59357. seriesModel.setData(
  59358. seriesData.map(dim, function (value) {
  59359. return !isInWindow(value) ? NaN : value;
  59360. })
  59361. );
  59362. }
  59363. else {
  59364. var range = {};
  59365. range[dim] = valueWindow;
  59366. // console.time('select');
  59367. seriesData.selectRange(range);
  59368. // console.timeEnd('select');
  59369. }
  59370. });
  59371. }
  59372. each$23(dataDims, function (dim) {
  59373. seriesData.setApproximateExtent(valueWindow, dim);
  59374. });
  59375. });
  59376. function isInWindow(value) {
  59377. return value >= valueWindow[0] && value <= valueWindow[1];
  59378. }
  59379. }
  59380. };
  59381. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  59382. var dataExtent = [Infinity, -Infinity];
  59383. each$23(seriesModels, function (seriesModel) {
  59384. var seriesData = seriesModel.getData();
  59385. if (seriesData) {
  59386. each$23(seriesData.mapDimension(axisDim, true), function (dim) {
  59387. var seriesExtent = seriesData.getApproximateExtent(dim);
  59388. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  59389. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  59390. });
  59391. }
  59392. });
  59393. if (dataExtent[1] < dataExtent[0]) {
  59394. dataExtent = [NaN, NaN];
  59395. }
  59396. // It is important to get "consistent" extent when more then one axes is
  59397. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  59398. // when zooming. But it is difficult to know what is "consistent", considering
  59399. // axes have different type or even different meanings (For example, two
  59400. // time axes are used to compare data of the same date in different years).
  59401. // So basically dataZoom just obtains extent by series.data (in category axis
  59402. // extent can be obtained from axis.data).
  59403. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  59404. // consistent.
  59405. fixExtentByAxis(axisProxy, dataExtent);
  59406. return dataExtent;
  59407. }
  59408. function fixExtentByAxis(axisProxy, dataExtent) {
  59409. var axisModel = axisProxy.getAxisModel();
  59410. var min = axisModel.getMin(true);
  59411. // For category axis, if min/max/scale are not set, extent is determined
  59412. // by axis.data by default.
  59413. var isCategoryAxis = axisModel.get('type') === 'category';
  59414. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  59415. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  59416. dataExtent[0] = min;
  59417. }
  59418. else if (isCategoryAxis) {
  59419. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  59420. }
  59421. var max = axisModel.getMax(true);
  59422. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  59423. dataExtent[1] = max;
  59424. }
  59425. else if (isCategoryAxis) {
  59426. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  59427. }
  59428. if (!axisModel.get('scale', true)) {
  59429. dataExtent[0] > 0 && (dataExtent[0] = 0);
  59430. dataExtent[1] < 0 && (dataExtent[1] = 0);
  59431. }
  59432. // For value axis, if min/max/scale are not set, we just use the extent obtained
  59433. // by series data, which may be a little different from the extent calculated by
  59434. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  59435. // little when zooming. So it will not be fixed until some users require it strongly.
  59436. return dataExtent;
  59437. }
  59438. function setAxisModel(axisProxy, isRestore) {
  59439. var axisModel = axisProxy.getAxisModel();
  59440. var percentWindow = axisProxy._percentWindow;
  59441. var valueWindow = axisProxy._valueWindow;
  59442. if (!percentWindow) {
  59443. return;
  59444. }
  59445. // [0, 500]: arbitrary value, guess axis extent.
  59446. var precision = getPixelPrecision(valueWindow, [0, 500]);
  59447. precision = Math.min(precision, 20);
  59448. // isRestore or isFull
  59449. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  59450. axisModel.setRange(
  59451. useOrigin ? null : +valueWindow[0].toFixed(precision),
  59452. useOrigin ? null : +valueWindow[1].toFixed(precision)
  59453. );
  59454. }
  59455. function setMinMaxSpan(axisProxy) {
  59456. var minMaxSpan = axisProxy._minMaxSpan = {};
  59457. var dataZoomModel = axisProxy._dataZoomModel;
  59458. each$23(['min', 'max'], function (minMax) {
  59459. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  59460. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  59461. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  59462. if (valueSpan != null) {
  59463. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  59464. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  59465. if (valueSpan != null) {
  59466. var dataExtent = axisProxy._dataExtent;
  59467. minMaxSpan[minMax + 'Span'] = linearMap(
  59468. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  59469. );
  59470. }
  59471. }
  59472. });
  59473. }
  59474. var each$22 = each$1;
  59475. var eachAxisDim = eachAxisDim$1;
  59476. var DataZoomModel = extendComponentModel({
  59477. type: 'dataZoom',
  59478. dependencies: [
  59479. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  59480. ],
  59481. /**
  59482. * @protected
  59483. */
  59484. defaultOption: {
  59485. zlevel: 0,
  59486. z: 4, // Higher than normal component (z: 2).
  59487. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  59488. xAxisIndex: null, // Default the first horizontal category axis.
  59489. yAxisIndex: null, // Default the first vertical category axis.
  59490. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  59491. // 'filter': data items which are out of window will be removed. This option is
  59492. // applicable when filtering outliers. For each data item, it will be
  59493. // filtered if one of the relevant dimensions is out of the window.
  59494. // 'weakFilter': data items which are out of window will be removed. This option
  59495. // is applicable when filtering outliers. For each data item, it will be
  59496. // filtered only if all of the relevant dimensions are out of the same
  59497. // side of the window.
  59498. // 'empty': data items which are out of window will be set to empty.
  59499. // This option is applicable when user should not neglect
  59500. // that there are some data items out of window.
  59501. // 'none': Do not filter.
  59502. // Taking line chart as an example, line will be broken in
  59503. // the filtered points when filterModel is set to 'empty', but
  59504. // be connected when set to 'filter'.
  59505. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  59506. // default 100. Do not throttle when use null/undefined.
  59507. // If animation === true and animationDurationUpdate > 0,
  59508. // default value is 100, otherwise 20.
  59509. start: 0, // Start percent. 0 ~ 100
  59510. end: 100, // End percent. 0 ~ 100
  59511. startValue: null, // Start value. If startValue specified, start is ignored.
  59512. endValue: null, // End value. If endValue specified, end is ignored.
  59513. minSpan: null, // 0 ~ 100
  59514. maxSpan: null, // 0 ~ 100
  59515. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  59516. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  59517. rangeMode: null // Array, can be 'value' or 'percent'.
  59518. },
  59519. /**
  59520. * @override
  59521. */
  59522. init: function (option, parentModel, ecModel) {
  59523. /**
  59524. * key like x_0, y_1
  59525. * @private
  59526. * @type {Object}
  59527. */
  59528. this._dataIntervalByAxis = {};
  59529. /**
  59530. * @private
  59531. */
  59532. this._dataInfo = {};
  59533. /**
  59534. * key like x_0, y_1
  59535. * @private
  59536. */
  59537. this._axisProxies = {};
  59538. /**
  59539. * @readOnly
  59540. */
  59541. this.textStyleModel;
  59542. /**
  59543. * @private
  59544. */
  59545. this._autoThrottle = true;
  59546. /**
  59547. * 'percent' or 'value'
  59548. * @private
  59549. */
  59550. this._rangePropMode = ['percent', 'percent'];
  59551. var rawOption = retrieveRaw(option);
  59552. this.mergeDefaultAndTheme(option, ecModel);
  59553. this.doInit(rawOption);
  59554. },
  59555. /**
  59556. * @override
  59557. */
  59558. mergeOption: function (newOption) {
  59559. var rawOption = retrieveRaw(newOption);
  59560. //FIX #2591
  59561. merge(this.option, newOption, true);
  59562. this.doInit(rawOption);
  59563. },
  59564. /**
  59565. * @protected
  59566. */
  59567. doInit: function (rawOption) {
  59568. var thisOption = this.option;
  59569. // Disable realtime view update if canvas is not supported.
  59570. if (!env$1.canvasSupported) {
  59571. thisOption.realtime = false;
  59572. }
  59573. this._setDefaultThrottle(rawOption);
  59574. updateRangeUse(this, rawOption);
  59575. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  59576. // start/end has higher priority over startValue/endValue if they
  59577. // both set, but we should make chart.setOption({endValue: 1000})
  59578. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  59579. if (this._rangePropMode[index] === 'value') {
  59580. thisOption[names[0]] = null;
  59581. }
  59582. // Otherwise do nothing and use the merge result.
  59583. }, this);
  59584. this.textStyleModel = this.getModel('textStyle');
  59585. this._resetTarget();
  59586. this._giveAxisProxies();
  59587. },
  59588. /**
  59589. * @private
  59590. */
  59591. _giveAxisProxies: function () {
  59592. var axisProxies = this._axisProxies;
  59593. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  59594. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  59595. // If exists, share axisProxy with other dataZoomModels.
  59596. var axisProxy = axisModel.__dzAxisProxy || (
  59597. // Use the first dataZoomModel as the main model of axisProxy.
  59598. axisModel.__dzAxisProxy = new AxisProxy(
  59599. dimNames.name, axisIndex, this, ecModel
  59600. )
  59601. );
  59602. // FIXME
  59603. // dispose __dzAxisProxy
  59604. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  59605. }, this);
  59606. },
  59607. /**
  59608. * @private
  59609. */
  59610. _resetTarget: function () {
  59611. var thisOption = this.option;
  59612. var autoMode = this._judgeAutoMode();
  59613. eachAxisDim(function (dimNames) {
  59614. var axisIndexName = dimNames.axisIndex;
  59615. thisOption[axisIndexName] = normalizeToArray(
  59616. thisOption[axisIndexName]
  59617. );
  59618. }, this);
  59619. if (autoMode === 'axisIndex') {
  59620. this._autoSetAxisIndex();
  59621. }
  59622. else if (autoMode === 'orient') {
  59623. this._autoSetOrient();
  59624. }
  59625. },
  59626. /**
  59627. * @private
  59628. */
  59629. _judgeAutoMode: function () {
  59630. // Auto set only works for setOption at the first time.
  59631. // The following is user's reponsibility. So using merged
  59632. // option is OK.
  59633. var thisOption = this.option;
  59634. var hasIndexSpecified = false;
  59635. eachAxisDim(function (dimNames) {
  59636. // When user set axisIndex as a empty array, we think that user specify axisIndex
  59637. // but do not want use auto mode. Because empty array may be encountered when
  59638. // some error occured.
  59639. if (thisOption[dimNames.axisIndex] != null) {
  59640. hasIndexSpecified = true;
  59641. }
  59642. }, this);
  59643. var orient = thisOption.orient;
  59644. if (orient == null && hasIndexSpecified) {
  59645. return 'orient';
  59646. }
  59647. else if (!hasIndexSpecified) {
  59648. if (orient == null) {
  59649. thisOption.orient = 'horizontal';
  59650. }
  59651. return 'axisIndex';
  59652. }
  59653. },
  59654. /**
  59655. * @private
  59656. */
  59657. _autoSetAxisIndex: function () {
  59658. var autoAxisIndex = true;
  59659. var orient = this.get('orient', true);
  59660. var thisOption = this.option;
  59661. var dependentModels = this.dependentModels;
  59662. if (autoAxisIndex) {
  59663. // Find axis that parallel to dataZoom as default.
  59664. var dimName = orient === 'vertical' ? 'y' : 'x';
  59665. if (dependentModels[dimName + 'Axis'].length) {
  59666. thisOption[dimName + 'AxisIndex'] = [0];
  59667. autoAxisIndex = false;
  59668. }
  59669. else {
  59670. each$22(dependentModels.singleAxis, function (singleAxisModel) {
  59671. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  59672. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  59673. autoAxisIndex = false;
  59674. }
  59675. });
  59676. }
  59677. }
  59678. if (autoAxisIndex) {
  59679. // Find the first category axis as default. (consider polar)
  59680. eachAxisDim(function (dimNames) {
  59681. if (!autoAxisIndex) {
  59682. return;
  59683. }
  59684. var axisIndices = [];
  59685. var axisModels = this.dependentModels[dimNames.axis];
  59686. if (axisModels.length && !axisIndices.length) {
  59687. for (var i = 0, len = axisModels.length; i < len; i++) {
  59688. if (axisModels[i].get('type') === 'category') {
  59689. axisIndices.push(i);
  59690. }
  59691. }
  59692. }
  59693. thisOption[dimNames.axisIndex] = axisIndices;
  59694. if (axisIndices.length) {
  59695. autoAxisIndex = false;
  59696. }
  59697. }, this);
  59698. }
  59699. if (autoAxisIndex) {
  59700. // FIXME
  59701. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  59702. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  59703. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  59704. // dataZoom component auto adopts series that reference to
  59705. // both xAxis and yAxis which type is 'value'.
  59706. this.ecModel.eachSeries(function (seriesModel) {
  59707. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  59708. eachAxisDim(function (dimNames) {
  59709. var axisIndices = thisOption[dimNames.axisIndex];
  59710. var axisIndex = seriesModel.get(dimNames.axisIndex);
  59711. var axisId = seriesModel.get(dimNames.axisId);
  59712. var axisModel = seriesModel.ecModel.queryComponents({
  59713. mainType: dimNames.axis,
  59714. index: axisIndex,
  59715. id: axisId
  59716. })[0];
  59717. if (__DEV__) {
  59718. if (!axisModel) {
  59719. throw new Error(
  59720. dimNames.axis + ' "' + retrieve(
  59721. axisIndex,
  59722. axisId,
  59723. 0
  59724. ) + '" not found'
  59725. );
  59726. }
  59727. }
  59728. axisIndex = axisModel.componentIndex;
  59729. if (indexOf(axisIndices, axisIndex) < 0) {
  59730. axisIndices.push(axisIndex);
  59731. }
  59732. });
  59733. }
  59734. }, this);
  59735. }
  59736. },
  59737. /**
  59738. * @private
  59739. */
  59740. _autoSetOrient: function () {
  59741. var dim;
  59742. // Find the first axis
  59743. this.eachTargetAxis(function (dimNames) {
  59744. !dim && (dim = dimNames.name);
  59745. }, this);
  59746. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  59747. },
  59748. /**
  59749. * @private
  59750. */
  59751. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  59752. // FIXME
  59753. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  59754. // 例如series.type === scatter时。
  59755. var is = true;
  59756. eachAxisDim(function (dimNames) {
  59757. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  59758. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  59759. if (!axisModel || axisModel.get('type') !== axisType) {
  59760. is = false;
  59761. }
  59762. }, this);
  59763. return is;
  59764. },
  59765. /**
  59766. * @private
  59767. */
  59768. _setDefaultThrottle: function (rawOption) {
  59769. // When first time user set throttle, auto throttle ends.
  59770. if (rawOption.hasOwnProperty('throttle')) {
  59771. this._autoThrottle = false;
  59772. }
  59773. if (this._autoThrottle) {
  59774. var globalOption = this.ecModel.option;
  59775. this.option.throttle =
  59776. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  59777. ? 100 : 20;
  59778. }
  59779. },
  59780. /**
  59781. * @public
  59782. */
  59783. getFirstTargetAxisModel: function () {
  59784. var firstAxisModel;
  59785. eachAxisDim(function (dimNames) {
  59786. if (firstAxisModel == null) {
  59787. var indices = this.get(dimNames.axisIndex);
  59788. if (indices.length) {
  59789. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  59790. }
  59791. }
  59792. }, this);
  59793. return firstAxisModel;
  59794. },
  59795. /**
  59796. * @public
  59797. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  59798. */
  59799. eachTargetAxis: function (callback, context) {
  59800. var ecModel = this.ecModel;
  59801. eachAxisDim(function (dimNames) {
  59802. each$22(
  59803. this.get(dimNames.axisIndex),
  59804. function (axisIndex) {
  59805. callback.call(context, dimNames, axisIndex, this, ecModel);
  59806. },
  59807. this
  59808. );
  59809. }, this);
  59810. },
  59811. /**
  59812. * @param {string} dimName
  59813. * @param {number} axisIndex
  59814. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  59815. */
  59816. getAxisProxy: function (dimName, axisIndex) {
  59817. return this._axisProxies[dimName + '_' + axisIndex];
  59818. },
  59819. /**
  59820. * @param {string} dimName
  59821. * @param {number} axisIndex
  59822. * @return {module:echarts/model/Model} If not found, return null/undefined.
  59823. */
  59824. getAxisModel: function (dimName, axisIndex) {
  59825. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  59826. return axisProxy && axisProxy.getAxisModel();
  59827. },
  59828. /**
  59829. * If not specified, set to undefined.
  59830. *
  59831. * @public
  59832. * @param {Object} opt
  59833. * @param {number} [opt.start]
  59834. * @param {number} [opt.end]
  59835. * @param {number} [opt.startValue]
  59836. * @param {number} [opt.endValue]
  59837. * @param {boolean} [ignoreUpdateRangeUsg=false]
  59838. */
  59839. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  59840. var option = this.option;
  59841. each$22([['start', 'startValue'], ['end', 'endValue']], function (names) {
  59842. // If only one of 'start' and 'startValue' is not null/undefined, the other
  59843. // should be cleared, which enable clear the option.
  59844. // If both of them are not set, keep option with the original value, which
  59845. // enable use only set start but not set end when calling `dispatchAction`.
  59846. // The same as 'end' and 'endValue'.
  59847. if (opt[names[0]] != null || opt[names[1]] != null) {
  59848. option[names[0]] = opt[names[0]];
  59849. option[names[1]] = opt[names[1]];
  59850. }
  59851. }, this);
  59852. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  59853. },
  59854. /**
  59855. * @public
  59856. * @return {Array.<number>} [startPercent, endPercent]
  59857. */
  59858. getPercentRange: function () {
  59859. var axisProxy = this.findRepresentativeAxisProxy();
  59860. if (axisProxy) {
  59861. return axisProxy.getDataPercentWindow();
  59862. }
  59863. },
  59864. /**
  59865. * @public
  59866. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  59867. *
  59868. * @param {string} [axisDimName]
  59869. * @param {number} [axisIndex]
  59870. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  59871. */
  59872. getValueRange: function (axisDimName, axisIndex) {
  59873. if (axisDimName == null && axisIndex == null) {
  59874. var axisProxy = this.findRepresentativeAxisProxy();
  59875. if (axisProxy) {
  59876. return axisProxy.getDataValueWindow();
  59877. }
  59878. }
  59879. else {
  59880. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  59881. }
  59882. },
  59883. /**
  59884. * @public
  59885. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  59886. * corresponding to the axisModel
  59887. * @return {module:echarts/component/dataZoom/AxisProxy}
  59888. */
  59889. findRepresentativeAxisProxy: function (axisModel) {
  59890. if (axisModel) {
  59891. return axisModel.__dzAxisProxy;
  59892. }
  59893. // Find the first hosted axisProxy
  59894. var axisProxies = this._axisProxies;
  59895. for (var key in axisProxies) {
  59896. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  59897. return axisProxies[key];
  59898. }
  59899. }
  59900. // If no hosted axis find not hosted axisProxy.
  59901. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  59902. // and the option.start or option.end settings are different. The percentRange
  59903. // should follow axisProxy.
  59904. // (We encounter this problem in toolbox data zoom.)
  59905. for (var key in axisProxies) {
  59906. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  59907. return axisProxies[key];
  59908. }
  59909. }
  59910. },
  59911. /**
  59912. * @return {Array.<string>}
  59913. */
  59914. getRangePropMode: function () {
  59915. return this._rangePropMode.slice();
  59916. }
  59917. });
  59918. function retrieveRaw(option) {
  59919. var ret = {};
  59920. each$22(
  59921. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  59922. function (name) {
  59923. option.hasOwnProperty(name) && (ret[name] = option[name]);
  59924. }
  59925. );
  59926. return ret;
  59927. }
  59928. function updateRangeUse(dataZoomModel, rawOption) {
  59929. var rangePropMode = dataZoomModel._rangePropMode;
  59930. var rangeModeInOption = dataZoomModel.get('rangeMode');
  59931. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  59932. var percentSpecified = rawOption[names[0]] != null;
  59933. var valueSpecified = rawOption[names[1]] != null;
  59934. if (percentSpecified && !valueSpecified) {
  59935. rangePropMode[index] = 'percent';
  59936. }
  59937. else if (!percentSpecified && valueSpecified) {
  59938. rangePropMode[index] = 'value';
  59939. }
  59940. else if (rangeModeInOption) {
  59941. rangePropMode[index] = rangeModeInOption[index];
  59942. }
  59943. else if (percentSpecified) { // percentSpecified && valueSpecified
  59944. rangePropMode[index] = 'percent';
  59945. }
  59946. // else remain its original setting.
  59947. });
  59948. }
  59949. var DataZoomView = Component.extend({
  59950. type: 'dataZoom',
  59951. render: function (dataZoomModel, ecModel, api, payload) {
  59952. this.dataZoomModel = dataZoomModel;
  59953. this.ecModel = ecModel;
  59954. this.api = api;
  59955. },
  59956. /**
  59957. * Find the first target coordinate system.
  59958. *
  59959. * @protected
  59960. * @return {Object} {
  59961. * grid: [
  59962. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  59963. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  59964. * ...
  59965. * ], // cartesians must not be null/undefined.
  59966. * polar: [
  59967. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  59968. * ...
  59969. * ], // polars must not be null/undefined.
  59970. * singleAxis: [
  59971. * {model: coord0, axisModels: [], coordIndex: 0}
  59972. * ]
  59973. */
  59974. getTargetCoordInfo: function () {
  59975. var dataZoomModel = this.dataZoomModel;
  59976. var ecModel = this.ecModel;
  59977. var coordSysLists = {};
  59978. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  59979. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  59980. if (axisModel) {
  59981. var coordModel = axisModel.getCoordSysModel();
  59982. coordModel && save(
  59983. coordModel,
  59984. axisModel,
  59985. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  59986. coordModel.componentIndex
  59987. );
  59988. }
  59989. }, this);
  59990. function save(coordModel, axisModel, store, coordIndex) {
  59991. var item;
  59992. for (var i = 0; i < store.length; i++) {
  59993. if (store[i].model === coordModel) {
  59994. item = store[i];
  59995. break;
  59996. }
  59997. }
  59998. if (!item) {
  59999. store.push(item = {
  60000. model: coordModel, axisModels: [], coordIndex: coordIndex
  60001. });
  60002. }
  60003. item.axisModels.push(axisModel);
  60004. }
  60005. return coordSysLists;
  60006. }
  60007. });
  60008. var SliderZoomModel = DataZoomModel.extend({
  60009. type: 'dataZoom.slider',
  60010. layoutMode: 'box',
  60011. /**
  60012. * @protected
  60013. */
  60014. defaultOption: {
  60015. show: true,
  60016. // ph => placeholder. Using placehoder here because
  60017. // deault value can only be drived in view stage.
  60018. right: 'ph', // Default align to grid rect.
  60019. top: 'ph', // Default align to grid rect.
  60020. width: 'ph', // Default align to grid rect.
  60021. height: 'ph', // Default align to grid rect.
  60022. left: null, // Default align to grid rect.
  60023. bottom: null, // Default align to grid rect.
  60024. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  60025. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  60026. // highest priority, remain for compatibility of
  60027. // previous version, but not recommended any more.
  60028. dataBackground: {
  60029. lineStyle: {
  60030. color: '#2f4554',
  60031. width: 0.5,
  60032. opacity: 0.3
  60033. },
  60034. areaStyle: {
  60035. color: 'rgba(47,69,84,0.3)',
  60036. opacity: 0.3
  60037. }
  60038. },
  60039. borderColor: '#ddd', // border color of the box. For compatibility,
  60040. // if dataBackgroundColor is set, borderColor
  60041. // is ignored.
  60042. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  60043. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  60044. // 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',
  60045. 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',
  60046. // Percent of the slider height
  60047. handleSize: '100%',
  60048. handleStyle: {
  60049. color: '#a7b7cc'
  60050. },
  60051. labelPrecision: null,
  60052. labelFormatter: null,
  60053. showDetail: true,
  60054. showDataShadow: 'auto', // Default auto decision.
  60055. realtime: true,
  60056. zoomLock: false, // Whether disable zoom.
  60057. textStyle: {
  60058. color: '#333'
  60059. }
  60060. }
  60061. });
  60062. var Rect$2 = Rect;
  60063. var linearMap$2 = linearMap;
  60064. var asc$2 = asc;
  60065. var bind$4 = bind;
  60066. var each$24 = each$1;
  60067. // Constants
  60068. var DEFAULT_LOCATION_EDGE_GAP = 7;
  60069. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  60070. var DEFAULT_FILLER_SIZE = 30;
  60071. var HORIZONTAL = 'horizontal';
  60072. var VERTICAL = 'vertical';
  60073. var LABEL_GAP = 5;
  60074. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  60075. var SliderZoomView = DataZoomView.extend({
  60076. type: 'dataZoom.slider',
  60077. init: function (ecModel, api) {
  60078. /**
  60079. * @private
  60080. * @type {Object}
  60081. */
  60082. this._displayables = {};
  60083. /**
  60084. * @private
  60085. * @type {string}
  60086. */
  60087. this._orient;
  60088. /**
  60089. * [0, 100]
  60090. * @private
  60091. */
  60092. this._range;
  60093. /**
  60094. * [coord of the first handle, coord of the second handle]
  60095. * @private
  60096. */
  60097. this._handleEnds;
  60098. /**
  60099. * [length, thick]
  60100. * @private
  60101. * @type {Array.<number>}
  60102. */
  60103. this._size;
  60104. /**
  60105. * @private
  60106. * @type {number}
  60107. */
  60108. this._handleWidth;
  60109. /**
  60110. * @private
  60111. * @type {number}
  60112. */
  60113. this._handleHeight;
  60114. /**
  60115. * @private
  60116. */
  60117. this._location;
  60118. /**
  60119. * @private
  60120. */
  60121. this._dragging;
  60122. /**
  60123. * @private
  60124. */
  60125. this._dataShadowInfo;
  60126. this.api = api;
  60127. },
  60128. /**
  60129. * @override
  60130. */
  60131. render: function (dataZoomModel, ecModel, api, payload) {
  60132. SliderZoomView.superApply(this, 'render', arguments);
  60133. createOrUpdate(
  60134. this,
  60135. '_dispatchZoomAction',
  60136. this.dataZoomModel.get('throttle'),
  60137. 'fixRate'
  60138. );
  60139. this._orient = dataZoomModel.get('orient');
  60140. if (this.dataZoomModel.get('show') === false) {
  60141. this.group.removeAll();
  60142. return;
  60143. }
  60144. // Notice: this._resetInterval() should not be executed when payload.type
  60145. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  60146. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  60147. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  60148. this._buildView();
  60149. }
  60150. this._updateView();
  60151. },
  60152. /**
  60153. * @override
  60154. */
  60155. remove: function () {
  60156. SliderZoomView.superApply(this, 'remove', arguments);
  60157. clear(this, '_dispatchZoomAction');
  60158. },
  60159. /**
  60160. * @override
  60161. */
  60162. dispose: function () {
  60163. SliderZoomView.superApply(this, 'dispose', arguments);
  60164. clear(this, '_dispatchZoomAction');
  60165. },
  60166. _buildView: function () {
  60167. var thisGroup = this.group;
  60168. thisGroup.removeAll();
  60169. this._resetLocation();
  60170. this._resetInterval();
  60171. var barGroup = this._displayables.barGroup = new Group();
  60172. this._renderBackground();
  60173. this._renderHandle();
  60174. this._renderDataShadow();
  60175. thisGroup.add(barGroup);
  60176. this._positionGroup();
  60177. },
  60178. /**
  60179. * @private
  60180. */
  60181. _resetLocation: function () {
  60182. var dataZoomModel = this.dataZoomModel;
  60183. var api = this.api;
  60184. // If some of x/y/width/height are not specified,
  60185. // auto-adapt according to target grid.
  60186. var coordRect = this._findCoordRect();
  60187. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  60188. // Default align by coordinate system rect.
  60189. var positionInfo = this._orient === HORIZONTAL
  60190. ? {
  60191. // Why using 'right', because right should be used in vertical,
  60192. // and it is better to be consistent for dealing with position param merge.
  60193. right: ecSize.width - coordRect.x - coordRect.width,
  60194. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  60195. width: coordRect.width,
  60196. height: DEFAULT_FILLER_SIZE
  60197. }
  60198. : { // vertical
  60199. right: DEFAULT_LOCATION_EDGE_GAP,
  60200. top: coordRect.y,
  60201. width: DEFAULT_FILLER_SIZE,
  60202. height: coordRect.height
  60203. };
  60204. // Do not write back to option and replace value 'ph', because
  60205. // the 'ph' value should be recalculated when resize.
  60206. var layoutParams = getLayoutParams(dataZoomModel.option);
  60207. // Replace the placeholder value.
  60208. each$1(['right', 'top', 'width', 'height'], function (name) {
  60209. if (layoutParams[name] === 'ph') {
  60210. layoutParams[name] = positionInfo[name];
  60211. }
  60212. });
  60213. var layoutRect = getLayoutRect(
  60214. layoutParams,
  60215. ecSize,
  60216. dataZoomModel.padding
  60217. );
  60218. this._location = {x: layoutRect.x, y: layoutRect.y};
  60219. this._size = [layoutRect.width, layoutRect.height];
  60220. this._orient === VERTICAL && this._size.reverse();
  60221. },
  60222. /**
  60223. * @private
  60224. */
  60225. _positionGroup: function () {
  60226. var thisGroup = this.group;
  60227. var location = this._location;
  60228. var orient = this._orient;
  60229. // Just use the first axis to determine mapping.
  60230. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  60231. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  60232. var barGroup = this._displayables.barGroup;
  60233. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  60234. // Transform barGroup.
  60235. barGroup.attr(
  60236. (orient === HORIZONTAL && !inverse)
  60237. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  60238. : (orient === HORIZONTAL && inverse)
  60239. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  60240. : (orient === VERTICAL && !inverse)
  60241. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  60242. // Dont use Math.PI, considering shadow direction.
  60243. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  60244. );
  60245. // Position barGroup
  60246. var rect = thisGroup.getBoundingRect([barGroup]);
  60247. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  60248. },
  60249. /**
  60250. * @private
  60251. */
  60252. _getViewExtent: function () {
  60253. return [0, this._size[0]];
  60254. },
  60255. _renderBackground: function () {
  60256. var dataZoomModel = this.dataZoomModel;
  60257. var size = this._size;
  60258. var barGroup = this._displayables.barGroup;
  60259. barGroup.add(new Rect$2({
  60260. silent: true,
  60261. shape: {
  60262. x: 0, y: 0, width: size[0], height: size[1]
  60263. },
  60264. style: {
  60265. fill: dataZoomModel.get('backgroundColor')
  60266. },
  60267. z2: -40
  60268. }));
  60269. // Click panel, over shadow, below handles.
  60270. barGroup.add(new Rect$2({
  60271. shape: {
  60272. x: 0, y: 0, width: size[0], height: size[1]
  60273. },
  60274. style: {
  60275. fill: 'transparent'
  60276. },
  60277. z2: 0,
  60278. onclick: bind(this._onClickPanelClick, this)
  60279. }));
  60280. },
  60281. _renderDataShadow: function () {
  60282. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  60283. if (!info) {
  60284. return;
  60285. }
  60286. var size = this._size;
  60287. var seriesModel = info.series;
  60288. var data = seriesModel.getRawData();
  60289. var otherDim = seriesModel.getShadowDim
  60290. ? seriesModel.getShadowDim() // @see candlestick
  60291. : info.otherDim;
  60292. if (otherDim == null) {
  60293. return;
  60294. }
  60295. var otherDataExtent = data.getDataExtent(otherDim);
  60296. // Nice extent.
  60297. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  60298. otherDataExtent = [
  60299. otherDataExtent[0] - otherOffset,
  60300. otherDataExtent[1] + otherOffset
  60301. ];
  60302. var otherShadowExtent = [0, size[1]];
  60303. var thisShadowExtent = [0, size[0]];
  60304. var areaPoints = [[size[0], 0], [0, 0]];
  60305. var linePoints = [];
  60306. var step = thisShadowExtent[1] / (data.count() - 1);
  60307. var thisCoord = 0;
  60308. // Optimize for large data shadow
  60309. var stride = Math.round(data.count() / size[0]);
  60310. var lastIsEmpty;
  60311. data.each([otherDim], function (value, index) {
  60312. if (stride > 0 && (index % stride)) {
  60313. thisCoord += step;
  60314. return;
  60315. }
  60316. // FIXME
  60317. // Should consider axis.min/axis.max when drawing dataShadow.
  60318. // FIXME
  60319. // 应该使用统一的空判断?还是在list里进行空判断?
  60320. var isEmpty = value == null || isNaN(value) || value === '';
  60321. // See #4235.
  60322. var otherCoord = isEmpty
  60323. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  60324. // Attempt to draw data shadow precisely when there are empty value.
  60325. if (isEmpty && !lastIsEmpty && index) {
  60326. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  60327. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  60328. }
  60329. else if (!isEmpty && lastIsEmpty) {
  60330. areaPoints.push([thisCoord, 0]);
  60331. linePoints.push([thisCoord, 0]);
  60332. }
  60333. areaPoints.push([thisCoord, otherCoord]);
  60334. linePoints.push([thisCoord, otherCoord]);
  60335. thisCoord += step;
  60336. lastIsEmpty = isEmpty;
  60337. });
  60338. var dataZoomModel = this.dataZoomModel;
  60339. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  60340. this._displayables.barGroup.add(new Polygon({
  60341. shape: {points: areaPoints},
  60342. style: defaults(
  60343. {fill: dataZoomModel.get('dataBackgroundColor')},
  60344. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  60345. ),
  60346. silent: true,
  60347. z2: -20
  60348. }));
  60349. this._displayables.barGroup.add(new Polyline({
  60350. shape: {points: linePoints},
  60351. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  60352. silent: true,
  60353. z2: -19
  60354. }));
  60355. },
  60356. _prepareDataShadowInfo: function () {
  60357. var dataZoomModel = this.dataZoomModel;
  60358. var showDataShadow = dataZoomModel.get('showDataShadow');
  60359. if (showDataShadow === false) {
  60360. return;
  60361. }
  60362. // Find a representative series.
  60363. var result;
  60364. var ecModel = this.ecModel;
  60365. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  60366. var seriesModels = dataZoomModel
  60367. .getAxisProxy(dimNames.name, axisIndex)
  60368. .getTargetSeriesModels();
  60369. each$1(seriesModels, function (seriesModel) {
  60370. if (result) {
  60371. return;
  60372. }
  60373. if (showDataShadow !== true && indexOf(
  60374. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  60375. ) < 0
  60376. ) {
  60377. return;
  60378. }
  60379. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  60380. var otherDim = getOtherDim(dimNames.name);
  60381. var otherAxisInverse;
  60382. var coordSys = seriesModel.coordinateSystem;
  60383. if (otherDim != null && coordSys.getOtherAxis) {
  60384. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  60385. }
  60386. otherDim = seriesModel.getData().mapDimension(otherDim);
  60387. result = {
  60388. thisAxis: thisAxis,
  60389. series: seriesModel,
  60390. thisDim: dimNames.name,
  60391. otherDim: otherDim,
  60392. otherAxisInverse: otherAxisInverse
  60393. };
  60394. }, this);
  60395. }, this);
  60396. return result;
  60397. },
  60398. _renderHandle: function () {
  60399. var displaybles = this._displayables;
  60400. var handles = displaybles.handles = [];
  60401. var handleLabels = displaybles.handleLabels = [];
  60402. var barGroup = this._displayables.barGroup;
  60403. var size = this._size;
  60404. var dataZoomModel = this.dataZoomModel;
  60405. barGroup.add(displaybles.filler = new Rect$2({
  60406. draggable: true,
  60407. cursor: getCursor(this._orient),
  60408. drift: bind$4(this._onDragMove, this, 'all'),
  60409. onmousemove: function (e) {
  60410. // Fot mobile devicem, prevent screen slider on the button.
  60411. stop(e.event);
  60412. },
  60413. ondragstart: bind$4(this._showDataInfo, this, true),
  60414. ondragend: bind$4(this._onDragEnd, this),
  60415. onmouseover: bind$4(this._showDataInfo, this, true),
  60416. onmouseout: bind$4(this._showDataInfo, this, false),
  60417. style: {
  60418. fill: dataZoomModel.get('fillerColor'),
  60419. textPosition : 'inside'
  60420. }
  60421. }));
  60422. // Frame border.
  60423. barGroup.add(new Rect$2(subPixelOptimizeRect({
  60424. silent: true,
  60425. shape: {
  60426. x: 0,
  60427. y: 0,
  60428. width: size[0],
  60429. height: size[1]
  60430. },
  60431. style: {
  60432. stroke: dataZoomModel.get('dataBackgroundColor')
  60433. || dataZoomModel.get('borderColor'),
  60434. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  60435. fill: 'rgba(0,0,0,0)'
  60436. }
  60437. })));
  60438. each$24([0, 1], function (handleIndex) {
  60439. var path = createIcon(
  60440. dataZoomModel.get('handleIcon'),
  60441. {
  60442. cursor: getCursor(this._orient),
  60443. draggable: true,
  60444. drift: bind$4(this._onDragMove, this, handleIndex),
  60445. onmousemove: function (e) {
  60446. // Fot mobile devicem, prevent screen slider on the button.
  60447. stop(e.event);
  60448. },
  60449. ondragend: bind$4(this._onDragEnd, this),
  60450. onmouseover: bind$4(this._showDataInfo, this, true),
  60451. onmouseout: bind$4(this._showDataInfo, this, false)
  60452. },
  60453. {x: -1, y: 0, width: 2, height: 2}
  60454. );
  60455. var bRect = path.getBoundingRect();
  60456. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  60457. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  60458. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  60459. var handleColor = dataZoomModel.get('handleColor');
  60460. // Compatitable with previous version
  60461. if (handleColor != null) {
  60462. path.style.fill = handleColor;
  60463. }
  60464. barGroup.add(handles[handleIndex] = path);
  60465. var textStyleModel = dataZoomModel.textStyleModel;
  60466. this.group.add(
  60467. handleLabels[handleIndex] = new Text({
  60468. silent: true,
  60469. invisible: true,
  60470. style: {
  60471. x: 0, y: 0, text: '',
  60472. textVerticalAlign: 'middle',
  60473. textAlign: 'center',
  60474. textFill: textStyleModel.getTextColor(),
  60475. textFont: textStyleModel.getFont()
  60476. },
  60477. z2: 10
  60478. }));
  60479. }, this);
  60480. },
  60481. /**
  60482. * @private
  60483. */
  60484. _resetInterval: function () {
  60485. var range = this._range = this.dataZoomModel.getPercentRange();
  60486. var viewExtent = this._getViewExtent();
  60487. this._handleEnds = [
  60488. linearMap$2(range[0], [0, 100], viewExtent, true),
  60489. linearMap$2(range[1], [0, 100], viewExtent, true)
  60490. ];
  60491. },
  60492. /**
  60493. * @private
  60494. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  60495. * @param {number} delta
  60496. */
  60497. _updateInterval: function (handleIndex, delta) {
  60498. var dataZoomModel = this.dataZoomModel;
  60499. var handleEnds = this._handleEnds;
  60500. var viewExtend = this._getViewExtent();
  60501. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  60502. var percentExtent = [0, 100];
  60503. sliderMove(
  60504. delta,
  60505. handleEnds,
  60506. viewExtend,
  60507. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  60508. minMaxSpan.minSpan != null
  60509. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  60510. minMaxSpan.maxSpan != null
  60511. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  60512. );
  60513. this._range = asc$2([
  60514. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  60515. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  60516. ]);
  60517. },
  60518. /**
  60519. * @private
  60520. */
  60521. _updateView: function (nonRealtime) {
  60522. var displaybles = this._displayables;
  60523. var handleEnds = this._handleEnds;
  60524. var handleInterval = asc$2(handleEnds.slice());
  60525. var size = this._size;
  60526. each$24([0, 1], function (handleIndex) {
  60527. // Handles
  60528. var handle = displaybles.handles[handleIndex];
  60529. var handleHeight = this._handleHeight;
  60530. handle.attr({
  60531. scale: [handleHeight / 2, handleHeight / 2],
  60532. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  60533. });
  60534. }, this);
  60535. // Filler
  60536. displaybles.filler.setShape({
  60537. x: handleInterval[0],
  60538. y: 0,
  60539. width: handleInterval[1] - handleInterval[0],
  60540. height: size[1]
  60541. });
  60542. this._updateDataInfo(nonRealtime);
  60543. },
  60544. /**
  60545. * @private
  60546. */
  60547. _updateDataInfo: function (nonRealtime) {
  60548. var dataZoomModel = this.dataZoomModel;
  60549. var displaybles = this._displayables;
  60550. var handleLabels = displaybles.handleLabels;
  60551. var orient = this._orient;
  60552. var labelTexts = ['', ''];
  60553. // FIXME
  60554. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  60555. if (dataZoomModel.get('showDetail')) {
  60556. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  60557. if (axisProxy) {
  60558. var axis = axisProxy.getAxisModel().axis;
  60559. var range = this._range;
  60560. var dataInterval = nonRealtime
  60561. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  60562. ? axisProxy.calculateDataWindow({
  60563. start: range[0], end: range[1]
  60564. }).valueWindow
  60565. : axisProxy.getDataValueWindow();
  60566. labelTexts = [
  60567. this._formatLabel(dataInterval[0], axis),
  60568. this._formatLabel(dataInterval[1], axis)
  60569. ];
  60570. }
  60571. }
  60572. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  60573. setLabel.call(this, 0);
  60574. setLabel.call(this, 1);
  60575. function setLabel(handleIndex) {
  60576. // Label
  60577. // Text should not transform by barGroup.
  60578. // Ignore handlers transform
  60579. var barTransform = getTransform(
  60580. displaybles.handles[handleIndex].parent, this.group
  60581. );
  60582. var direction = transformDirection(
  60583. handleIndex === 0 ? 'right' : 'left', barTransform
  60584. );
  60585. var offset = this._handleWidth / 2 + LABEL_GAP;
  60586. var textPoint = applyTransform$1(
  60587. [
  60588. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  60589. this._size[1] / 2
  60590. ],
  60591. barTransform
  60592. );
  60593. handleLabels[handleIndex].setStyle({
  60594. x: textPoint[0],
  60595. y: textPoint[1],
  60596. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  60597. textAlign: orient === HORIZONTAL ? direction : 'center',
  60598. text: labelTexts[handleIndex]
  60599. });
  60600. }
  60601. },
  60602. /**
  60603. * @private
  60604. */
  60605. _formatLabel: function (value, axis) {
  60606. var dataZoomModel = this.dataZoomModel;
  60607. var labelFormatter = dataZoomModel.get('labelFormatter');
  60608. var labelPrecision = dataZoomModel.get('labelPrecision');
  60609. if (labelPrecision == null || labelPrecision === 'auto') {
  60610. labelPrecision = axis.getPixelPrecision();
  60611. }
  60612. var valueStr = (value == null || isNaN(value))
  60613. ? ''
  60614. // FIXME Glue code
  60615. : (axis.type === 'category' || axis.type === 'time')
  60616. ? axis.scale.getLabel(Math.round(value))
  60617. // param of toFixed should less then 20.
  60618. : value.toFixed(Math.min(labelPrecision, 20));
  60619. return isFunction$1(labelFormatter)
  60620. ? labelFormatter(value, valueStr)
  60621. : isString(labelFormatter)
  60622. ? labelFormatter.replace('{value}', valueStr)
  60623. : valueStr;
  60624. },
  60625. /**
  60626. * @private
  60627. * @param {boolean} showOrHide true: show, false: hide
  60628. */
  60629. _showDataInfo: function (showOrHide) {
  60630. // Always show when drgging.
  60631. showOrHide = this._dragging || showOrHide;
  60632. var handleLabels = this._displayables.handleLabels;
  60633. handleLabels[0].attr('invisible', !showOrHide);
  60634. handleLabels[1].attr('invisible', !showOrHide);
  60635. },
  60636. _onDragMove: function (handleIndex, dx, dy) {
  60637. this._dragging = true;
  60638. // Transform dx, dy to bar coordination.
  60639. var barTransform = this._displayables.barGroup.getLocalTransform();
  60640. var vertex = applyTransform$1([dx, dy], barTransform, true);
  60641. this._updateInterval(handleIndex, vertex[0]);
  60642. var realtime = this.dataZoomModel.get('realtime');
  60643. this._updateView(!realtime);
  60644. realtime && this._dispatchZoomAction();
  60645. },
  60646. _onDragEnd: function () {
  60647. this._dragging = false;
  60648. this._showDataInfo(false);
  60649. // While in realtime mode and stream mode, dispatch action when
  60650. // drag end will cause the whole view rerender, which is unnecessary.
  60651. var realtime = this.dataZoomModel.get('realtime');
  60652. !realtime && this._dispatchZoomAction();
  60653. },
  60654. _onClickPanelClick: function (e) {
  60655. var size = this._size;
  60656. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  60657. if (localPoint[0] < 0 || localPoint[0] > size[0]
  60658. || localPoint[1] < 0 || localPoint[1] > size[1]
  60659. ) {
  60660. return;
  60661. }
  60662. var handleEnds = this._handleEnds;
  60663. var center = (handleEnds[0] + handleEnds[1]) / 2;
  60664. this._updateInterval('all', localPoint[0] - center);
  60665. this._updateView();
  60666. this._dispatchZoomAction();
  60667. },
  60668. /**
  60669. * This action will be throttled.
  60670. * @private
  60671. */
  60672. _dispatchZoomAction: function () {
  60673. var range = this._range;
  60674. this.api.dispatchAction({
  60675. type: 'dataZoom',
  60676. from: this.uid,
  60677. dataZoomId: this.dataZoomModel.id,
  60678. start: range[0],
  60679. end: range[1]
  60680. });
  60681. },
  60682. /**
  60683. * @private
  60684. */
  60685. _findCoordRect: function () {
  60686. // Find the grid coresponding to the first axis referred by dataZoom.
  60687. var rect;
  60688. each$24(this.getTargetCoordInfo(), function (coordInfoList) {
  60689. if (!rect && coordInfoList.length) {
  60690. var coordSys = coordInfoList[0].model.coordinateSystem;
  60691. rect = coordSys.getRect && coordSys.getRect();
  60692. }
  60693. });
  60694. if (!rect) {
  60695. var width = this.api.getWidth();
  60696. var height = this.api.getHeight();
  60697. rect = {
  60698. x: width * 0.2,
  60699. y: height * 0.2,
  60700. width: width * 0.6,
  60701. height: height * 0.6
  60702. };
  60703. }
  60704. return rect;
  60705. }
  60706. });
  60707. function getOtherDim(thisDim) {
  60708. // FIXME
  60709. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  60710. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  60711. return map$$1[thisDim];
  60712. }
  60713. function getCursor(orient) {
  60714. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  60715. }
  60716. DataZoomModel.extend({
  60717. type: 'dataZoom.inside',
  60718. /**
  60719. * @protected
  60720. */
  60721. defaultOption: {
  60722. disabled: false, // Whether disable this inside zoom.
  60723. zoomLock: false, // Whether disable zoom but only pan.
  60724. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  60725. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  60726. preventDefaultMouseMove: true
  60727. }
  60728. });
  60729. // Only create one roam controller for each coordinate system.
  60730. // one roam controller might be refered by two inside data zoom
  60731. // components (for example, one for x and one for y). When user
  60732. // pan or zoom, only dispatch one action for those data zoom
  60733. // components.
  60734. var curry$6 = curry;
  60735. var ATTR$1 = '\0_ec_dataZoom_roams';
  60736. /**
  60737. * @public
  60738. * @param {module:echarts/ExtensionAPI} api
  60739. * @param {Object} dataZoomInfo
  60740. * @param {string} dataZoomInfo.coordId
  60741. * @param {Function} dataZoomInfo.containsPoint
  60742. * @param {Array.<string>} dataZoomInfo.allCoordIds
  60743. * @param {string} dataZoomInfo.dataZoomId
  60744. * @param {number} dataZoomInfo.throttleRate
  60745. * @param {Function} dataZoomInfo.panGetRange
  60746. * @param {Function} dataZoomInfo.zoomGetRange
  60747. * @param {boolean} [dataZoomInfo.zoomLock]
  60748. * @param {boolean} [dataZoomInfo.disabled]
  60749. */
  60750. function register$2(api, dataZoomInfo) {
  60751. var store = giveStore(api);
  60752. var theDataZoomId = dataZoomInfo.dataZoomId;
  60753. var theCoordId = dataZoomInfo.coordId;
  60754. // Do clean when a dataZoom changes its target coordnate system.
  60755. // Avoid memory leak, dispose all not-used-registered.
  60756. each$1(store, function (record, coordId) {
  60757. var dataZoomInfos = record.dataZoomInfos;
  60758. if (dataZoomInfos[theDataZoomId]
  60759. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  60760. ) {
  60761. delete dataZoomInfos[theDataZoomId];
  60762. record.count--;
  60763. }
  60764. });
  60765. cleanStore(store);
  60766. var record = store[theCoordId];
  60767. // Create if needed.
  60768. if (!record) {
  60769. record = store[theCoordId] = {
  60770. coordId: theCoordId,
  60771. dataZoomInfos: {},
  60772. count: 0
  60773. };
  60774. record.controller = createController(api, record);
  60775. record.dispatchAction = curry(dispatchAction$1, api);
  60776. }
  60777. // Update reference of dataZoom.
  60778. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  60779. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  60780. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  60781. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  60782. // Consider resize, area should be always updated.
  60783. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  60784. // Update throttle.
  60785. createOrUpdate(
  60786. record,
  60787. 'dispatchAction',
  60788. dataZoomInfo.throttleRate,
  60789. 'fixRate'
  60790. );
  60791. }
  60792. /**
  60793. * @public
  60794. * @param {module:echarts/ExtensionAPI} api
  60795. * @param {string} dataZoomId
  60796. */
  60797. function unregister$1(api, dataZoomId) {
  60798. var store = giveStore(api);
  60799. each$1(store, function (record) {
  60800. record.controller.dispose();
  60801. var dataZoomInfos = record.dataZoomInfos;
  60802. if (dataZoomInfos[dataZoomId]) {
  60803. delete dataZoomInfos[dataZoomId];
  60804. record.count--;
  60805. }
  60806. });
  60807. cleanStore(store);
  60808. }
  60809. /**
  60810. * @public
  60811. */
  60812. function shouldRecordRange(payload, dataZoomId) {
  60813. if (payload && payload.type === 'dataZoom' && payload.batch) {
  60814. for (var i = 0, len = payload.batch.length; i < len; i++) {
  60815. if (payload.batch[i].dataZoomId === dataZoomId) {
  60816. return false;
  60817. }
  60818. }
  60819. }
  60820. return true;
  60821. }
  60822. /**
  60823. * @public
  60824. */
  60825. function generateCoordId(coordModel) {
  60826. return coordModel.type + '\0_' + coordModel.id;
  60827. }
  60828. /**
  60829. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  60830. * @type {Array.<Object>}
  60831. */
  60832. function giveStore(api) {
  60833. // Mount store on zrender instance, so that we do not
  60834. // need to worry about dispose.
  60835. var zr = api.getZr();
  60836. return zr[ATTR$1] || (zr[ATTR$1] = {});
  60837. }
  60838. function createController(api, newRecord) {
  60839. var controller = new RoamController(api.getZr());
  60840. controller.on('pan', curry$6(onPan, newRecord));
  60841. controller.on('zoom', curry$6(onZoom, newRecord));
  60842. return controller;
  60843. }
  60844. function cleanStore(store) {
  60845. each$1(store, function (record, coordId) {
  60846. if (!record.count) {
  60847. record.controller.dispose();
  60848. delete store[coordId];
  60849. }
  60850. });
  60851. }
  60852. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  60853. wrapAndDispatch(record, function (info) {
  60854. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  60855. });
  60856. }
  60857. function onZoom(record, scale, mouseX, mouseY) {
  60858. wrapAndDispatch(record, function (info) {
  60859. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  60860. });
  60861. }
  60862. function wrapAndDispatch(record, getRange) {
  60863. var batch = [];
  60864. each$1(record.dataZoomInfos, function (info) {
  60865. var range = getRange(info);
  60866. !info.disabled && range && batch.push({
  60867. dataZoomId: info.dataZoomId,
  60868. start: range[0],
  60869. end: range[1]
  60870. });
  60871. });
  60872. record.dispatchAction(batch);
  60873. }
  60874. /**
  60875. * This action will be throttled.
  60876. */
  60877. function dispatchAction$1(api, batch) {
  60878. api.dispatchAction({
  60879. type: 'dataZoom',
  60880. batch: batch
  60881. });
  60882. }
  60883. /**
  60884. * Merge roamController settings when multiple dataZooms share one roamController.
  60885. */
  60886. function mergeControllerParams(dataZoomInfos) {
  60887. var controlType;
  60888. var opt = {};
  60889. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  60890. // as string, it is probably revert to reserved word by compress tool. See #7411.
  60891. var prefix = 'type_';
  60892. var typePriority = {
  60893. 'type_true': 2,
  60894. 'type_move': 1,
  60895. 'type_false': 0,
  60896. 'type_undefined': -1
  60897. };
  60898. each$1(dataZoomInfos, function (dataZoomInfo) {
  60899. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  60900. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  60901. controlType = oneType;
  60902. }
  60903. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  60904. extend(opt, dataZoomInfo.roamControllerOpt);
  60905. });
  60906. return {
  60907. controlType: controlType,
  60908. opt: opt
  60909. };
  60910. }
  60911. var bind$5 = bind;
  60912. var InsideZoomView = DataZoomView.extend({
  60913. type: 'dataZoom.inside',
  60914. /**
  60915. * @override
  60916. */
  60917. init: function (ecModel, api) {
  60918. /**
  60919. * 'throttle' is used in this.dispatchAction, so we save range
  60920. * to avoid missing some 'pan' info.
  60921. * @private
  60922. * @type {Array.<number>}
  60923. */
  60924. this._range;
  60925. },
  60926. /**
  60927. * @override
  60928. */
  60929. render: function (dataZoomModel, ecModel, api, payload) {
  60930. InsideZoomView.superApply(this, 'render', arguments);
  60931. // Notice: origin this._range should be maintained, and should not be re-fetched
  60932. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  60933. // info will be missed because of 'throttle' of this.dispatchAction.
  60934. if (shouldRecordRange(payload, dataZoomModel.id)) {
  60935. this._range = dataZoomModel.getPercentRange();
  60936. }
  60937. // Reset controllers.
  60938. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  60939. var allCoordIds = map(coordInfoList, function (coordInfo) {
  60940. return generateCoordId(coordInfo.model);
  60941. });
  60942. each$1(coordInfoList, function (coordInfo) {
  60943. var coordModel = coordInfo.model;
  60944. var dataZoomOption = dataZoomModel.option;
  60945. register$2(
  60946. api,
  60947. {
  60948. coordId: generateCoordId(coordModel),
  60949. allCoordIds: allCoordIds,
  60950. containsPoint: function (e, x, y) {
  60951. return coordModel.coordinateSystem.containPoint([x, y]);
  60952. },
  60953. dataZoomId: dataZoomModel.id,
  60954. throttleRate: dataZoomModel.get('throttle', true),
  60955. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  60956. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  60957. zoomLock: dataZoomOption.zoomLock,
  60958. disabled: dataZoomOption.disabled,
  60959. roamControllerOpt: {
  60960. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  60961. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  60962. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  60963. }
  60964. }
  60965. );
  60966. }, this);
  60967. }, this);
  60968. },
  60969. /**
  60970. * @override
  60971. */
  60972. dispose: function () {
  60973. unregister$1(this.api, this.dataZoomModel.id);
  60974. InsideZoomView.superApply(this, 'dispose', arguments);
  60975. this._range = null;
  60976. },
  60977. /**
  60978. * @private
  60979. */
  60980. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  60981. var range = this._range.slice();
  60982. // Calculate transform by the first axis.
  60983. var axisModel = coordInfo.axisModels[0];
  60984. if (!axisModel) {
  60985. return;
  60986. }
  60987. var directionInfo = getDirectionInfo[coordSysName](
  60988. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  60989. );
  60990. var percentDelta = directionInfo.signal
  60991. * (range[1] - range[0])
  60992. * directionInfo.pixel / directionInfo.pixelLength;
  60993. sliderMove(percentDelta, range, [0, 100], 'all');
  60994. return (this._range = range);
  60995. },
  60996. /**
  60997. * @private
  60998. */
  60999. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  61000. var range = this._range.slice();
  61001. // Calculate transform by the first axis.
  61002. var axisModel = coordInfo.axisModels[0];
  61003. if (!axisModel) {
  61004. return;
  61005. }
  61006. var directionInfo = getDirectionInfo[coordSysName](
  61007. null, [mouseX, mouseY], axisModel, controller, coordInfo
  61008. );
  61009. var percentPoint = (
  61010. directionInfo.signal > 0
  61011. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  61012. : (directionInfo.pixel - directionInfo.pixelStart)
  61013. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  61014. scale = Math.max(1 / scale, 0);
  61015. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  61016. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  61017. // Restrict range.
  61018. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  61019. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  61020. return (this._range = range);
  61021. }
  61022. });
  61023. var getDirectionInfo = {
  61024. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  61025. var axis = axisModel.axis;
  61026. var ret = {};
  61027. var rect = coordInfo.model.coordinateSystem.getRect();
  61028. oldPoint = oldPoint || [0, 0];
  61029. if (axis.dim === 'x') {
  61030. ret.pixel = newPoint[0] - oldPoint[0];
  61031. ret.pixelLength = rect.width;
  61032. ret.pixelStart = rect.x;
  61033. ret.signal = axis.inverse ? 1 : -1;
  61034. }
  61035. else { // axis.dim === 'y'
  61036. ret.pixel = newPoint[1] - oldPoint[1];
  61037. ret.pixelLength = rect.height;
  61038. ret.pixelStart = rect.y;
  61039. ret.signal = axis.inverse ? -1 : 1;
  61040. }
  61041. return ret;
  61042. },
  61043. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  61044. var axis = axisModel.axis;
  61045. var ret = {};
  61046. var polar = coordInfo.model.coordinateSystem;
  61047. var radiusExtent = polar.getRadiusAxis().getExtent();
  61048. var angleExtent = polar.getAngleAxis().getExtent();
  61049. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  61050. newPoint = polar.pointToCoord(newPoint);
  61051. if (axisModel.mainType === 'radiusAxis') {
  61052. ret.pixel = newPoint[0] - oldPoint[0];
  61053. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  61054. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  61055. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  61056. ret.pixelStart = radiusExtent[0];
  61057. ret.signal = axis.inverse ? 1 : -1;
  61058. }
  61059. else { // 'angleAxis'
  61060. ret.pixel = newPoint[1] - oldPoint[1];
  61061. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  61062. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  61063. ret.pixelLength = angleExtent[1] - angleExtent[0];
  61064. ret.pixelStart = angleExtent[0];
  61065. ret.signal = axis.inverse ? -1 : 1;
  61066. }
  61067. return ret;
  61068. },
  61069. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  61070. var axis = axisModel.axis;
  61071. var rect = coordInfo.model.coordinateSystem.getRect();
  61072. var ret = {};
  61073. oldPoint = oldPoint || [0, 0];
  61074. if (axis.orient === 'horizontal') {
  61075. ret.pixel = newPoint[0] - oldPoint[0];
  61076. ret.pixelLength = rect.width;
  61077. ret.pixelStart = rect.x;
  61078. ret.signal = axis.inverse ? 1 : -1;
  61079. }
  61080. else { // 'vertical'
  61081. ret.pixel = newPoint[1] - oldPoint[1];
  61082. ret.pixelLength = rect.height;
  61083. ret.pixelStart = rect.y;
  61084. ret.signal = axis.inverse ? -1 : 1;
  61085. }
  61086. return ret;
  61087. }
  61088. };
  61089. registerProcessor({
  61090. getTargetSeries: function (ecModel) {
  61091. var seriesModelMap = createHashMap();
  61092. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61093. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61094. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  61095. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  61096. seriesModelMap.set(seriesModel.uid, seriesModel);
  61097. });
  61098. });
  61099. });
  61100. return seriesModelMap;
  61101. },
  61102. isOverallFilter: true,
  61103. // Consider appendData, where filter should be performed. Because data process is
  61104. // in block mode currently, it is not need to worry about that the overallProgress
  61105. // execute every frame.
  61106. overallReset: function (ecModel, api) {
  61107. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61108. // We calculate window and reset axis here but not in model
  61109. // init stage and not after action dispatch handler, because
  61110. // reset should be called after seriesData.restoreData.
  61111. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61112. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  61113. });
  61114. // Caution: data zoom filtering is order sensitive when using
  61115. // percent range and no min/max/scale set on axis.
  61116. // For example, we have dataZoom definition:
  61117. // [
  61118. // {xAxisIndex: 0, start: 30, end: 70},
  61119. // {yAxisIndex: 0, start: 20, end: 80}
  61120. // ]
  61121. // In this case, [20, 80] of y-dataZoom should be based on data
  61122. // that have filtered by x-dataZoom using range of [30, 70],
  61123. // but should not be based on full raw data. Thus sliding
  61124. // x-dataZoom will change both ranges of xAxis and yAxis,
  61125. // while sliding y-dataZoom will only change the range of yAxis.
  61126. // So we should filter x-axis after reset x-axis immediately,
  61127. // and then reset y-axis and filter y-axis.
  61128. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61129. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  61130. });
  61131. });
  61132. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61133. // Fullfill all of the range props so that user
  61134. // is able to get them from chart.getOption().
  61135. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  61136. var percentRange = axisProxy.getDataPercentWindow();
  61137. var valueRange = axisProxy.getDataValueWindow();
  61138. dataZoomModel.setRawRange({
  61139. start: percentRange[0],
  61140. end: percentRange[1],
  61141. startValue: valueRange[0],
  61142. endValue: valueRange[1]
  61143. }, true);
  61144. });
  61145. }
  61146. });
  61147. registerAction('dataZoom', function (payload, ecModel) {
  61148. var linkedNodesFinder = createLinkedNodesFinder(
  61149. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  61150. eachAxisDim$1,
  61151. function (model, dimNames) {
  61152. return model.get(dimNames.axisIndex);
  61153. }
  61154. );
  61155. var effectedModels = [];
  61156. ecModel.eachComponent(
  61157. {mainType: 'dataZoom', query: payload},
  61158. function (model, index) {
  61159. effectedModels.push.apply(
  61160. effectedModels, linkedNodesFinder(model).nodes
  61161. );
  61162. }
  61163. );
  61164. each$1(effectedModels, function (dataZoomModel, index) {
  61165. dataZoomModel.setRawRange({
  61166. start: payload.start,
  61167. end: payload.end,
  61168. startValue: payload.startValue,
  61169. endValue: payload.endValue
  61170. });
  61171. });
  61172. });
  61173. /**
  61174. * DataZoom component entry
  61175. */
  61176. var each$25 = each$1;
  61177. var preprocessor$2 = function (option) {
  61178. var visualMap = option && option.visualMap;
  61179. if (!isArray(visualMap)) {
  61180. visualMap = visualMap ? [visualMap] : [];
  61181. }
  61182. each$25(visualMap, function (opt) {
  61183. if (!opt) {
  61184. return;
  61185. }
  61186. // rename splitList to pieces
  61187. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  61188. opt.pieces = opt.splitList;
  61189. delete opt.splitList;
  61190. }
  61191. var pieces = opt.pieces;
  61192. if (pieces && isArray(pieces)) {
  61193. each$25(pieces, function (piece) {
  61194. if (isObject$1(piece)) {
  61195. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  61196. piece.min = piece.start;
  61197. }
  61198. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  61199. piece.max = piece.end;
  61200. }
  61201. }
  61202. });
  61203. }
  61204. });
  61205. };
  61206. function has$1(obj, name) {
  61207. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  61208. }
  61209. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  61210. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  61211. return (
  61212. !option.categories
  61213. && (
  61214. !(
  61215. option.pieces
  61216. ? option.pieces.length > 0
  61217. : option.splitNumber > 0
  61218. )
  61219. || option.calculable
  61220. )
  61221. )
  61222. ? 'continuous' : 'piecewise';
  61223. });
  61224. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  61225. registerVisual(VISUAL_PRIORITY, {
  61226. createOnAllSeries: true,
  61227. reset: function (seriesModel, ecModel) {
  61228. var resetDefines = [];
  61229. ecModel.eachComponent('visualMap', function (visualMapModel) {
  61230. if (!visualMapModel.isTargetSeries(seriesModel)) {
  61231. return;
  61232. }
  61233. resetDefines.push(incrementalApplyVisual(
  61234. visualMapModel.stateList,
  61235. visualMapModel.targetVisuals,
  61236. bind(visualMapModel.getValueState, visualMapModel),
  61237. visualMapModel.getDataDimension(seriesModel.getData())
  61238. ));
  61239. });
  61240. return resetDefines;
  61241. }
  61242. });
  61243. // Only support color.
  61244. registerVisual(VISUAL_PRIORITY, {
  61245. createOnAllSeries: true,
  61246. reset: function (seriesModel, ecModel) {
  61247. var data = seriesModel.getData();
  61248. var visualMetaList = [];
  61249. ecModel.eachComponent('visualMap', function (visualMapModel) {
  61250. if (visualMapModel.isTargetSeries(seriesModel)) {
  61251. var visualMeta = visualMapModel.getVisualMeta(
  61252. bind(getColorVisual, null, seriesModel, visualMapModel)
  61253. ) || {stops: [], outerColors: []};
  61254. var concreteDim = visualMapModel.getDataDimension(data);
  61255. var dimInfo = data.getDimensionInfo(concreteDim);
  61256. if (dimInfo != null) {
  61257. // visualMeta.dimension should be dimension index, but not concrete dimension.
  61258. visualMeta.dimension = dimInfo.index;
  61259. visualMetaList.push(visualMeta);
  61260. }
  61261. }
  61262. });
  61263. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  61264. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  61265. }
  61266. });
  61267. // FIXME
  61268. // performance and export for heatmap?
  61269. // value can be Infinity or -Infinity
  61270. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  61271. var mappings = visualMapModel.targetVisuals[valueState];
  61272. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  61273. var resultVisual = {
  61274. color: seriesModel.getData().getVisual('color') // default color.
  61275. };
  61276. for (var i = 0, len = visualTypes.length; i < len; i++) {
  61277. var type = visualTypes[i];
  61278. var mapping = mappings[
  61279. type === 'opacity' ? '__alphaForOpacity' : type
  61280. ];
  61281. mapping && mapping.applyVisual(value, getVisual, setVisual);
  61282. }
  61283. return resultVisual.color;
  61284. function getVisual(key) {
  61285. return resultVisual[key];
  61286. }
  61287. function setVisual(key, value) {
  61288. resultVisual[key] = value;
  61289. }
  61290. }
  61291. /**
  61292. * @file Visual mapping.
  61293. */
  61294. var visualDefault = {
  61295. /**
  61296. * @public
  61297. */
  61298. get: function (visualType, key, isCategory) {
  61299. var value = clone(
  61300. (defaultOption$3[visualType] || {})[key]
  61301. );
  61302. return isCategory
  61303. ? (isArray(value) ? value[value.length - 1] : value)
  61304. : value;
  61305. }
  61306. };
  61307. var defaultOption$3 = {
  61308. color: {
  61309. active: ['#006edd', '#e0ffff'],
  61310. inactive: ['rgba(0,0,0,0)']
  61311. },
  61312. colorHue: {
  61313. active: [0, 360],
  61314. inactive: [0, 0]
  61315. },
  61316. colorSaturation: {
  61317. active: [0.3, 1],
  61318. inactive: [0, 0]
  61319. },
  61320. colorLightness: {
  61321. active: [0.9, 0.5],
  61322. inactive: [0, 0]
  61323. },
  61324. colorAlpha: {
  61325. active: [0.3, 1],
  61326. inactive: [0, 0]
  61327. },
  61328. opacity: {
  61329. active: [0.3, 1],
  61330. inactive: [0, 0]
  61331. },
  61332. symbol: {
  61333. active: ['circle', 'roundRect', 'diamond'],
  61334. inactive: ['none']
  61335. },
  61336. symbolSize: {
  61337. active: [10, 50],
  61338. inactive: [0, 0]
  61339. }
  61340. };
  61341. var mapVisual$2 = VisualMapping.mapVisual;
  61342. var eachVisual = VisualMapping.eachVisual;
  61343. var isArray$3 = isArray;
  61344. var each$26 = each$1;
  61345. var asc$3 = asc;
  61346. var linearMap$3 = linearMap;
  61347. var noop$2 = noop;
  61348. var VisualMapModel = extendComponentModel({
  61349. type: 'visualMap',
  61350. dependencies: ['series'],
  61351. /**
  61352. * @readOnly
  61353. * @type {Array.<string>}
  61354. */
  61355. stateList: ['inRange', 'outOfRange'],
  61356. /**
  61357. * @readOnly
  61358. * @type {Array.<string>}
  61359. */
  61360. replacableOptionKeys: [
  61361. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  61362. ],
  61363. /**
  61364. * [lowerBound, upperBound]
  61365. *
  61366. * @readOnly
  61367. * @type {Array.<number>}
  61368. */
  61369. dataBound: [-Infinity, Infinity],
  61370. /**
  61371. * @readOnly
  61372. * @type {string|Object}
  61373. */
  61374. layoutMode: {type: 'box', ignoreSize: true},
  61375. /**
  61376. * @protected
  61377. */
  61378. defaultOption: {
  61379. show: true,
  61380. zlevel: 0,
  61381. z: 4,
  61382. seriesIndex: 'all', // 'all' or null/undefined: all series.
  61383. // A number or an array of number: the specified series.
  61384. // set min: 0, max: 200, only for campatible with ec2.
  61385. // In fact min max should not have default value.
  61386. min: 0, // min value, must specified if pieces is not specified.
  61387. max: 200, // max value, must specified if pieces is not specified.
  61388. dimension: null,
  61389. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  61390. // 'symbol', 'symbolSize'
  61391. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  61392. // 'colorLightness', 'colorAlpha',
  61393. // 'symbol', 'symbolSize'
  61394. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  61395. right: null, // The same as left.
  61396. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  61397. bottom: 0, // The same as top.
  61398. itemWidth: null,
  61399. itemHeight: null,
  61400. inverse: false,
  61401. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  61402. backgroundColor: 'rgba(0,0,0,0)',
  61403. borderColor: '#ccc', // 值域边框颜色
  61404. contentColor: '#5793f3',
  61405. inactiveColor: '#aaa',
  61406. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  61407. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  61408. // 接受数组分别设定上右下左边距,同css
  61409. textGap: 10, //
  61410. precision: 0, // 小数精度,默认为0,无小数点
  61411. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  61412. formatter: null,
  61413. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  61414. textStyle: {
  61415. color: '#333' // 值域文字颜色
  61416. }
  61417. },
  61418. /**
  61419. * @protected
  61420. */
  61421. init: function (option, parentModel, ecModel) {
  61422. /**
  61423. * @private
  61424. * @type {Array.<number>}
  61425. */
  61426. this._dataExtent;
  61427. /**
  61428. * @readOnly
  61429. */
  61430. this.targetVisuals = {};
  61431. /**
  61432. * @readOnly
  61433. */
  61434. this.controllerVisuals = {};
  61435. /**
  61436. * @readOnly
  61437. */
  61438. this.textStyleModel;
  61439. /**
  61440. * [width, height]
  61441. * @readOnly
  61442. * @type {Array.<number>}
  61443. */
  61444. this.itemSize;
  61445. this.mergeDefaultAndTheme(option, ecModel);
  61446. },
  61447. /**
  61448. * @protected
  61449. */
  61450. optionUpdated: function (newOption, isInit) {
  61451. var thisOption = this.option;
  61452. // FIXME
  61453. // necessary?
  61454. // Disable realtime view update if canvas is not supported.
  61455. if (!env$1.canvasSupported) {
  61456. thisOption.realtime = false;
  61457. }
  61458. !isInit && replaceVisualOption(
  61459. thisOption, newOption, this.replacableOptionKeys
  61460. );
  61461. this.textStyleModel = this.getModel('textStyle');
  61462. this.resetItemSize();
  61463. this.completeVisualOption();
  61464. },
  61465. /**
  61466. * @protected
  61467. */
  61468. resetVisual: function (supplementVisualOption) {
  61469. var stateList = this.stateList;
  61470. supplementVisualOption = bind(supplementVisualOption, this);
  61471. this.controllerVisuals = createVisualMappings(
  61472. this.option.controller, stateList, supplementVisualOption
  61473. );
  61474. this.targetVisuals = createVisualMappings(
  61475. this.option.target, stateList, supplementVisualOption
  61476. );
  61477. },
  61478. /**
  61479. * @protected
  61480. * @return {Array.<number>} An array of series indices.
  61481. */
  61482. getTargetSeriesIndices: function () {
  61483. var optionSeriesIndex = this.option.seriesIndex;
  61484. var seriesIndices = [];
  61485. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  61486. this.ecModel.eachSeries(function (seriesModel, index) {
  61487. seriesIndices.push(index);
  61488. });
  61489. }
  61490. else {
  61491. seriesIndices = normalizeToArray(optionSeriesIndex);
  61492. }
  61493. return seriesIndices;
  61494. },
  61495. /**
  61496. * @public
  61497. */
  61498. eachTargetSeries: function (callback, context) {
  61499. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  61500. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  61501. }, this);
  61502. },
  61503. /**
  61504. * @pubilc
  61505. */
  61506. isTargetSeries: function (seriesModel) {
  61507. var is = false;
  61508. this.eachTargetSeries(function (model) {
  61509. model === seriesModel && (is = true);
  61510. });
  61511. return is;
  61512. },
  61513. /**
  61514. * @example
  61515. * this.formatValueText(someVal); // format single numeric value to text.
  61516. * this.formatValueText(someVal, true); // format single category value to text.
  61517. * this.formatValueText([min, max]); // format numeric min-max to text.
  61518. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  61519. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  61520. *
  61521. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  61522. * @param {boolean} [isCategory=false] Only available when value is number.
  61523. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  61524. * @return {string}
  61525. * @protected
  61526. */
  61527. formatValueText: function(value, isCategory, edgeSymbols) {
  61528. var option = this.option;
  61529. var precision = option.precision;
  61530. var dataBound = this.dataBound;
  61531. var formatter = option.formatter;
  61532. var isMinMax;
  61533. var textValue;
  61534. edgeSymbols = edgeSymbols || ['<', '>'];
  61535. if (isArray(value)) {
  61536. value = value.slice();
  61537. isMinMax = true;
  61538. }
  61539. textValue = isCategory
  61540. ? value
  61541. : (isMinMax
  61542. ? [toFixed(value[0]), toFixed(value[1])]
  61543. : toFixed(value)
  61544. );
  61545. if (isString(formatter)) {
  61546. return formatter
  61547. .replace('{value}', isMinMax ? textValue[0] : textValue)
  61548. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  61549. }
  61550. else if (isFunction$1(formatter)) {
  61551. return isMinMax
  61552. ? formatter(value[0], value[1])
  61553. : formatter(value);
  61554. }
  61555. if (isMinMax) {
  61556. if (value[0] === dataBound[0]) {
  61557. return edgeSymbols[0] + ' ' + textValue[1];
  61558. }
  61559. else if (value[1] === dataBound[1]) {
  61560. return edgeSymbols[1] + ' ' + textValue[0];
  61561. }
  61562. else {
  61563. return textValue[0] + ' - ' + textValue[1];
  61564. }
  61565. }
  61566. else { // Format single value (includes category case).
  61567. return textValue;
  61568. }
  61569. function toFixed(val) {
  61570. return val === dataBound[0]
  61571. ? 'min'
  61572. : val === dataBound[1]
  61573. ? 'max'
  61574. : (+val).toFixed(Math.min(precision, 20));
  61575. }
  61576. },
  61577. /**
  61578. * @protected
  61579. */
  61580. resetExtent: function () {
  61581. var thisOption = this.option;
  61582. // Can not calculate data extent by data here.
  61583. // Because series and data may be modified in processing stage.
  61584. // So we do not support the feature "auto min/max".
  61585. var extent = asc$3([thisOption.min, thisOption.max]);
  61586. this._dataExtent = extent;
  61587. },
  61588. /**
  61589. * @public
  61590. * @param {module:echarts/data/List} list
  61591. * @return {string} Concrete dimention. If return null/undefined,
  61592. * no dimension used.
  61593. */
  61594. getDataDimension: function (list) {
  61595. var optDim = this.option.dimension;
  61596. var listDimensions = list.dimensions;
  61597. if (optDim == null && !listDimensions.length) {
  61598. return;
  61599. }
  61600. if (optDim != null) {
  61601. return list.getDimension(optDim);
  61602. }
  61603. var dimNames = list.dimensions;
  61604. for (var i = dimNames.length - 1; i >= 0; i--) {
  61605. var dimName = dimNames[i];
  61606. var dimInfo = list.getDimensionInfo(dimName);
  61607. if (!dimInfo.isCalculationCoord) {
  61608. return dimName;
  61609. }
  61610. }
  61611. },
  61612. /**
  61613. * @public
  61614. * @override
  61615. */
  61616. getExtent: function () {
  61617. return this._dataExtent.slice();
  61618. },
  61619. /**
  61620. * @protected
  61621. */
  61622. completeVisualOption: function () {
  61623. var ecModel = this.ecModel;
  61624. var thisOption = this.option;
  61625. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  61626. var target = thisOption.target || (thisOption.target = {});
  61627. var controller = thisOption.controller || (thisOption.controller = {});
  61628. merge(target, base); // Do not override
  61629. merge(controller, base); // Do not override
  61630. var isCategory = this.isCategory();
  61631. completeSingle.call(this, target);
  61632. completeSingle.call(this, controller);
  61633. completeInactive.call(this, target, 'inRange', 'outOfRange');
  61634. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  61635. completeController.call(this, controller);
  61636. function completeSingle(base) {
  61637. // Compatible with ec2 dataRange.color.
  61638. // The mapping order of dataRange.color is: [high value, ..., low value]
  61639. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  61640. // Notice: ec2 has no inverse.
  61641. if (isArray$3(thisOption.color)
  61642. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  61643. // So adding color only when no inRange defined.
  61644. && !base.inRange
  61645. ) {
  61646. base.inRange = {color: thisOption.color.slice().reverse()};
  61647. }
  61648. // Compatible with previous logic, always give a defautl color, otherwise
  61649. // simple config with no inRange and outOfRange will not work.
  61650. // Originally we use visualMap.color as the default color, but setOption at
  61651. // the second time the default color will be erased. So we change to use
  61652. // constant DEFAULT_COLOR.
  61653. // If user do not want the defualt color, set inRange: {color: null}.
  61654. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  61655. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  61656. each$26(this.stateList, function (state) {
  61657. var visualType = base[state];
  61658. if (isString(visualType)) {
  61659. var defa = visualDefault.get(visualType, 'active', isCategory);
  61660. if (defa) {
  61661. base[state] = {};
  61662. base[state][visualType] = defa;
  61663. }
  61664. else {
  61665. // Mark as not specified.
  61666. delete base[state];
  61667. }
  61668. }
  61669. }, this);
  61670. }
  61671. function completeInactive(base, stateExist, stateAbsent) {
  61672. var optExist = base[stateExist];
  61673. var optAbsent = base[stateAbsent];
  61674. if (optExist && !optAbsent) {
  61675. optAbsent = base[stateAbsent] = {};
  61676. each$26(optExist, function (visualData, visualType) {
  61677. if (!VisualMapping.isValidType(visualType)) {
  61678. return;
  61679. }
  61680. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  61681. if (defa != null) {
  61682. optAbsent[visualType] = defa;
  61683. // Compatibable with ec2:
  61684. // Only inactive color to rgba(0,0,0,0) can not
  61685. // make label transparent, so use opacity also.
  61686. if (visualType === 'color'
  61687. && !optAbsent.hasOwnProperty('opacity')
  61688. && !optAbsent.hasOwnProperty('colorAlpha')
  61689. ) {
  61690. optAbsent.opacity = [0, 0];
  61691. }
  61692. }
  61693. });
  61694. }
  61695. }
  61696. function completeController(controller) {
  61697. var symbolExists = (controller.inRange || {}).symbol
  61698. || (controller.outOfRange || {}).symbol;
  61699. var symbolSizeExists = (controller.inRange || {}).symbolSize
  61700. || (controller.outOfRange || {}).symbolSize;
  61701. var inactiveColor = this.get('inactiveColor');
  61702. each$26(this.stateList, function (state) {
  61703. var itemSize = this.itemSize;
  61704. var visuals = controller[state];
  61705. // Set inactive color for controller if no other color
  61706. // attr (like colorAlpha) specified.
  61707. if (!visuals) {
  61708. visuals = controller[state] = {
  61709. color: isCategory ? inactiveColor : [inactiveColor]
  61710. };
  61711. }
  61712. // Consistent symbol and symbolSize if not specified.
  61713. if (visuals.symbol == null) {
  61714. visuals.symbol = symbolExists
  61715. && clone(symbolExists)
  61716. || (isCategory ? 'roundRect' : ['roundRect']);
  61717. }
  61718. if (visuals.symbolSize == null) {
  61719. visuals.symbolSize = symbolSizeExists
  61720. && clone(symbolSizeExists)
  61721. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  61722. }
  61723. // Filter square and none.
  61724. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  61725. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  61726. });
  61727. // Normalize symbolSize
  61728. var symbolSize = visuals.symbolSize;
  61729. if (symbolSize != null) {
  61730. var max = -Infinity;
  61731. // symbolSize can be object when categories defined.
  61732. eachVisual(symbolSize, function (value) {
  61733. value > max && (max = value);
  61734. });
  61735. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  61736. return linearMap$3(value, [0, max], [0, itemSize[0]], true);
  61737. });
  61738. }
  61739. }, this);
  61740. }
  61741. },
  61742. /**
  61743. * @protected
  61744. */
  61745. resetItemSize: function () {
  61746. this.itemSize = [
  61747. parseFloat(this.get('itemWidth')),
  61748. parseFloat(this.get('itemHeight'))
  61749. ];
  61750. },
  61751. /**
  61752. * @public
  61753. */
  61754. isCategory: function () {
  61755. return !!this.option.categories;
  61756. },
  61757. /**
  61758. * @public
  61759. * @abstract
  61760. */
  61761. setSelected: noop$2,
  61762. /**
  61763. * @public
  61764. * @abstract
  61765. * @param {*|module:echarts/data/List} valueOrData
  61766. * @param {number} dataIndex
  61767. * @return {string} state See this.stateList
  61768. */
  61769. getValueState: noop$2,
  61770. /**
  61771. * FIXME
  61772. * Do not publish to thirt-part-dev temporarily
  61773. * util the interface is stable. (Should it return
  61774. * a function but not visual meta?)
  61775. *
  61776. * @pubilc
  61777. * @abstract
  61778. * @param {Function} getColorVisual
  61779. * params: value, valueState
  61780. * return: color
  61781. * @return {Object} visualMeta
  61782. * should includes {stops, outerColors}
  61783. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  61784. */
  61785. getVisualMeta: noop$2
  61786. });
  61787. // Constant
  61788. var DEFAULT_BAR_BOUND = [20, 140];
  61789. var ContinuousModel = VisualMapModel.extend({
  61790. type: 'visualMap.continuous',
  61791. /**
  61792. * @protected
  61793. */
  61794. defaultOption: {
  61795. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  61796. calculable: false, // This prop effect default component type determine,
  61797. // See echarts/component/visualMap/typeDefaulter.
  61798. range: null, // selected range. In default case `range` is [min, max]
  61799. // and can auto change along with modification of min max,
  61800. // util use specifid a range.
  61801. realtime: true, // Whether realtime update.
  61802. itemHeight: null, // The length of the range control edge.
  61803. itemWidth: null, // The length of the other side.
  61804. hoverLink: true, // Enable hover highlight.
  61805. hoverLinkDataSize: null,// The size of hovered data.
  61806. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  61807. // If not specified, follow the value of `realtime`.
  61808. },
  61809. /**
  61810. * @override
  61811. */
  61812. optionUpdated: function (newOption, isInit) {
  61813. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  61814. this.resetExtent();
  61815. this.resetVisual(function (mappingOption) {
  61816. mappingOption.mappingMethod = 'linear';
  61817. mappingOption.dataExtent = this.getExtent();
  61818. });
  61819. this._resetRange();
  61820. },
  61821. /**
  61822. * @protected
  61823. * @override
  61824. */
  61825. resetItemSize: function () {
  61826. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  61827. var itemSize = this.itemSize;
  61828. this._orient === 'horizontal' && itemSize.reverse();
  61829. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  61830. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  61831. },
  61832. /**
  61833. * @private
  61834. */
  61835. _resetRange: function () {
  61836. var dataExtent = this.getExtent();
  61837. var range = this.option.range;
  61838. if (!range || range.auto) {
  61839. // `range` should always be array (so we dont use other
  61840. // value like 'auto') for user-friend. (consider getOption).
  61841. dataExtent.auto = 1;
  61842. this.option.range = dataExtent;
  61843. }
  61844. else if (isArray(range)) {
  61845. if (range[0] > range[1]) {
  61846. range.reverse();
  61847. }
  61848. range[0] = Math.max(range[0], dataExtent[0]);
  61849. range[1] = Math.min(range[1], dataExtent[1]);
  61850. }
  61851. },
  61852. /**
  61853. * @protected
  61854. * @override
  61855. */
  61856. completeVisualOption: function () {
  61857. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  61858. each$1(this.stateList, function (state) {
  61859. var symbolSize = this.option.controller[state].symbolSize;
  61860. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  61861. symbolSize[0] = 0; // For good looking.
  61862. }
  61863. }, this);
  61864. },
  61865. /**
  61866. * @override
  61867. */
  61868. setSelected: function (selected) {
  61869. this.option.range = selected.slice();
  61870. this._resetRange();
  61871. },
  61872. /**
  61873. * @public
  61874. */
  61875. getSelected: function () {
  61876. var dataExtent = this.getExtent();
  61877. var dataInterval = asc(
  61878. (this.get('range') || []).slice()
  61879. );
  61880. // Clamp
  61881. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  61882. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  61883. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  61884. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  61885. return dataInterval;
  61886. },
  61887. /**
  61888. * @override
  61889. */
  61890. getValueState: function (value) {
  61891. var range = this.option.range;
  61892. var dataExtent = this.getExtent();
  61893. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  61894. // range[1] is processed likewise.
  61895. return (
  61896. (range[0] <= dataExtent[0] || range[0] <= value)
  61897. && (range[1] >= dataExtent[1] || value <= range[1])
  61898. ) ? 'inRange' : 'outOfRange';
  61899. },
  61900. /**
  61901. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  61902. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  61903. */
  61904. findTargetDataIndices: function (range) {
  61905. var result = [];
  61906. this.eachTargetSeries(function (seriesModel) {
  61907. var dataIndices = [];
  61908. var data = seriesModel.getData();
  61909. data.each(this.getDataDimension(data), function (value, dataIndex) {
  61910. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  61911. }, this);
  61912. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  61913. }, this);
  61914. return result;
  61915. },
  61916. /**
  61917. * @implement
  61918. */
  61919. getVisualMeta: function (getColorVisual) {
  61920. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  61921. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  61922. var stops = [];
  61923. function setStop(value, valueState) {
  61924. stops.push({
  61925. value: value,
  61926. color: getColorVisual(value, valueState)
  61927. });
  61928. }
  61929. // Format to: outOfRange -- inRange -- outOfRange.
  61930. var iIdx = 0;
  61931. var oIdx = 0;
  61932. var iLen = iVals.length;
  61933. var oLen = oVals.length;
  61934. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  61935. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  61936. if (oVals[oIdx] < iVals[iIdx]) {
  61937. setStop(oVals[oIdx], 'outOfRange');
  61938. }
  61939. }
  61940. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  61941. // If range is full, value beyond min, max will be clamped.
  61942. // make a singularity
  61943. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  61944. setStop(iVals[iIdx], 'inRange');
  61945. }
  61946. for (var first = 1; oIdx < oLen; oIdx++) {
  61947. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  61948. // make a singularity
  61949. if (first) {
  61950. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  61951. first = 0;
  61952. }
  61953. setStop(oVals[oIdx], 'outOfRange');
  61954. }
  61955. }
  61956. var stopsLen = stops.length;
  61957. return {
  61958. stops: stops,
  61959. outerColors: [
  61960. stopsLen ? stops[0].color : 'transparent',
  61961. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  61962. ]
  61963. };
  61964. }
  61965. });
  61966. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  61967. if (dataExtent[0] === dataExtent[1]) {
  61968. return dataExtent.slice();
  61969. }
  61970. // When using colorHue mapping, it is not linear color any more.
  61971. // Moreover, canvas gradient seems not to be accurate linear.
  61972. // FIXME
  61973. // Should be arbitrary value 100? or based on pixel size?
  61974. var count = 200;
  61975. var step = (dataExtent[1] - dataExtent[0]) / count;
  61976. var value = dataExtent[0];
  61977. var stopValues = [];
  61978. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  61979. stopValues.push(value);
  61980. value += step;
  61981. }
  61982. stopValues.push(dataExtent[1]);
  61983. return stopValues;
  61984. }
  61985. var VisualMapView = extendComponentView({
  61986. type: 'visualMap',
  61987. /**
  61988. * @readOnly
  61989. * @type {Object}
  61990. */
  61991. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  61992. init: function (ecModel, api) {
  61993. /**
  61994. * @readOnly
  61995. * @type {module:echarts/model/Global}
  61996. */
  61997. this.ecModel = ecModel;
  61998. /**
  61999. * @readOnly
  62000. * @type {module:echarts/ExtensionAPI}
  62001. */
  62002. this.api = api;
  62003. /**
  62004. * @readOnly
  62005. * @type {module:echarts/component/visualMap/visualMapModel}
  62006. */
  62007. this.visualMapModel;
  62008. },
  62009. /**
  62010. * @protected
  62011. */
  62012. render: function (visualMapModel, ecModel, api, payload) {
  62013. this.visualMapModel = visualMapModel;
  62014. if (visualMapModel.get('show') === false) {
  62015. this.group.removeAll();
  62016. return;
  62017. }
  62018. this.doRender.apply(this, arguments);
  62019. },
  62020. /**
  62021. * @protected
  62022. */
  62023. renderBackground: function (group) {
  62024. var visualMapModel = this.visualMapModel;
  62025. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  62026. var rect = group.getBoundingRect();
  62027. group.add(new Rect({
  62028. z2: -1, // Lay background rect on the lowest layer.
  62029. silent: true,
  62030. shape: {
  62031. x: rect.x - padding[3],
  62032. y: rect.y - padding[0],
  62033. width: rect.width + padding[3] + padding[1],
  62034. height: rect.height + padding[0] + padding[2]
  62035. },
  62036. style: {
  62037. fill: visualMapModel.get('backgroundColor'),
  62038. stroke: visualMapModel.get('borderColor'),
  62039. lineWidth: visualMapModel.get('borderWidth')
  62040. }
  62041. }));
  62042. },
  62043. /**
  62044. * @protected
  62045. * @param {number} targetValue can be Infinity or -Infinity
  62046. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  62047. * @param {Object} [opts]
  62048. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  62049. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  62050. * @return {*} Visual value.
  62051. */
  62052. getControllerVisual: function (targetValue, visualCluster, opts) {
  62053. opts = opts || {};
  62054. var forceState = opts.forceState;
  62055. var visualMapModel = this.visualMapModel;
  62056. var visualObj = {};
  62057. // Default values.
  62058. if (visualCluster === 'symbol') {
  62059. visualObj.symbol = visualMapModel.get('itemSymbol');
  62060. }
  62061. if (visualCluster === 'color') {
  62062. var defaultColor = visualMapModel.get('contentColor');
  62063. visualObj.color = defaultColor;
  62064. }
  62065. function getter(key) {
  62066. return visualObj[key];
  62067. }
  62068. function setter(key, value) {
  62069. visualObj[key] = value;
  62070. }
  62071. var mappings = visualMapModel.controllerVisuals[
  62072. forceState || visualMapModel.getValueState(targetValue)
  62073. ];
  62074. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  62075. each$1(visualTypes, function (type) {
  62076. var visualMapping = mappings[type];
  62077. if (opts.convertOpacityToAlpha && type === 'opacity') {
  62078. type = 'colorAlpha';
  62079. visualMapping = mappings.__alphaForOpacity;
  62080. }
  62081. if (VisualMapping.dependsOn(type, visualCluster)) {
  62082. visualMapping && visualMapping.applyVisual(
  62083. targetValue, getter, setter
  62084. );
  62085. }
  62086. });
  62087. return visualObj[visualCluster];
  62088. },
  62089. /**
  62090. * @protected
  62091. */
  62092. positionGroup: function (group) {
  62093. var model = this.visualMapModel;
  62094. var api = this.api;
  62095. positionElement(
  62096. group,
  62097. model.getBoxLayoutParams(),
  62098. {width: api.getWidth(), height: api.getHeight()}
  62099. );
  62100. },
  62101. /**
  62102. * @protected
  62103. * @abstract
  62104. */
  62105. doRender: noop
  62106. });
  62107. /**
  62108. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  62109. * @param {module:echarts/ExtensionAPI} api
  62110. * @param {Array.<number>} itemSize always [short, long]
  62111. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  62112. */
  62113. function getItemAlign(visualMapModel, api, itemSize) {
  62114. var modelOption = visualMapModel.option;
  62115. var itemAlign = modelOption.align;
  62116. if (itemAlign != null && itemAlign !== 'auto') {
  62117. return itemAlign;
  62118. }
  62119. // Auto decision align.
  62120. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  62121. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  62122. var paramsSet = [
  62123. ['left', 'right', 'width'],
  62124. ['top', 'bottom', 'height']
  62125. ];
  62126. var reals = paramsSet[realIndex];
  62127. var fakeValue = [0, null, 10];
  62128. var layoutInput = {};
  62129. for (var i = 0; i < 3; i++) {
  62130. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  62131. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  62132. }
  62133. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  62134. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  62135. return reals[
  62136. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  62137. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  62138. ];
  62139. }
  62140. /**
  62141. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  62142. * dataIndexInside means filtered index.
  62143. */
  62144. function convertDataIndex(batch) {
  62145. each$1(batch || [], function (batchItem) {
  62146. if (batch.dataIndex != null) {
  62147. batch.dataIndexInside = batch.dataIndex;
  62148. batch.dataIndex = null;
  62149. }
  62150. });
  62151. return batch;
  62152. }
  62153. var linearMap$4 = linearMap;
  62154. var each$27 = each$1;
  62155. var mathMin$7 = Math.min;
  62156. var mathMax$7 = Math.max;
  62157. // Arbitrary value
  62158. var HOVER_LINK_SIZE = 12;
  62159. var HOVER_LINK_OUT = 6;
  62160. // Notice:
  62161. // Any "interval" should be by the order of [low, high].
  62162. // "handle0" (handleIndex === 0) maps to
  62163. // low data value: this._dataInterval[0] and has low coord.
  62164. // "handle1" (handleIndex === 1) maps to
  62165. // high data value: this._dataInterval[1] and has high coord.
  62166. // The logic of transform is implemented in this._createBarGroup.
  62167. var ContinuousView = VisualMapView.extend({
  62168. type: 'visualMap.continuous',
  62169. /**
  62170. * @override
  62171. */
  62172. init: function () {
  62173. ContinuousView.superApply(this, 'init', arguments);
  62174. /**
  62175. * @private
  62176. */
  62177. this._shapes = {};
  62178. /**
  62179. * @private
  62180. */
  62181. this._dataInterval = [];
  62182. /**
  62183. * @private
  62184. */
  62185. this._handleEnds = [];
  62186. /**
  62187. * @private
  62188. */
  62189. this._orient;
  62190. /**
  62191. * @private
  62192. */
  62193. this._useHandle;
  62194. /**
  62195. * @private
  62196. */
  62197. this._hoverLinkDataIndices = [];
  62198. /**
  62199. * @private
  62200. */
  62201. this._dragging;
  62202. /**
  62203. * @private
  62204. */
  62205. this._hovering;
  62206. },
  62207. /**
  62208. * @protected
  62209. * @override
  62210. */
  62211. doRender: function (visualMapModel, ecModel, api, payload) {
  62212. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  62213. this._buildView();
  62214. }
  62215. },
  62216. /**
  62217. * @private
  62218. */
  62219. _buildView: function () {
  62220. this.group.removeAll();
  62221. var visualMapModel = this.visualMapModel;
  62222. var thisGroup = this.group;
  62223. this._orient = visualMapModel.get('orient');
  62224. this._useHandle = visualMapModel.get('calculable');
  62225. this._resetInterval();
  62226. this._renderBar(thisGroup);
  62227. var dataRangeText = visualMapModel.get('text');
  62228. this._renderEndsText(thisGroup, dataRangeText, 0);
  62229. this._renderEndsText(thisGroup, dataRangeText, 1);
  62230. // Do this for background size calculation.
  62231. this._updateView(true);
  62232. // After updating view, inner shapes is built completely,
  62233. // and then background can be rendered.
  62234. this.renderBackground(thisGroup);
  62235. // Real update view
  62236. this._updateView();
  62237. this._enableHoverLinkToSeries();
  62238. this._enableHoverLinkFromSeries();
  62239. this.positionGroup(thisGroup);
  62240. },
  62241. /**
  62242. * @private
  62243. */
  62244. _renderEndsText: function (group, dataRangeText, endsIndex) {
  62245. if (!dataRangeText) {
  62246. return;
  62247. }
  62248. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  62249. var text = dataRangeText[1 - endsIndex];
  62250. text = text != null ? text + '' : '';
  62251. var visualMapModel = this.visualMapModel;
  62252. var textGap = visualMapModel.get('textGap');
  62253. var itemSize = visualMapModel.itemSize;
  62254. var barGroup = this._shapes.barGroup;
  62255. var position = this._applyTransform(
  62256. [
  62257. itemSize[0] / 2,
  62258. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  62259. ],
  62260. barGroup
  62261. );
  62262. var align = this._applyTransform(
  62263. endsIndex === 0 ? 'bottom' : 'top',
  62264. barGroup
  62265. );
  62266. var orient = this._orient;
  62267. var textStyleModel = this.visualMapModel.textStyleModel;
  62268. this.group.add(new Text({
  62269. style: {
  62270. x: position[0],
  62271. y: position[1],
  62272. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  62273. textAlign: orient === 'horizontal' ? align : 'center',
  62274. text: text,
  62275. textFont: textStyleModel.getFont(),
  62276. textFill: textStyleModel.getTextColor()
  62277. }
  62278. }));
  62279. },
  62280. /**
  62281. * @private
  62282. */
  62283. _renderBar: function (targetGroup) {
  62284. var visualMapModel = this.visualMapModel;
  62285. var shapes = this._shapes;
  62286. var itemSize = visualMapModel.itemSize;
  62287. var orient = this._orient;
  62288. var useHandle = this._useHandle;
  62289. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  62290. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  62291. // Bar
  62292. barGroup.add(shapes.outOfRange = createPolygon());
  62293. barGroup.add(shapes.inRange = createPolygon(
  62294. null,
  62295. useHandle ? getCursor$1(this._orient) : null,
  62296. bind(this._dragHandle, this, 'all', false),
  62297. bind(this._dragHandle, this, 'all', true)
  62298. ));
  62299. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  62300. var textSize = mathMax$7(textRect.width, textRect.height);
  62301. // Handle
  62302. if (useHandle) {
  62303. shapes.handleThumbs = [];
  62304. shapes.handleLabels = [];
  62305. shapes.handleLabelPoints = [];
  62306. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  62307. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  62308. }
  62309. this._createIndicator(barGroup, itemSize, textSize, orient);
  62310. targetGroup.add(barGroup);
  62311. },
  62312. /**
  62313. * @private
  62314. */
  62315. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  62316. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  62317. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  62318. var handleThumb = createPolygon(
  62319. createHandlePoints(handleIndex, textSize),
  62320. getCursor$1(this._orient),
  62321. onDrift,
  62322. onDragEnd
  62323. );
  62324. handleThumb.position[0] = itemSize[0];
  62325. barGroup.add(handleThumb);
  62326. // Text is always horizontal layout but should not be effected by
  62327. // transform (orient/inverse). So label is built separately but not
  62328. // use zrender/graphic/helper/RectText, and is located based on view
  62329. // group (according to handleLabelPoint) but not barGroup.
  62330. var textStyleModel = this.visualMapModel.textStyleModel;
  62331. var handleLabel = new Text({
  62332. draggable: true,
  62333. drift: onDrift,
  62334. onmousemove: function (e) {
  62335. // Fot mobile devicem, prevent screen slider on the button.
  62336. stop(e.event);
  62337. },
  62338. ondragend: onDragEnd,
  62339. style: {
  62340. x: 0, y: 0, text: '',
  62341. textFont: textStyleModel.getFont(),
  62342. textFill: textStyleModel.getTextColor()
  62343. }
  62344. });
  62345. this.group.add(handleLabel);
  62346. var handleLabelPoint = [
  62347. orient === 'horizontal'
  62348. ? textSize / 2
  62349. : textSize * 1.5,
  62350. orient === 'horizontal'
  62351. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  62352. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  62353. ];
  62354. var shapes = this._shapes;
  62355. shapes.handleThumbs[handleIndex] = handleThumb;
  62356. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  62357. shapes.handleLabels[handleIndex] = handleLabel;
  62358. },
  62359. /**
  62360. * @private
  62361. */
  62362. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  62363. var indicator = createPolygon([[0, 0]], 'move');
  62364. indicator.position[0] = itemSize[0];
  62365. indicator.attr({invisible: true, silent: true});
  62366. barGroup.add(indicator);
  62367. var textStyleModel = this.visualMapModel.textStyleModel;
  62368. var indicatorLabel = new Text({
  62369. silent: true,
  62370. invisible: true,
  62371. style: {
  62372. x: 0, y: 0, text: '',
  62373. textFont: textStyleModel.getFont(),
  62374. textFill: textStyleModel.getTextColor()
  62375. }
  62376. });
  62377. this.group.add(indicatorLabel);
  62378. var indicatorLabelPoint = [
  62379. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  62380. 0
  62381. ];
  62382. var shapes = this._shapes;
  62383. shapes.indicator = indicator;
  62384. shapes.indicatorLabel = indicatorLabel;
  62385. shapes.indicatorLabelPoint = indicatorLabelPoint;
  62386. },
  62387. /**
  62388. * @private
  62389. */
  62390. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  62391. if (!this._useHandle) {
  62392. return;
  62393. }
  62394. this._dragging = !isEnd;
  62395. if (!isEnd) {
  62396. // Transform dx, dy to bar coordination.
  62397. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  62398. this._updateInterval(handleIndex, vertex[1]);
  62399. // Considering realtime, update view should be executed
  62400. // before dispatch action.
  62401. this._updateView();
  62402. }
  62403. // dragEnd do not dispatch action when realtime.
  62404. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  62405. this.api.dispatchAction({
  62406. type: 'selectDataRange',
  62407. from: this.uid,
  62408. visualMapId: this.visualMapModel.id,
  62409. selected: this._dataInterval.slice()
  62410. });
  62411. }
  62412. if (isEnd) {
  62413. !this._hovering && this._clearHoverLinkToSeries();
  62414. }
  62415. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  62416. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  62417. }
  62418. },
  62419. /**
  62420. * @private
  62421. */
  62422. _resetInterval: function () {
  62423. var visualMapModel = this.visualMapModel;
  62424. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  62425. var dataExtent = visualMapModel.getExtent();
  62426. var sizeExtent = [0, visualMapModel.itemSize[1]];
  62427. this._handleEnds = [
  62428. linearMap$4(dataInterval[0], dataExtent, sizeExtent, true),
  62429. linearMap$4(dataInterval[1], dataExtent, sizeExtent, true)
  62430. ];
  62431. },
  62432. /**
  62433. * @private
  62434. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  62435. * @param {number} dx
  62436. * @param {number} dy
  62437. */
  62438. _updateInterval: function (handleIndex, delta) {
  62439. delta = delta || 0;
  62440. var visualMapModel = this.visualMapModel;
  62441. var handleEnds = this._handleEnds;
  62442. var sizeExtent = [0, visualMapModel.itemSize[1]];
  62443. sliderMove(
  62444. delta,
  62445. handleEnds,
  62446. sizeExtent,
  62447. handleIndex,
  62448. // cross is forbiden
  62449. 0
  62450. );
  62451. var dataExtent = visualMapModel.getExtent();
  62452. // Update data interval.
  62453. this._dataInterval = [
  62454. linearMap$4(handleEnds[0], sizeExtent, dataExtent, true),
  62455. linearMap$4(handleEnds[1], sizeExtent, dataExtent, true)
  62456. ];
  62457. },
  62458. /**
  62459. * @private
  62460. */
  62461. _updateView: function (forSketch) {
  62462. var visualMapModel = this.visualMapModel;
  62463. var dataExtent = visualMapModel.getExtent();
  62464. var shapes = this._shapes;
  62465. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  62466. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  62467. var visualInRange = this._createBarVisual(
  62468. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  62469. );
  62470. var visualOutOfRange = this._createBarVisual(
  62471. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  62472. );
  62473. shapes.inRange
  62474. .setStyle({
  62475. fill: visualInRange.barColor,
  62476. opacity: visualInRange.opacity
  62477. })
  62478. .setShape('points', visualInRange.barPoints);
  62479. shapes.outOfRange
  62480. .setStyle({
  62481. fill: visualOutOfRange.barColor,
  62482. opacity: visualOutOfRange.opacity
  62483. })
  62484. .setShape('points', visualOutOfRange.barPoints);
  62485. this._updateHandle(inRangeHandleEnds, visualInRange);
  62486. },
  62487. /**
  62488. * @private
  62489. */
  62490. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  62491. var opts = {
  62492. forceState: forceState,
  62493. convertOpacityToAlpha: true
  62494. };
  62495. var colorStops = this._makeColorGradient(dataInterval, opts);
  62496. var symbolSizes = [
  62497. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  62498. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  62499. ];
  62500. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  62501. return {
  62502. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  62503. barPoints: barPoints,
  62504. handlesColor: [
  62505. colorStops[0].color,
  62506. colorStops[colorStops.length - 1].color
  62507. ]
  62508. };
  62509. },
  62510. /**
  62511. * @private
  62512. */
  62513. _makeColorGradient: function (dataInterval, opts) {
  62514. // Considering colorHue, which is not linear, so we have to sample
  62515. // to calculate gradient color stops, but not only caculate head
  62516. // and tail.
  62517. var sampleNumber = 100; // Arbitrary value.
  62518. var colorStops = [];
  62519. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  62520. colorStops.push({
  62521. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  62522. offset: 0
  62523. });
  62524. for (var i = 1; i < sampleNumber; i++) {
  62525. var currValue = dataInterval[0] + step * i;
  62526. if (currValue > dataInterval[1]) {
  62527. break;
  62528. }
  62529. colorStops.push({
  62530. color: this.getControllerVisual(currValue, 'color', opts),
  62531. offset: i / sampleNumber
  62532. });
  62533. }
  62534. colorStops.push({
  62535. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  62536. offset: 1
  62537. });
  62538. return colorStops;
  62539. },
  62540. /**
  62541. * @private
  62542. */
  62543. _createBarPoints: function (handleEnds, symbolSizes) {
  62544. var itemSize = this.visualMapModel.itemSize;
  62545. return [
  62546. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  62547. [itemSize[0], handleEnds[0]],
  62548. [itemSize[0], handleEnds[1]],
  62549. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  62550. ];
  62551. },
  62552. /**
  62553. * @private
  62554. */
  62555. _createBarGroup: function (itemAlign) {
  62556. var orient = this._orient;
  62557. var inverse = this.visualMapModel.get('inverse');
  62558. return new Group(
  62559. (orient === 'horizontal' && !inverse)
  62560. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  62561. : (orient === 'horizontal' && inverse)
  62562. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  62563. : (orient === 'vertical' && !inverse)
  62564. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  62565. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  62566. );
  62567. },
  62568. /**
  62569. * @private
  62570. */
  62571. _updateHandle: function (handleEnds, visualInRange) {
  62572. if (!this._useHandle) {
  62573. return;
  62574. }
  62575. var shapes = this._shapes;
  62576. var visualMapModel = this.visualMapModel;
  62577. var handleThumbs = shapes.handleThumbs;
  62578. var handleLabels = shapes.handleLabels;
  62579. each$27([0, 1], function (handleIndex) {
  62580. var handleThumb = handleThumbs[handleIndex];
  62581. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  62582. handleThumb.position[1] = handleEnds[handleIndex];
  62583. // Update handle label position.
  62584. var textPoint = applyTransform$1(
  62585. shapes.handleLabelPoints[handleIndex],
  62586. getTransform(handleThumb, this.group)
  62587. );
  62588. handleLabels[handleIndex].setStyle({
  62589. x: textPoint[0],
  62590. y: textPoint[1],
  62591. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  62592. textVerticalAlign: 'middle',
  62593. textAlign: this._applyTransform(
  62594. this._orient === 'horizontal'
  62595. ? (handleIndex === 0 ? 'bottom' : 'top')
  62596. : 'left',
  62597. shapes.barGroup
  62598. )
  62599. });
  62600. }, this);
  62601. },
  62602. /**
  62603. * @private
  62604. * @param {number} cursorValue
  62605. * @param {number} textValue
  62606. * @param {string} [rangeSymbol]
  62607. * @param {number} [halfHoverLinkSize]
  62608. */
  62609. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  62610. var visualMapModel = this.visualMapModel;
  62611. var dataExtent = visualMapModel.getExtent();
  62612. var itemSize = visualMapModel.itemSize;
  62613. var sizeExtent = [0, itemSize[1]];
  62614. var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true);
  62615. var shapes = this._shapes;
  62616. var indicator = shapes.indicator;
  62617. if (!indicator) {
  62618. return;
  62619. }
  62620. indicator.position[1] = pos;
  62621. indicator.attr('invisible', false);
  62622. indicator.setShape('points', createIndicatorPoints(
  62623. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  62624. ));
  62625. var opts = {convertOpacityToAlpha: true};
  62626. var color = this.getControllerVisual(cursorValue, 'color', opts);
  62627. indicator.setStyle('fill', color);
  62628. // Update handle label position.
  62629. var textPoint = applyTransform$1(
  62630. shapes.indicatorLabelPoint,
  62631. getTransform(indicator, this.group)
  62632. );
  62633. var indicatorLabel = shapes.indicatorLabel;
  62634. indicatorLabel.attr('invisible', false);
  62635. var align = this._applyTransform('left', shapes.barGroup);
  62636. var orient = this._orient;
  62637. indicatorLabel.setStyle({
  62638. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  62639. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  62640. textAlign: orient === 'horizontal' ? 'center' : align,
  62641. x: textPoint[0],
  62642. y: textPoint[1]
  62643. });
  62644. },
  62645. /**
  62646. * @private
  62647. */
  62648. _enableHoverLinkToSeries: function () {
  62649. var self = this;
  62650. this._shapes.barGroup
  62651. .on('mousemove', function (e) {
  62652. self._hovering = true;
  62653. if (!self._dragging) {
  62654. var itemSize = self.visualMapModel.itemSize;
  62655. var pos = self._applyTransform(
  62656. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  62657. );
  62658. // For hover link show when hover handle, which might be
  62659. // below or upper than sizeExtent.
  62660. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  62661. self._doHoverLinkToSeries(
  62662. pos[1],
  62663. 0 <= pos[0] && pos[0] <= itemSize[0]
  62664. );
  62665. }
  62666. })
  62667. .on('mouseout', function () {
  62668. // When mouse is out of handle, hoverLink still need
  62669. // to be displayed when realtime is set as false.
  62670. self._hovering = false;
  62671. !self._dragging && self._clearHoverLinkToSeries();
  62672. });
  62673. },
  62674. /**
  62675. * @private
  62676. */
  62677. _enableHoverLinkFromSeries: function () {
  62678. var zr = this.api.getZr();
  62679. if (this.visualMapModel.option.hoverLink) {
  62680. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  62681. zr.on('mouseout', this._hideIndicator, this);
  62682. }
  62683. else {
  62684. this._clearHoverLinkFromSeries();
  62685. }
  62686. },
  62687. /**
  62688. * @private
  62689. */
  62690. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  62691. var visualMapModel = this.visualMapModel;
  62692. var itemSize = visualMapModel.itemSize;
  62693. if (!visualMapModel.option.hoverLink) {
  62694. return;
  62695. }
  62696. var sizeExtent = [0, itemSize[1]];
  62697. var dataExtent = visualMapModel.getExtent();
  62698. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  62699. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  62700. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  62701. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  62702. var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true);
  62703. var valueRange = [
  62704. linearMap$4(hoverRange[0], sizeExtent, dataExtent, true),
  62705. linearMap$4(hoverRange[1], sizeExtent, dataExtent, true)
  62706. ];
  62707. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  62708. // where china and india has very large population.
  62709. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  62710. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  62711. // Do not show indicator when mouse is over handle,
  62712. // otherwise labels overlap, especially when dragging.
  62713. if (hoverOnBar) {
  62714. if (valueRange[0] === -Infinity) {
  62715. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  62716. }
  62717. else if (valueRange[1] === Infinity) {
  62718. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  62719. }
  62720. else {
  62721. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  62722. }
  62723. }
  62724. // When realtime is set as false, handles, which are in barGroup,
  62725. // also trigger hoverLink, which help user to realize where they
  62726. // focus on when dragging. (see test/heatmap-large.html)
  62727. // When realtime is set as true, highlight will not show when hover
  62728. // handle, because the label on handle, which displays a exact value
  62729. // but not range, might mislead users.
  62730. var oldBatch = this._hoverLinkDataIndices;
  62731. var newBatch = [];
  62732. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  62733. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  62734. }
  62735. var resultBatches = compressBatches(oldBatch, newBatch);
  62736. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  62737. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  62738. },
  62739. /**
  62740. * @private
  62741. */
  62742. _hoverLinkFromSeriesMouseOver: function (e) {
  62743. var el = e.target;
  62744. var visualMapModel = this.visualMapModel;
  62745. if (!el || el.dataIndex == null) {
  62746. return;
  62747. }
  62748. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  62749. if (!visualMapModel.isTargetSeries(dataModel)) {
  62750. return;
  62751. }
  62752. var data = dataModel.getData(el.dataType);
  62753. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  62754. if (!isNaN(value)) {
  62755. this._showIndicator(value, value);
  62756. }
  62757. },
  62758. /**
  62759. * @private
  62760. */
  62761. _hideIndicator: function () {
  62762. var shapes = this._shapes;
  62763. shapes.indicator && shapes.indicator.attr('invisible', true);
  62764. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  62765. },
  62766. /**
  62767. * @private
  62768. */
  62769. _clearHoverLinkToSeries: function () {
  62770. this._hideIndicator();
  62771. var indices = this._hoverLinkDataIndices;
  62772. this._dispatchHighDown('downplay', convertDataIndex(indices));
  62773. indices.length = 0;
  62774. },
  62775. /**
  62776. * @private
  62777. */
  62778. _clearHoverLinkFromSeries: function () {
  62779. this._hideIndicator();
  62780. var zr = this.api.getZr();
  62781. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  62782. zr.off('mouseout', this._hideIndicator);
  62783. },
  62784. /**
  62785. * @private
  62786. */
  62787. _applyTransform: function (vertex, element, inverse, global) {
  62788. var transform = getTransform(element, global ? null : this.group);
  62789. return graphic[
  62790. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  62791. ](vertex, transform, inverse);
  62792. },
  62793. /**
  62794. * @private
  62795. */
  62796. _dispatchHighDown: function (type, batch) {
  62797. batch && batch.length && this.api.dispatchAction({
  62798. type: type,
  62799. batch: batch
  62800. });
  62801. },
  62802. /**
  62803. * @override
  62804. */
  62805. dispose: function () {
  62806. this._clearHoverLinkFromSeries();
  62807. this._clearHoverLinkToSeries();
  62808. },
  62809. /**
  62810. * @override
  62811. */
  62812. remove: function () {
  62813. this._clearHoverLinkFromSeries();
  62814. this._clearHoverLinkToSeries();
  62815. }
  62816. });
  62817. function createPolygon(points, cursor, onDrift, onDragEnd) {
  62818. return new Polygon({
  62819. shape: {points: points},
  62820. draggable: !!onDrift,
  62821. cursor: cursor,
  62822. drift: onDrift,
  62823. onmousemove: function (e) {
  62824. // Fot mobile devicem, prevent screen slider on the button.
  62825. stop(e.event);
  62826. },
  62827. ondragend: onDragEnd
  62828. });
  62829. }
  62830. function createHandlePoints(handleIndex, textSize) {
  62831. return handleIndex === 0
  62832. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  62833. : [[0, 0], [textSize, 0], [textSize, textSize]];
  62834. }
  62835. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  62836. return isRange
  62837. ? [ // indicate range
  62838. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  62839. [HOVER_LINK_OUT, 0],
  62840. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  62841. ]
  62842. : [ // indicate single value
  62843. [0, 0], [5, -5], [5, 5]
  62844. ];
  62845. }
  62846. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  62847. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  62848. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  62849. if (hoverLinkDataSize) {
  62850. halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  62851. }
  62852. return halfHoverLinkSize;
  62853. }
  62854. function useHoverLinkOnHandle(visualMapModel) {
  62855. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  62856. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  62857. }
  62858. function getCursor$1(orient) {
  62859. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  62860. }
  62861. var actionInfo$2 = {
  62862. type: 'selectDataRange',
  62863. event: 'dataRangeSelected',
  62864. // FIXME use updateView appears wrong
  62865. update: 'update'
  62866. };
  62867. registerAction(actionInfo$2, function (payload, ecModel) {
  62868. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  62869. model.setSelected(payload.selected);
  62870. });
  62871. });
  62872. /**
  62873. * DataZoom component entry
  62874. */
  62875. registerPreprocessor(preprocessor$2);
  62876. var PiecewiseModel = VisualMapModel.extend({
  62877. type: 'visualMap.piecewise',
  62878. /**
  62879. * Order Rule:
  62880. *
  62881. * option.categories / option.pieces / option.text / option.selected:
  62882. * If !option.inverse,
  62883. * Order when vertical: ['top', ..., 'bottom'].
  62884. * Order when horizontal: ['left', ..., 'right'].
  62885. * If option.inverse, the meaning of
  62886. * the order should be reversed.
  62887. *
  62888. * this._pieceList:
  62889. * The order is always [low, ..., high].
  62890. *
  62891. * Mapping from location to low-high:
  62892. * If !option.inverse
  62893. * When vertical, top is high.
  62894. * When horizontal, right is high.
  62895. * If option.inverse, reverse.
  62896. */
  62897. /**
  62898. * @protected
  62899. */
  62900. defaultOption: {
  62901. selected: null, // Object. If not specified, means selected.
  62902. // When pieces and splitNumber: {'0': true, '5': true}
  62903. // When categories: {'cate1': false, 'cate3': true}
  62904. // When selected === false, means all unselected.
  62905. minOpen: false, // Whether include values that smaller than `min`.
  62906. maxOpen: false, // Whether include values that bigger than `max`.
  62907. align: 'auto', // 'auto', 'left', 'right'
  62908. itemWidth: 20, // When put the controller vertically, it is the length of
  62909. // horizontal side of each item. Otherwise, vertical side.
  62910. itemHeight: 14, // When put the controller vertically, it is the length of
  62911. // vertical side of each item. Otherwise, horizontal side.
  62912. itemSymbol: 'roundRect',
  62913. pieceList: null, // Each item is Object, with some of those attrs:
  62914. // {min, max, lt, gt, lte, gte, value,
  62915. // color, colorSaturation, colorAlpha, opacity,
  62916. // symbol, symbolSize}, which customize the range or visual
  62917. // coding of the certain piece. Besides, see "Order Rule".
  62918. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  62919. // Attr min/max are ignored when categories set. See "Order Rule"
  62920. splitNumber: 5, // If set to 5, auto split five pieces equally.
  62921. // If set to 0 and component type not set, component type will be
  62922. // determined as "continuous". (It is less reasonable but for ec2
  62923. // compatibility, see echarts/component/visualMap/typeDefaulter)
  62924. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  62925. itemGap: 10, // The gap between two items, in px.
  62926. hoverLink: true, // Enable hover highlight.
  62927. showLabel: null // By default, when text is used, label will hide (the logic
  62928. // is remained for compatibility reason)
  62929. },
  62930. /**
  62931. * @override
  62932. */
  62933. optionUpdated: function (newOption, isInit) {
  62934. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  62935. /**
  62936. * The order is always [low, ..., high].
  62937. * [{text: string, interval: Array.<number>}, ...]
  62938. * @private
  62939. * @type {Array.<Object>}
  62940. */
  62941. this._pieceList = [];
  62942. this.resetExtent();
  62943. /**
  62944. * 'pieces', 'categories', 'splitNumber'
  62945. * @type {string}
  62946. */
  62947. var mode = this._mode = this._determineMode();
  62948. resetMethods[this._mode].call(this);
  62949. this._resetSelected(newOption, isInit);
  62950. var categories = this.option.categories;
  62951. this.resetVisual(function (mappingOption, state) {
  62952. if (mode === 'categories') {
  62953. mappingOption.mappingMethod = 'category';
  62954. mappingOption.categories = clone(categories);
  62955. }
  62956. else {
  62957. mappingOption.dataExtent = this.getExtent();
  62958. mappingOption.mappingMethod = 'piecewise';
  62959. mappingOption.pieceList = map(this._pieceList, function (piece) {
  62960. var piece = clone(piece);
  62961. if (state !== 'inRange') {
  62962. // FIXME
  62963. // outOfRange do not support special visual in pieces.
  62964. piece.visual = null;
  62965. }
  62966. return piece;
  62967. });
  62968. }
  62969. });
  62970. },
  62971. /**
  62972. * @protected
  62973. * @override
  62974. */
  62975. completeVisualOption: function () {
  62976. // Consider this case:
  62977. // visualMap: {
  62978. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  62979. // }
  62980. // where no inRange/outOfRange set but only pieces. So we should make
  62981. // default inRange/outOfRange for this case, otherwise visuals that only
  62982. // appear in `pieces` will not be taken into account in visual encoding.
  62983. var option = this.option;
  62984. var visualTypesInPieces = {};
  62985. var visualTypes = VisualMapping.listVisualTypes();
  62986. var isCategory = this.isCategory();
  62987. each$1(option.pieces, function (piece) {
  62988. each$1(visualTypes, function (visualType) {
  62989. if (piece.hasOwnProperty(visualType)) {
  62990. visualTypesInPieces[visualType] = 1;
  62991. }
  62992. });
  62993. });
  62994. each$1(visualTypesInPieces, function (v, visualType) {
  62995. var exists = 0;
  62996. each$1(this.stateList, function (state) {
  62997. exists |= has(option, state, visualType)
  62998. || has(option.target, state, visualType);
  62999. }, this);
  63000. !exists && each$1(this.stateList, function (state) {
  63001. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  63002. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  63003. );
  63004. });
  63005. }, this);
  63006. function has(obj, state, visualType) {
  63007. return obj && obj[state] && (
  63008. isObject$1(obj[state])
  63009. ? obj[state].hasOwnProperty(visualType)
  63010. : obj[state] === visualType // e.g., inRange: 'symbol'
  63011. );
  63012. }
  63013. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  63014. },
  63015. _resetSelected: function (newOption, isInit) {
  63016. var thisOption = this.option;
  63017. var pieceList = this._pieceList;
  63018. // Selected do not merge but all override.
  63019. var selected = (isInit ? thisOption : newOption).selected || {};
  63020. thisOption.selected = selected;
  63021. // Consider 'not specified' means true.
  63022. each$1(pieceList, function (piece, index) {
  63023. var key = this.getSelectedMapKey(piece);
  63024. if (!selected.hasOwnProperty(key)) {
  63025. selected[key] = true;
  63026. }
  63027. }, this);
  63028. if (thisOption.selectedMode === 'single') {
  63029. // Ensure there is only one selected.
  63030. var hasSel = false;
  63031. each$1(pieceList, function (piece, index) {
  63032. var key = this.getSelectedMapKey(piece);
  63033. if (selected[key]) {
  63034. hasSel
  63035. ? (selected[key] = false)
  63036. : (hasSel = true);
  63037. }
  63038. }, this);
  63039. }
  63040. // thisOption.selectedMode === 'multiple', default: all selected.
  63041. },
  63042. /**
  63043. * @public
  63044. */
  63045. getSelectedMapKey: function (piece) {
  63046. return this._mode === 'categories'
  63047. ? piece.value + '' : piece.index + '';
  63048. },
  63049. /**
  63050. * @public
  63051. */
  63052. getPieceList: function () {
  63053. return this._pieceList;
  63054. },
  63055. /**
  63056. * @private
  63057. * @return {string}
  63058. */
  63059. _determineMode: function () {
  63060. var option = this.option;
  63061. return option.pieces && option.pieces.length > 0
  63062. ? 'pieces'
  63063. : this.option.categories
  63064. ? 'categories'
  63065. : 'splitNumber';
  63066. },
  63067. /**
  63068. * @public
  63069. * @override
  63070. */
  63071. setSelected: function (selected) {
  63072. this.option.selected = clone(selected);
  63073. },
  63074. /**
  63075. * @public
  63076. * @override
  63077. */
  63078. getValueState: function (value) {
  63079. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  63080. return index != null
  63081. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  63082. ? 'inRange' : 'outOfRange'
  63083. )
  63084. : 'outOfRange';
  63085. },
  63086. /**
  63087. * @public
  63088. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  63089. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  63090. */
  63091. findTargetDataIndices: function (pieceIndex) {
  63092. var result = [];
  63093. this.eachTargetSeries(function (seriesModel) {
  63094. var dataIndices = [];
  63095. var data = seriesModel.getData();
  63096. data.each(this.getDataDimension(data), function (value, dataIndex) {
  63097. // Should always base on model pieceList, because it is order sensitive.
  63098. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  63099. pIdx === pieceIndex && dataIndices.push(dataIndex);
  63100. }, this);
  63101. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  63102. }, this);
  63103. return result;
  63104. },
  63105. /**
  63106. * @private
  63107. * @param {Object} piece piece.value or piece.interval is required.
  63108. * @return {number} Can be Infinity or -Infinity
  63109. */
  63110. getRepresentValue: function (piece) {
  63111. var representValue;
  63112. if (this.isCategory()) {
  63113. representValue = piece.value;
  63114. }
  63115. else {
  63116. if (piece.value != null) {
  63117. representValue = piece.value;
  63118. }
  63119. else {
  63120. var pieceInterval = piece.interval || [];
  63121. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  63122. ? 0
  63123. : (pieceInterval[0] + pieceInterval[1]) / 2;
  63124. }
  63125. }
  63126. return representValue;
  63127. },
  63128. getVisualMeta: function (getColorVisual) {
  63129. // Do not support category. (category axis is ordinal, numerical)
  63130. if (this.isCategory()) {
  63131. return;
  63132. }
  63133. var stops = [];
  63134. var outerColors = [];
  63135. var visualMapModel = this;
  63136. function setStop(interval, valueState) {
  63137. var representValue = visualMapModel.getRepresentValue({interval: interval});
  63138. if (!valueState) {
  63139. valueState = visualMapModel.getValueState(representValue);
  63140. }
  63141. var color = getColorVisual(representValue, valueState);
  63142. if (interval[0] === -Infinity) {
  63143. outerColors[0] = color;
  63144. }
  63145. else if (interval[1] === Infinity) {
  63146. outerColors[1] = color;
  63147. }
  63148. else {
  63149. stops.push(
  63150. {value: interval[0], color: color},
  63151. {value: interval[1], color: color}
  63152. );
  63153. }
  63154. }
  63155. // Suplement
  63156. var pieceList = this._pieceList.slice();
  63157. if (!pieceList.length) {
  63158. pieceList.push({interval: [-Infinity, Infinity]});
  63159. }
  63160. else {
  63161. var edge = pieceList[0].interval[0];
  63162. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  63163. edge = pieceList[pieceList.length - 1].interval[1];
  63164. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  63165. }
  63166. var curr = -Infinity;
  63167. each$1(pieceList, function (piece) {
  63168. var interval = piece.interval;
  63169. if (interval) {
  63170. // Fulfill gap.
  63171. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  63172. setStop(interval.slice());
  63173. curr = interval[1];
  63174. }
  63175. }, this);
  63176. return {stops: stops, outerColors: outerColors};
  63177. }
  63178. });
  63179. /**
  63180. * Key is this._mode
  63181. * @type {Object}
  63182. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  63183. */
  63184. var resetMethods = {
  63185. splitNumber: function () {
  63186. var thisOption = this.option;
  63187. var pieceList = this._pieceList;
  63188. var precision = Math.min(thisOption.precision, 20);
  63189. var dataExtent = this.getExtent();
  63190. var splitNumber = thisOption.splitNumber;
  63191. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  63192. thisOption.splitNumber = splitNumber;
  63193. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  63194. // Precision auto-adaption
  63195. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  63196. precision++;
  63197. }
  63198. thisOption.precision = precision;
  63199. splitStep = +splitStep.toFixed(precision);
  63200. var index = 0;
  63201. if (thisOption.minOpen) {
  63202. pieceList.push({
  63203. index: index++,
  63204. interval: [-Infinity, dataExtent[0]],
  63205. close: [0, 0]
  63206. });
  63207. }
  63208. for (
  63209. var curr = dataExtent[0], len = index + splitNumber;
  63210. index < len;
  63211. curr += splitStep
  63212. ) {
  63213. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  63214. pieceList.push({
  63215. index: index++,
  63216. interval: [curr, max],
  63217. close: [1, 1]
  63218. });
  63219. }
  63220. if (thisOption.maxOpen) {
  63221. pieceList.push({
  63222. index: index++,
  63223. interval: [dataExtent[1], Infinity],
  63224. close: [0, 0]
  63225. });
  63226. }
  63227. reformIntervals(pieceList);
  63228. each$1(pieceList, function (piece) {
  63229. piece.text = this.formatValueText(piece.interval);
  63230. }, this);
  63231. },
  63232. categories: function () {
  63233. var thisOption = this.option;
  63234. each$1(thisOption.categories, function (cate) {
  63235. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  63236. // 是否改一致。
  63237. this._pieceList.push({
  63238. text: this.formatValueText(cate, true),
  63239. value: cate
  63240. });
  63241. }, this);
  63242. // See "Order Rule".
  63243. normalizeReverse(thisOption, this._pieceList);
  63244. },
  63245. pieces: function () {
  63246. var thisOption = this.option;
  63247. var pieceList = this._pieceList;
  63248. each$1(thisOption.pieces, function (pieceListItem, index) {
  63249. if (!isObject$1(pieceListItem)) {
  63250. pieceListItem = {value: pieceListItem};
  63251. }
  63252. var item = {text: '', index: index};
  63253. if (pieceListItem.label != null) {
  63254. item.text = pieceListItem.label;
  63255. }
  63256. if (pieceListItem.hasOwnProperty('value')) {
  63257. var value = item.value = pieceListItem.value;
  63258. item.interval = [value, value];
  63259. item.close = [1, 1];
  63260. }
  63261. else {
  63262. // `min` `max` is legacy option.
  63263. // `lt` `gt` `lte` `gte` is recommanded.
  63264. var interval = item.interval = [];
  63265. var close = item.close = [0, 0];
  63266. var closeList = [1, 0, 1];
  63267. var infinityList = [-Infinity, Infinity];
  63268. var useMinMax = [];
  63269. for (var lg = 0; lg < 2; lg++) {
  63270. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  63271. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  63272. interval[lg] = pieceListItem[names[i]];
  63273. close[lg] = closeList[i];
  63274. useMinMax[lg] = i === 2;
  63275. }
  63276. interval[lg] == null && (interval[lg] = infinityList[lg]);
  63277. }
  63278. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  63279. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  63280. if (__DEV__) {
  63281. if (interval[0] > interval[1]) {
  63282. console.warn(
  63283. 'Piece ' + index + 'is illegal: ' + interval
  63284. + ' lower bound should not greater then uppper bound.'
  63285. );
  63286. }
  63287. }
  63288. if (interval[0] === interval[1] && close[0] && close[1]) {
  63289. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  63290. // we use value to lift the priority when min === max
  63291. item.value = interval[0];
  63292. }
  63293. }
  63294. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  63295. pieceList.push(item);
  63296. }, this);
  63297. // See "Order Rule".
  63298. normalizeReverse(thisOption, pieceList);
  63299. // Only pieces
  63300. reformIntervals(pieceList);
  63301. each$1(pieceList, function (piece) {
  63302. var close = piece.close;
  63303. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  63304. piece.text = piece.text || this.formatValueText(
  63305. piece.value != null ? piece.value : piece.interval,
  63306. false,
  63307. edgeSymbols
  63308. );
  63309. }, this);
  63310. }
  63311. };
  63312. function normalizeReverse(thisOption, pieceList) {
  63313. var inverse = thisOption.inverse;
  63314. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  63315. pieceList.reverse();
  63316. }
  63317. }
  63318. var PiecewiseVisualMapView = VisualMapView.extend({
  63319. type: 'visualMap.piecewise',
  63320. /**
  63321. * @protected
  63322. * @override
  63323. */
  63324. doRender: function () {
  63325. var thisGroup = this.group;
  63326. thisGroup.removeAll();
  63327. var visualMapModel = this.visualMapModel;
  63328. var textGap = visualMapModel.get('textGap');
  63329. var textStyleModel = visualMapModel.textStyleModel;
  63330. var textFont = textStyleModel.getFont();
  63331. var textFill = textStyleModel.getTextColor();
  63332. var itemAlign = this._getItemAlign();
  63333. var itemSize = visualMapModel.itemSize;
  63334. var viewData = this._getViewData();
  63335. var endsText = viewData.endsText;
  63336. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  63337. endsText && this._renderEndsText(
  63338. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  63339. );
  63340. each$1(viewData.viewPieceList, renderItem, this);
  63341. endsText && this._renderEndsText(
  63342. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  63343. );
  63344. box(
  63345. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  63346. );
  63347. this.renderBackground(thisGroup);
  63348. this.positionGroup(thisGroup);
  63349. function renderItem(item) {
  63350. var piece = item.piece;
  63351. var itemGroup = new Group();
  63352. itemGroup.onclick = bind(this._onItemClick, this, piece);
  63353. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  63354. var representValue = visualMapModel.getRepresentValue(piece);
  63355. this._createItemSymbol(
  63356. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  63357. );
  63358. if (showLabel) {
  63359. var visualState = this.visualMapModel.getValueState(representValue);
  63360. itemGroup.add(new Text({
  63361. style: {
  63362. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  63363. y: itemSize[1] / 2,
  63364. text: piece.text,
  63365. textVerticalAlign: 'middle',
  63366. textAlign: itemAlign,
  63367. textFont: textFont,
  63368. textFill: textFill,
  63369. opacity: visualState === 'outOfRange' ? 0.5 : 1
  63370. }
  63371. }));
  63372. }
  63373. thisGroup.add(itemGroup);
  63374. }
  63375. },
  63376. /**
  63377. * @private
  63378. */
  63379. _enableHoverLink: function (itemGroup, pieceIndex) {
  63380. itemGroup
  63381. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  63382. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  63383. function onHoverLink(method) {
  63384. var visualMapModel = this.visualMapModel;
  63385. visualMapModel.option.hoverLink && this.api.dispatchAction({
  63386. type: method,
  63387. batch: convertDataIndex(
  63388. visualMapModel.findTargetDataIndices(pieceIndex)
  63389. )
  63390. });
  63391. }
  63392. },
  63393. /**
  63394. * @private
  63395. */
  63396. _getItemAlign: function () {
  63397. var visualMapModel = this.visualMapModel;
  63398. var modelOption = visualMapModel.option;
  63399. if (modelOption.orient === 'vertical') {
  63400. return getItemAlign(
  63401. visualMapModel, this.api, visualMapModel.itemSize
  63402. );
  63403. }
  63404. else { // horizontal, most case left unless specifying right.
  63405. var align = modelOption.align;
  63406. if (!align || align === 'auto') {
  63407. align = 'left';
  63408. }
  63409. return align;
  63410. }
  63411. },
  63412. /**
  63413. * @private
  63414. */
  63415. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  63416. if (!text) {
  63417. return;
  63418. }
  63419. var itemGroup = new Group();
  63420. var textStyleModel = this.visualMapModel.textStyleModel;
  63421. itemGroup.add(new Text({
  63422. style: {
  63423. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  63424. y: itemSize[1] / 2,
  63425. textVerticalAlign: 'middle',
  63426. textAlign: showLabel ? itemAlign : 'center',
  63427. text: text,
  63428. textFont: textStyleModel.getFont(),
  63429. textFill: textStyleModel.getTextColor()
  63430. }
  63431. }));
  63432. group.add(itemGroup);
  63433. },
  63434. /**
  63435. * @private
  63436. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  63437. */
  63438. _getViewData: function () {
  63439. var visualMapModel = this.visualMapModel;
  63440. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  63441. return {piece: piece, indexInModelPieceList: index};
  63442. });
  63443. var endsText = visualMapModel.get('text');
  63444. // Consider orient and inverse.
  63445. var orient = visualMapModel.get('orient');
  63446. var inverse = visualMapModel.get('inverse');
  63447. // Order of model pieceList is always [low, ..., high]
  63448. if (orient === 'horizontal' ? inverse : !inverse) {
  63449. viewPieceList.reverse();
  63450. }
  63451. // Origin order of endsText is [high, low]
  63452. else if (endsText) {
  63453. endsText = endsText.slice().reverse();
  63454. }
  63455. return {viewPieceList: viewPieceList, endsText: endsText};
  63456. },
  63457. /**
  63458. * @private
  63459. */
  63460. _createItemSymbol: function (group, representValue, shapeParam) {
  63461. group.add(createSymbol(
  63462. this.getControllerVisual(representValue, 'symbol'),
  63463. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  63464. this.getControllerVisual(representValue, 'color')
  63465. ));
  63466. },
  63467. /**
  63468. * @private
  63469. */
  63470. _onItemClick: function (piece) {
  63471. var visualMapModel = this.visualMapModel;
  63472. var option = visualMapModel.option;
  63473. var selected = clone(option.selected);
  63474. var newKey = visualMapModel.getSelectedMapKey(piece);
  63475. if (option.selectedMode === 'single') {
  63476. selected[newKey] = true;
  63477. each$1(selected, function (o, key) {
  63478. selected[key] = key === newKey;
  63479. });
  63480. }
  63481. else {
  63482. selected[newKey] = !selected[newKey];
  63483. }
  63484. this.api.dispatchAction({
  63485. type: 'selectDataRange',
  63486. from: this.uid,
  63487. visualMapId: this.visualMapModel.id,
  63488. selected: selected
  63489. });
  63490. }
  63491. });
  63492. /**
  63493. * DataZoom component entry
  63494. */
  63495. registerPreprocessor(preprocessor$2);
  63496. /**
  63497. * visualMap component entry
  63498. */
  63499. var addCommas$1 = addCommas;
  63500. var encodeHTML$1 = encodeHTML;
  63501. function fillLabel(opt) {
  63502. defaultEmphasis(opt, 'label', ['show']);
  63503. }
  63504. var MarkerModel = extendComponentModel({
  63505. type: 'marker',
  63506. dependencies: ['series', 'grid', 'polar', 'geo'],
  63507. /**
  63508. * @overrite
  63509. */
  63510. init: function (option, parentModel, ecModel, extraOpt) {
  63511. if (__DEV__) {
  63512. if (this.type === 'marker') {
  63513. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  63514. }
  63515. }
  63516. this.mergeDefaultAndTheme(option, ecModel);
  63517. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  63518. },
  63519. /**
  63520. * @return {boolean}
  63521. */
  63522. isAnimationEnabled: function () {
  63523. if (env$1.node) {
  63524. return false;
  63525. }
  63526. var hostSeries = this.__hostSeries;
  63527. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  63528. },
  63529. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  63530. var MarkerModel = this.constructor;
  63531. var modelPropName = this.mainType + 'Model';
  63532. if (!createdBySelf) {
  63533. ecModel.eachSeries(function (seriesModel) {
  63534. var markerOpt = seriesModel.get(this.mainType);
  63535. var markerModel = seriesModel[modelPropName];
  63536. if (!markerOpt || !markerOpt.data) {
  63537. seriesModel[modelPropName] = null;
  63538. return;
  63539. }
  63540. if (!markerModel) {
  63541. if (isInit) {
  63542. // Default label emphasis `position` and `show`
  63543. fillLabel(markerOpt);
  63544. }
  63545. each$1(markerOpt.data, function (item) {
  63546. // FIXME Overwrite fillLabel method ?
  63547. if (item instanceof Array) {
  63548. fillLabel(item[0]);
  63549. fillLabel(item[1]);
  63550. }
  63551. else {
  63552. fillLabel(item);
  63553. }
  63554. });
  63555. markerModel = new MarkerModel(
  63556. markerOpt, this, ecModel
  63557. );
  63558. extend(markerModel, {
  63559. mainType: this.mainType,
  63560. // Use the same series index and name
  63561. seriesIndex: seriesModel.seriesIndex,
  63562. name: seriesModel.name,
  63563. createdBySelf: true
  63564. });
  63565. markerModel.__hostSeries = seriesModel;
  63566. }
  63567. else {
  63568. markerModel.mergeOption(markerOpt, ecModel, true);
  63569. }
  63570. seriesModel[modelPropName] = markerModel;
  63571. }, this);
  63572. }
  63573. },
  63574. formatTooltip: function (dataIndex) {
  63575. var data = this.getData();
  63576. var value = this.getRawValue(dataIndex);
  63577. var formattedValue = isArray(value)
  63578. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  63579. var name = data.getName(dataIndex);
  63580. var html = encodeHTML$1(this.name);
  63581. if (value != null || name) {
  63582. html += '<br />';
  63583. }
  63584. if (name) {
  63585. html += encodeHTML$1(name);
  63586. if (value != null) {
  63587. html += ' : ';
  63588. }
  63589. }
  63590. if (value != null) {
  63591. html += encodeHTML$1(formattedValue);
  63592. }
  63593. return html;
  63594. },
  63595. getData: function () {
  63596. return this._data;
  63597. },
  63598. setData: function (data) {
  63599. this._data = data;
  63600. }
  63601. });
  63602. mixin(MarkerModel, dataFormatMixin);
  63603. MarkerModel.extend({
  63604. type: 'markPoint',
  63605. defaultOption: {
  63606. zlevel: 0,
  63607. z: 5,
  63608. symbol: 'pin',
  63609. symbolSize: 50,
  63610. //symbolRotate: 0,
  63611. //symbolOffset: [0, 0]
  63612. tooltip: {
  63613. trigger: 'item'
  63614. },
  63615. label: {
  63616. show: true,
  63617. position: 'inside'
  63618. },
  63619. itemStyle: {
  63620. borderWidth: 2
  63621. },
  63622. emphasis: {
  63623. label: {
  63624. show: true
  63625. }
  63626. }
  63627. }
  63628. });
  63629. var indexOf$2 = indexOf;
  63630. function hasXOrY(item) {
  63631. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  63632. }
  63633. function hasXAndY(item) {
  63634. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  63635. }
  63636. // Make it simple, do not visit all stacked value to count precision.
  63637. // function getPrecision(data, valueAxisDim, dataIndex) {
  63638. // var precision = -1;
  63639. // var stackedDim = data.mapDimension(valueAxisDim);
  63640. // do {
  63641. // precision = Math.max(
  63642. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  63643. // precision
  63644. // );
  63645. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  63646. // if (stackedOnSeries) {
  63647. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  63648. // data = stackedOnSeries.getData();
  63649. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  63650. // stackedDim = data.getCalculationInfo('stackedDimension');
  63651. // }
  63652. // else {
  63653. // data = null;
  63654. // }
  63655. // } while (data);
  63656. // return precision;
  63657. // }
  63658. function markerTypeCalculatorWithExtent(
  63659. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  63660. ) {
  63661. var coordArr = [];
  63662. var stacked = isDimensionStacked(data, targetDataDim, otherDataDim);
  63663. var calcDataDim = stacked
  63664. ? data.getCalculationInfo('stackResultDimension')
  63665. : targetDataDim;
  63666. var value = numCalculate(data, calcDataDim, mlType);
  63667. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  63668. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  63669. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  63670. // Make it simple, do not visit all stacked value to count precision.
  63671. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  63672. precision = Math.min(precision, 20);
  63673. if (precision >= 0) {
  63674. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  63675. }
  63676. return coordArr;
  63677. }
  63678. var curry$7 = curry;
  63679. // TODO Specified percent
  63680. var markerTypeCalculator = {
  63681. /**
  63682. * @method
  63683. * @param {module:echarts/data/List} data
  63684. * @param {string} baseAxisDim
  63685. * @param {string} valueAxisDim
  63686. */
  63687. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  63688. /**
  63689. * @method
  63690. * @param {module:echarts/data/List} data
  63691. * @param {string} baseAxisDim
  63692. * @param {string} valueAxisDim
  63693. */
  63694. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  63695. /**
  63696. * @method
  63697. * @param {module:echarts/data/List} data
  63698. * @param {string} baseAxisDim
  63699. * @param {string} valueAxisDim
  63700. */
  63701. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  63702. };
  63703. /**
  63704. * Transform markPoint data item to format used in List by do the following
  63705. * 1. Calculate statistic like `max`, `min`, `average`
  63706. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  63707. * @param {module:echarts/model/Series} seriesModel
  63708. * @param {module:echarts/coord/*} [coordSys]
  63709. * @param {Object} item
  63710. * @return {Object}
  63711. */
  63712. function dataTransform(seriesModel, item) {
  63713. var data = seriesModel.getData();
  63714. var coordSys = seriesModel.coordinateSystem;
  63715. // 1. If not specify the position with pixel directly
  63716. // 2. If `coord` is not a data array. Which uses `xAxis`,
  63717. // `yAxis` to specify the coord on each dimension
  63718. // parseFloat first because item.x and item.y can be percent string like '20%'
  63719. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  63720. var dims = coordSys.dimensions;
  63721. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  63722. // Clone the option
  63723. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  63724. item = clone(item);
  63725. if (item.type
  63726. && markerTypeCalculator[item.type]
  63727. && axisInfo.baseAxis && axisInfo.valueAxis
  63728. ) {
  63729. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  63730. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  63731. item.coord = markerTypeCalculator[item.type](
  63732. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  63733. otherCoordIndex, targetCoordIndex
  63734. );
  63735. // Force to use the value of calculated value.
  63736. item.value = item.coord[targetCoordIndex];
  63737. }
  63738. else {
  63739. // FIXME Only has one of xAxis and yAxis.
  63740. var coord = [
  63741. item.xAxis != null ? item.xAxis : item.radiusAxis,
  63742. item.yAxis != null ? item.yAxis : item.angleAxis
  63743. ];
  63744. // Each coord support max, min, average
  63745. for (var i = 0; i < 2; i++) {
  63746. if (markerTypeCalculator[coord[i]]) {
  63747. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  63748. }
  63749. }
  63750. item.coord = coord;
  63751. }
  63752. }
  63753. return item;
  63754. }
  63755. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  63756. var ret = {};
  63757. if (item.valueIndex != null || item.valueDim != null) {
  63758. ret.valueDataDim = item.valueIndex != null
  63759. ? data.getDimension(item.valueIndex) : item.valueDim;
  63760. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  63761. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  63762. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  63763. }
  63764. else {
  63765. ret.baseAxis = seriesModel.getBaseAxis();
  63766. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  63767. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  63768. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  63769. }
  63770. return ret;
  63771. }
  63772. function dataDimToCoordDim(seriesModel, dataDim) {
  63773. var data = seriesModel.getData();
  63774. var dimensions = data.dimensions;
  63775. dataDim = data.getDimension(dataDim);
  63776. for (var i = 0; i < dimensions.length; i++) {
  63777. var dimItem = data.getDimensionInfo(dimensions[i]);
  63778. if (dimItem.name === dataDim) {
  63779. return dimItem.coordDim;
  63780. }
  63781. }
  63782. }
  63783. /**
  63784. * Filter data which is out of coordinateSystem range
  63785. * [dataFilter description]
  63786. * @param {module:echarts/coord/*} [coordSys]
  63787. * @param {Object} item
  63788. * @return {boolean}
  63789. */
  63790. function dataFilter$1(coordSys, item) {
  63791. // Alwalys return true if there is no coordSys
  63792. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  63793. ? coordSys.containData(item.coord) : true;
  63794. }
  63795. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  63796. // x, y, radius, angle
  63797. if (dimIndex < 2) {
  63798. return item.coord && item.coord[dimIndex];
  63799. }
  63800. return item.value;
  63801. }
  63802. function numCalculate(data, valueDataDim, type) {
  63803. if (type === 'average') {
  63804. var sum = 0;
  63805. var count = 0;
  63806. data.each(valueDataDim, function (val, idx) {
  63807. if (!isNaN(val)) {
  63808. sum += val;
  63809. count++;
  63810. }
  63811. });
  63812. return sum / count;
  63813. }
  63814. else {
  63815. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  63816. }
  63817. }
  63818. var MarkerView = extendComponentView({
  63819. type: 'marker',
  63820. init: function () {
  63821. /**
  63822. * Markline grouped by series
  63823. * @private
  63824. * @type {module:zrender/core/util.HashMap}
  63825. */
  63826. this.markerGroupMap = createHashMap();
  63827. },
  63828. render: function (markerModel, ecModel, api) {
  63829. var markerGroupMap = this.markerGroupMap;
  63830. markerGroupMap.each(function (item) {
  63831. item.__keep = false;
  63832. });
  63833. var markerModelKey = this.type + 'Model';
  63834. ecModel.eachSeries(function (seriesModel) {
  63835. var markerModel = seriesModel[markerModelKey];
  63836. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  63837. }, this);
  63838. markerGroupMap.each(function (item) {
  63839. !item.__keep && this.group.remove(item.group);
  63840. }, this);
  63841. },
  63842. renderSeries: function () {}
  63843. });
  63844. function updateMarkerLayout(mpData, seriesModel, api) {
  63845. var coordSys = seriesModel.coordinateSystem;
  63846. mpData.each(function (idx) {
  63847. var itemModel = mpData.getItemModel(idx);
  63848. var point;
  63849. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  63850. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  63851. if (!isNaN(xPx) && !isNaN(yPx)) {
  63852. point = [xPx, yPx];
  63853. }
  63854. // Chart like bar may have there own marker positioning logic
  63855. else if (seriesModel.getMarkerPosition) {
  63856. // Use the getMarkerPoisition
  63857. point = seriesModel.getMarkerPosition(
  63858. mpData.getValues(mpData.dimensions, idx)
  63859. );
  63860. }
  63861. else if (coordSys) {
  63862. var x = mpData.get(coordSys.dimensions[0], idx);
  63863. var y = mpData.get(coordSys.dimensions[1], idx);
  63864. point = coordSys.dataToPoint([x, y]);
  63865. }
  63866. // Use x, y if has any
  63867. if (!isNaN(xPx)) {
  63868. point[0] = xPx;
  63869. }
  63870. if (!isNaN(yPx)) {
  63871. point[1] = yPx;
  63872. }
  63873. mpData.setItemLayout(idx, point);
  63874. });
  63875. }
  63876. MarkerView.extend({
  63877. type: 'markPoint',
  63878. // updateLayout: function (markPointModel, ecModel, api) {
  63879. // ecModel.eachSeries(function (seriesModel) {
  63880. // var mpModel = seriesModel.markPointModel;
  63881. // if (mpModel) {
  63882. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63883. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63884. // }
  63885. // }, this);
  63886. // },
  63887. updateTransform: function (markPointModel, ecModel, api) {
  63888. ecModel.eachSeries(function (seriesModel) {
  63889. var mpModel = seriesModel.markPointModel;
  63890. if (mpModel) {
  63891. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63892. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63893. }
  63894. }, this);
  63895. },
  63896. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  63897. var coordSys = seriesModel.coordinateSystem;
  63898. var seriesId = seriesModel.id;
  63899. var seriesData = seriesModel.getData();
  63900. var symbolDrawMap = this.markerGroupMap;
  63901. var symbolDraw = symbolDrawMap.get(seriesId)
  63902. || symbolDrawMap.set(seriesId, new SymbolDraw());
  63903. var mpData = createList$1(coordSys, seriesModel, mpModel);
  63904. // FIXME
  63905. mpModel.setData(mpData);
  63906. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63907. mpData.each(function (idx) {
  63908. var itemModel = mpData.getItemModel(idx);
  63909. var symbolSize = itemModel.getShallow('symbolSize');
  63910. if (typeof symbolSize === 'function') {
  63911. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  63912. symbolSize = symbolSize(
  63913. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  63914. );
  63915. }
  63916. mpData.setItemVisual(idx, {
  63917. symbolSize: symbolSize,
  63918. color: itemModel.get('itemStyle.color')
  63919. || seriesData.getVisual('color'),
  63920. symbol: itemModel.getShallow('symbol')
  63921. });
  63922. });
  63923. // TODO Text are wrong
  63924. symbolDraw.updateData(mpData);
  63925. this.group.add(symbolDraw.group);
  63926. // Set host model for tooltip
  63927. // FIXME
  63928. mpData.eachItemGraphicEl(function (el) {
  63929. el.traverse(function (child) {
  63930. child.dataModel = mpModel;
  63931. });
  63932. });
  63933. symbolDraw.__keep = true;
  63934. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  63935. }
  63936. });
  63937. /**
  63938. * @inner
  63939. * @param {module:echarts/coord/*} [coordSys]
  63940. * @param {module:echarts/model/Series} seriesModel
  63941. * @param {module:echarts/model/Model} mpModel
  63942. */
  63943. function createList$1(coordSys, seriesModel, mpModel) {
  63944. var coordDimsInfos;
  63945. if (coordSys) {
  63946. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  63947. var info = seriesModel.getData().getDimensionInfo(
  63948. seriesModel.getData().mapDimension(coordDim)
  63949. ) || {};
  63950. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  63951. return defaults({name: coordDim}, info);
  63952. });
  63953. }
  63954. else {
  63955. coordDimsInfos =[{
  63956. name: 'value',
  63957. type: 'float'
  63958. }];
  63959. }
  63960. var mpData = new List(coordDimsInfos, mpModel);
  63961. var dataOpt = map(mpModel.get('data'), curry(
  63962. dataTransform, seriesModel
  63963. ));
  63964. if (coordSys) {
  63965. dataOpt = filter(
  63966. dataOpt, curry(dataFilter$1, coordSys)
  63967. );
  63968. }
  63969. mpData.initData(dataOpt, null,
  63970. coordSys ? dimValueGetter : function (item) {
  63971. return item.value;
  63972. }
  63973. );
  63974. return mpData;
  63975. }
  63976. // HINT Markpoint can't be used too much
  63977. registerPreprocessor(function (opt) {
  63978. // Make sure markPoint component is enabled
  63979. opt.markPoint = opt.markPoint || {};
  63980. });
  63981. MarkerModel.extend({
  63982. type: 'markLine',
  63983. defaultOption: {
  63984. zlevel: 0,
  63985. z: 5,
  63986. symbol: ['circle', 'arrow'],
  63987. symbolSize: [8, 16],
  63988. //symbolRotate: 0,
  63989. precision: 2,
  63990. tooltip: {
  63991. trigger: 'item'
  63992. },
  63993. label: {
  63994. show: true,
  63995. position: 'end'
  63996. },
  63997. lineStyle: {
  63998. type: 'dashed'
  63999. },
  64000. emphasis: {
  64001. label: {
  64002. show: true
  64003. },
  64004. lineStyle: {
  64005. width: 3
  64006. }
  64007. },
  64008. animationEasing: 'linear'
  64009. }
  64010. });
  64011. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  64012. var data = seriesModel.getData();
  64013. // Special type markLine like 'min', 'max', 'average'
  64014. var mlType = item.type;
  64015. if (!isArray(item)
  64016. && (
  64017. mlType === 'min' || mlType === 'max' || mlType === 'average'
  64018. // In case
  64019. // data: [{
  64020. // yAxis: 10
  64021. // }]
  64022. || (item.xAxis != null || item.yAxis != null)
  64023. )
  64024. ) {
  64025. var valueAxis;
  64026. var valueDataDim;
  64027. var value;
  64028. if (item.yAxis != null || item.xAxis != null) {
  64029. valueDataDim = item.yAxis != null ? 'y' : 'x';
  64030. valueAxis = coordSys.getAxis(valueDataDim);
  64031. value = retrieve(item.yAxis, item.xAxis);
  64032. }
  64033. else {
  64034. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  64035. valueDataDim = axisInfo.valueDataDim;
  64036. valueAxis = axisInfo.valueAxis;
  64037. value = numCalculate(data, valueDataDim, mlType);
  64038. }
  64039. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  64040. var baseIndex = 1 - valueIndex;
  64041. var mlFrom = clone(item);
  64042. var mlTo = {};
  64043. mlFrom.type = null;
  64044. mlFrom.coord = [];
  64045. mlTo.coord = [];
  64046. mlFrom.coord[baseIndex] = -Infinity;
  64047. mlTo.coord[baseIndex] = Infinity;
  64048. var precision = mlModel.get('precision');
  64049. if (precision >= 0 && typeof value === 'number') {
  64050. value = +value.toFixed(Math.min(precision, 20));
  64051. }
  64052. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  64053. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  64054. type: mlType,
  64055. valueIndex: item.valueIndex,
  64056. // Force to use the value of calculated value.
  64057. value: value
  64058. }];
  64059. }
  64060. item = [
  64061. dataTransform(seriesModel, item[0]),
  64062. dataTransform(seriesModel, item[1]),
  64063. extend({}, item[2])
  64064. ];
  64065. // Avoid line data type is extended by from(to) data type
  64066. item[2].type = item[2].type || '';
  64067. // Merge from option and to option into line option
  64068. merge(item[2], item[0]);
  64069. merge(item[2], item[1]);
  64070. return item;
  64071. };
  64072. function isInifinity(val) {
  64073. return !isNaN(val) && !isFinite(val);
  64074. }
  64075. // If a markLine has one dim
  64076. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  64077. var otherDimIndex = 1 - dimIndex;
  64078. var dimName = coordSys.dimensions[dimIndex];
  64079. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  64080. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  64081. }
  64082. function markLineFilter(coordSys, item) {
  64083. if (coordSys.type === 'cartesian2d') {
  64084. var fromCoord = item[0].coord;
  64085. var toCoord = item[1].coord;
  64086. // In case
  64087. // {
  64088. // markLine: {
  64089. // data: [{ yAxis: 2 }]
  64090. // }
  64091. // }
  64092. if (
  64093. fromCoord && toCoord &&
  64094. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  64095. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  64096. ) {
  64097. return true;
  64098. }
  64099. }
  64100. return dataFilter$1(coordSys, item[0])
  64101. && dataFilter$1(coordSys, item[1]);
  64102. }
  64103. function updateSingleMarkerEndLayout(
  64104. data, idx, isFrom, seriesModel, api
  64105. ) {
  64106. var coordSys = seriesModel.coordinateSystem;
  64107. var itemModel = data.getItemModel(idx);
  64108. var point;
  64109. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  64110. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  64111. if (!isNaN(xPx) && !isNaN(yPx)) {
  64112. point = [xPx, yPx];
  64113. }
  64114. else {
  64115. // Chart like bar may have there own marker positioning logic
  64116. if (seriesModel.getMarkerPosition) {
  64117. // Use the getMarkerPoisition
  64118. point = seriesModel.getMarkerPosition(
  64119. data.getValues(data.dimensions, idx)
  64120. );
  64121. }
  64122. else {
  64123. var dims = coordSys.dimensions;
  64124. var x = data.get(dims[0], idx);
  64125. var y = data.get(dims[1], idx);
  64126. point = coordSys.dataToPoint([x, y]);
  64127. }
  64128. // Expand line to the edge of grid if value on one axis is Inifnity
  64129. // In case
  64130. // markLine: {
  64131. // data: [{
  64132. // yAxis: 2
  64133. // // or
  64134. // type: 'average'
  64135. // }]
  64136. // }
  64137. if (coordSys.type === 'cartesian2d') {
  64138. var xAxis = coordSys.getAxis('x');
  64139. var yAxis = coordSys.getAxis('y');
  64140. var dims = coordSys.dimensions;
  64141. if (isInifinity(data.get(dims[0], idx))) {
  64142. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  64143. }
  64144. else if (isInifinity(data.get(dims[1], idx))) {
  64145. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  64146. }
  64147. }
  64148. // Use x, y if has any
  64149. if (!isNaN(xPx)) {
  64150. point[0] = xPx;
  64151. }
  64152. if (!isNaN(yPx)) {
  64153. point[1] = yPx;
  64154. }
  64155. }
  64156. data.setItemLayout(idx, point);
  64157. }
  64158. MarkerView.extend({
  64159. type: 'markLine',
  64160. // updateLayout: function (markLineModel, ecModel, api) {
  64161. // ecModel.eachSeries(function (seriesModel) {
  64162. // var mlModel = seriesModel.markLineModel;
  64163. // if (mlModel) {
  64164. // var mlData = mlModel.getData();
  64165. // var fromData = mlModel.__from;
  64166. // var toData = mlModel.__to;
  64167. // // Update visual and layout of from symbol and to symbol
  64168. // fromData.each(function (idx) {
  64169. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  64170. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  64171. // });
  64172. // // Update layout of line
  64173. // mlData.each(function (idx) {
  64174. // mlData.setItemLayout(idx, [
  64175. // fromData.getItemLayout(idx),
  64176. // toData.getItemLayout(idx)
  64177. // ]);
  64178. // });
  64179. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  64180. // }
  64181. // }, this);
  64182. // },
  64183. updateTransform: function (markLineModel, ecModel, api) {
  64184. ecModel.eachSeries(function (seriesModel) {
  64185. var mlModel = seriesModel.markLineModel;
  64186. if (mlModel) {
  64187. var mlData = mlModel.getData();
  64188. var fromData = mlModel.__from;
  64189. var toData = mlModel.__to;
  64190. // Update visual and layout of from symbol and to symbol
  64191. fromData.each(function (idx) {
  64192. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  64193. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  64194. });
  64195. // Update layout of line
  64196. mlData.each(function (idx) {
  64197. mlData.setItemLayout(idx, [
  64198. fromData.getItemLayout(idx),
  64199. toData.getItemLayout(idx)
  64200. ]);
  64201. });
  64202. this.markerGroupMap.get(seriesModel.id).updateLayout();
  64203. }
  64204. }, this);
  64205. },
  64206. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  64207. var coordSys = seriesModel.coordinateSystem;
  64208. var seriesId = seriesModel.id;
  64209. var seriesData = seriesModel.getData();
  64210. var lineDrawMap = this.markerGroupMap;
  64211. var lineDraw = lineDrawMap.get(seriesId)
  64212. || lineDrawMap.set(seriesId, new LineDraw());
  64213. this.group.add(lineDraw.group);
  64214. var mlData = createList$2(coordSys, seriesModel, mlModel);
  64215. var fromData = mlData.from;
  64216. var toData = mlData.to;
  64217. var lineData = mlData.line;
  64218. mlModel.__from = fromData;
  64219. mlModel.__to = toData;
  64220. // Line data for tooltip and formatter
  64221. mlModel.setData(lineData);
  64222. var symbolType = mlModel.get('symbol');
  64223. var symbolSize = mlModel.get('symbolSize');
  64224. if (!isArray(symbolType)) {
  64225. symbolType = [symbolType, symbolType];
  64226. }
  64227. if (typeof symbolSize === 'number') {
  64228. symbolSize = [symbolSize, symbolSize];
  64229. }
  64230. // Update visual and layout of from symbol and to symbol
  64231. mlData.from.each(function (idx) {
  64232. updateDataVisualAndLayout(fromData, idx, true);
  64233. updateDataVisualAndLayout(toData, idx, false);
  64234. });
  64235. // Update visual and layout of line
  64236. lineData.each(function (idx) {
  64237. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  64238. lineData.setItemVisual(idx, {
  64239. color: lineColor || fromData.getItemVisual(idx, 'color')
  64240. });
  64241. lineData.setItemLayout(idx, [
  64242. fromData.getItemLayout(idx),
  64243. toData.getItemLayout(idx)
  64244. ]);
  64245. lineData.setItemVisual(idx, {
  64246. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  64247. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  64248. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  64249. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  64250. });
  64251. });
  64252. lineDraw.updateData(lineData);
  64253. // Set host model for tooltip
  64254. // FIXME
  64255. mlData.line.eachItemGraphicEl(function (el, idx) {
  64256. el.traverse(function (child) {
  64257. child.dataModel = mlModel;
  64258. });
  64259. });
  64260. function updateDataVisualAndLayout(data, idx, isFrom) {
  64261. var itemModel = data.getItemModel(idx);
  64262. updateSingleMarkerEndLayout(
  64263. data, idx, isFrom, seriesModel, api
  64264. );
  64265. data.setItemVisual(idx, {
  64266. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  64267. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  64268. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  64269. });
  64270. }
  64271. lineDraw.__keep = true;
  64272. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  64273. }
  64274. });
  64275. /**
  64276. * @inner
  64277. * @param {module:echarts/coord/*} coordSys
  64278. * @param {module:echarts/model/Series} seriesModel
  64279. * @param {module:echarts/model/Model} mpModel
  64280. */
  64281. function createList$2(coordSys, seriesModel, mlModel) {
  64282. var coordDimsInfos;
  64283. if (coordSys) {
  64284. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  64285. var info = seriesModel.getData().getDimensionInfo(
  64286. seriesModel.getData().mapDimension(coordDim)
  64287. ) || {};
  64288. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  64289. return defaults({name: coordDim}, info);
  64290. });
  64291. }
  64292. else {
  64293. coordDimsInfos =[{
  64294. name: 'value',
  64295. type: 'float'
  64296. }];
  64297. }
  64298. var fromData = new List(coordDimsInfos, mlModel);
  64299. var toData = new List(coordDimsInfos, mlModel);
  64300. // No dimensions
  64301. var lineData = new List([], mlModel);
  64302. var optData = map(mlModel.get('data'), curry(
  64303. markLineTransform, seriesModel, coordSys, mlModel
  64304. ));
  64305. if (coordSys) {
  64306. optData = filter(
  64307. optData, curry(markLineFilter, coordSys)
  64308. );
  64309. }
  64310. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  64311. return item.value;
  64312. };
  64313. fromData.initData(
  64314. map(optData, function (item) { return item[0]; }),
  64315. null, dimValueGetter$$1
  64316. );
  64317. toData.initData(
  64318. map(optData, function (item) { return item[1]; }),
  64319. null, dimValueGetter$$1
  64320. );
  64321. lineData.initData(
  64322. map(optData, function (item) { return item[2]; })
  64323. );
  64324. lineData.hasItemOption = true;
  64325. return {
  64326. from: fromData,
  64327. to: toData,
  64328. line: lineData
  64329. };
  64330. }
  64331. registerPreprocessor(function (opt) {
  64332. // Make sure markLine component is enabled
  64333. opt.markLine = opt.markLine || {};
  64334. });
  64335. MarkerModel.extend({
  64336. type: 'markArea',
  64337. defaultOption: {
  64338. zlevel: 0,
  64339. // PENDING
  64340. z: 1,
  64341. tooltip: {
  64342. trigger: 'item'
  64343. },
  64344. // markArea should fixed on the coordinate system
  64345. animation: false,
  64346. label: {
  64347. show: true,
  64348. position: 'top'
  64349. },
  64350. itemStyle: {
  64351. // color and borderColor default to use color from series
  64352. // color: 'auto'
  64353. // borderColor: 'auto'
  64354. borderWidth: 0
  64355. },
  64356. emphasis: {
  64357. label: {
  64358. show: true,
  64359. position: 'top'
  64360. }
  64361. }
  64362. }
  64363. });
  64364. // TODO Better on polar
  64365. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  64366. var lt = dataTransform(seriesModel, item[0]);
  64367. var rb = dataTransform(seriesModel, item[1]);
  64368. var retrieve$$1 = retrieve;
  64369. // FIXME make sure lt is less than rb
  64370. var ltCoord = lt.coord;
  64371. var rbCoord = rb.coord;
  64372. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  64373. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  64374. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  64375. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  64376. // Merge option into one
  64377. var result = mergeAll([{}, lt, rb]);
  64378. result.coord = [
  64379. lt.coord, rb.coord
  64380. ];
  64381. result.x0 = lt.x;
  64382. result.y0 = lt.y;
  64383. result.x1 = rb.x;
  64384. result.y1 = rb.y;
  64385. return result;
  64386. };
  64387. function isInifinity$1(val) {
  64388. return !isNaN(val) && !isFinite(val);
  64389. }
  64390. // If a markArea has one dim
  64391. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  64392. var otherDimIndex = 1 - dimIndex;
  64393. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  64394. }
  64395. function markAreaFilter(coordSys, item) {
  64396. var fromCoord = item.coord[0];
  64397. var toCoord = item.coord[1];
  64398. if (coordSys.type === 'cartesian2d') {
  64399. // In case
  64400. // {
  64401. // markArea: {
  64402. // data: [{ yAxis: 2 }]
  64403. // }
  64404. // }
  64405. if (
  64406. fromCoord && toCoord &&
  64407. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  64408. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  64409. ) {
  64410. return true;
  64411. }
  64412. }
  64413. return dataFilter$1(coordSys, {
  64414. coord: fromCoord,
  64415. x: item.x0,
  64416. y: item.y0
  64417. })
  64418. || dataFilter$1(coordSys, {
  64419. coord: toCoord,
  64420. x: item.x1,
  64421. y: item.y1
  64422. });
  64423. }
  64424. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  64425. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  64426. var coordSys = seriesModel.coordinateSystem;
  64427. var itemModel = data.getItemModel(idx);
  64428. var point;
  64429. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  64430. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  64431. if (!isNaN(xPx) && !isNaN(yPx)) {
  64432. point = [xPx, yPx];
  64433. }
  64434. else {
  64435. // Chart like bar may have there own marker positioning logic
  64436. if (seriesModel.getMarkerPosition) {
  64437. // Use the getMarkerPoisition
  64438. point = seriesModel.getMarkerPosition(
  64439. data.getValues(dims, idx)
  64440. );
  64441. }
  64442. else {
  64443. var x = data.get(dims[0], idx);
  64444. var y = data.get(dims[1], idx);
  64445. var pt = [x, y];
  64446. coordSys.clampData && coordSys.clampData(pt, pt);
  64447. point = coordSys.dataToPoint(pt, true);
  64448. }
  64449. if (coordSys.type === 'cartesian2d') {
  64450. var xAxis = coordSys.getAxis('x');
  64451. var yAxis = coordSys.getAxis('y');
  64452. var x = data.get(dims[0], idx);
  64453. var y = data.get(dims[1], idx);
  64454. if (isInifinity$1(x)) {
  64455. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  64456. }
  64457. else if (isInifinity$1(y)) {
  64458. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  64459. }
  64460. }
  64461. // Use x, y if has any
  64462. if (!isNaN(xPx)) {
  64463. point[0] = xPx;
  64464. }
  64465. if (!isNaN(yPx)) {
  64466. point[1] = yPx;
  64467. }
  64468. }
  64469. return point;
  64470. }
  64471. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  64472. MarkerView.extend({
  64473. type: 'markArea',
  64474. // updateLayout: function (markAreaModel, ecModel, api) {
  64475. // ecModel.eachSeries(function (seriesModel) {
  64476. // var maModel = seriesModel.markAreaModel;
  64477. // if (maModel) {
  64478. // var areaData = maModel.getData();
  64479. // areaData.each(function (idx) {
  64480. // var points = zrUtil.map(dimPermutations, function (dim) {
  64481. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64482. // });
  64483. // // Layout
  64484. // areaData.setItemLayout(idx, points);
  64485. // var el = areaData.getItemGraphicEl(idx);
  64486. // el.setShape('points', points);
  64487. // });
  64488. // }
  64489. // }, this);
  64490. // },
  64491. updateTransform: function (markAreaModel, ecModel, api) {
  64492. ecModel.eachSeries(function (seriesModel) {
  64493. var maModel = seriesModel.markAreaModel;
  64494. if (maModel) {
  64495. var areaData = maModel.getData();
  64496. areaData.each(function (idx) {
  64497. var points = map(dimPermutations, function (dim) {
  64498. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64499. });
  64500. // Layout
  64501. areaData.setItemLayout(idx, points);
  64502. var el = areaData.getItemGraphicEl(idx);
  64503. el.setShape('points', points);
  64504. });
  64505. }
  64506. }, this);
  64507. },
  64508. renderSeries: function (seriesModel, maModel, ecModel, api) {
  64509. var coordSys = seriesModel.coordinateSystem;
  64510. var seriesName = seriesModel.name;
  64511. var seriesData = seriesModel.getData();
  64512. var areaGroupMap = this.markerGroupMap;
  64513. var polygonGroup = areaGroupMap.get(seriesName)
  64514. || areaGroupMap.set(seriesName, {group: new Group()});
  64515. this.group.add(polygonGroup.group);
  64516. polygonGroup.__keep = true;
  64517. var areaData = createList$3(coordSys, seriesModel, maModel);
  64518. // Line data for tooltip and formatter
  64519. maModel.setData(areaData);
  64520. // Update visual and layout of line
  64521. areaData.each(function (idx) {
  64522. // Layout
  64523. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  64524. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64525. }));
  64526. // Visual
  64527. areaData.setItemVisual(idx, {
  64528. color: seriesData.getVisual('color')
  64529. });
  64530. });
  64531. areaData.diff(polygonGroup.__data)
  64532. .add(function (idx) {
  64533. var polygon = new Polygon({
  64534. shape: {
  64535. points: areaData.getItemLayout(idx)
  64536. }
  64537. });
  64538. areaData.setItemGraphicEl(idx, polygon);
  64539. polygonGroup.group.add(polygon);
  64540. })
  64541. .update(function (newIdx, oldIdx) {
  64542. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  64543. updateProps(polygon, {
  64544. shape: {
  64545. points: areaData.getItemLayout(newIdx)
  64546. }
  64547. }, maModel, newIdx);
  64548. polygonGroup.group.add(polygon);
  64549. areaData.setItemGraphicEl(newIdx, polygon);
  64550. })
  64551. .remove(function (idx) {
  64552. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  64553. polygonGroup.group.remove(polygon);
  64554. })
  64555. .execute();
  64556. areaData.eachItemGraphicEl(function (polygon, idx) {
  64557. var itemModel = areaData.getItemModel(idx);
  64558. var labelModel = itemModel.getModel('label');
  64559. var labelHoverModel = itemModel.getModel('emphasis.label');
  64560. var color = areaData.getItemVisual(idx, 'color');
  64561. polygon.useStyle(
  64562. defaults(
  64563. itemModel.getModel('itemStyle').getItemStyle(),
  64564. {
  64565. fill: modifyAlpha(color, 0.4),
  64566. stroke: color
  64567. }
  64568. )
  64569. );
  64570. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  64571. setLabelStyle(
  64572. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  64573. {
  64574. labelFetcher: maModel,
  64575. labelDataIndex: idx,
  64576. defaultText: areaData.getName(idx) || '',
  64577. isRectText: true,
  64578. autoColor: color
  64579. }
  64580. );
  64581. setHoverStyle(polygon, {});
  64582. polygon.dataModel = maModel;
  64583. });
  64584. polygonGroup.__data = areaData;
  64585. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  64586. }
  64587. });
  64588. /**
  64589. * @inner
  64590. * @param {module:echarts/coord/*} coordSys
  64591. * @param {module:echarts/model/Series} seriesModel
  64592. * @param {module:echarts/model/Model} mpModel
  64593. */
  64594. function createList$3(coordSys, seriesModel, maModel) {
  64595. var coordDimsInfos;
  64596. var areaData;
  64597. var dims = ['x0', 'y0', 'x1', 'y1'];
  64598. if (coordSys) {
  64599. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  64600. var data = seriesModel.getData();
  64601. var info = data.getDimensionInfo(
  64602. data.mapDimension(coordDim)
  64603. ) || {};
  64604. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  64605. return defaults({name: coordDim}, info);
  64606. });
  64607. areaData = new List(map(dims, function (dim, idx) {
  64608. return {
  64609. name: dim,
  64610. type: coordDimsInfos[idx % 2].type
  64611. };
  64612. }), maModel);
  64613. }
  64614. else {
  64615. coordDimsInfos =[{
  64616. name: 'value',
  64617. type: 'float'
  64618. }];
  64619. areaData = new List(coordDimsInfos, maModel);
  64620. }
  64621. var optData = map(maModel.get('data'), curry(
  64622. markAreaTransform, seriesModel, coordSys, maModel
  64623. ));
  64624. if (coordSys) {
  64625. optData = filter(
  64626. optData, curry(markAreaFilter, coordSys)
  64627. );
  64628. }
  64629. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  64630. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  64631. } : function (item) {
  64632. return item.value;
  64633. };
  64634. areaData.initData(optData, null, dimValueGetter$$1);
  64635. areaData.hasItemOption = true;
  64636. return areaData;
  64637. }
  64638. registerPreprocessor(function (opt) {
  64639. // Make sure markArea component is enabled
  64640. opt.markArea = opt.markArea || {};
  64641. });
  64642. var preprocessor$3 = function (option) {
  64643. var timelineOpt = option && option.timeline;
  64644. if (!isArray(timelineOpt)) {
  64645. timelineOpt = timelineOpt ? [timelineOpt] : [];
  64646. }
  64647. each$1(timelineOpt, function (opt) {
  64648. if (!opt) {
  64649. return;
  64650. }
  64651. compatibleEC2(opt);
  64652. });
  64653. };
  64654. function compatibleEC2(opt) {
  64655. var type = opt.type;
  64656. var ec2Types = {'number': 'value', 'time': 'time'};
  64657. // Compatible with ec2
  64658. if (ec2Types[type]) {
  64659. opt.axisType = ec2Types[type];
  64660. delete opt.type;
  64661. }
  64662. transferItem(opt);
  64663. if (has$2(opt, 'controlPosition')) {
  64664. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  64665. if (!has$2(controlStyle, 'position')) {
  64666. controlStyle.position = opt.controlPosition;
  64667. }
  64668. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  64669. controlStyle.show = false;
  64670. delete controlStyle.position;
  64671. }
  64672. delete opt.controlPosition;
  64673. }
  64674. each$1(opt.data || [], function (dataItem) {
  64675. if (isObject$1(dataItem) && !isArray(dataItem)) {
  64676. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  64677. // In ec2, using name as value.
  64678. dataItem.value = dataItem.name;
  64679. }
  64680. transferItem(dataItem);
  64681. }
  64682. });
  64683. }
  64684. function transferItem(opt) {
  64685. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  64686. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  64687. // Transfer label out
  64688. var label = opt.label || (opt.label || {});
  64689. var labelNormal = label.normal || (label.normal = {});
  64690. var excludeLabelAttr = {normal: 1, emphasis: 1};
  64691. each$1(label, function (value, name) {
  64692. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  64693. labelNormal[name] = value;
  64694. }
  64695. });
  64696. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  64697. label.emphasis = itemStyleEmphasis.label;
  64698. delete itemStyleEmphasis.label;
  64699. }
  64700. }
  64701. function has$2(obj, attr) {
  64702. return obj.hasOwnProperty(attr);
  64703. }
  64704. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  64705. // Only slider now.
  64706. return 'slider';
  64707. });
  64708. registerAction(
  64709. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  64710. function (payload, ecModel) {
  64711. var timelineModel = ecModel.getComponent('timeline');
  64712. if (timelineModel && payload.currentIndex != null) {
  64713. timelineModel.setCurrentIndex(payload.currentIndex);
  64714. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  64715. timelineModel.setPlayState(false);
  64716. }
  64717. }
  64718. // Set normalized currentIndex to payload.
  64719. ecModel.resetOption('timeline');
  64720. return defaults({
  64721. currentIndex: timelineModel.option.currentIndex
  64722. }, payload);
  64723. }
  64724. );
  64725. registerAction(
  64726. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  64727. function (payload, ecModel) {
  64728. var timelineModel = ecModel.getComponent('timeline');
  64729. if (timelineModel && payload.playState != null) {
  64730. timelineModel.setPlayState(payload.playState);
  64731. }
  64732. }
  64733. );
  64734. var TimelineModel = ComponentModel.extend({
  64735. type: 'timeline',
  64736. layoutMode: 'box',
  64737. /**
  64738. * @protected
  64739. */
  64740. defaultOption: {
  64741. zlevel: 0, // 一级层叠
  64742. z: 4, // 二级层叠
  64743. show: true,
  64744. axisType: 'time', // 模式是时间类型,支持 value, category
  64745. realtime: true,
  64746. left: '20%',
  64747. top: null,
  64748. right: '20%',
  64749. bottom: 0,
  64750. width: null,
  64751. height: 40,
  64752. padding: 5,
  64753. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  64754. autoPlay: false,
  64755. rewind: false, // 反向播放
  64756. loop: true,
  64757. playInterval: 2000, // 播放时间间隔,单位ms
  64758. currentIndex: 0,
  64759. itemStyle: {},
  64760. label: {
  64761. color: '#000'
  64762. },
  64763. data: []
  64764. },
  64765. /**
  64766. * @override
  64767. */
  64768. init: function (option, parentModel, ecModel) {
  64769. /**
  64770. * @private
  64771. * @type {module:echarts/data/List}
  64772. */
  64773. this._data;
  64774. /**
  64775. * @private
  64776. * @type {Array.<string>}
  64777. */
  64778. this._names;
  64779. this.mergeDefaultAndTheme(option, ecModel);
  64780. this._initData();
  64781. },
  64782. /**
  64783. * @override
  64784. */
  64785. mergeOption: function (option) {
  64786. TimelineModel.superApply(this, 'mergeOption', arguments);
  64787. this._initData();
  64788. },
  64789. /**
  64790. * @param {number} [currentIndex]
  64791. */
  64792. setCurrentIndex: function (currentIndex) {
  64793. if (currentIndex == null) {
  64794. currentIndex = this.option.currentIndex;
  64795. }
  64796. var count = this._data.count();
  64797. if (this.option.loop) {
  64798. currentIndex = (currentIndex % count + count) % count;
  64799. }
  64800. else {
  64801. currentIndex >= count && (currentIndex = count - 1);
  64802. currentIndex < 0 && (currentIndex = 0);
  64803. }
  64804. this.option.currentIndex = currentIndex;
  64805. },
  64806. /**
  64807. * @return {number} currentIndex
  64808. */
  64809. getCurrentIndex: function () {
  64810. return this.option.currentIndex;
  64811. },
  64812. /**
  64813. * @return {boolean}
  64814. */
  64815. isIndexMax: function () {
  64816. return this.getCurrentIndex() >= this._data.count() - 1;
  64817. },
  64818. /**
  64819. * @param {boolean} state true: play, false: stop
  64820. */
  64821. setPlayState: function (state) {
  64822. this.option.autoPlay = !!state;
  64823. },
  64824. /**
  64825. * @return {boolean} true: play, false: stop
  64826. */
  64827. getPlayState: function () {
  64828. return !!this.option.autoPlay;
  64829. },
  64830. /**
  64831. * @private
  64832. */
  64833. _initData: function () {
  64834. var thisOption = this.option;
  64835. var dataArr = thisOption.data || [];
  64836. var axisType = thisOption.axisType;
  64837. var names = this._names = [];
  64838. if (axisType === 'category') {
  64839. var idxArr = [];
  64840. each$1(dataArr, function (item, index) {
  64841. var value = getDataItemValue(item);
  64842. var newItem;
  64843. if (isObject$1(item)) {
  64844. newItem = clone(item);
  64845. newItem.value = index;
  64846. }
  64847. else {
  64848. newItem = index;
  64849. }
  64850. idxArr.push(newItem);
  64851. if (!isString(value) && (value == null || isNaN(value))) {
  64852. value = '';
  64853. }
  64854. names.push(value + '');
  64855. });
  64856. dataArr = idxArr;
  64857. }
  64858. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  64859. var data = this._data = new List([{name: 'value', type: dimType}], this);
  64860. data.initData(dataArr, names);
  64861. },
  64862. getData: function () {
  64863. return this._data;
  64864. },
  64865. /**
  64866. * @public
  64867. * @return {Array.<string>} categoreis
  64868. */
  64869. getCategories: function () {
  64870. if (this.get('axisType') === 'category') {
  64871. return this._names.slice();
  64872. }
  64873. }
  64874. });
  64875. var SliderTimelineModel = TimelineModel.extend({
  64876. type: 'timeline.slider',
  64877. /**
  64878. * @protected
  64879. */
  64880. defaultOption: {
  64881. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  64882. borderColor: '#ccc', // 时间轴边框颜色
  64883. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  64884. orient: 'horizontal', // 'vertical'
  64885. inverse: false,
  64886. tooltip: { // boolean or Object
  64887. trigger: 'item' // data item may also have tootip attr.
  64888. },
  64889. symbol: 'emptyCircle',
  64890. symbolSize: 10,
  64891. lineStyle: {
  64892. show: true,
  64893. width: 2,
  64894. color: '#304654'
  64895. },
  64896. label: { // 文本标签
  64897. position: 'auto', // auto left right top bottom
  64898. // When using number, label position is not
  64899. // restricted by viewRect.
  64900. // positive: right/bottom, negative: left/top
  64901. show: true,
  64902. interval: 'auto',
  64903. rotate: 0,
  64904. // formatter: null,
  64905. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64906. color: '#304654'
  64907. },
  64908. itemStyle: {
  64909. color: '#304654',
  64910. borderWidth: 1
  64911. },
  64912. checkpointStyle: {
  64913. symbol: 'circle',
  64914. symbolSize: 13,
  64915. color: '#c23531',
  64916. borderWidth: 5,
  64917. borderColor: 'rgba(194,53,49, 0.5)',
  64918. animation: true,
  64919. animationDuration: 300,
  64920. animationEasing: 'quinticInOut'
  64921. },
  64922. controlStyle: {
  64923. show: true,
  64924. showPlayBtn: true,
  64925. showPrevBtn: true,
  64926. showNextBtn: true,
  64927. itemSize: 22,
  64928. itemGap: 12,
  64929. position: 'left', // 'left' 'right' 'top' 'bottom'
  64930. 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
  64931. 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
  64932. 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
  64933. 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
  64934. color: '#304654',
  64935. borderColor: '#304654',
  64936. borderWidth: 1
  64937. },
  64938. emphasis: {
  64939. label: {
  64940. show: true,
  64941. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64942. color: '#c23531'
  64943. },
  64944. itemStyle: {
  64945. color: '#c23531'
  64946. },
  64947. controlStyle: {
  64948. color: '#c23531',
  64949. borderColor: '#c23531',
  64950. borderWidth: 2
  64951. }
  64952. },
  64953. data: []
  64954. }
  64955. });
  64956. mixin(SliderTimelineModel, dataFormatMixin);
  64957. var TimelineView = Component.extend({
  64958. type: 'timeline'
  64959. });
  64960. /**
  64961. * Extend axis 2d
  64962. * @constructor module:echarts/coord/cartesian/Axis2D
  64963. * @extends {module:echarts/coord/cartesian/Axis}
  64964. * @param {string} dim
  64965. * @param {*} scale
  64966. * @param {Array.<number>} coordExtent
  64967. * @param {string} axisType
  64968. * @param {string} position
  64969. */
  64970. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  64971. Axis.call(this, dim, scale, coordExtent);
  64972. /**
  64973. * Axis type
  64974. * - 'category'
  64975. * - 'value'
  64976. * - 'time'
  64977. * - 'log'
  64978. * @type {string}
  64979. */
  64980. this.type = axisType || 'value';
  64981. /**
  64982. * @private
  64983. * @type {number}
  64984. */
  64985. this._autoLabelInterval;
  64986. /**
  64987. * Axis model
  64988. * @param {module:echarts/component/TimelineModel}
  64989. */
  64990. this.model = null;
  64991. };
  64992. TimelineAxis.prototype = {
  64993. constructor: TimelineAxis,
  64994. /**
  64995. * @public
  64996. * @return {number}
  64997. */
  64998. getLabelInterval: function () {
  64999. var timelineModel = this.model;
  65000. var labelModel = timelineModel.getModel('label');
  65001. var labelInterval = labelModel.get('interval');
  65002. if (labelInterval != null && labelInterval != 'auto') {
  65003. return labelInterval;
  65004. }
  65005. var labelInterval = this._autoLabelInterval;
  65006. if (!labelInterval) {
  65007. labelInterval = this._autoLabelInterval = getAxisLabelInterval(
  65008. map(this.scale.getTicks(), this.dataToCoord, this),
  65009. getFormattedLabels(this, labelModel.get('formatter')),
  65010. labelModel.getFont(),
  65011. timelineModel.get('orient') === 'horizontal' ? 0 : 90,
  65012. labelModel.get('rotate')
  65013. );
  65014. }
  65015. return labelInterval;
  65016. },
  65017. /**
  65018. * If label is ignored.
  65019. * Automatically used when axis is category and label can not be all shown
  65020. * @public
  65021. * @param {number} idx
  65022. * @return {boolean}
  65023. */
  65024. isLabelIgnored: function (idx) {
  65025. if (this.type === 'category') {
  65026. var labelInterval = this.getLabelInterval();
  65027. return ((typeof labelInterval === 'function')
  65028. && !labelInterval(idx, this.scale.getLabel(idx)))
  65029. || idx % (labelInterval + 1);
  65030. }
  65031. }
  65032. };
  65033. inherits(TimelineAxis, Axis);
  65034. var bind$6 = bind;
  65035. var each$28 = each$1;
  65036. var PI$4 = Math.PI;
  65037. TimelineView.extend({
  65038. type: 'timeline.slider',
  65039. init: function (ecModel, api) {
  65040. this.api = api;
  65041. /**
  65042. * @private
  65043. * @type {module:echarts/component/timeline/TimelineAxis}
  65044. */
  65045. this._axis;
  65046. /**
  65047. * @private
  65048. * @type {module:zrender/core/BoundingRect}
  65049. */
  65050. this._viewRect;
  65051. /**
  65052. * @type {number}
  65053. */
  65054. this._timer;
  65055. /**
  65056. * @type {module:zrender/Element}
  65057. */
  65058. this._currentPointer;
  65059. /**
  65060. * @type {module:zrender/container/Group}
  65061. */
  65062. this._mainGroup;
  65063. /**
  65064. * @type {module:zrender/container/Group}
  65065. */
  65066. this._labelGroup;
  65067. },
  65068. /**
  65069. * @override
  65070. */
  65071. render: function (timelineModel, ecModel, api, payload) {
  65072. this.model = timelineModel;
  65073. this.api = api;
  65074. this.ecModel = ecModel;
  65075. this.group.removeAll();
  65076. if (timelineModel.get('show', true)) {
  65077. var layoutInfo = this._layout(timelineModel, api);
  65078. var mainGroup = this._createGroup('mainGroup');
  65079. var labelGroup = this._createGroup('labelGroup');
  65080. /**
  65081. * @private
  65082. * @type {module:echarts/component/timeline/TimelineAxis}
  65083. */
  65084. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  65085. timelineModel.formatTooltip = function (dataIndex) {
  65086. return encodeHTML(axis.scale.getLabel(dataIndex));
  65087. };
  65088. each$28(
  65089. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  65090. function (name) {
  65091. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  65092. },
  65093. this
  65094. );
  65095. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  65096. this._position(layoutInfo, timelineModel);
  65097. }
  65098. this._doPlayStop();
  65099. },
  65100. /**
  65101. * @override
  65102. */
  65103. remove: function () {
  65104. this._clearTimer();
  65105. this.group.removeAll();
  65106. },
  65107. /**
  65108. * @override
  65109. */
  65110. dispose: function () {
  65111. this._clearTimer();
  65112. },
  65113. _layout: function (timelineModel, api) {
  65114. var labelPosOpt = timelineModel.get('label.position');
  65115. var orient = timelineModel.get('orient');
  65116. var viewRect = getViewRect$4(timelineModel, api);
  65117. // Auto label offset.
  65118. if (labelPosOpt == null || labelPosOpt === 'auto') {
  65119. labelPosOpt = orient === 'horizontal'
  65120. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  65121. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  65122. }
  65123. else if (isNaN(labelPosOpt)) {
  65124. labelPosOpt = ({
  65125. horizontal: {top: '-', bottom: '+'},
  65126. vertical: {left: '-', right: '+'}
  65127. })[orient][labelPosOpt];
  65128. }
  65129. var labelAlignMap = {
  65130. horizontal: 'center',
  65131. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  65132. };
  65133. var labelBaselineMap = {
  65134. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  65135. vertical: 'middle'
  65136. };
  65137. var rotationMap = {
  65138. horizontal: 0,
  65139. vertical: PI$4 / 2
  65140. };
  65141. // Position
  65142. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  65143. var controlModel = timelineModel.getModel('controlStyle');
  65144. var showControl = controlModel.get('show', true);
  65145. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  65146. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  65147. var sizePlusGap = controlSize + controlGap;
  65148. // Special label rotate.
  65149. var labelRotation = timelineModel.get('label.rotate') || 0;
  65150. labelRotation = labelRotation * PI$4 / 180; // To radian.
  65151. var playPosition;
  65152. var prevBtnPosition;
  65153. var nextBtnPosition;
  65154. var axisExtent;
  65155. var controlPosition = controlModel.get('position', true);
  65156. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  65157. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  65158. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  65159. var xLeft = 0;
  65160. var xRight = mainLength;
  65161. // position[0] means left, position[1] means middle.
  65162. if (controlPosition === 'left' || controlPosition === 'bottom') {
  65163. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  65164. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  65165. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65166. }
  65167. else { // 'top' 'right'
  65168. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65169. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  65170. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65171. }
  65172. axisExtent = [xLeft, xRight];
  65173. if (timelineModel.get('inverse')) {
  65174. axisExtent.reverse();
  65175. }
  65176. return {
  65177. viewRect: viewRect,
  65178. mainLength: mainLength,
  65179. orient: orient,
  65180. rotation: rotationMap[orient],
  65181. labelRotation: labelRotation,
  65182. labelPosOpt: labelPosOpt,
  65183. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  65184. labelBaseline: timelineModel.get('label.verticalAlign')
  65185. || timelineModel.get('label.baseline')
  65186. || labelBaselineMap[orient],
  65187. // Based on mainGroup.
  65188. playPosition: playPosition,
  65189. prevBtnPosition: prevBtnPosition,
  65190. nextBtnPosition: nextBtnPosition,
  65191. axisExtent: axisExtent,
  65192. controlSize: controlSize,
  65193. controlGap: controlGap
  65194. };
  65195. },
  65196. _position: function (layoutInfo, timelineModel) {
  65197. // Position is be called finally, because bounding rect is needed for
  65198. // adapt content to fill viewRect (auto adapt offset).
  65199. // Timeline may be not all in the viewRect when 'offset' is specified
  65200. // as a number, because it is more appropriate that label aligns at
  65201. // 'offset' but not the other edge defined by viewRect.
  65202. var mainGroup = this._mainGroup;
  65203. var labelGroup = this._labelGroup;
  65204. var viewRect = layoutInfo.viewRect;
  65205. if (layoutInfo.orient === 'vertical') {
  65206. // transform to horizontal, inverse rotate by left-top point.
  65207. var m = create$1();
  65208. var rotateOriginX = viewRect.x;
  65209. var rotateOriginY = viewRect.y + viewRect.height;
  65210. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  65211. rotate(m, m, -PI$4 / 2);
  65212. translate(m, m, [rotateOriginX, rotateOriginY]);
  65213. viewRect = viewRect.clone();
  65214. viewRect.applyTransform(m);
  65215. }
  65216. var viewBound = getBound(viewRect);
  65217. var mainBound = getBound(mainGroup.getBoundingRect());
  65218. var labelBound = getBound(labelGroup.getBoundingRect());
  65219. var mainPosition = mainGroup.position;
  65220. var labelsPosition = labelGroup.position;
  65221. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  65222. var labelPosOpt = layoutInfo.labelPosOpt;
  65223. if (isNaN(labelPosOpt)) { // '+' or '-'
  65224. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  65225. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  65226. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  65227. }
  65228. else {
  65229. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  65230. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  65231. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  65232. }
  65233. mainGroup.attr('position', mainPosition);
  65234. labelGroup.attr('position', labelsPosition);
  65235. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  65236. setOrigin(mainGroup);
  65237. setOrigin(labelGroup);
  65238. function setOrigin(targetGroup) {
  65239. var pos = targetGroup.position;
  65240. targetGroup.origin = [
  65241. viewBound[0][0] - pos[0],
  65242. viewBound[1][0] - pos[1]
  65243. ];
  65244. }
  65245. function getBound(rect) {
  65246. // [[xmin, xmax], [ymin, ymax]]
  65247. return [
  65248. [rect.x, rect.x + rect.width],
  65249. [rect.y, rect.y + rect.height]
  65250. ];
  65251. }
  65252. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  65253. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  65254. }
  65255. },
  65256. _createAxis: function (layoutInfo, timelineModel) {
  65257. var data = timelineModel.getData();
  65258. var axisType = timelineModel.get('axisType');
  65259. var scale = createScaleByModel(timelineModel, axisType);
  65260. var dataExtent = data.getDataExtent('value');
  65261. scale.setExtent(dataExtent[0], dataExtent[1]);
  65262. this._customizeScale(scale, data);
  65263. scale.niceTicks();
  65264. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  65265. axis.model = timelineModel;
  65266. return axis;
  65267. },
  65268. _customizeScale: function (scale, data) {
  65269. scale.getTicks = function () {
  65270. return data.mapArray(['value'], function (value) {
  65271. return value;
  65272. });
  65273. };
  65274. scale.getTicksLabels = function () {
  65275. return map(this.getTicks(), scale.getLabel, scale);
  65276. };
  65277. },
  65278. _createGroup: function (name) {
  65279. var newGroup = this['_' + name] = new Group();
  65280. this.group.add(newGroup);
  65281. return newGroup;
  65282. },
  65283. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  65284. var axisExtent = axis.getExtent();
  65285. if (!timelineModel.get('lineStyle.show')) {
  65286. return;
  65287. }
  65288. group.add(new Line({
  65289. shape: {
  65290. x1: axisExtent[0], y1: 0,
  65291. x2: axisExtent[1], y2: 0
  65292. },
  65293. style: extend(
  65294. {lineCap: 'round'},
  65295. timelineModel.getModel('lineStyle').getLineStyle()
  65296. ),
  65297. silent: true,
  65298. z2: 1
  65299. }));
  65300. },
  65301. /**
  65302. * @private
  65303. */
  65304. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  65305. var data = timelineModel.getData();
  65306. var ticks = axis.scale.getTicks();
  65307. each$28(ticks, function (value, dataIndex) {
  65308. var tickCoord = axis.dataToCoord(value);
  65309. var itemModel = data.getItemModel(dataIndex);
  65310. var itemStyleModel = itemModel.getModel('itemStyle');
  65311. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  65312. var symbolOpt = {
  65313. position: [tickCoord, 0],
  65314. onclick: bind$6(this._changeTimeline, this, dataIndex)
  65315. };
  65316. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  65317. setHoverStyle(el, hoverStyleModel.getItemStyle());
  65318. if (itemModel.get('tooltip')) {
  65319. el.dataIndex = dataIndex;
  65320. el.dataModel = timelineModel;
  65321. }
  65322. else {
  65323. el.dataIndex = el.dataModel = null;
  65324. }
  65325. }, this);
  65326. },
  65327. /**
  65328. * @private
  65329. */
  65330. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  65331. var labelModel = timelineModel.getModel('label');
  65332. if (!labelModel.get('show')) {
  65333. return;
  65334. }
  65335. var data = timelineModel.getData();
  65336. var ticks = axis.scale.getTicks();
  65337. var labels = getFormattedLabels(
  65338. axis, labelModel.get('formatter')
  65339. );
  65340. var labelInterval = axis.getLabelInterval();
  65341. each$28(ticks, function (tick, dataIndex) {
  65342. if (axis.isLabelIgnored(dataIndex, labelInterval)) {
  65343. return;
  65344. }
  65345. var itemModel = data.getItemModel(dataIndex);
  65346. var normalLabelModel = itemModel.getModel('label');
  65347. var hoverLabelModel = itemModel.getModel('emphasis.label');
  65348. var tickCoord = axis.dataToCoord(tick);
  65349. var textEl = new Text({
  65350. position: [tickCoord, 0],
  65351. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  65352. onclick: bind$6(this._changeTimeline, this, dataIndex),
  65353. silent: false
  65354. });
  65355. setTextStyle(textEl.style, normalLabelModel, {
  65356. text: labels[dataIndex],
  65357. textAlign: layoutInfo.labelAlign,
  65358. textVerticalAlign: layoutInfo.labelBaseline
  65359. });
  65360. group.add(textEl);
  65361. setHoverStyle(
  65362. textEl, setTextStyle({}, hoverLabelModel)
  65363. );
  65364. }, this);
  65365. },
  65366. /**
  65367. * @private
  65368. */
  65369. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  65370. var controlSize = layoutInfo.controlSize;
  65371. var rotation = layoutInfo.rotation;
  65372. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  65373. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  65374. var rect = [0, -controlSize / 2, controlSize, controlSize];
  65375. var playState = timelineModel.getPlayState();
  65376. var inverse = timelineModel.get('inverse', true);
  65377. makeBtn(
  65378. layoutInfo.nextBtnPosition,
  65379. 'controlStyle.nextIcon',
  65380. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  65381. );
  65382. makeBtn(
  65383. layoutInfo.prevBtnPosition,
  65384. 'controlStyle.prevIcon',
  65385. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  65386. );
  65387. makeBtn(
  65388. layoutInfo.playPosition,
  65389. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  65390. bind$6(this._handlePlayClick, this, !playState),
  65391. true
  65392. );
  65393. function makeBtn(position, iconPath, onclick, willRotate) {
  65394. if (!position) {
  65395. return;
  65396. }
  65397. var opt = {
  65398. position: position,
  65399. origin: [controlSize / 2, 0],
  65400. rotation: willRotate ? -rotation : 0,
  65401. rectHover: true,
  65402. style: itemStyle,
  65403. onclick: onclick
  65404. };
  65405. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  65406. group.add(btn);
  65407. setHoverStyle(btn, hoverStyle);
  65408. }
  65409. },
  65410. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  65411. var data = timelineModel.getData();
  65412. var currentIndex = timelineModel.getCurrentIndex();
  65413. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  65414. var me = this;
  65415. var callback = {
  65416. onCreate: function (pointer) {
  65417. pointer.draggable = true;
  65418. pointer.drift = bind$6(me._handlePointerDrag, me);
  65419. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  65420. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  65421. },
  65422. onUpdate: function (pointer) {
  65423. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  65424. }
  65425. };
  65426. // Reuse when exists, for animation and drag.
  65427. this._currentPointer = giveSymbol(
  65428. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  65429. );
  65430. },
  65431. _handlePlayClick: function (nextState) {
  65432. this._clearTimer();
  65433. this.api.dispatchAction({
  65434. type: 'timelinePlayChange',
  65435. playState: nextState,
  65436. from: this.uid
  65437. });
  65438. },
  65439. _handlePointerDrag: function (dx, dy, e) {
  65440. this._clearTimer();
  65441. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  65442. },
  65443. _handlePointerDragend: function (e) {
  65444. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  65445. },
  65446. _pointerChangeTimeline: function (mousePos, trigger) {
  65447. var toCoord = this._toAxisCoord(mousePos)[0];
  65448. var axis = this._axis;
  65449. var axisExtent = asc(axis.getExtent().slice());
  65450. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  65451. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  65452. this._currentPointer.position[0] = toCoord;
  65453. this._currentPointer.dirty();
  65454. var targetDataIndex = this._findNearestTick(toCoord);
  65455. var timelineModel = this.model;
  65456. if (trigger || (
  65457. targetDataIndex !== timelineModel.getCurrentIndex()
  65458. && timelineModel.get('realtime')
  65459. )) {
  65460. this._changeTimeline(targetDataIndex);
  65461. }
  65462. },
  65463. _doPlayStop: function () {
  65464. this._clearTimer();
  65465. if (this.model.getPlayState()) {
  65466. this._timer = setTimeout(
  65467. bind$6(handleFrame, this),
  65468. this.model.get('playInterval')
  65469. );
  65470. }
  65471. function handleFrame() {
  65472. // Do not cache
  65473. var timelineModel = this.model;
  65474. this._changeTimeline(
  65475. timelineModel.getCurrentIndex()
  65476. + (timelineModel.get('rewind', true) ? -1 : 1)
  65477. );
  65478. }
  65479. },
  65480. _toAxisCoord: function (vertex) {
  65481. var trans = this._mainGroup.getLocalTransform();
  65482. return applyTransform$1(vertex, trans, true);
  65483. },
  65484. _findNearestTick: function (axisCoord) {
  65485. var data = this.model.getData();
  65486. var dist = Infinity;
  65487. var targetDataIndex;
  65488. var axis = this._axis;
  65489. data.each(['value'], function (value, dataIndex) {
  65490. var coord = axis.dataToCoord(value);
  65491. var d = Math.abs(coord - axisCoord);
  65492. if (d < dist) {
  65493. dist = d;
  65494. targetDataIndex = dataIndex;
  65495. }
  65496. });
  65497. return targetDataIndex;
  65498. },
  65499. _clearTimer: function () {
  65500. if (this._timer) {
  65501. clearTimeout(this._timer);
  65502. this._timer = null;
  65503. }
  65504. },
  65505. _changeTimeline: function (nextIndex) {
  65506. var currentIndex = this.model.getCurrentIndex();
  65507. if (nextIndex === '+') {
  65508. nextIndex = currentIndex + 1;
  65509. }
  65510. else if (nextIndex === '-') {
  65511. nextIndex = currentIndex - 1;
  65512. }
  65513. this.api.dispatchAction({
  65514. type: 'timelineChange',
  65515. currentIndex: nextIndex,
  65516. from: this.uid
  65517. });
  65518. }
  65519. });
  65520. function getViewRect$4(model, api) {
  65521. return getLayoutRect(
  65522. model.getBoxLayoutParams(),
  65523. {
  65524. width: api.getWidth(),
  65525. height: api.getHeight()
  65526. },
  65527. model.get('padding')
  65528. );
  65529. }
  65530. function makeIcon(timelineModel, objPath, rect, opts) {
  65531. var icon = makePath(
  65532. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  65533. clone(opts || {}),
  65534. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  65535. 'center'
  65536. );
  65537. return icon;
  65538. }
  65539. /**
  65540. * Create symbol or update symbol
  65541. * opt: basic position and event handlers
  65542. */
  65543. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  65544. var color = itemStyleModel.get('color');
  65545. if (!symbol) {
  65546. var symbolType = hostModel.get('symbol');
  65547. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  65548. symbol.setStyle('strokeNoScale', true);
  65549. group.add(symbol);
  65550. callback && callback.onCreate(symbol);
  65551. }
  65552. else {
  65553. symbol.setColor(color);
  65554. group.add(symbol); // Group may be new, also need to add.
  65555. callback && callback.onUpdate(symbol);
  65556. }
  65557. // Style
  65558. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  65559. symbol.setStyle(itemStyle);
  65560. // Transform and events.
  65561. opt = merge({
  65562. rectHover: true,
  65563. z2: 100
  65564. }, opt, true);
  65565. var symbolSize = hostModel.get('symbolSize');
  65566. symbolSize = symbolSize instanceof Array
  65567. ? symbolSize.slice()
  65568. : [+symbolSize, +symbolSize];
  65569. symbolSize[0] /= 2;
  65570. symbolSize[1] /= 2;
  65571. opt.scale = symbolSize;
  65572. var symbolOffset = hostModel.get('symbolOffset');
  65573. if (symbolOffset) {
  65574. var pos = opt.position = opt.position || [0, 0];
  65575. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  65576. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  65577. }
  65578. var symbolRotate = hostModel.get('symbolRotate');
  65579. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  65580. symbol.attr(opt);
  65581. // FIXME
  65582. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  65583. // getBoundingRect will return wrong result.
  65584. // (This is supposed to be resolved in zrender, but it is a little difficult to
  65585. // leverage performance and auto updateTransform)
  65586. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  65587. symbol.updateTransform();
  65588. return symbol;
  65589. }
  65590. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  65591. if (pointer.dragging) {
  65592. return;
  65593. }
  65594. var pointerModel = timelineModel.getModel('checkpointStyle');
  65595. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  65596. if (noAnimation || !pointerModel.get('animation', true)) {
  65597. pointer.attr({position: [toCoord, 0]});
  65598. }
  65599. else {
  65600. pointer.stopAnimation(true);
  65601. pointer.animateTo(
  65602. {position: [toCoord, 0]},
  65603. pointerModel.get('animationDuration', true),
  65604. pointerModel.get('animationEasing', true)
  65605. );
  65606. }
  65607. }
  65608. /**
  65609. * DataZoom component entry
  65610. */
  65611. registerPreprocessor(preprocessor$3);
  65612. var ToolboxModel = extendComponentModel({
  65613. type: 'toolbox',
  65614. layoutMode: {
  65615. type: 'box',
  65616. ignoreSize: true
  65617. },
  65618. mergeDefaultAndTheme: function (option) {
  65619. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  65620. each$1(this.option.feature, function (featureOpt, featureName) {
  65621. var Feature = get$1(featureName);
  65622. Feature && merge(featureOpt, Feature.defaultOption);
  65623. });
  65624. },
  65625. defaultOption: {
  65626. show: true,
  65627. z: 6,
  65628. zlevel: 0,
  65629. orient: 'horizontal',
  65630. left: 'right',
  65631. top: 'top',
  65632. // right
  65633. // bottom
  65634. backgroundColor: 'transparent',
  65635. borderColor: '#ccc',
  65636. borderRadius: 0,
  65637. borderWidth: 0,
  65638. padding: 5,
  65639. itemSize: 15,
  65640. itemGap: 8,
  65641. showTitle: true,
  65642. iconStyle: {
  65643. borderColor: '#666',
  65644. color: 'none'
  65645. },
  65646. emphasis: {
  65647. iconStyle: {
  65648. borderColor: '#3E98C5'
  65649. }
  65650. }
  65651. // textStyle: {},
  65652. // feature
  65653. }
  65654. });
  65655. extendComponentView({
  65656. type: 'toolbox',
  65657. render: function (toolboxModel, ecModel, api, payload) {
  65658. var group = this.group;
  65659. group.removeAll();
  65660. if (!toolboxModel.get('show')) {
  65661. return;
  65662. }
  65663. var itemSize = +toolboxModel.get('itemSize');
  65664. var featureOpts = toolboxModel.get('feature') || {};
  65665. var features = this._features || (this._features = {});
  65666. var featureNames = [];
  65667. each$1(featureOpts, function (opt, name) {
  65668. featureNames.push(name);
  65669. });
  65670. (new DataDiffer(this._featureNames || [], featureNames))
  65671. .add(processFeature)
  65672. .update(processFeature)
  65673. .remove(curry(processFeature, null))
  65674. .execute();
  65675. // Keep for diff.
  65676. this._featureNames = featureNames;
  65677. function processFeature(newIndex, oldIndex) {
  65678. var featureName = featureNames[newIndex];
  65679. var oldName = featureNames[oldIndex];
  65680. var featureOpt = featureOpts[featureName];
  65681. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  65682. var feature;
  65683. if (featureName && !oldName) { // Create
  65684. if (isUserFeatureName(featureName)) {
  65685. feature = {
  65686. model: featureModel,
  65687. onclick: featureModel.option.onclick,
  65688. featureName: featureName
  65689. };
  65690. }
  65691. else {
  65692. var Feature = get$1(featureName);
  65693. if (!Feature) {
  65694. return;
  65695. }
  65696. feature = new Feature(featureModel, ecModel, api);
  65697. }
  65698. features[featureName] = feature;
  65699. }
  65700. else {
  65701. feature = features[oldName];
  65702. // If feature does not exsit.
  65703. if (!feature) {
  65704. return;
  65705. }
  65706. feature.model = featureModel;
  65707. feature.ecModel = ecModel;
  65708. feature.api = api;
  65709. }
  65710. if (!featureName && oldName) {
  65711. feature.dispose && feature.dispose(ecModel, api);
  65712. return;
  65713. }
  65714. if (!featureModel.get('show') || feature.unusable) {
  65715. feature.remove && feature.remove(ecModel, api);
  65716. return;
  65717. }
  65718. createIconPaths(featureModel, feature, featureName);
  65719. featureModel.setIconStatus = function (iconName, status) {
  65720. var option = this.option;
  65721. var iconPaths = this.iconPaths;
  65722. option.iconStatus = option.iconStatus || {};
  65723. option.iconStatus[iconName] = status;
  65724. // FIXME
  65725. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  65726. };
  65727. if (feature.render) {
  65728. feature.render(featureModel, ecModel, api, payload);
  65729. }
  65730. }
  65731. function createIconPaths(featureModel, feature, featureName) {
  65732. var iconStyleModel = featureModel.getModel('iconStyle');
  65733. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  65734. // If one feature has mutiple icon. they are orginaized as
  65735. // {
  65736. // icon: {
  65737. // foo: '',
  65738. // bar: ''
  65739. // },
  65740. // title: {
  65741. // foo: '',
  65742. // bar: ''
  65743. // }
  65744. // }
  65745. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  65746. var titles = featureModel.get('title') || {};
  65747. if (typeof icons === 'string') {
  65748. var icon = icons;
  65749. var title = titles;
  65750. icons = {};
  65751. titles = {};
  65752. icons[featureName] = icon;
  65753. titles[featureName] = title;
  65754. }
  65755. var iconPaths = featureModel.iconPaths = {};
  65756. each$1(icons, function (iconStr, iconName) {
  65757. var path = createIcon(
  65758. iconStr,
  65759. {},
  65760. {
  65761. x: -itemSize / 2,
  65762. y: -itemSize / 2,
  65763. width: itemSize,
  65764. height: itemSize
  65765. }
  65766. );
  65767. path.setStyle(iconStyleModel.getItemStyle());
  65768. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  65769. setHoverStyle(path);
  65770. if (toolboxModel.get('showTitle')) {
  65771. path.__title = titles[iconName];
  65772. path.on('mouseover', function () {
  65773. // Should not reuse above hoverStyle, which might be modified.
  65774. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  65775. path.setStyle({
  65776. text: titles[iconName],
  65777. textPosition: hoverStyle.textPosition || 'bottom',
  65778. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  65779. textAlign: hoverStyle.textAlign || 'center'
  65780. });
  65781. })
  65782. .on('mouseout', function () {
  65783. path.setStyle({
  65784. textFill: null
  65785. });
  65786. });
  65787. }
  65788. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  65789. group.add(path);
  65790. path.on('click', bind(
  65791. feature.onclick, feature, ecModel, api, iconName
  65792. ));
  65793. iconPaths[iconName] = path;
  65794. });
  65795. }
  65796. layout$3(group, toolboxModel, api);
  65797. // Render background after group is layout
  65798. // FIXME
  65799. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  65800. // Adjust icon title positions to avoid them out of screen
  65801. group.eachChild(function (icon) {
  65802. var titleText = icon.__title;
  65803. var hoverStyle = icon.hoverStyle;
  65804. // May be background element
  65805. if (hoverStyle && titleText) {
  65806. var rect = getBoundingRect(
  65807. titleText, makeFont(hoverStyle)
  65808. );
  65809. var offsetX = icon.position[0] + group.position[0];
  65810. var offsetY = icon.position[1] + group.position[1] + itemSize;
  65811. var needPutOnTop = false;
  65812. if (offsetY + rect.height > api.getHeight()) {
  65813. hoverStyle.textPosition = 'top';
  65814. needPutOnTop = true;
  65815. }
  65816. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  65817. if (offsetX + rect.width / 2 > api.getWidth()) {
  65818. hoverStyle.textPosition = ['100%', topOffset];
  65819. hoverStyle.textAlign = 'right';
  65820. }
  65821. else if (offsetX - rect.width / 2 < 0) {
  65822. hoverStyle.textPosition = [0, topOffset];
  65823. hoverStyle.textAlign = 'left';
  65824. }
  65825. }
  65826. });
  65827. },
  65828. updateView: function (toolboxModel, ecModel, api, payload) {
  65829. each$1(this._features, function (feature) {
  65830. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  65831. });
  65832. },
  65833. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  65834. // zrUtil.each(this._features, function (feature) {
  65835. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  65836. // });
  65837. // },
  65838. remove: function (ecModel, api) {
  65839. each$1(this._features, function (feature) {
  65840. feature.remove && feature.remove(ecModel, api);
  65841. });
  65842. this.group.removeAll();
  65843. },
  65844. dispose: function (ecModel, api) {
  65845. each$1(this._features, function (feature) {
  65846. feature.dispose && feature.dispose(ecModel, api);
  65847. });
  65848. }
  65849. });
  65850. function isUserFeatureName(featureName) {
  65851. return featureName.indexOf('my') === 0;
  65852. }
  65853. var saveAsImageLang = lang.toolbox.saveAsImage;
  65854. function SaveAsImage(model) {
  65855. this.model = model;
  65856. }
  65857. SaveAsImage.defaultOption = {
  65858. show: true,
  65859. 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',
  65860. title: saveAsImageLang.title,
  65861. type: 'png',
  65862. // Default use option.backgroundColor
  65863. // backgroundColor: '#fff',
  65864. name: '',
  65865. excludeComponents: ['toolbox'],
  65866. pixelRatio: 1,
  65867. lang: saveAsImageLang.lang.slice()
  65868. };
  65869. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  65870. var proto$4 = SaveAsImage.prototype;
  65871. proto$4.onclick = function (ecModel, api) {
  65872. var model = this.model;
  65873. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  65874. var $a = document.createElement('a');
  65875. var type = model.get('type', true) || 'png';
  65876. $a.download = title + '.' + type;
  65877. $a.target = '_blank';
  65878. var url = api.getConnectedDataURL({
  65879. type: type,
  65880. backgroundColor: model.get('backgroundColor', true)
  65881. || ecModel.get('backgroundColor') || '#fff',
  65882. excludeComponents: model.get('excludeComponents'),
  65883. pixelRatio: model.get('pixelRatio')
  65884. });
  65885. $a.href = url;
  65886. // Chrome and Firefox
  65887. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  65888. var evt = new MouseEvent('click', {
  65889. view: window,
  65890. bubbles: true,
  65891. cancelable: false
  65892. });
  65893. $a.dispatchEvent(evt);
  65894. }
  65895. // IE
  65896. else {
  65897. if (window.navigator.msSaveOrOpenBlob) {
  65898. var bstr = atob(url.split(',')[1]);
  65899. var n = bstr.length;
  65900. var u8arr = new Uint8Array(n);
  65901. while(n--) {
  65902. u8arr[n] = bstr.charCodeAt(n);
  65903. }
  65904. var blob = new Blob([u8arr]);
  65905. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  65906. }
  65907. else {
  65908. var lang$$1 = model.get('lang');
  65909. var html = '' +
  65910. '<body style="margin:0;">' +
  65911. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  65912. '</body>';
  65913. var tab = window.open();
  65914. tab.document.write(html);
  65915. }
  65916. }
  65917. };
  65918. register$1(
  65919. 'saveAsImage', SaveAsImage
  65920. );
  65921. var magicTypeLang = lang.toolbox.magicType;
  65922. function MagicType(model) {
  65923. this.model = model;
  65924. }
  65925. MagicType.defaultOption = {
  65926. show: true,
  65927. type: [],
  65928. // Icon group
  65929. icon: {
  65930. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  65931. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  65932. 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
  65933. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  65934. },
  65935. // `line`, `bar`, `stack`, `tiled`
  65936. title: clone(magicTypeLang.title),
  65937. option: {},
  65938. seriesIndex: {}
  65939. };
  65940. var proto$5 = MagicType.prototype;
  65941. proto$5.getIcons = function () {
  65942. var model = this.model;
  65943. var availableIcons = model.get('icon');
  65944. var icons = {};
  65945. each$1(model.get('type'), function (type) {
  65946. if (availableIcons[type]) {
  65947. icons[type] = availableIcons[type];
  65948. }
  65949. });
  65950. return icons;
  65951. };
  65952. var seriesOptGenreator = {
  65953. 'line': function (seriesType, seriesId, seriesModel, model) {
  65954. if (seriesType === 'bar') {
  65955. return merge({
  65956. id: seriesId,
  65957. type: 'line',
  65958. // Preserve data related option
  65959. data: seriesModel.get('data'),
  65960. stack: seriesModel.get('stack'),
  65961. markPoint: seriesModel.get('markPoint'),
  65962. markLine: seriesModel.get('markLine')
  65963. }, model.get('option.line') || {}, true);
  65964. }
  65965. },
  65966. 'bar': function (seriesType, seriesId, seriesModel, model) {
  65967. if (seriesType === 'line') {
  65968. return merge({
  65969. id: seriesId,
  65970. type: 'bar',
  65971. // Preserve data related option
  65972. data: seriesModel.get('data'),
  65973. stack: seriesModel.get('stack'),
  65974. markPoint: seriesModel.get('markPoint'),
  65975. markLine: seriesModel.get('markLine')
  65976. }, model.get('option.bar') || {}, true);
  65977. }
  65978. },
  65979. 'stack': function (seriesType, seriesId, seriesModel, model) {
  65980. if (seriesType === 'line' || seriesType === 'bar') {
  65981. return merge({
  65982. id: seriesId,
  65983. stack: '__ec_magicType_stack__'
  65984. }, model.get('option.stack') || {}, true);
  65985. }
  65986. },
  65987. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  65988. if (seriesType === 'line' || seriesType === 'bar') {
  65989. return merge({
  65990. id: seriesId,
  65991. stack: ''
  65992. }, model.get('option.tiled') || {}, true);
  65993. }
  65994. }
  65995. };
  65996. var radioTypes = [
  65997. ['line', 'bar'],
  65998. ['stack', 'tiled']
  65999. ];
  66000. proto$5.onclick = function (ecModel, api, type) {
  66001. var model = this.model;
  66002. var seriesIndex = model.get('seriesIndex.' + type);
  66003. // Not supported magicType
  66004. if (!seriesOptGenreator[type]) {
  66005. return;
  66006. }
  66007. var newOption = {
  66008. series: []
  66009. };
  66010. var generateNewSeriesTypes = function (seriesModel) {
  66011. var seriesType = seriesModel.subType;
  66012. var seriesId = seriesModel.id;
  66013. var newSeriesOpt = seriesOptGenreator[type](
  66014. seriesType, seriesId, seriesModel, model
  66015. );
  66016. if (newSeriesOpt) {
  66017. // PENDING If merge original option?
  66018. defaults(newSeriesOpt, seriesModel.option);
  66019. newOption.series.push(newSeriesOpt);
  66020. }
  66021. // Modify boundaryGap
  66022. var coordSys = seriesModel.coordinateSystem;
  66023. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  66024. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  66025. if (categoryAxis) {
  66026. var axisDim = categoryAxis.dim;
  66027. var axisType = axisDim + 'Axis';
  66028. var axisModel = ecModel.queryComponents({
  66029. mainType: axisType,
  66030. index: seriesModel.get(name + 'Index'),
  66031. id: seriesModel.get(name + 'Id')
  66032. })[0];
  66033. var axisIndex = axisModel.componentIndex;
  66034. newOption[axisType] = newOption[axisType] || [];
  66035. for (var i = 0; i <= axisIndex; i++) {
  66036. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  66037. }
  66038. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  66039. }
  66040. }
  66041. };
  66042. each$1(radioTypes, function (radio) {
  66043. if (indexOf(radio, type) >= 0) {
  66044. each$1(radio, function (item) {
  66045. model.setIconStatus(item, 'normal');
  66046. });
  66047. }
  66048. });
  66049. model.setIconStatus(type, 'emphasis');
  66050. ecModel.eachComponent(
  66051. {
  66052. mainType: 'series',
  66053. query: seriesIndex == null ? null : {
  66054. seriesIndex: seriesIndex
  66055. }
  66056. }, generateNewSeriesTypes
  66057. );
  66058. api.dispatchAction({
  66059. type: 'changeMagicType',
  66060. currentType: type,
  66061. newOption: newOption
  66062. });
  66063. };
  66064. registerAction({
  66065. type: 'changeMagicType',
  66066. event: 'magicTypeChanged',
  66067. update: 'prepareAndUpdate'
  66068. }, function (payload, ecModel) {
  66069. ecModel.mergeOption(payload.newOption);
  66070. });
  66071. register$1('magicType', MagicType);
  66072. var dataViewLang = lang.toolbox.dataView;
  66073. var BLOCK_SPLITER = new Array(60).join('-');
  66074. var ITEM_SPLITER = '\t';
  66075. /**
  66076. * Group series into two types
  66077. * 1. on category axis, like line, bar
  66078. * 2. others, like scatter, pie
  66079. * @param {module:echarts/model/Global} ecModel
  66080. * @return {Object}
  66081. * @inner
  66082. */
  66083. function groupSeries(ecModel) {
  66084. var seriesGroupByCategoryAxis = {};
  66085. var otherSeries = [];
  66086. var meta = [];
  66087. ecModel.eachRawSeries(function (seriesModel) {
  66088. var coordSys = seriesModel.coordinateSystem;
  66089. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  66090. var baseAxis = coordSys.getBaseAxis();
  66091. if (baseAxis.type === 'category') {
  66092. var key = baseAxis.dim + '_' + baseAxis.index;
  66093. if (!seriesGroupByCategoryAxis[key]) {
  66094. seriesGroupByCategoryAxis[key] = {
  66095. categoryAxis: baseAxis,
  66096. valueAxis: coordSys.getOtherAxis(baseAxis),
  66097. series: []
  66098. };
  66099. meta.push({
  66100. axisDim: baseAxis.dim,
  66101. axisIndex: baseAxis.index
  66102. });
  66103. }
  66104. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  66105. }
  66106. else {
  66107. otherSeries.push(seriesModel);
  66108. }
  66109. }
  66110. else {
  66111. otherSeries.push(seriesModel);
  66112. }
  66113. });
  66114. return {
  66115. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  66116. other: otherSeries,
  66117. meta: meta
  66118. };
  66119. }
  66120. /**
  66121. * Assemble content of series on cateogory axis
  66122. * @param {Array.<module:echarts/model/Series>} series
  66123. * @return {string}
  66124. * @inner
  66125. */
  66126. function assembleSeriesWithCategoryAxis(series) {
  66127. var tables = [];
  66128. each$1(series, function (group, key) {
  66129. var categoryAxis = group.categoryAxis;
  66130. var valueAxis = group.valueAxis;
  66131. var valueAxisDim = valueAxis.dim;
  66132. var headers = [' '].concat(map(group.series, function (series) {
  66133. return series.name;
  66134. }));
  66135. var columns = [categoryAxis.model.getCategories()];
  66136. each$1(group.series, function (series) {
  66137. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  66138. return val;
  66139. }));
  66140. });
  66141. // Assemble table content
  66142. var lines = [headers.join(ITEM_SPLITER)];
  66143. for (var i = 0; i < columns[0].length; i++) {
  66144. var items = [];
  66145. for (var j = 0; j < columns.length; j++) {
  66146. items.push(columns[j][i]);
  66147. }
  66148. lines.push(items.join(ITEM_SPLITER));
  66149. }
  66150. tables.push(lines.join('\n'));
  66151. });
  66152. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  66153. }
  66154. /**
  66155. * Assemble content of other series
  66156. * @param {Array.<module:echarts/model/Series>} series
  66157. * @return {string}
  66158. * @inner
  66159. */
  66160. function assembleOtherSeries(series) {
  66161. return map(series, function (series) {
  66162. var data = series.getRawData();
  66163. var lines = [series.name];
  66164. var vals = [];
  66165. data.each(data.dimensions, function () {
  66166. var argLen = arguments.length;
  66167. var dataIndex = arguments[argLen - 1];
  66168. var name = data.getName(dataIndex);
  66169. for (var i = 0; i < argLen - 1; i++) {
  66170. vals[i] = arguments[i];
  66171. }
  66172. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  66173. });
  66174. return lines.join('\n');
  66175. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  66176. }
  66177. /**
  66178. * @param {module:echarts/model/Global}
  66179. * @return {Object}
  66180. * @inner
  66181. */
  66182. function getContentFromModel(ecModel) {
  66183. var result = groupSeries(ecModel);
  66184. return {
  66185. value: filter([
  66186. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  66187. assembleOtherSeries(result.other)
  66188. ], function (str) {
  66189. return str.replace(/[\n\t\s]/g, '');
  66190. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  66191. meta: result.meta
  66192. };
  66193. }
  66194. function trim$1(str) {
  66195. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  66196. }
  66197. /**
  66198. * If a block is tsv format
  66199. */
  66200. function isTSVFormat(block) {
  66201. // Simple method to find out if a block is tsv format
  66202. var firstLine = block.slice(0, block.indexOf('\n'));
  66203. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  66204. return true;
  66205. }
  66206. }
  66207. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  66208. /**
  66209. * @param {string} tsv
  66210. * @return {Object}
  66211. */
  66212. function parseTSVContents(tsv) {
  66213. var tsvLines = tsv.split(/\n+/g);
  66214. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  66215. var categories = [];
  66216. var series = map(headers, function (header) {
  66217. return {
  66218. name: header,
  66219. data: []
  66220. };
  66221. });
  66222. for (var i = 0; i < tsvLines.length; i++) {
  66223. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  66224. categories.push(items.shift());
  66225. for (var j = 0; j < items.length; j++) {
  66226. series[j] && (series[j].data[i] = items[j]);
  66227. }
  66228. }
  66229. return {
  66230. series: series,
  66231. categories: categories
  66232. };
  66233. }
  66234. /**
  66235. * @param {string} str
  66236. * @return {Array.<Object>}
  66237. * @inner
  66238. */
  66239. function parseListContents(str) {
  66240. var lines = str.split(/\n+/g);
  66241. var seriesName = trim$1(lines.shift());
  66242. var data = [];
  66243. for (var i = 0; i < lines.length; i++) {
  66244. var items = trim$1(lines[i]).split(itemSplitRegex);
  66245. var name = '';
  66246. var value;
  66247. var hasName = false;
  66248. if (isNaN(items[0])) { // First item is name
  66249. hasName = true;
  66250. name = items[0];
  66251. items = items.slice(1);
  66252. data[i] = {
  66253. name: name,
  66254. value: []
  66255. };
  66256. value = data[i].value;
  66257. }
  66258. else {
  66259. value = data[i] = [];
  66260. }
  66261. for (var j = 0; j < items.length; j++) {
  66262. value.push(+items[j]);
  66263. }
  66264. if (value.length === 1) {
  66265. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  66266. }
  66267. }
  66268. return {
  66269. name: seriesName,
  66270. data: data
  66271. };
  66272. }
  66273. /**
  66274. * @param {string} str
  66275. * @param {Array.<Object>} blockMetaList
  66276. * @return {Object}
  66277. * @inner
  66278. */
  66279. function parseContents(str, blockMetaList) {
  66280. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  66281. var newOption = {
  66282. series: []
  66283. };
  66284. each$1(blocks, function (block, idx) {
  66285. if (isTSVFormat(block)) {
  66286. var result = parseTSVContents(block);
  66287. var blockMeta = blockMetaList[idx];
  66288. var axisKey = blockMeta.axisDim + 'Axis';
  66289. if (blockMeta) {
  66290. newOption[axisKey] = newOption[axisKey] || [];
  66291. newOption[axisKey][blockMeta.axisIndex] = {
  66292. data: result.categories
  66293. };
  66294. newOption.series = newOption.series.concat(result.series);
  66295. }
  66296. }
  66297. else {
  66298. var result = parseListContents(block);
  66299. newOption.series.push(result);
  66300. }
  66301. });
  66302. return newOption;
  66303. }
  66304. /**
  66305. * @alias {module:echarts/component/toolbox/feature/DataView}
  66306. * @constructor
  66307. * @param {module:echarts/model/Model} model
  66308. */
  66309. function DataView(model) {
  66310. this._dom = null;
  66311. this.model = model;
  66312. }
  66313. DataView.defaultOption = {
  66314. show: true,
  66315. readOnly: false,
  66316. optionToContent: null,
  66317. contentToOption: null,
  66318. 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',
  66319. title: clone(dataViewLang.title),
  66320. lang: clone(dataViewLang.lang),
  66321. backgroundColor: '#fff',
  66322. textColor: '#000',
  66323. textareaColor: '#fff',
  66324. textareaBorderColor: '#333',
  66325. buttonColor: '#c23531',
  66326. buttonTextColor: '#fff'
  66327. };
  66328. DataView.prototype.onclick = function (ecModel, api) {
  66329. var container = api.getDom();
  66330. var model = this.model;
  66331. if (this._dom) {
  66332. container.removeChild(this._dom);
  66333. }
  66334. var root = document.createElement('div');
  66335. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  66336. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  66337. // Create elements
  66338. var header = document.createElement('h4');
  66339. var lang$$1 = model.get('lang') || [];
  66340. header.innerHTML = lang$$1[0] || model.get('title');
  66341. header.style.cssText = 'margin: 10px 20px;';
  66342. header.style.color = model.get('textColor');
  66343. var viewMain = document.createElement('div');
  66344. var textarea = document.createElement('textarea');
  66345. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  66346. var optionToContent = model.get('optionToContent');
  66347. var contentToOption = model.get('contentToOption');
  66348. var result = getContentFromModel(ecModel);
  66349. if (typeof optionToContent === 'function') {
  66350. var htmlOrDom = optionToContent(api.getOption());
  66351. if (typeof htmlOrDom === 'string') {
  66352. viewMain.innerHTML = htmlOrDom;
  66353. }
  66354. else if (isDom(htmlOrDom)) {
  66355. viewMain.appendChild(htmlOrDom);
  66356. }
  66357. }
  66358. else {
  66359. // Use default textarea
  66360. viewMain.appendChild(textarea);
  66361. textarea.readOnly = model.get('readOnly');
  66362. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  66363. textarea.style.color = model.get('textColor');
  66364. textarea.style.borderColor = model.get('textareaBorderColor');
  66365. textarea.style.backgroundColor = model.get('textareaColor');
  66366. textarea.value = result.value;
  66367. }
  66368. var blockMetaList = result.meta;
  66369. var buttonContainer = document.createElement('div');
  66370. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  66371. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  66372. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  66373. var closeButton = document.createElement('div');
  66374. var refreshButton = document.createElement('div');
  66375. buttonStyle += ';background-color:' + model.get('buttonColor');
  66376. buttonStyle += ';color:' + model.get('buttonTextColor');
  66377. var self = this;
  66378. function close() {
  66379. container.removeChild(root);
  66380. self._dom = null;
  66381. }
  66382. addEventListener(closeButton, 'click', close);
  66383. addEventListener(refreshButton, 'click', function () {
  66384. var newOption;
  66385. try {
  66386. if (typeof contentToOption === 'function') {
  66387. newOption = contentToOption(viewMain, api.getOption());
  66388. }
  66389. else {
  66390. newOption = parseContents(textarea.value, blockMetaList);
  66391. }
  66392. }
  66393. catch (e) {
  66394. close();
  66395. throw new Error('Data view format error ' + e);
  66396. }
  66397. if (newOption) {
  66398. api.dispatchAction({
  66399. type: 'changeDataView',
  66400. newOption: newOption
  66401. });
  66402. }
  66403. close();
  66404. });
  66405. closeButton.innerHTML = lang$$1[1];
  66406. refreshButton.innerHTML = lang$$1[2];
  66407. refreshButton.style.cssText = buttonStyle;
  66408. closeButton.style.cssText = buttonStyle;
  66409. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  66410. buttonContainer.appendChild(closeButton);
  66411. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  66412. addEventListener(textarea, 'keydown', function (e) {
  66413. if ((e.keyCode || e.which) === 9) {
  66414. // get caret position/selection
  66415. var val = this.value;
  66416. var start = this.selectionStart;
  66417. var end = this.selectionEnd;
  66418. // set textarea value to: text before caret + tab + text after caret
  66419. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  66420. // put caret at right position again
  66421. this.selectionStart = this.selectionEnd = start + 1;
  66422. // prevent the focus lose
  66423. stop(e);
  66424. }
  66425. });
  66426. root.appendChild(header);
  66427. root.appendChild(viewMain);
  66428. root.appendChild(buttonContainer);
  66429. viewMain.style.height = (container.clientHeight - 80) + 'px';
  66430. container.appendChild(root);
  66431. this._dom = root;
  66432. };
  66433. DataView.prototype.remove = function (ecModel, api) {
  66434. this._dom && api.getDom().removeChild(this._dom);
  66435. };
  66436. DataView.prototype.dispose = function (ecModel, api) {
  66437. this.remove(ecModel, api);
  66438. };
  66439. /**
  66440. * @inner
  66441. */
  66442. function tryMergeDataOption(newData, originalData) {
  66443. return map(newData, function (newVal, idx) {
  66444. var original = originalData && originalData[idx];
  66445. if (isObject$1(original) && !isArray(original)) {
  66446. if (isObject$1(newVal) && !isArray(newVal)) {
  66447. newVal = newVal.value;
  66448. }
  66449. // Original data has option
  66450. return defaults({
  66451. value: newVal
  66452. }, original);
  66453. }
  66454. else {
  66455. return newVal;
  66456. }
  66457. });
  66458. }
  66459. register$1('dataView', DataView);
  66460. registerAction({
  66461. type: 'changeDataView',
  66462. event: 'dataViewChanged',
  66463. update: 'prepareAndUpdate'
  66464. }, function (payload, ecModel) {
  66465. var newSeriesOptList = [];
  66466. each$1(payload.newOption.series, function (seriesOpt) {
  66467. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  66468. if (!seriesModel) {
  66469. // New created series
  66470. // Geuss the series type
  66471. newSeriesOptList.push(extend({
  66472. // Default is scatter
  66473. type: 'scatter'
  66474. }, seriesOpt));
  66475. }
  66476. else {
  66477. var originalData = seriesModel.get('data');
  66478. newSeriesOptList.push({
  66479. name: seriesOpt.name,
  66480. data: tryMergeDataOption(seriesOpt.data, originalData)
  66481. });
  66482. }
  66483. });
  66484. ecModel.mergeOption(defaults({
  66485. series: newSeriesOptList
  66486. }, payload.newOption));
  66487. });
  66488. var each$30 = each$1;
  66489. var ATTR$2 = '\0_ec_hist_store';
  66490. /**
  66491. * @param {module:echarts/model/Global} ecModel
  66492. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  66493. */
  66494. function push(ecModel, newSnapshot) {
  66495. var store = giveStore$1(ecModel);
  66496. // If previous dataZoom can not be found,
  66497. // complete an range with current range.
  66498. each$30(newSnapshot, function (batchItem, dataZoomId) {
  66499. var i = store.length - 1;
  66500. for (; i >= 0; i--) {
  66501. var snapshot = store[i];
  66502. if (snapshot[dataZoomId]) {
  66503. break;
  66504. }
  66505. }
  66506. if (i < 0) {
  66507. // No origin range set, create one by current range.
  66508. var dataZoomModel = ecModel.queryComponents(
  66509. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  66510. )[0];
  66511. if (dataZoomModel) {
  66512. var percentRange = dataZoomModel.getPercentRange();
  66513. store[0][dataZoomId] = {
  66514. dataZoomId: dataZoomId,
  66515. start: percentRange[0],
  66516. end: percentRange[1]
  66517. };
  66518. }
  66519. }
  66520. });
  66521. store.push(newSnapshot);
  66522. }
  66523. /**
  66524. * @param {module:echarts/model/Global} ecModel
  66525. * @return {Object} snapshot
  66526. */
  66527. function pop(ecModel) {
  66528. var store = giveStore$1(ecModel);
  66529. var head = store[store.length - 1];
  66530. store.length > 1 && store.pop();
  66531. // Find top for all dataZoom.
  66532. var snapshot = {};
  66533. each$30(head, function (batchItem, dataZoomId) {
  66534. for (var i = store.length - 1; i >= 0; i--) {
  66535. var batchItem = store[i][dataZoomId];
  66536. if (batchItem) {
  66537. snapshot[dataZoomId] = batchItem;
  66538. break;
  66539. }
  66540. }
  66541. });
  66542. return snapshot;
  66543. }
  66544. /**
  66545. * @param {module:echarts/model/Global} ecModel
  66546. */
  66547. function clear$1(ecModel) {
  66548. ecModel[ATTR$2] = null;
  66549. }
  66550. /**
  66551. * @param {module:echarts/model/Global} ecModel
  66552. * @return {number} records. always >= 1.
  66553. */
  66554. function count(ecModel) {
  66555. return giveStore$1(ecModel).length;
  66556. }
  66557. /**
  66558. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  66559. * History length of each dataZoom may be different.
  66560. * this._history[0] is used to store origin range.
  66561. * @type {Array.<Object>}
  66562. */
  66563. function giveStore$1(ecModel) {
  66564. var store = ecModel[ATTR$2];
  66565. if (!store) {
  66566. store = ecModel[ATTR$2] = [{}];
  66567. }
  66568. return store;
  66569. }
  66570. DataZoomModel.extend({
  66571. type: 'dataZoom.select'
  66572. });
  66573. DataZoomView.extend({
  66574. type: 'dataZoom.select'
  66575. });
  66576. /**
  66577. * DataZoom component entry
  66578. */
  66579. // Use dataZoomSelect
  66580. var dataZoomLang = lang.toolbox.dataZoom;
  66581. var each$29 = each$1;
  66582. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  66583. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  66584. function DataZoom(model, ecModel, api) {
  66585. /**
  66586. * @private
  66587. * @type {module:echarts/component/helper/BrushController}
  66588. */
  66589. (this._brushController = new BrushController(api.getZr()))
  66590. .on('brush', bind(this._onBrush, this))
  66591. .mount();
  66592. /**
  66593. * @private
  66594. * @type {boolean}
  66595. */
  66596. this._isZoomActive;
  66597. }
  66598. DataZoom.defaultOption = {
  66599. show: true,
  66600. // Icon group
  66601. icon: {
  66602. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  66603. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  66604. },
  66605. // `zoom`, `back`
  66606. title: clone(dataZoomLang.title)
  66607. };
  66608. var proto$6 = DataZoom.prototype;
  66609. proto$6.render = function (featureModel, ecModel, api, payload) {
  66610. this.model = featureModel;
  66611. this.ecModel = ecModel;
  66612. this.api = api;
  66613. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  66614. updateBackBtnStatus(featureModel, ecModel);
  66615. };
  66616. proto$6.onclick = function (ecModel, api, type) {
  66617. handlers$1[type].call(this);
  66618. };
  66619. proto$6.remove = function (ecModel, api) {
  66620. this._brushController.unmount();
  66621. };
  66622. proto$6.dispose = function (ecModel, api) {
  66623. this._brushController.dispose();
  66624. };
  66625. /**
  66626. * @private
  66627. */
  66628. var handlers$1 = {
  66629. zoom: function () {
  66630. var nextActive = !this._isZoomActive;
  66631. this.api.dispatchAction({
  66632. type: 'takeGlobalCursor',
  66633. key: 'dataZoomSelect',
  66634. dataZoomSelectActive: nextActive
  66635. });
  66636. },
  66637. back: function () {
  66638. this._dispatchZoomAction(pop(this.ecModel));
  66639. }
  66640. };
  66641. /**
  66642. * @private
  66643. */
  66644. proto$6._onBrush = function (areas, opt) {
  66645. if (!opt.isEnd || !areas.length) {
  66646. return;
  66647. }
  66648. var snapshot = {};
  66649. var ecModel = this.ecModel;
  66650. this._brushController.updateCovers([]); // remove cover
  66651. var brushTargetManager = new BrushTargetManager(
  66652. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  66653. );
  66654. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  66655. if (coordSys.type !== 'cartesian2d') {
  66656. return;
  66657. }
  66658. var brushType = area.brushType;
  66659. if (brushType === 'rect') {
  66660. setBatch('x', coordSys, coordRange[0]);
  66661. setBatch('y', coordSys, coordRange[1]);
  66662. }
  66663. else {
  66664. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  66665. }
  66666. });
  66667. push(ecModel, snapshot);
  66668. this._dispatchZoomAction(snapshot);
  66669. function setBatch(dimName, coordSys, minMax) {
  66670. var axis = coordSys.getAxis(dimName);
  66671. var axisModel = axis.model;
  66672. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  66673. // Restrict range.
  66674. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  66675. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  66676. minMax = sliderMove(
  66677. 0, minMax.slice(), axis.scale.getExtent(), 0,
  66678. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  66679. );
  66680. }
  66681. dataZoomModel && (snapshot[dataZoomModel.id] = {
  66682. dataZoomId: dataZoomModel.id,
  66683. startValue: minMax[0],
  66684. endValue: minMax[1]
  66685. });
  66686. }
  66687. function findDataZoom(dimName, axisModel, ecModel) {
  66688. var found;
  66689. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  66690. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  66691. has && (found = dzModel);
  66692. });
  66693. return found;
  66694. }
  66695. };
  66696. /**
  66697. * @private
  66698. */
  66699. proto$6._dispatchZoomAction = function (snapshot) {
  66700. var batch = [];
  66701. // Convert from hash map to array.
  66702. each$29(snapshot, function (batchItem, dataZoomId) {
  66703. batch.push(clone(batchItem));
  66704. });
  66705. batch.length && this.api.dispatchAction({
  66706. type: 'dataZoom',
  66707. from: this.uid,
  66708. batch: batch
  66709. });
  66710. };
  66711. function retrieveAxisSetting(option) {
  66712. var setting = {};
  66713. // Compatible with previous setting: null => all axis, false => no axis.
  66714. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  66715. setting[name] = option[name];
  66716. setting[name] == null && (setting[name] = 'all');
  66717. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  66718. });
  66719. return setting;
  66720. }
  66721. function updateBackBtnStatus(featureModel, ecModel) {
  66722. featureModel.setIconStatus(
  66723. 'back',
  66724. count(ecModel) > 1 ? 'emphasis' : 'normal'
  66725. );
  66726. }
  66727. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  66728. var zoomActive = view._isZoomActive;
  66729. if (payload && payload.type === 'takeGlobalCursor') {
  66730. zoomActive = payload.key === 'dataZoomSelect'
  66731. ? payload.dataZoomSelectActive : false;
  66732. }
  66733. view._isZoomActive = zoomActive;
  66734. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  66735. var brushTargetManager = new BrushTargetManager(
  66736. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  66737. );
  66738. view._brushController
  66739. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  66740. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  66741. ? 'lineX'
  66742. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  66743. ? 'lineY'
  66744. : 'rect';
  66745. }))
  66746. .enableBrush(
  66747. zoomActive
  66748. ? {
  66749. brushType: 'auto',
  66750. brushStyle: {
  66751. // FIXME user customized?
  66752. lineWidth: 0,
  66753. fill: 'rgba(0,0,0,0.2)'
  66754. }
  66755. }
  66756. : false
  66757. );
  66758. }
  66759. register$1('dataZoom', DataZoom);
  66760. // Create special dataZoom option for select
  66761. registerPreprocessor(function (option) {
  66762. if (!option) {
  66763. return;
  66764. }
  66765. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  66766. if (!isArray(dataZoomOpts)) {
  66767. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  66768. }
  66769. var toolboxOpt = option.toolbox;
  66770. if (toolboxOpt) {
  66771. // Assume there is only one toolbox
  66772. if (isArray(toolboxOpt)) {
  66773. toolboxOpt = toolboxOpt[0];
  66774. }
  66775. if (toolboxOpt && toolboxOpt.feature) {
  66776. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  66777. addForAxis('xAxis', dataZoomOpt);
  66778. addForAxis('yAxis', dataZoomOpt);
  66779. }
  66780. }
  66781. function addForAxis(axisName, dataZoomOpt) {
  66782. if (!dataZoomOpt) {
  66783. return;
  66784. }
  66785. // Try not to modify model, because it is not merged yet.
  66786. var axisIndicesName = axisName + 'Index';
  66787. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  66788. if (givenAxisIndices != null
  66789. && givenAxisIndices != 'all'
  66790. && !isArray(givenAxisIndices)
  66791. ) {
  66792. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  66793. }
  66794. forEachComponent(axisName, function (axisOpt, axisIndex) {
  66795. if (givenAxisIndices != null
  66796. && givenAxisIndices != 'all'
  66797. && indexOf(givenAxisIndices, axisIndex) === -1
  66798. ) {
  66799. return;
  66800. }
  66801. var newOpt = {
  66802. type: 'select',
  66803. $fromToolbox: true,
  66804. // Id for merge mapping.
  66805. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  66806. };
  66807. // FIXME
  66808. // Only support one axis now.
  66809. newOpt[axisIndicesName] = axisIndex;
  66810. dataZoomOpts.push(newOpt);
  66811. });
  66812. }
  66813. function forEachComponent(mainType, cb) {
  66814. var opts = option[mainType];
  66815. if (!isArray(opts)) {
  66816. opts = opts ? [opts] : [];
  66817. }
  66818. each$29(opts, cb);
  66819. }
  66820. });
  66821. var restoreLang = lang.toolbox.restore;
  66822. function Restore(model) {
  66823. this.model = model;
  66824. }
  66825. Restore.defaultOption = {
  66826. show: true,
  66827. 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',
  66828. title: restoreLang.title
  66829. };
  66830. var proto$7 = Restore.prototype;
  66831. proto$7.onclick = function (ecModel, api, type) {
  66832. clear$1(ecModel);
  66833. api.dispatchAction({
  66834. type: 'restore',
  66835. from: this.uid
  66836. });
  66837. };
  66838. register$1('restore', Restore);
  66839. registerAction(
  66840. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  66841. function (payload, ecModel) {
  66842. ecModel.resetOption('recreate');
  66843. }
  66844. );
  66845. var urn = 'urn:schemas-microsoft-com:vml';
  66846. var win = typeof window === 'undefined' ? null : window;
  66847. var vmlInited = false;
  66848. var doc = win && win.document;
  66849. function createNode(tagName) {
  66850. return doCreateNode(tagName);
  66851. }
  66852. // Avoid assign to an exported variable, for transforming to cjs.
  66853. var doCreateNode;
  66854. if (doc && !env$1.canvasSupported) {
  66855. try {
  66856. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  66857. doCreateNode = function (tagName) {
  66858. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  66859. };
  66860. }
  66861. catch (e) {
  66862. doCreateNode = function (tagName) {
  66863. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  66864. };
  66865. }
  66866. }
  66867. // From raphael
  66868. function initVML() {
  66869. if (vmlInited || !doc) {
  66870. return;
  66871. }
  66872. vmlInited = true;
  66873. var styleSheets = doc.styleSheets;
  66874. if (styleSheets.length < 31) {
  66875. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  66876. }
  66877. else {
  66878. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  66879. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  66880. }
  66881. }
  66882. // http://www.w3.org/TR/NOTE-VML
  66883. // TODO Use proxy like svg instead of overwrite brush methods
  66884. var CMD$3 = PathProxy.CMD;
  66885. var round$3 = Math.round;
  66886. var sqrt = Math.sqrt;
  66887. var abs$1 = Math.abs;
  66888. var cos = Math.cos;
  66889. var sin = Math.sin;
  66890. var mathMax$8 = Math.max;
  66891. if (!env$1.canvasSupported) {
  66892. var comma = ',';
  66893. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  66894. var Z = 21600;
  66895. var Z2 = Z / 2;
  66896. var ZLEVEL_BASE = 100000;
  66897. var Z_BASE$1 = 1000;
  66898. var initRootElStyle = function (el) {
  66899. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  66900. el.coordsize = Z + ',' + Z;
  66901. el.coordorigin = '0,0';
  66902. };
  66903. var encodeHtmlAttribute = function (s) {
  66904. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  66905. };
  66906. var rgb2Str = function (r, g, b) {
  66907. return 'rgb(' + [r, g, b].join(',') + ')';
  66908. };
  66909. var append = function (parent, child) {
  66910. if (child && parent && child.parentNode !== parent) {
  66911. parent.appendChild(child);
  66912. }
  66913. };
  66914. var remove = function (parent, child) {
  66915. if (child && parent && child.parentNode === parent) {
  66916. parent.removeChild(child);
  66917. }
  66918. };
  66919. var getZIndex = function (zlevel, z, z2) {
  66920. // z 的取值范围为 [0, 1000]
  66921. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  66922. };
  66923. var parsePercent$3 = function (value, maxValue) {
  66924. if (typeof value === 'string') {
  66925. if (value.lastIndexOf('%') >= 0) {
  66926. return parseFloat(value) / 100 * maxValue;
  66927. }
  66928. return parseFloat(value);
  66929. }
  66930. return value;
  66931. };
  66932. /***************************************************
  66933. * PATH
  66934. **************************************************/
  66935. var setColorAndOpacity = function (el, color, opacity) {
  66936. var colorArr = parse(color);
  66937. opacity = +opacity;
  66938. if (isNaN(opacity)) {
  66939. opacity = 1;
  66940. }
  66941. if (colorArr) {
  66942. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  66943. el.opacity = opacity * colorArr[3];
  66944. }
  66945. };
  66946. var getColorAndAlpha = function (color) {
  66947. var colorArr = parse(color);
  66948. return [
  66949. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  66950. colorArr[3]
  66951. ];
  66952. };
  66953. var updateFillNode = function (el, style, zrEl) {
  66954. // TODO pattern
  66955. var fill = style.fill;
  66956. if (fill != null) {
  66957. // Modified from excanvas
  66958. if (fill instanceof Gradient) {
  66959. var gradientType;
  66960. var angle = 0;
  66961. var focus = [0, 0];
  66962. // additional offset
  66963. var shift = 0;
  66964. // scale factor for offset
  66965. var expansion = 1;
  66966. var rect = zrEl.getBoundingRect();
  66967. var rectWidth = rect.width;
  66968. var rectHeight = rect.height;
  66969. if (fill.type === 'linear') {
  66970. gradientType = 'gradient';
  66971. var transform = zrEl.transform;
  66972. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66973. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  66974. if (transform) {
  66975. applyTransform(p0, p0, transform);
  66976. applyTransform(p1, p1, transform);
  66977. }
  66978. var dx = p1[0] - p0[0];
  66979. var dy = p1[1] - p0[1];
  66980. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  66981. // The angle should be a non-negative number.
  66982. if (angle < 0) {
  66983. angle += 360;
  66984. }
  66985. // Very small angles produce an unexpected result because they are
  66986. // converted to a scientific notation string.
  66987. if (angle < 1e-6) {
  66988. angle = 0;
  66989. }
  66990. }
  66991. else {
  66992. gradientType = 'gradientradial';
  66993. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66994. var transform = zrEl.transform;
  66995. var scale$$1 = zrEl.scale;
  66996. var width = rectWidth;
  66997. var height = rectHeight;
  66998. focus = [
  66999. // Percent in bounding rect
  67000. (p0[0] - rect.x) / width,
  67001. (p0[1] - rect.y) / height
  67002. ];
  67003. if (transform) {
  67004. applyTransform(p0, p0, transform);
  67005. }
  67006. width /= scale$$1[0] * Z;
  67007. height /= scale$$1[1] * Z;
  67008. var dimension = mathMax$8(width, height);
  67009. shift = 2 * 0 / dimension;
  67010. expansion = 2 * fill.r / dimension - shift;
  67011. }
  67012. // We need to sort the color stops in ascending order by offset,
  67013. // otherwise IE won't interpret it correctly.
  67014. var stops = fill.colorStops.slice();
  67015. stops.sort(function(cs1, cs2) {
  67016. return cs1.offset - cs2.offset;
  67017. });
  67018. var length$$1 = stops.length;
  67019. // Color and alpha list of first and last stop
  67020. var colorAndAlphaList = [];
  67021. var colors = [];
  67022. for (var i = 0; i < length$$1; i++) {
  67023. var stop = stops[i];
  67024. var colorAndAlpha = getColorAndAlpha(stop.color);
  67025. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  67026. if (i === 0 || i === length$$1 - 1) {
  67027. colorAndAlphaList.push(colorAndAlpha);
  67028. }
  67029. }
  67030. if (length$$1 >= 2) {
  67031. var color1 = colorAndAlphaList[0][0];
  67032. var color2 = colorAndAlphaList[1][0];
  67033. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  67034. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  67035. el.type = gradientType;
  67036. el.method = 'none';
  67037. el.focus = '100%';
  67038. el.angle = angle;
  67039. el.color = color1;
  67040. el.color2 = color2;
  67041. el.colors = colors.join(',');
  67042. // When colors attribute is used, the meanings of opacity and o:opacity2
  67043. // are reversed.
  67044. el.opacity = opacity2;
  67045. // FIXME g_o_:opacity ?
  67046. el.opacity2 = opacity1;
  67047. }
  67048. if (gradientType === 'radial') {
  67049. el.focusposition = focus.join(',');
  67050. }
  67051. }
  67052. else {
  67053. // FIXME Change from Gradient fill to color fill
  67054. setColorAndOpacity(el, fill, style.opacity);
  67055. }
  67056. }
  67057. };
  67058. var updateStrokeNode = function (el, style) {
  67059. // if (style.lineJoin != null) {
  67060. // el.joinstyle = style.lineJoin;
  67061. // }
  67062. // if (style.miterLimit != null) {
  67063. // el.miterlimit = style.miterLimit * Z;
  67064. // }
  67065. // if (style.lineCap != null) {
  67066. // el.endcap = style.lineCap;
  67067. // }
  67068. if (style.lineDash != null) {
  67069. el.dashstyle = style.lineDash.join(' ');
  67070. }
  67071. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  67072. setColorAndOpacity(el, style.stroke, style.opacity);
  67073. }
  67074. };
  67075. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  67076. var isFill = type == 'fill';
  67077. var el = vmlEl.getElementsByTagName(type)[0];
  67078. // Stroke must have lineWidth
  67079. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  67080. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  67081. // FIXME Remove before updating, or set `colors` will throw error
  67082. if (style[type] instanceof Gradient) {
  67083. remove(vmlEl, el);
  67084. }
  67085. if (!el) {
  67086. el = createNode(type);
  67087. }
  67088. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  67089. append(vmlEl, el);
  67090. }
  67091. else {
  67092. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  67093. remove(vmlEl, el);
  67094. }
  67095. };
  67096. var points$3 = [[], [], []];
  67097. var pathDataToString = function (path, m) {
  67098. var M = CMD$3.M;
  67099. var C = CMD$3.C;
  67100. var L = CMD$3.L;
  67101. var A = CMD$3.A;
  67102. var Q = CMD$3.Q;
  67103. var str = [];
  67104. var nPoint;
  67105. var cmdStr;
  67106. var cmd;
  67107. var i;
  67108. var xi;
  67109. var yi;
  67110. var data = path.data;
  67111. var dataLength = path.len();
  67112. for (i = 0; i < dataLength;) {
  67113. cmd = data[i++];
  67114. cmdStr = '';
  67115. nPoint = 0;
  67116. switch (cmd) {
  67117. case M:
  67118. cmdStr = ' m ';
  67119. nPoint = 1;
  67120. xi = data[i++];
  67121. yi = data[i++];
  67122. points$3[0][0] = xi;
  67123. points$3[0][1] = yi;
  67124. break;
  67125. case L:
  67126. cmdStr = ' l ';
  67127. nPoint = 1;
  67128. xi = data[i++];
  67129. yi = data[i++];
  67130. points$3[0][0] = xi;
  67131. points$3[0][1] = yi;
  67132. break;
  67133. case Q:
  67134. case C:
  67135. cmdStr = ' c ';
  67136. nPoint = 3;
  67137. var x1 = data[i++];
  67138. var y1 = data[i++];
  67139. var x2 = data[i++];
  67140. var y2 = data[i++];
  67141. var x3;
  67142. var y3;
  67143. if (cmd === Q) {
  67144. // Convert quadratic to cubic using degree elevation
  67145. x3 = x2;
  67146. y3 = y2;
  67147. x2 = (x2 + 2 * x1) / 3;
  67148. y2 = (y2 + 2 * y1) / 3;
  67149. x1 = (xi + 2 * x1) / 3;
  67150. y1 = (yi + 2 * y1) / 3;
  67151. }
  67152. else {
  67153. x3 = data[i++];
  67154. y3 = data[i++];
  67155. }
  67156. points$3[0][0] = x1;
  67157. points$3[0][1] = y1;
  67158. points$3[1][0] = x2;
  67159. points$3[1][1] = y2;
  67160. points$3[2][0] = x3;
  67161. points$3[2][1] = y3;
  67162. xi = x3;
  67163. yi = y3;
  67164. break;
  67165. case A:
  67166. var x = 0;
  67167. var y = 0;
  67168. var sx = 1;
  67169. var sy = 1;
  67170. var angle = 0;
  67171. if (m) {
  67172. // Extract SRT from matrix
  67173. x = m[4];
  67174. y = m[5];
  67175. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  67176. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  67177. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  67178. }
  67179. var cx = data[i++];
  67180. var cy = data[i++];
  67181. var rx = data[i++];
  67182. var ry = data[i++];
  67183. var startAngle = data[i++] + angle;
  67184. var endAngle = data[i++] + startAngle + angle;
  67185. // FIXME
  67186. // var psi = data[i++];
  67187. i++;
  67188. var clockwise = data[i++];
  67189. var x0 = cx + cos(startAngle) * rx;
  67190. var y0 = cy + sin(startAngle) * ry;
  67191. var x1 = cx + cos(endAngle) * rx;
  67192. var y1 = cy + sin(endAngle) * ry;
  67193. var type = clockwise ? ' wa ' : ' at ';
  67194. if (Math.abs(x0 - x1) < 1e-4) {
  67195. // IE won't render arches drawn counter clockwise if x0 == x1.
  67196. if (Math.abs(endAngle - startAngle) > 1e-2) {
  67197. // Offset x0 by 1/80 of a pixel. Use something
  67198. // that can be represented in binary
  67199. if (clockwise) {
  67200. x0 += 270 / Z;
  67201. }
  67202. }
  67203. else {
  67204. // Avoid case draw full circle
  67205. if (Math.abs(y0 - cy) < 1e-4) {
  67206. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  67207. y1 -= 270 / Z;
  67208. }
  67209. else {
  67210. y1 += 270 / Z;
  67211. }
  67212. }
  67213. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  67214. x1 += 270 / Z;
  67215. }
  67216. else {
  67217. x1 -= 270 / Z;
  67218. }
  67219. }
  67220. }
  67221. str.push(
  67222. type,
  67223. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  67224. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  67225. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  67226. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  67227. round$3((x0 * sx + x) * Z - Z2), comma,
  67228. round$3((y0 * sy + y) * Z - Z2), comma,
  67229. round$3((x1 * sx + x) * Z - Z2), comma,
  67230. round$3((y1 * sy + y) * Z - Z2)
  67231. );
  67232. xi = x1;
  67233. yi = y1;
  67234. break;
  67235. case CMD$3.R:
  67236. var p0 = points$3[0];
  67237. var p1 = points$3[1];
  67238. // x0, y0
  67239. p0[0] = data[i++];
  67240. p0[1] = data[i++];
  67241. // x1, y1
  67242. p1[0] = p0[0] + data[i++];
  67243. p1[1] = p0[1] + data[i++];
  67244. if (m) {
  67245. applyTransform(p0, p0, m);
  67246. applyTransform(p1, p1, m);
  67247. }
  67248. p0[0] = round$3(p0[0] * Z - Z2);
  67249. p1[0] = round$3(p1[0] * Z - Z2);
  67250. p0[1] = round$3(p0[1] * Z - Z2);
  67251. p1[1] = round$3(p1[1] * Z - Z2);
  67252. str.push(
  67253. // x0, y0
  67254. ' m ', p0[0], comma, p0[1],
  67255. // x1, y0
  67256. ' l ', p1[0], comma, p0[1],
  67257. // x1, y1
  67258. ' l ', p1[0], comma, p1[1],
  67259. // x0, y1
  67260. ' l ', p0[0], comma, p1[1]
  67261. );
  67262. break;
  67263. case CMD$3.Z:
  67264. // FIXME Update xi, yi
  67265. str.push(' x ');
  67266. }
  67267. if (nPoint > 0) {
  67268. str.push(cmdStr);
  67269. for (var k = 0; k < nPoint; k++) {
  67270. var p = points$3[k];
  67271. m && applyTransform(p, p, m);
  67272. // 不 round 会非常慢
  67273. str.push(
  67274. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  67275. k < nPoint - 1 ? comma : ''
  67276. );
  67277. }
  67278. }
  67279. }
  67280. return str.join('');
  67281. };
  67282. // Rewrite the original path method
  67283. Path.prototype.brushVML = function (vmlRoot) {
  67284. var style = this.style;
  67285. var vmlEl = this._vmlEl;
  67286. if (!vmlEl) {
  67287. vmlEl = createNode('shape');
  67288. initRootElStyle(vmlEl);
  67289. this._vmlEl = vmlEl;
  67290. }
  67291. updateFillAndStroke(vmlEl, 'fill', style, this);
  67292. updateFillAndStroke(vmlEl, 'stroke', style, this);
  67293. var m = this.transform;
  67294. var needTransform = m != null;
  67295. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  67296. if (strokeEl) {
  67297. var lineWidth = style.lineWidth;
  67298. // Get the line scale.
  67299. // Determinant of this.m_ means how much the area is enlarged by the
  67300. // transformation. So its square root can be used as a scale factor
  67301. // for width.
  67302. if (needTransform && !style.strokeNoScale) {
  67303. var det = m[0] * m[3] - m[1] * m[2];
  67304. lineWidth *= sqrt(abs$1(det));
  67305. }
  67306. strokeEl.weight = lineWidth + 'px';
  67307. }
  67308. var path = this.path || (this.path = new PathProxy());
  67309. if (this.__dirtyPath) {
  67310. path.beginPath();
  67311. this.buildPath(path, this.shape);
  67312. path.toStatic();
  67313. this.__dirtyPath = false;
  67314. }
  67315. vmlEl.path = pathDataToString(path, this.transform);
  67316. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67317. // Append to root
  67318. append(vmlRoot, vmlEl);
  67319. // Text
  67320. if (style.text != null) {
  67321. this.drawRectText(vmlRoot, this.getBoundingRect());
  67322. }
  67323. else {
  67324. this.removeRectText(vmlRoot);
  67325. }
  67326. };
  67327. Path.prototype.onRemove = function (vmlRoot) {
  67328. remove(vmlRoot, this._vmlEl);
  67329. this.removeRectText(vmlRoot);
  67330. };
  67331. Path.prototype.onAdd = function (vmlRoot) {
  67332. append(vmlRoot, this._vmlEl);
  67333. this.appendRectText(vmlRoot);
  67334. };
  67335. /***************************************************
  67336. * IMAGE
  67337. **************************************************/
  67338. var isImage = function (img) {
  67339. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  67340. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  67341. // return img instanceof Image;
  67342. };
  67343. // Rewrite the original path method
  67344. ZImage.prototype.brushVML = function (vmlRoot) {
  67345. var style = this.style;
  67346. var image = style.image;
  67347. // Image original width, height
  67348. var ow;
  67349. var oh;
  67350. if (isImage(image)) {
  67351. var src = image.src;
  67352. if (src === this._imageSrc) {
  67353. ow = this._imageWidth;
  67354. oh = this._imageHeight;
  67355. }
  67356. else {
  67357. var imageRuntimeStyle = image.runtimeStyle;
  67358. var oldRuntimeWidth = imageRuntimeStyle.width;
  67359. var oldRuntimeHeight = imageRuntimeStyle.height;
  67360. imageRuntimeStyle.width = 'auto';
  67361. imageRuntimeStyle.height = 'auto';
  67362. // get the original size
  67363. ow = image.width;
  67364. oh = image.height;
  67365. // and remove overides
  67366. imageRuntimeStyle.width = oldRuntimeWidth;
  67367. imageRuntimeStyle.height = oldRuntimeHeight;
  67368. // Caching image original width, height and src
  67369. this._imageSrc = src;
  67370. this._imageWidth = ow;
  67371. this._imageHeight = oh;
  67372. }
  67373. image = src;
  67374. }
  67375. else {
  67376. if (image === this._imageSrc) {
  67377. ow = this._imageWidth;
  67378. oh = this._imageHeight;
  67379. }
  67380. }
  67381. if (!image) {
  67382. return;
  67383. }
  67384. var x = style.x || 0;
  67385. var y = style.y || 0;
  67386. var dw = style.width;
  67387. var dh = style.height;
  67388. var sw = style.sWidth;
  67389. var sh = style.sHeight;
  67390. var sx = style.sx || 0;
  67391. var sy = style.sy || 0;
  67392. var hasCrop = sw && sh;
  67393. var vmlEl = this._vmlEl;
  67394. if (!vmlEl) {
  67395. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  67396. // vmlEl = vmlCore.createNode('group');
  67397. vmlEl = doc.createElement('div');
  67398. initRootElStyle(vmlEl);
  67399. this._vmlEl = vmlEl;
  67400. }
  67401. var vmlElStyle = vmlEl.style;
  67402. var hasRotation = false;
  67403. var m;
  67404. var scaleX = 1;
  67405. var scaleY = 1;
  67406. if (this.transform) {
  67407. m = this.transform;
  67408. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  67409. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  67410. hasRotation = m[1] || m[2];
  67411. }
  67412. if (hasRotation) {
  67413. // If filters are necessary (rotation exists), create them
  67414. // filters are bog-slow, so only create them if abbsolutely necessary
  67415. // The following check doesn't account for skews (which don't exist
  67416. // in the canvas spec (yet) anyway.
  67417. // From excanvas
  67418. var p0 = [x, y];
  67419. var p1 = [x + dw, y];
  67420. var p2 = [x, y + dh];
  67421. var p3 = [x + dw, y + dh];
  67422. applyTransform(p0, p0, m);
  67423. applyTransform(p1, p1, m);
  67424. applyTransform(p2, p2, m);
  67425. applyTransform(p3, p3, m);
  67426. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  67427. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  67428. var transformFilter = [];
  67429. transformFilter.push('M11=', m[0] / scaleX, comma,
  67430. 'M12=', m[2] / scaleY, comma,
  67431. 'M21=', m[1] / scaleX, comma,
  67432. 'M22=', m[3] / scaleY, comma,
  67433. 'Dx=', round$3(x * scaleX + m[4]), comma,
  67434. 'Dy=', round$3(y * scaleY + m[5]));
  67435. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  67436. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  67437. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  67438. + transformFilter.join('') + ', SizingMethod=clip)';
  67439. }
  67440. else {
  67441. if (m) {
  67442. x = x * scaleX + m[4];
  67443. y = y * scaleY + m[5];
  67444. }
  67445. vmlElStyle.filter = '';
  67446. vmlElStyle.left = round$3(x) + 'px';
  67447. vmlElStyle.top = round$3(y) + 'px';
  67448. }
  67449. var imageEl = this._imageEl;
  67450. var cropEl = this._cropEl;
  67451. if (!imageEl) {
  67452. imageEl = doc.createElement('div');
  67453. this._imageEl = imageEl;
  67454. }
  67455. var imageELStyle = imageEl.style;
  67456. if (hasCrop) {
  67457. // Needs know image original width and height
  67458. if (! (ow && oh)) {
  67459. var tmpImage = new Image();
  67460. var self = this;
  67461. tmpImage.onload = function () {
  67462. tmpImage.onload = null;
  67463. ow = tmpImage.width;
  67464. oh = tmpImage.height;
  67465. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  67466. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  67467. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  67468. // Caching image original width, height and src
  67469. self._imageWidth = ow;
  67470. self._imageHeight = oh;
  67471. self._imageSrc = image;
  67472. };
  67473. tmpImage.src = image;
  67474. }
  67475. else {
  67476. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  67477. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  67478. }
  67479. if (! cropEl) {
  67480. cropEl = doc.createElement('div');
  67481. cropEl.style.overflow = 'hidden';
  67482. this._cropEl = cropEl;
  67483. }
  67484. var cropElStyle = cropEl.style;
  67485. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  67486. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  67487. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  67488. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  67489. if (! cropEl.parentNode) {
  67490. vmlEl.appendChild(cropEl);
  67491. }
  67492. if (imageEl.parentNode != cropEl) {
  67493. cropEl.appendChild(imageEl);
  67494. }
  67495. }
  67496. else {
  67497. imageELStyle.width = round$3(scaleX * dw) + 'px';
  67498. imageELStyle.height = round$3(scaleY * dh) + 'px';
  67499. vmlEl.appendChild(imageEl);
  67500. if (cropEl && cropEl.parentNode) {
  67501. vmlEl.removeChild(cropEl);
  67502. this._cropEl = null;
  67503. }
  67504. }
  67505. var filterStr = '';
  67506. var alpha = style.opacity;
  67507. if (alpha < 1) {
  67508. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  67509. }
  67510. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  67511. imageELStyle.filter = filterStr;
  67512. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67513. // Append to root
  67514. append(vmlRoot, vmlEl);
  67515. // Text
  67516. if (style.text != null) {
  67517. this.drawRectText(vmlRoot, this.getBoundingRect());
  67518. }
  67519. };
  67520. ZImage.prototype.onRemove = function (vmlRoot) {
  67521. remove(vmlRoot, this._vmlEl);
  67522. this._vmlEl = null;
  67523. this._cropEl = null;
  67524. this._imageEl = null;
  67525. this.removeRectText(vmlRoot);
  67526. };
  67527. ZImage.prototype.onAdd = function (vmlRoot) {
  67528. append(vmlRoot, this._vmlEl);
  67529. this.appendRectText(vmlRoot);
  67530. };
  67531. /***************************************************
  67532. * TEXT
  67533. **************************************************/
  67534. var DEFAULT_STYLE_NORMAL = 'normal';
  67535. var fontStyleCache = {};
  67536. var fontStyleCacheCount = 0;
  67537. var MAX_FONT_CACHE_SIZE = 100;
  67538. var fontEl = document.createElement('div');
  67539. var getFontStyle = function (fontString) {
  67540. var fontStyle = fontStyleCache[fontString];
  67541. if (!fontStyle) {
  67542. // Clear cache
  67543. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  67544. fontStyleCacheCount = 0;
  67545. fontStyleCache = {};
  67546. }
  67547. var style = fontEl.style;
  67548. var fontFamily;
  67549. try {
  67550. style.font = fontString;
  67551. fontFamily = style.fontFamily.split(',')[0];
  67552. }
  67553. catch (e) {
  67554. }
  67555. fontStyle = {
  67556. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  67557. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  67558. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  67559. size: parseFloat(style.fontSize || 12) | 0,
  67560. family: fontFamily || 'Microsoft YaHei'
  67561. };
  67562. fontStyleCache[fontString] = fontStyle;
  67563. fontStyleCacheCount++;
  67564. }
  67565. return fontStyle;
  67566. };
  67567. var textMeasureEl;
  67568. // Overwrite measure text method
  67569. $override$1('measureText', function (text, textFont) {
  67570. var doc$$1 = doc;
  67571. if (!textMeasureEl) {
  67572. textMeasureEl = doc$$1.createElement('div');
  67573. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  67574. + 'padding:0;margin:0;border:none;white-space:pre;';
  67575. doc.body.appendChild(textMeasureEl);
  67576. }
  67577. try {
  67578. textMeasureEl.style.font = textFont;
  67579. } catch (ex) {
  67580. // Ignore failures to set to invalid font.
  67581. }
  67582. textMeasureEl.innerHTML = '';
  67583. // Don't use innerHTML or innerText because they allow markup/whitespace.
  67584. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  67585. return {
  67586. width: textMeasureEl.offsetWidth
  67587. };
  67588. });
  67589. var tmpRect$2 = new BoundingRect();
  67590. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  67591. var style = this.style;
  67592. // Optimize, avoid normalize every time.
  67593. this.__dirty && normalizeTextStyle(style, true);
  67594. var text = style.text;
  67595. // Convert to string
  67596. text != null && (text += '');
  67597. if (!text) {
  67598. return;
  67599. }
  67600. // Convert rich text to plain text. Rich text is not supported in
  67601. // IE8-, but tags in rich text template will be removed.
  67602. if (style.rich) {
  67603. var contentBlock = parseRichText(text, style);
  67604. text = [];
  67605. for (var i = 0; i < contentBlock.lines.length; i++) {
  67606. var tokens = contentBlock.lines[i].tokens;
  67607. var textLine = [];
  67608. for (var j = 0; j < tokens.length; j++) {
  67609. textLine.push(tokens[j].text);
  67610. }
  67611. text.push(textLine.join(''));
  67612. }
  67613. text = text.join('\n');
  67614. }
  67615. var x;
  67616. var y;
  67617. var align = style.textAlign;
  67618. var verticalAlign = style.textVerticalAlign;
  67619. var fontStyle = getFontStyle(style.font);
  67620. // FIXME encodeHtmlAttribute ?
  67621. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  67622. + fontStyle.size + 'px "' + fontStyle.family + '"';
  67623. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  67624. // Transform rect to view space
  67625. var m = this.transform;
  67626. // Ignore transform for text in other element
  67627. if (m && !fromTextEl) {
  67628. tmpRect$2.copy(rect);
  67629. tmpRect$2.applyTransform(m);
  67630. rect = tmpRect$2;
  67631. }
  67632. if (!fromTextEl) {
  67633. var textPosition = style.textPosition;
  67634. var distance$$1 = style.textDistance;
  67635. // Text position represented by coord
  67636. if (textPosition instanceof Array) {
  67637. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  67638. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  67639. align = align || 'left';
  67640. }
  67641. else {
  67642. var res = adjustTextPositionOnRect(
  67643. textPosition, rect, distance$$1
  67644. );
  67645. x = res.x;
  67646. y = res.y;
  67647. // Default align and baseline when has textPosition
  67648. align = align || res.textAlign;
  67649. verticalAlign = verticalAlign || res.textVerticalAlign;
  67650. }
  67651. }
  67652. else {
  67653. x = rect.x;
  67654. y = rect.y;
  67655. }
  67656. x = adjustTextX(x, textRect.width, align);
  67657. y = adjustTextY(y, textRect.height, verticalAlign);
  67658. // Force baseline 'middle'
  67659. y += textRect.height / 2;
  67660. // var fontSize = fontStyle.size;
  67661. // 1.75 is an arbitrary number, as there is no info about the text baseline
  67662. // switch (baseline) {
  67663. // case 'hanging':
  67664. // case 'top':
  67665. // y += fontSize / 1.75;
  67666. // break;
  67667. // case 'middle':
  67668. // break;
  67669. // default:
  67670. // // case null:
  67671. // // case 'alphabetic':
  67672. // // case 'ideographic':
  67673. // // case 'bottom':
  67674. // y -= fontSize / 2.25;
  67675. // break;
  67676. // }
  67677. // switch (align) {
  67678. // case 'left':
  67679. // break;
  67680. // case 'center':
  67681. // x -= textRect.width / 2;
  67682. // break;
  67683. // case 'right':
  67684. // x -= textRect.width;
  67685. // break;
  67686. // case 'end':
  67687. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  67688. // break;
  67689. // case 'start':
  67690. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  67691. // break;
  67692. // default:
  67693. // align = 'left';
  67694. // }
  67695. var createNode$$1 = createNode;
  67696. var textVmlEl = this._textVmlEl;
  67697. var pathEl;
  67698. var textPathEl;
  67699. var skewEl;
  67700. if (!textVmlEl) {
  67701. textVmlEl = createNode$$1('line');
  67702. pathEl = createNode$$1('path');
  67703. textPathEl = createNode$$1('textpath');
  67704. skewEl = createNode$$1('skew');
  67705. // FIXME Why here is not cammel case
  67706. // Align 'center' seems wrong
  67707. textPathEl.style['v-text-align'] = 'left';
  67708. initRootElStyle(textVmlEl);
  67709. pathEl.textpathok = true;
  67710. textPathEl.on = true;
  67711. textVmlEl.from = '0 0';
  67712. textVmlEl.to = '1000 0.05';
  67713. append(textVmlEl, skewEl);
  67714. append(textVmlEl, pathEl);
  67715. append(textVmlEl, textPathEl);
  67716. this._textVmlEl = textVmlEl;
  67717. }
  67718. else {
  67719. // 这里是在前面 appendChild 保证顺序的前提下
  67720. skewEl = textVmlEl.firstChild;
  67721. pathEl = skewEl.nextSibling;
  67722. textPathEl = pathEl.nextSibling;
  67723. }
  67724. var coords = [x, y];
  67725. var textVmlElStyle = textVmlEl.style;
  67726. // Ignore transform for text in other element
  67727. if (m && fromTextEl) {
  67728. applyTransform(coords, coords, m);
  67729. skewEl.on = true;
  67730. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  67731. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  67732. // Text position
  67733. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  67734. // Left top point as origin
  67735. skewEl.origin = '0 0';
  67736. textVmlElStyle.left = '0px';
  67737. textVmlElStyle.top = '0px';
  67738. }
  67739. else {
  67740. skewEl.on = false;
  67741. textVmlElStyle.left = round$3(x) + 'px';
  67742. textVmlElStyle.top = round$3(y) + 'px';
  67743. }
  67744. textPathEl.string = encodeHtmlAttribute(text);
  67745. // TODO
  67746. try {
  67747. textPathEl.style.font = font;
  67748. }
  67749. // Error font format
  67750. catch (e) {}
  67751. updateFillAndStroke(textVmlEl, 'fill', {
  67752. fill: style.textFill,
  67753. opacity: style.opacity
  67754. }, this);
  67755. updateFillAndStroke(textVmlEl, 'stroke', {
  67756. stroke: style.textStroke,
  67757. opacity: style.opacity,
  67758. lineDash: style.lineDash
  67759. }, this);
  67760. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67761. // Attached to root
  67762. append(vmlRoot, textVmlEl);
  67763. };
  67764. var removeRectText = function (vmlRoot) {
  67765. remove(vmlRoot, this._textVmlEl);
  67766. this._textVmlEl = null;
  67767. };
  67768. var appendRectText = function (vmlRoot) {
  67769. append(vmlRoot, this._textVmlEl);
  67770. };
  67771. var list = [RectText, Displayable, ZImage, Path, Text];
  67772. // In case Displayable has been mixed in RectText
  67773. for (var i$3 = 0; i$3 < list.length; i$3++) {
  67774. var proto$8 = list[i$3].prototype;
  67775. proto$8.drawRectText = drawRectText;
  67776. proto$8.removeRectText = removeRectText;
  67777. proto$8.appendRectText = appendRectText;
  67778. }
  67779. Text.prototype.brushVML = function (vmlRoot) {
  67780. var style = this.style;
  67781. if (style.text != null) {
  67782. this.drawRectText(vmlRoot, {
  67783. x: style.x || 0, y: style.y || 0,
  67784. width: 0, height: 0
  67785. }, this.getBoundingRect(), true);
  67786. }
  67787. else {
  67788. this.removeRectText(vmlRoot);
  67789. }
  67790. };
  67791. Text.prototype.onRemove = function (vmlRoot) {
  67792. this.removeRectText(vmlRoot);
  67793. };
  67794. Text.prototype.onAdd = function (vmlRoot) {
  67795. this.appendRectText(vmlRoot);
  67796. };
  67797. }
  67798. /**
  67799. * VML Painter.
  67800. *
  67801. * @module zrender/vml/Painter
  67802. */
  67803. function parseInt10$1(val) {
  67804. return parseInt(val, 10);
  67805. }
  67806. /**
  67807. * @alias module:zrender/vml/Painter
  67808. */
  67809. function VMLPainter(root, storage) {
  67810. initVML();
  67811. this.root = root;
  67812. this.storage = storage;
  67813. var vmlViewport = document.createElement('div');
  67814. var vmlRoot = document.createElement('div');
  67815. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  67816. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  67817. root.appendChild(vmlViewport);
  67818. this._vmlRoot = vmlRoot;
  67819. this._vmlViewport = vmlViewport;
  67820. this.resize();
  67821. // Modify storage
  67822. var oldDelFromStorage = storage.delFromStorage;
  67823. var oldAddToStorage = storage.addToStorage;
  67824. storage.delFromStorage = function (el) {
  67825. oldDelFromStorage.call(storage, el);
  67826. if (el) {
  67827. el.onRemove && el.onRemove(vmlRoot);
  67828. }
  67829. };
  67830. storage.addToStorage = function (el) {
  67831. // Displayable already has a vml node
  67832. el.onAdd && el.onAdd(vmlRoot);
  67833. oldAddToStorage.call(storage, el);
  67834. };
  67835. this._firstPaint = true;
  67836. }
  67837. VMLPainter.prototype = {
  67838. constructor: VMLPainter,
  67839. getType: function () {
  67840. return 'vml';
  67841. },
  67842. /**
  67843. * @return {HTMLDivElement}
  67844. */
  67845. getViewportRoot: function () {
  67846. return this._vmlViewport;
  67847. },
  67848. getViewportRootOffset: function () {
  67849. var viewportRoot = this.getViewportRoot();
  67850. if (viewportRoot) {
  67851. return {
  67852. offsetLeft: viewportRoot.offsetLeft || 0,
  67853. offsetTop: viewportRoot.offsetTop || 0
  67854. };
  67855. }
  67856. },
  67857. /**
  67858. * 刷新
  67859. */
  67860. refresh: function () {
  67861. var list = this.storage.getDisplayList(true, true);
  67862. this._paintList(list);
  67863. },
  67864. _paintList: function (list) {
  67865. var vmlRoot = this._vmlRoot;
  67866. for (var i = 0; i < list.length; i++) {
  67867. var el = list[i];
  67868. if (el.invisible || el.ignore) {
  67869. if (!el.__alreadyNotVisible) {
  67870. el.onRemove(vmlRoot);
  67871. }
  67872. // Set as already invisible
  67873. el.__alreadyNotVisible = true;
  67874. }
  67875. else {
  67876. if (el.__alreadyNotVisible) {
  67877. el.onAdd(vmlRoot);
  67878. }
  67879. el.__alreadyNotVisible = false;
  67880. if (el.__dirty) {
  67881. el.beforeBrush && el.beforeBrush();
  67882. (el.brushVML || el.brush).call(el, vmlRoot);
  67883. el.afterBrush && el.afterBrush();
  67884. }
  67885. }
  67886. el.__dirty = false;
  67887. }
  67888. if (this._firstPaint) {
  67889. // Detached from document at first time
  67890. // to avoid page refreshing too many times
  67891. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  67892. this._vmlViewport.appendChild(vmlRoot);
  67893. this._firstPaint = false;
  67894. }
  67895. },
  67896. resize: function (width, height) {
  67897. var width = width == null ? this._getWidth() : width;
  67898. var height = height == null ? this._getHeight() : height;
  67899. if (this._width != width || this._height != height) {
  67900. this._width = width;
  67901. this._height = height;
  67902. var vmlViewportStyle = this._vmlViewport.style;
  67903. vmlViewportStyle.width = width + 'px';
  67904. vmlViewportStyle.height = height + 'px';
  67905. }
  67906. },
  67907. dispose: function () {
  67908. this.root.innerHTML = '';
  67909. this._vmlRoot =
  67910. this._vmlViewport =
  67911. this.storage = null;
  67912. },
  67913. getWidth: function () {
  67914. return this._width;
  67915. },
  67916. getHeight: function () {
  67917. return this._height;
  67918. },
  67919. clear: function () {
  67920. if (this._vmlViewport) {
  67921. this.root.removeChild(this._vmlViewport);
  67922. }
  67923. },
  67924. _getWidth: function () {
  67925. var root = this.root;
  67926. var stl = root.currentStyle;
  67927. return ((root.clientWidth || parseInt10$1(stl.width))
  67928. - parseInt10$1(stl.paddingLeft)
  67929. - parseInt10$1(stl.paddingRight)) | 0;
  67930. },
  67931. _getHeight: function () {
  67932. var root = this.root;
  67933. var stl = root.currentStyle;
  67934. return ((root.clientHeight || parseInt10$1(stl.height))
  67935. - parseInt10$1(stl.paddingTop)
  67936. - parseInt10$1(stl.paddingBottom)) | 0;
  67937. }
  67938. };
  67939. // Not supported methods
  67940. function createMethodNotSupport(method) {
  67941. return function () {
  67942. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  67943. };
  67944. }
  67945. // Unsupported methods
  67946. each$1([
  67947. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  67948. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  67949. ], function (name) {
  67950. VMLPainter.prototype[name] = createMethodNotSupport(name);
  67951. });
  67952. registerPainter('vml', VMLPainter);
  67953. var svgURI = 'http://www.w3.org/2000/svg';
  67954. function createElement(name) {
  67955. return document.createElementNS(svgURI, name);
  67956. }
  67957. // TODO
  67958. // 1. shadow
  67959. // 2. Image: sx, sy, sw, sh
  67960. var CMD$4 = PathProxy.CMD;
  67961. var arrayJoin = Array.prototype.join;
  67962. var NONE = 'none';
  67963. var mathRound = Math.round;
  67964. var mathSin$3 = Math.sin;
  67965. var mathCos$3 = Math.cos;
  67966. var PI$5 = Math.PI;
  67967. var PI2$7 = Math.PI * 2;
  67968. var degree = 180 / PI$5;
  67969. var EPSILON$4 = 1e-4;
  67970. function round4(val) {
  67971. return mathRound(val * 1e4) / 1e4;
  67972. }
  67973. function isAroundZero$1(val) {
  67974. return val < EPSILON$4 && val > -EPSILON$4;
  67975. }
  67976. function pathHasFill(style, isText) {
  67977. var fill = isText ? style.textFill : style.fill;
  67978. return fill != null && fill !== NONE;
  67979. }
  67980. function pathHasStroke(style, isText) {
  67981. var stroke = isText ? style.textStroke : style.stroke;
  67982. return stroke != null && stroke !== NONE;
  67983. }
  67984. function setTransform(svgEl, m) {
  67985. if (m) {
  67986. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  67987. }
  67988. }
  67989. function attr(el, key, val) {
  67990. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  67991. // Don't set attribute for gradient, since it need new dom nodes
  67992. el.setAttribute(key, val);
  67993. }
  67994. }
  67995. function attrXLink(el, key, val) {
  67996. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  67997. }
  67998. function bindStyle(svgEl, style, isText) {
  67999. if (pathHasFill(style, isText)) {
  68000. var fill = isText ? style.textFill : style.fill;
  68001. fill = fill === 'transparent' ? NONE : fill;
  68002. /**
  68003. * FIXME:
  68004. * This is a temporary fix for Chrome's clipping bug
  68005. * that happens when a clip-path is referring another one.
  68006. * This fix should be used before Chrome's bug is fixed.
  68007. * For an element that has clip-path, and fill is none,
  68008. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  68009. * Otherwise, it will show black fill color.
  68010. * 0.002 is used because this won't work for alpha values smaller
  68011. * than 0.002.
  68012. *
  68013. * See
  68014. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  68015. * for more information.
  68016. */
  68017. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  68018. fill = 'rgba(0, 0, 0, 0.002)';
  68019. }
  68020. attr(svgEl, 'fill', fill);
  68021. attr(svgEl, 'fill-opacity', style.opacity);
  68022. }
  68023. else {
  68024. attr(svgEl, 'fill', NONE);
  68025. }
  68026. if (pathHasStroke(style, isText)) {
  68027. var stroke = isText ? style.textStroke : style.stroke;
  68028. stroke = stroke === 'transparent' ? NONE : stroke;
  68029. attr(svgEl, 'stroke', stroke);
  68030. var strokeWidth = isText
  68031. ? style.textStrokeWidth
  68032. : style.lineWidth;
  68033. var strokeScale = !isText && style.strokeNoScale
  68034. ? style.host.getLineScale()
  68035. : 1;
  68036. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  68037. // stroke then fill for text; fill then stroke for others
  68038. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  68039. attr(svgEl, 'stroke-opacity', style.opacity);
  68040. var lineDash = style.lineDash;
  68041. if (lineDash) {
  68042. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  68043. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  68044. }
  68045. else {
  68046. attr(svgEl, 'stroke-dasharray', '');
  68047. }
  68048. // PENDING
  68049. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  68050. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  68051. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  68052. }
  68053. else {
  68054. attr(svgEl, 'stroke', NONE);
  68055. }
  68056. }
  68057. /***************************************************
  68058. * PATH
  68059. **************************************************/
  68060. function pathDataToString$1(path) {
  68061. var str = [];
  68062. var data = path.data;
  68063. var dataLength = path.len();
  68064. for (var i = 0; i < dataLength;) {
  68065. var cmd = data[i++];
  68066. var cmdStr = '';
  68067. var nData = 0;
  68068. switch (cmd) {
  68069. case CMD$4.M:
  68070. cmdStr = 'M';
  68071. nData = 2;
  68072. break;
  68073. case CMD$4.L:
  68074. cmdStr = 'L';
  68075. nData = 2;
  68076. break;
  68077. case CMD$4.Q:
  68078. cmdStr = 'Q';
  68079. nData = 4;
  68080. break;
  68081. case CMD$4.C:
  68082. cmdStr = 'C';
  68083. nData = 6;
  68084. break;
  68085. case CMD$4.A:
  68086. var cx = data[i++];
  68087. var cy = data[i++];
  68088. var rx = data[i++];
  68089. var ry = data[i++];
  68090. var theta = data[i++];
  68091. var dTheta = data[i++];
  68092. var psi = data[i++];
  68093. var clockwise = data[i++];
  68094. var dThetaPositive = Math.abs(dTheta);
  68095. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  68096. && !isAroundZero$1(dThetaPositive);
  68097. var large = false;
  68098. if (dThetaPositive >= PI2$7) {
  68099. large = true;
  68100. }
  68101. else if (isAroundZero$1(dThetaPositive)) {
  68102. large = false;
  68103. }
  68104. else {
  68105. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  68106. === !!clockwise;
  68107. }
  68108. var x0 = round4(cx + rx * mathCos$3(theta));
  68109. var y0 = round4(cy + ry * mathSin$3(theta));
  68110. // It will not draw if start point and end point are exactly the same
  68111. // We need to shift the end point with a small value
  68112. // FIXME A better way to draw circle ?
  68113. if (isCircle) {
  68114. if (clockwise) {
  68115. dTheta = PI2$7 - 1e-4;
  68116. }
  68117. else {
  68118. dTheta = -PI2$7 + 1e-4;
  68119. }
  68120. large = true;
  68121. if (i === 9) {
  68122. // Move to (x0, y0) only when CMD.A comes at the
  68123. // first position of a shape.
  68124. // For instance, when drawing a ring, CMD.A comes
  68125. // after CMD.M, so it's unnecessary to move to
  68126. // (x0, y0).
  68127. str.push('M', x0, y0);
  68128. }
  68129. }
  68130. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  68131. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  68132. // FIXME Ellipse
  68133. str.push('A', round4(rx), round4(ry),
  68134. mathRound(psi * degree), +large, +clockwise, x, y);
  68135. break;
  68136. case CMD$4.Z:
  68137. cmdStr = 'Z';
  68138. break;
  68139. case CMD$4.R:
  68140. var x = round4(data[i++]);
  68141. var y = round4(data[i++]);
  68142. var w = round4(data[i++]);
  68143. var h = round4(data[i++]);
  68144. str.push(
  68145. 'M', x, y,
  68146. 'L', x + w, y,
  68147. 'L', x + w, y + h,
  68148. 'L', x, y + h,
  68149. 'L', x, y
  68150. );
  68151. break;
  68152. }
  68153. cmdStr && str.push(cmdStr);
  68154. for (var j = 0; j < nData; j++) {
  68155. // PENDING With scale
  68156. str.push(round4(data[i++]));
  68157. }
  68158. }
  68159. return str.join(' ');
  68160. }
  68161. var svgPath = {};
  68162. svgPath.brush = function (el) {
  68163. var style = el.style;
  68164. var svgEl = el.__svgEl;
  68165. if (!svgEl) {
  68166. svgEl = createElement('path');
  68167. el.__svgEl = svgEl;
  68168. }
  68169. if (!el.path) {
  68170. el.createPathProxy();
  68171. }
  68172. var path = el.path;
  68173. if (el.__dirtyPath) {
  68174. path.beginPath();
  68175. el.buildPath(path, el.shape);
  68176. el.__dirtyPath = false;
  68177. var pathStr = pathDataToString$1(path);
  68178. if (pathStr.indexOf('NaN') < 0) {
  68179. // Ignore illegal path, which may happen such in out-of-range
  68180. // data in Calendar series.
  68181. attr(svgEl, 'd', pathStr);
  68182. }
  68183. }
  68184. bindStyle(svgEl, style);
  68185. setTransform(svgEl, el.transform);
  68186. if (style.text != null) {
  68187. svgTextDrawRectText(el, el.getBoundingRect());
  68188. }
  68189. };
  68190. /***************************************************
  68191. * IMAGE
  68192. **************************************************/
  68193. var svgImage = {};
  68194. svgImage.brush = function (el) {
  68195. var style = el.style;
  68196. var image = style.image;
  68197. if (image instanceof HTMLImageElement) {
  68198. var src = image.src;
  68199. image = src;
  68200. }
  68201. if (! image) {
  68202. return;
  68203. }
  68204. var x = style.x || 0;
  68205. var y = style.y || 0;
  68206. var dw = style.width;
  68207. var dh = style.height;
  68208. var svgEl = el.__svgEl;
  68209. if (! svgEl) {
  68210. svgEl = createElement('image');
  68211. el.__svgEl = svgEl;
  68212. }
  68213. if (image !== el.__imageSrc) {
  68214. attrXLink(svgEl, 'href', image);
  68215. // Caching image src
  68216. el.__imageSrc = image;
  68217. }
  68218. attr(svgEl, 'width', dw);
  68219. attr(svgEl, 'height', dh);
  68220. attr(svgEl, 'x', x);
  68221. attr(svgEl, 'y', y);
  68222. setTransform(svgEl, el.transform);
  68223. if (style.text != null) {
  68224. svgTextDrawRectText(el, el.getBoundingRect());
  68225. }
  68226. };
  68227. /***************************************************
  68228. * TEXT
  68229. **************************************************/
  68230. var svgText = {};
  68231. var tmpRect$3 = new BoundingRect();
  68232. var svgTextDrawRectText = function (el, rect, textRect) {
  68233. var style = el.style;
  68234. el.__dirty && normalizeTextStyle(style, true);
  68235. var text = style.text;
  68236. // Convert to string
  68237. if (text == null) {
  68238. // Draw no text only when text is set to null, but not ''
  68239. return;
  68240. }
  68241. else {
  68242. text += '';
  68243. }
  68244. var textSvgEl = el.__textSvgEl;
  68245. if (! textSvgEl) {
  68246. textSvgEl = createElement('text');
  68247. el.__textSvgEl = textSvgEl;
  68248. }
  68249. var x;
  68250. var y;
  68251. var textPosition = style.textPosition;
  68252. var distance = style.textDistance;
  68253. var align = style.textAlign || 'left';
  68254. if (typeof style.fontSize === 'number') {
  68255. style.fontSize += 'px';
  68256. }
  68257. var font = style.font
  68258. || [
  68259. style.fontStyle || '',
  68260. style.fontWeight || '',
  68261. style.fontSize || '',
  68262. style.fontFamily || ''
  68263. ].join(' ')
  68264. || DEFAULT_FONT;
  68265. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  68266. textRect = getBoundingRect(text, font, align,
  68267. verticalAlign);
  68268. var lineHeight = textRect.lineHeight;
  68269. // Text position represented by coord
  68270. if (textPosition instanceof Array) {
  68271. x = rect.x + textPosition[0];
  68272. y = rect.y + textPosition[1];
  68273. }
  68274. else {
  68275. var newPos = adjustTextPositionOnRect(
  68276. textPosition, rect, distance
  68277. );
  68278. x = newPos.x;
  68279. y = newPos.y;
  68280. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  68281. align = newPos.textAlign;
  68282. }
  68283. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  68284. if (font) {
  68285. textSvgEl.style.font = font;
  68286. }
  68287. var textPadding = style.textPadding;
  68288. // Make baseline top
  68289. attr(textSvgEl, 'x', x);
  68290. attr(textSvgEl, 'y', y);
  68291. bindStyle(textSvgEl, style, true);
  68292. if (el instanceof Text || el.style.transformText) {
  68293. // Transform text with element
  68294. setTransform(textSvgEl, el.transform);
  68295. }
  68296. else {
  68297. if (el.transform) {
  68298. tmpRect$3.copy(rect);
  68299. tmpRect$3.applyTransform(el.transform);
  68300. rect = tmpRect$3;
  68301. }
  68302. else {
  68303. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  68304. rect.x = pos[0];
  68305. rect.y = pos[1];
  68306. }
  68307. // Text rotation, but no element transform
  68308. var origin = style.textOrigin;
  68309. if (origin === 'center') {
  68310. x = textRect.width / 2 + x;
  68311. y = textRect.height / 2 + y;
  68312. }
  68313. else if (origin) {
  68314. x = origin[0] + x;
  68315. y = origin[1] + y;
  68316. }
  68317. var rotate = -style.textRotation * 180 / Math.PI;
  68318. attr(textSvgEl, 'transform', 'rotate(' + rotate + ','
  68319. + x + ',' + y + ')');
  68320. }
  68321. var textLines = text.split('\n');
  68322. var nTextLines = textLines.length;
  68323. var textAnchor = align;
  68324. // PENDING
  68325. if (textAnchor === 'left') {
  68326. textAnchor = 'start';
  68327. textPadding && (x += textPadding[3]);
  68328. }
  68329. else if (textAnchor === 'right') {
  68330. textAnchor = 'end';
  68331. textPadding && (x -= textPadding[1]);
  68332. }
  68333. else if (textAnchor === 'center') {
  68334. textAnchor = 'middle';
  68335. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  68336. }
  68337. var dy = 0;
  68338. if (verticalAlign === 'baseline') {
  68339. dy = -textRect.height + lineHeight;
  68340. textPadding && (dy -= textPadding[2]);
  68341. }
  68342. else if (verticalAlign === 'middle') {
  68343. dy = (-textRect.height + lineHeight) / 2;
  68344. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  68345. }
  68346. else {
  68347. textPadding && (dy += textPadding[0]);
  68348. }
  68349. // Font may affect position of each tspan elements
  68350. if (el.__text !== text || el.__textFont !== font) {
  68351. var tspanList = el.__tspanList || [];
  68352. el.__tspanList = tspanList;
  68353. for (var i = 0; i < nTextLines; i++) {
  68354. // Using cached tspan elements
  68355. var tspan = tspanList[i];
  68356. if (! tspan) {
  68357. tspan = tspanList[i] = createElement('tspan');
  68358. textSvgEl.appendChild(tspan);
  68359. attr(tspan, 'alignment-baseline', verticalAlign);
  68360. attr(tspan, 'text-anchor', textAnchor);
  68361. }
  68362. else {
  68363. tspan.innerHTML = '';
  68364. }
  68365. attr(tspan, 'x', x);
  68366. attr(tspan, 'y', y + i * lineHeight + dy);
  68367. tspan.appendChild(document.createTextNode(textLines[i]));
  68368. }
  68369. // Remove unsed tspan elements
  68370. for (; i < tspanList.length; i++) {
  68371. textSvgEl.removeChild(tspanList[i]);
  68372. }
  68373. tspanList.length = nTextLines;
  68374. el.__text = text;
  68375. el.__textFont = font;
  68376. }
  68377. else if (el.__tspanList.length) {
  68378. // Update span x and y
  68379. var len = el.__tspanList.length;
  68380. for (var i = 0; i < len; ++i) {
  68381. var tspan = el.__tspanList[i];
  68382. if (tspan) {
  68383. attr(tspan, 'x', x);
  68384. attr(tspan, 'y', y + i * lineHeight + dy);
  68385. }
  68386. }
  68387. }
  68388. };
  68389. function getVerticalAlignForSvg(verticalAlign) {
  68390. if (verticalAlign === 'middle') {
  68391. return 'middle';
  68392. }
  68393. else if (verticalAlign === 'bottom') {
  68394. return 'baseline';
  68395. }
  68396. else {
  68397. return 'hanging';
  68398. }
  68399. }
  68400. svgText.drawRectText = svgTextDrawRectText;
  68401. svgText.brush = function (el) {
  68402. var style = el.style;
  68403. if (style.text != null) {
  68404. // 强制设置 textPosition
  68405. style.textPosition = [0, 0];
  68406. svgTextDrawRectText(el, {
  68407. x: style.x || 0, y: style.y || 0,
  68408. width: 0, height: 0
  68409. }, el.getBoundingRect());
  68410. }
  68411. };
  68412. // Myers' Diff Algorithm
  68413. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  68414. function Diff() {}
  68415. Diff.prototype = {
  68416. diff: function (oldArr, newArr, equals) {
  68417. if (!equals) {
  68418. equals = function (a, b) {
  68419. return a === b;
  68420. };
  68421. }
  68422. this.equals = equals;
  68423. var self = this;
  68424. oldArr = oldArr.slice();
  68425. newArr = newArr.slice();
  68426. // Allow subclasses to massage the input prior to running
  68427. var newLen = newArr.length;
  68428. var oldLen = oldArr.length;
  68429. var editLength = 1;
  68430. var maxEditLength = newLen + oldLen;
  68431. var bestPath = [{ newPos: -1, components: [] }];
  68432. // Seed editLength = 0, i.e. the content starts with the same values
  68433. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  68434. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  68435. var indices = [];
  68436. for (var i = 0; i < newArr.length; i++) {
  68437. indices.push(i);
  68438. }
  68439. // Identity per the equality and tokenizer
  68440. return [{
  68441. indices: indices, count: newArr.length
  68442. }];
  68443. }
  68444. // Main worker method. checks all permutations of a given edit length for acceptance.
  68445. function execEditLength() {
  68446. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  68447. var basePath;
  68448. var addPath = bestPath[diagonalPath - 1];
  68449. var removePath = bestPath[diagonalPath + 1];
  68450. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  68451. if (addPath) {
  68452. // No one else is going to attempt to use this value, clear it
  68453. bestPath[diagonalPath - 1] = undefined;
  68454. }
  68455. var canAdd = addPath && addPath.newPos + 1 < newLen;
  68456. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  68457. if (!canAdd && !canRemove) {
  68458. // If this path is a terminal then prune
  68459. bestPath[diagonalPath] = undefined;
  68460. continue;
  68461. }
  68462. // Select the diagonal that we want to branch from. We select the prior
  68463. // path whose position in the new string is the farthest from the origin
  68464. // and does not pass the bounds of the diff graph
  68465. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  68466. basePath = clonePath(removePath);
  68467. self.pushComponent(basePath.components, undefined, true);
  68468. }
  68469. else {
  68470. basePath = addPath; // No need to clone, we've pulled it from the list
  68471. basePath.newPos++;
  68472. self.pushComponent(basePath.components, true, undefined);
  68473. }
  68474. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  68475. // If we have hit the end of both strings, then we are done
  68476. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  68477. return buildValues(self, basePath.components, newArr, oldArr);
  68478. }
  68479. else {
  68480. // Otherwise track this path as a potential candidate and continue.
  68481. bestPath[diagonalPath] = basePath;
  68482. }
  68483. }
  68484. editLength++;
  68485. }
  68486. while (editLength <= maxEditLength) {
  68487. var ret = execEditLength();
  68488. if (ret) {
  68489. return ret;
  68490. }
  68491. }
  68492. },
  68493. pushComponent: function (components, added, removed) {
  68494. var last = components[components.length - 1];
  68495. if (last && last.added === added && last.removed === removed) {
  68496. // We need to clone here as the component clone operation is just
  68497. // as shallow array clone
  68498. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  68499. }
  68500. else {
  68501. components.push({count: 1, added: added, removed: removed });
  68502. }
  68503. },
  68504. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  68505. var newLen = newArr.length;
  68506. var oldLen = oldArr.length;
  68507. var newPos = basePath.newPos;
  68508. var oldPos = newPos - diagonalPath;
  68509. var commonCount = 0;
  68510. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  68511. newPos++;
  68512. oldPos++;
  68513. commonCount++;
  68514. }
  68515. if (commonCount) {
  68516. basePath.components.push({count: commonCount});
  68517. }
  68518. basePath.newPos = newPos;
  68519. return oldPos;
  68520. },
  68521. tokenize: function (value) {
  68522. return value.slice();
  68523. },
  68524. join: function (value) {
  68525. return value.slice();
  68526. }
  68527. };
  68528. function buildValues(diff, components, newArr, oldArr) {
  68529. var componentPos = 0;
  68530. var componentLen = components.length;
  68531. var newPos = 0;
  68532. var oldPos = 0;
  68533. for (; componentPos < componentLen; componentPos++) {
  68534. var component = components[componentPos];
  68535. if (!component.removed) {
  68536. var indices = [];
  68537. for (var i = newPos; i < newPos + component.count; i++) {
  68538. indices.push(i);
  68539. }
  68540. component.indices = indices;
  68541. newPos += component.count;
  68542. // Common case
  68543. if (!component.added) {
  68544. oldPos += component.count;
  68545. }
  68546. }
  68547. else {
  68548. var indices = [];
  68549. for (var i = oldPos; i < oldPos + component.count; i++) {
  68550. indices.push(i);
  68551. }
  68552. component.indices = indices;
  68553. oldPos += component.count;
  68554. }
  68555. }
  68556. return components;
  68557. }
  68558. function clonePath(path) {
  68559. return { newPos: path.newPos, components: path.components.slice(0) };
  68560. }
  68561. var arrayDiff = new Diff();
  68562. var arrayDiff$1 = function (oldArr, newArr, callback) {
  68563. return arrayDiff.diff(oldArr, newArr, callback);
  68564. };
  68565. /**
  68566. * @file Manages elements that can be defined in <defs> in SVG,
  68567. * e.g., gradients, clip path, etc.
  68568. * @author Zhang Wenli
  68569. */
  68570. var MARK_UNUSED = '0';
  68571. var MARK_USED = '1';
  68572. /**
  68573. * Manages elements that can be defined in <defs> in SVG,
  68574. * e.g., gradients, clip path, etc.
  68575. *
  68576. * @class
  68577. * @param {number} zrId zrender instance id
  68578. * @param {SVGElement} svgRoot root of SVG document
  68579. * @param {string|string[]} tagNames possible tag names
  68580. * @param {string} markLabel label name to make if the element
  68581. * is used
  68582. */
  68583. function Definable(
  68584. zrId,
  68585. svgRoot,
  68586. tagNames,
  68587. markLabel,
  68588. domName
  68589. ) {
  68590. this._zrId = zrId;
  68591. this._svgRoot = svgRoot;
  68592. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  68593. this._markLabel = markLabel;
  68594. this._domName = domName || '_dom';
  68595. this.nextId = 0;
  68596. }
  68597. Definable.prototype.createElement = createElement;
  68598. /**
  68599. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  68600. *
  68601. * @param {boolean} isForceCreating if need to create when not exists
  68602. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  68603. * exist and isForceCreating is false
  68604. */
  68605. Definable.prototype.getDefs = function (isForceCreating) {
  68606. var svgRoot = this._svgRoot;
  68607. var defs = this._svgRoot.getElementsByTagName('defs');
  68608. if (defs.length === 0) {
  68609. // Not exist
  68610. if (isForceCreating) {
  68611. defs = svgRoot.insertBefore(
  68612. this.createElement('defs'), // Create new tag
  68613. svgRoot.firstChild // Insert in the front of svg
  68614. );
  68615. if (!defs.contains) {
  68616. // IE doesn't support contains method
  68617. defs.contains = function (el) {
  68618. var children = defs.children;
  68619. if (!children) {
  68620. return false;
  68621. }
  68622. for (var i = children.length - 1; i >= 0; --i) {
  68623. if (children[i] === el) {
  68624. return true;
  68625. }
  68626. }
  68627. return false;
  68628. };
  68629. }
  68630. return defs;
  68631. }
  68632. else {
  68633. return null;
  68634. }
  68635. }
  68636. else {
  68637. return defs[0];
  68638. }
  68639. };
  68640. /**
  68641. * Update DOM element if necessary.
  68642. *
  68643. * @param {Object|string} element style element. e.g., for gradient,
  68644. * it may be '#ccc' or {type: 'linear', ...}
  68645. * @param {Function|undefined} onUpdate update callback
  68646. */
  68647. Definable.prototype.update = function (element, onUpdate) {
  68648. if (!element) {
  68649. return;
  68650. }
  68651. var defs = this.getDefs(false);
  68652. if (element[this._domName] && defs.contains(element[this._domName])) {
  68653. // Update DOM
  68654. if (typeof onUpdate === 'function') {
  68655. onUpdate(element);
  68656. }
  68657. }
  68658. else {
  68659. // No previous dom, create new
  68660. var dom = this.add(element);
  68661. if (dom) {
  68662. element[this._domName] = dom;
  68663. }
  68664. }
  68665. };
  68666. /**
  68667. * Add gradient dom to defs
  68668. *
  68669. * @param {SVGElement} dom DOM to be added to <defs>
  68670. */
  68671. Definable.prototype.addDom = function (dom) {
  68672. var defs = this.getDefs(true);
  68673. defs.appendChild(dom);
  68674. };
  68675. /**
  68676. * Remove DOM of a given element.
  68677. *
  68678. * @param {SVGElement} element element to remove dom
  68679. */
  68680. Definable.prototype.removeDom = function (element) {
  68681. var defs = this.getDefs(false);
  68682. if (defs && element[this._domName]) {
  68683. defs.removeChild(element[this._domName]);
  68684. element[this._domName] = null;
  68685. }
  68686. };
  68687. /**
  68688. * Get DOMs of this element.
  68689. *
  68690. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  68691. */
  68692. Definable.prototype.getDoms = function () {
  68693. var defs = this.getDefs(false);
  68694. if (!defs) {
  68695. // No dom when defs is not defined
  68696. return [];
  68697. }
  68698. var doms = [];
  68699. each$1(this._tagNames, function (tagName) {
  68700. var tags = defs.getElementsByTagName(tagName);
  68701. // Note that tags is HTMLCollection, which is array-like
  68702. // rather than real array.
  68703. // So `doms.concat(tags)` add tags as one object.
  68704. doms = doms.concat([].slice.call(tags));
  68705. });
  68706. return doms;
  68707. };
  68708. /**
  68709. * Mark DOMs to be unused before painting, and clear unused ones at the end
  68710. * of the painting.
  68711. */
  68712. Definable.prototype.markAllUnused = function () {
  68713. var doms = this.getDoms();
  68714. var that = this;
  68715. each$1(doms, function (dom) {
  68716. dom[that._markLabel] = MARK_UNUSED;
  68717. });
  68718. };
  68719. /**
  68720. * Mark a single DOM to be used.
  68721. *
  68722. * @param {SVGElement} dom DOM to mark
  68723. */
  68724. Definable.prototype.markUsed = function (dom) {
  68725. if (dom) {
  68726. dom[this._markLabel] = MARK_USED;
  68727. }
  68728. };
  68729. /**
  68730. * Remove unused DOMs defined in <defs>
  68731. */
  68732. Definable.prototype.removeUnused = function () {
  68733. var defs = this.getDefs(false);
  68734. if (!defs) {
  68735. // Nothing to remove
  68736. return;
  68737. }
  68738. var doms = this.getDoms();
  68739. var that = this;
  68740. each$1(doms, function (dom) {
  68741. if (dom[that._markLabel] !== MARK_USED) {
  68742. // Remove gradient
  68743. defs.removeChild(dom);
  68744. }
  68745. });
  68746. };
  68747. /**
  68748. * Get SVG proxy.
  68749. *
  68750. * @param {Displayable} displayable displayable element
  68751. * @return {Path|Image|Text} svg proxy of given element
  68752. */
  68753. Definable.prototype.getSvgProxy = function (displayable) {
  68754. if (displayable instanceof Path) {
  68755. return svgPath;
  68756. }
  68757. else if (displayable instanceof ZImage) {
  68758. return svgImage;
  68759. }
  68760. else if (displayable instanceof Text) {
  68761. return svgText;
  68762. }
  68763. else {
  68764. return svgPath;
  68765. }
  68766. };
  68767. /**
  68768. * Get text SVG element.
  68769. *
  68770. * @param {Displayable} displayable displayable element
  68771. * @return {SVGElement} SVG element of text
  68772. */
  68773. Definable.prototype.getTextSvgElement = function (displayable) {
  68774. return displayable.__textSvgEl;
  68775. };
  68776. /**
  68777. * Get SVG element.
  68778. *
  68779. * @param {Displayable} displayable displayable element
  68780. * @return {SVGElement} SVG element
  68781. */
  68782. Definable.prototype.getSvgElement = function (displayable) {
  68783. return displayable.__svgEl;
  68784. };
  68785. /**
  68786. * @file Manages SVG gradient elements.
  68787. * @author Zhang Wenli
  68788. */
  68789. /**
  68790. * Manages SVG gradient elements.
  68791. *
  68792. * @class
  68793. * @extends Definable
  68794. * @param {number} zrId zrender instance id
  68795. * @param {SVGElement} svgRoot root of SVG document
  68796. */
  68797. function GradientManager(zrId, svgRoot) {
  68798. Definable.call(
  68799. this,
  68800. zrId,
  68801. svgRoot,
  68802. ['linearGradient', 'radialGradient'],
  68803. '__gradient_in_use__'
  68804. );
  68805. }
  68806. inherits(GradientManager, Definable);
  68807. /**
  68808. * Create new gradient DOM for fill or stroke if not exist,
  68809. * but will not update gradient if exists.
  68810. *
  68811. * @param {SvgElement} svgElement SVG element to paint
  68812. * @param {Displayable} displayable zrender displayable element
  68813. */
  68814. GradientManager.prototype.addWithoutUpdate = function (
  68815. svgElement,
  68816. displayable
  68817. ) {
  68818. if (displayable && displayable.style) {
  68819. var that = this;
  68820. each$1(['fill', 'stroke'], function (fillOrStroke) {
  68821. if (displayable.style[fillOrStroke]
  68822. && (displayable.style[fillOrStroke].type === 'linear'
  68823. || displayable.style[fillOrStroke].type === 'radial')
  68824. ) {
  68825. var gradient = displayable.style[fillOrStroke];
  68826. var defs = that.getDefs(true);
  68827. // Create dom in <defs> if not exists
  68828. var dom;
  68829. if (gradient._dom) {
  68830. // Gradient exists
  68831. dom = gradient._dom;
  68832. if (!defs.contains(gradient._dom)) {
  68833. // _dom is no longer in defs, recreate
  68834. that.addDom(dom);
  68835. }
  68836. }
  68837. else {
  68838. // New dom
  68839. dom = that.add(gradient);
  68840. }
  68841. that.markUsed(displayable);
  68842. var id = dom.getAttribute('id');
  68843. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  68844. }
  68845. });
  68846. }
  68847. };
  68848. /**
  68849. * Add a new gradient tag in <defs>
  68850. *
  68851. * @param {Gradient} gradient zr gradient instance
  68852. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  68853. * created DOM
  68854. */
  68855. GradientManager.prototype.add = function (gradient) {
  68856. var dom;
  68857. if (gradient.type === 'linear') {
  68858. dom = this.createElement('linearGradient');
  68859. }
  68860. else if (gradient.type === 'radial') {
  68861. dom = this.createElement('radialGradient');
  68862. }
  68863. else {
  68864. zrLog('Illegal gradient type.');
  68865. return null;
  68866. }
  68867. // Set dom id with gradient id, since each gradient instance
  68868. // will have no more than one dom element.
  68869. // id may exists before for those dirty elements, in which case
  68870. // id should remain the same, and other attributes should be
  68871. // updated.
  68872. gradient.id = gradient.id || this.nextId++;
  68873. dom.setAttribute('id', 'zr' + this._zrId
  68874. + '-gradient-' + gradient.id);
  68875. this.updateDom(gradient, dom);
  68876. this.addDom(dom);
  68877. return dom;
  68878. };
  68879. /**
  68880. * Update gradient.
  68881. *
  68882. * @param {Gradient} gradient zr gradient instance
  68883. */
  68884. GradientManager.prototype.update = function (gradient) {
  68885. var that = this;
  68886. Definable.prototype.update.call(this, gradient, function () {
  68887. var type = gradient.type;
  68888. var tagName = gradient._dom.tagName;
  68889. if (type === 'linear' && tagName === 'linearGradient'
  68890. || type === 'radial' && tagName === 'radialGradient'
  68891. ) {
  68892. // Gradient type is not changed, update gradient
  68893. that.updateDom(gradient, gradient._dom);
  68894. }
  68895. else {
  68896. // Remove and re-create if type is changed
  68897. that.removeDom(gradient);
  68898. that.add(gradient);
  68899. }
  68900. });
  68901. };
  68902. /**
  68903. * Update gradient dom
  68904. *
  68905. * @param {Gradient} gradient zr gradient instance
  68906. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  68907. * DOM to update
  68908. */
  68909. GradientManager.prototype.updateDom = function (gradient, dom) {
  68910. if (gradient.type === 'linear') {
  68911. dom.setAttribute('x1', gradient.x);
  68912. dom.setAttribute('y1', gradient.y);
  68913. dom.setAttribute('x2', gradient.x2);
  68914. dom.setAttribute('y2', gradient.y2);
  68915. }
  68916. else if (gradient.type === 'radial') {
  68917. dom.setAttribute('cx', gradient.x);
  68918. dom.setAttribute('cy', gradient.y);
  68919. dom.setAttribute('r', gradient.r);
  68920. }
  68921. else {
  68922. zrLog('Illegal gradient type.');
  68923. return;
  68924. }
  68925. if (gradient.global) {
  68926. // x1, x2, y1, y2 in range of 0 to canvas width or height
  68927. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  68928. }
  68929. else {
  68930. // x1, x2, y1, y2 in range of 0 to 1
  68931. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  68932. }
  68933. // Remove color stops if exists
  68934. dom.innerHTML = '';
  68935. // Add color stops
  68936. var colors = gradient.colorStops;
  68937. for (var i = 0, len = colors.length; i < len; ++i) {
  68938. var stop = this.createElement('stop');
  68939. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  68940. stop.setAttribute('stop-color', colors[i].color);
  68941. dom.appendChild(stop);
  68942. }
  68943. // Store dom element in gradient, to avoid creating multiple
  68944. // dom instances for the same gradient element
  68945. gradient._dom = dom;
  68946. };
  68947. /**
  68948. * Mark a single gradient to be used
  68949. *
  68950. * @param {Displayable} displayable displayable element
  68951. */
  68952. GradientManager.prototype.markUsed = function (displayable) {
  68953. if (displayable.style) {
  68954. var gradient = displayable.style.fill;
  68955. if (gradient && gradient._dom) {
  68956. Definable.prototype.markUsed.call(this, gradient._dom);
  68957. }
  68958. gradient = displayable.style.stroke;
  68959. if (gradient && gradient._dom) {
  68960. Definable.prototype.markUsed.call(this, gradient._dom);
  68961. }
  68962. }
  68963. };
  68964. /**
  68965. * @file Manages SVG clipPath elements.
  68966. * @author Zhang Wenli
  68967. */
  68968. /**
  68969. * Manages SVG clipPath elements.
  68970. *
  68971. * @class
  68972. * @extends Definable
  68973. * @param {number} zrId zrender instance id
  68974. * @param {SVGElement} svgRoot root of SVG document
  68975. */
  68976. function ClippathManager(zrId, svgRoot) {
  68977. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  68978. }
  68979. inherits(ClippathManager, Definable);
  68980. /**
  68981. * Update clipPath.
  68982. *
  68983. * @param {Displayable} displayable displayable element
  68984. */
  68985. ClippathManager.prototype.update = function (displayable) {
  68986. var svgEl = this.getSvgElement(displayable);
  68987. if (svgEl) {
  68988. this.updateDom(svgEl, displayable.__clipPaths, false);
  68989. }
  68990. var textEl = this.getTextSvgElement(displayable);
  68991. if (textEl) {
  68992. // Make another clipPath for text, since it's transform
  68993. // matrix is not the same with svgElement
  68994. this.updateDom(textEl, displayable.__clipPaths, true);
  68995. }
  68996. this.markUsed(displayable);
  68997. };
  68998. /**
  68999. * Create an SVGElement of displayable and create a <clipPath> of its
  69000. * clipPath
  69001. *
  69002. * @param {Displayable} parentEl parent element
  69003. * @param {ClipPath[]} clipPaths clipPaths of parent element
  69004. * @param {boolean} isText if parent element is Text
  69005. */
  69006. ClippathManager.prototype.updateDom = function (
  69007. parentEl,
  69008. clipPaths,
  69009. isText
  69010. ) {
  69011. if (clipPaths && clipPaths.length > 0) {
  69012. // Has clipPath, create <clipPath> with the first clipPath
  69013. var defs = this.getDefs(true);
  69014. var clipPath = clipPaths[0];
  69015. var clipPathEl;
  69016. var id;
  69017. var dom = isText ? '_textDom' : '_dom';
  69018. if (clipPath[dom]) {
  69019. // Use a dom that is already in <defs>
  69020. id = clipPath[dom].getAttribute('id');
  69021. clipPathEl = clipPath[dom];
  69022. // Use a dom that is already in <defs>
  69023. if (!defs.contains(clipPathEl)) {
  69024. // This happens when set old clipPath that has
  69025. // been previously removed
  69026. defs.appendChild(clipPathEl);
  69027. }
  69028. }
  69029. else {
  69030. // New <clipPath>
  69031. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  69032. ++this.nextId;
  69033. clipPathEl = this.createElement('clipPath');
  69034. clipPathEl.setAttribute('id', id);
  69035. defs.appendChild(clipPathEl);
  69036. clipPath[dom] = clipPathEl;
  69037. }
  69038. // Build path and add to <clipPath>
  69039. var svgProxy = this.getSvgProxy(clipPath);
  69040. if (clipPath.transform
  69041. && clipPath.parent.invTransform
  69042. && !isText
  69043. ) {
  69044. /**
  69045. * If a clipPath has a parent with transform, the transform
  69046. * of parent should not be considered when setting transform
  69047. * of clipPath. So we need to transform back from parent's
  69048. * transform, which is done by multiplying parent's inverse
  69049. * transform.
  69050. */
  69051. // Store old transform
  69052. var transform = Array.prototype.slice.call(
  69053. clipPath.transform
  69054. );
  69055. // Transform back from parent, and brush path
  69056. mul$1(
  69057. clipPath.transform,
  69058. clipPath.parent.invTransform,
  69059. clipPath.transform
  69060. );
  69061. svgProxy.brush(clipPath);
  69062. // Set back transform of clipPath
  69063. clipPath.transform = transform;
  69064. }
  69065. else {
  69066. svgProxy.brush(clipPath);
  69067. }
  69068. var pathEl = this.getSvgElement(clipPath);
  69069. clipPathEl.innerHTML = '';
  69070. /**
  69071. * Use `cloneNode()` here to appendChild to multiple parents,
  69072. * which may happend when Text and other shapes are using the same
  69073. * clipPath. Since Text will create an extra clipPath DOM due to
  69074. * different transform rules.
  69075. */
  69076. clipPathEl.appendChild(pathEl.cloneNode());
  69077. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  69078. if (clipPaths.length > 1) {
  69079. // Make the other clipPaths recursively
  69080. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  69081. }
  69082. }
  69083. else {
  69084. // No clipPath
  69085. if (parentEl) {
  69086. parentEl.setAttribute('clip-path', 'none');
  69087. }
  69088. }
  69089. };
  69090. /**
  69091. * Mark a single clipPath to be used
  69092. *
  69093. * @param {Displayable} displayable displayable element
  69094. */
  69095. ClippathManager.prototype.markUsed = function (displayable) {
  69096. var that = this;
  69097. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  69098. each$1(displayable.__clipPaths, function (clipPath) {
  69099. if (clipPath._dom) {
  69100. Definable.prototype.markUsed.call(that, clipPath._dom);
  69101. }
  69102. if (clipPath._textDom) {
  69103. Definable.prototype.markUsed.call(that, clipPath._textDom);
  69104. }
  69105. });
  69106. }
  69107. };
  69108. /**
  69109. * @file Manages SVG shadow elements.
  69110. * @author Zhang Wenli
  69111. */
  69112. /**
  69113. * Manages SVG shadow elements.
  69114. *
  69115. * @class
  69116. * @extends Definable
  69117. * @param {number} zrId zrender instance id
  69118. * @param {SVGElement} svgRoot root of SVG document
  69119. */
  69120. function ShadowManager(zrId, svgRoot) {
  69121. Definable.call(
  69122. this,
  69123. zrId,
  69124. svgRoot,
  69125. ['filter'],
  69126. '__filter_in_use__',
  69127. '_shadowDom'
  69128. );
  69129. }
  69130. inherits(ShadowManager, Definable);
  69131. /**
  69132. * Create new shadow DOM for fill or stroke if not exist,
  69133. * but will not update shadow if exists.
  69134. *
  69135. * @param {SvgElement} svgElement SVG element to paint
  69136. * @param {Displayable} displayable zrender displayable element
  69137. */
  69138. ShadowManager.prototype.addWithoutUpdate = function (
  69139. svgElement,
  69140. displayable
  69141. ) {
  69142. if (displayable && hasShadow(displayable.style)) {
  69143. var style = displayable.style;
  69144. // Create dom in <defs> if not exists
  69145. var dom;
  69146. if (style._shadowDom) {
  69147. // Gradient exists
  69148. dom = style._shadowDom;
  69149. var defs = this.getDefs(true);
  69150. if (!defs.contains(style._shadowDom)) {
  69151. // _shadowDom is no longer in defs, recreate
  69152. this.addDom(dom);
  69153. }
  69154. }
  69155. else {
  69156. // New dom
  69157. dom = this.add(displayable);
  69158. }
  69159. this.markUsed(displayable);
  69160. var id = dom.getAttribute('id');
  69161. svgElement.style.filter = 'url(#' + id + ')';
  69162. }
  69163. };
  69164. /**
  69165. * Add a new shadow tag in <defs>
  69166. *
  69167. * @param {Displayable} displayable zrender displayable element
  69168. * @return {SVGFilterElement} created DOM
  69169. */
  69170. ShadowManager.prototype.add = function (displayable) {
  69171. var dom = this.createElement('filter');
  69172. var style = displayable.style;
  69173. // Set dom id with shadow id, since each shadow instance
  69174. // will have no more than one dom element.
  69175. // id may exists before for those dirty elements, in which case
  69176. // id should remain the same, and other attributes should be
  69177. // updated.
  69178. style._shadowDomId = style._shadowDomId || this.nextId++;
  69179. dom.setAttribute('id', 'zr' + this._zrId
  69180. + '-shadow-' + style._shadowDomId);
  69181. this.updateDom(displayable, dom);
  69182. this.addDom(dom);
  69183. return dom;
  69184. };
  69185. /**
  69186. * Update shadow.
  69187. *
  69188. * @param {Displayable} displayable zrender displayable element
  69189. */
  69190. ShadowManager.prototype.update = function (svgElement, displayable) {
  69191. var style = displayable.style;
  69192. if (hasShadow(style)) {
  69193. var that = this;
  69194. Definable.prototype.update.call(this, displayable, function (style) {
  69195. that.updateDom(displayable, style._shadowDom);
  69196. });
  69197. }
  69198. else {
  69199. // Remove shadow
  69200. this.remove(svgElement, style);
  69201. }
  69202. };
  69203. /**
  69204. * Remove DOM and clear parent filter
  69205. */
  69206. ShadowManager.prototype.remove = function (svgElement, style) {
  69207. if (style._shadowDomId != null) {
  69208. this.removeDom(style);
  69209. svgElement.style.filter = '';
  69210. }
  69211. };
  69212. /**
  69213. * Update shadow dom
  69214. *
  69215. * @param {Displayable} displayable zrender displayable element
  69216. * @param {SVGFilterElement} dom DOM to update
  69217. */
  69218. ShadowManager.prototype.updateDom = function (displayable, dom) {
  69219. var domChild = dom.getElementsByTagName('feDropShadow');
  69220. if (domChild.length === 0) {
  69221. domChild = this.createElement('feDropShadow');
  69222. }
  69223. else {
  69224. domChild = domChild[0];
  69225. }
  69226. var style = displayable.style;
  69227. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  69228. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  69229. // TODO: textBoxShadowBlur is not supported yet
  69230. var offsetX, offsetY, blur, color;
  69231. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  69232. offsetX = style.shadowOffsetX || 0;
  69233. offsetY = style.shadowOffsetY || 0;
  69234. blur = style.shadowBlur;
  69235. color = style.shadowColor;
  69236. }
  69237. else if (style.textShadowBlur) {
  69238. offsetX = style.textShadowOffsetX || 0;
  69239. offsetY = style.textShadowOffsetY || 0;
  69240. blur = style.textShadowBlur;
  69241. color = style.textShadowColor;
  69242. }
  69243. else {
  69244. // Remove shadow
  69245. this.removeDom(dom, style);
  69246. return;
  69247. }
  69248. domChild.setAttribute('dx', offsetX / scaleX);
  69249. domChild.setAttribute('dy', offsetY / scaleY);
  69250. domChild.setAttribute('flood-color', color);
  69251. // Divide by two here so that it looks the same as in canvas
  69252. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  69253. var stdDx = blur / 2 / scaleX;
  69254. var stdDy = blur / 2 / scaleY;
  69255. var stdDeviation = stdDx + ' ' + stdDy;
  69256. domChild.setAttribute('stdDeviation', stdDeviation);
  69257. // Fix filter clipping problem
  69258. dom.setAttribute('x', '-100%');
  69259. dom.setAttribute('y', '-100%');
  69260. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  69261. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  69262. dom.appendChild(domChild);
  69263. // Store dom element in shadow, to avoid creating multiple
  69264. // dom instances for the same shadow element
  69265. style._shadowDom = dom;
  69266. };
  69267. /**
  69268. * Mark a single shadow to be used
  69269. *
  69270. * @param {Displayable} displayable displayable element
  69271. */
  69272. ShadowManager.prototype.markUsed = function (displayable) {
  69273. var style = displayable.style;
  69274. if (style && style._shadowDom) {
  69275. Definable.prototype.markUsed.call(this, style._shadowDom);
  69276. }
  69277. };
  69278. function hasShadow(style) {
  69279. // TODO: textBoxShadowBlur is not supported yet
  69280. return style
  69281. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  69282. || style.textShadowBlur || style.textShadowOffsetX
  69283. || style.textShadowOffsetY);
  69284. }
  69285. /**
  69286. * SVG Painter
  69287. * @module zrender/svg/Painter
  69288. */
  69289. function parseInt10$2(val) {
  69290. return parseInt(val, 10);
  69291. }
  69292. function getSvgProxy(el) {
  69293. if (el instanceof Path) {
  69294. return svgPath;
  69295. }
  69296. else if (el instanceof ZImage) {
  69297. return svgImage;
  69298. }
  69299. else if (el instanceof Text) {
  69300. return svgText;
  69301. }
  69302. else {
  69303. return svgPath;
  69304. }
  69305. }
  69306. function checkParentAvailable(parent, child) {
  69307. return child && parent && child.parentNode !== parent;
  69308. }
  69309. function insertAfter(parent, child, prevSibling) {
  69310. if (checkParentAvailable(parent, child) && prevSibling) {
  69311. var nextSibling = prevSibling.nextSibling;
  69312. nextSibling ? parent.insertBefore(child, nextSibling)
  69313. : parent.appendChild(child);
  69314. }
  69315. }
  69316. function prepend(parent, child) {
  69317. if (checkParentAvailable(parent, child)) {
  69318. var firstChild = parent.firstChild;
  69319. firstChild ? parent.insertBefore(child, firstChild)
  69320. : parent.appendChild(child);
  69321. }
  69322. }
  69323. function remove$1(parent, child) {
  69324. if (child && parent && child.parentNode === parent) {
  69325. parent.removeChild(child);
  69326. }
  69327. }
  69328. function getTextSvgElement(displayable) {
  69329. return displayable.__textSvgEl;
  69330. }
  69331. function getSvgElement(displayable) {
  69332. return displayable.__svgEl;
  69333. }
  69334. /**
  69335. * @alias module:zrender/svg/Painter
  69336. * @constructor
  69337. * @param {HTMLElement} root 绘图容器
  69338. * @param {module:zrender/Storage} storage
  69339. * @param {Object} opts
  69340. */
  69341. var SVGPainter = function (root, storage, opts, zrId) {
  69342. this.root = root;
  69343. this.storage = storage;
  69344. this._opts = opts = extend({}, opts || {});
  69345. var svgRoot = createElement('svg');
  69346. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  69347. svgRoot.setAttribute('version', '1.1');
  69348. svgRoot.setAttribute('baseProfile', 'full');
  69349. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  69350. this.gradientManager = new GradientManager(zrId, svgRoot);
  69351. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  69352. this.shadowManager = new ShadowManager(zrId, svgRoot);
  69353. var viewport = document.createElement('div');
  69354. viewport.style.cssText = 'overflow:hidden;position:relative';
  69355. this._svgRoot = svgRoot;
  69356. this._viewport = viewport;
  69357. root.appendChild(viewport);
  69358. viewport.appendChild(svgRoot);
  69359. this.resize(opts.width, opts.height);
  69360. this._visibleList = [];
  69361. };
  69362. SVGPainter.prototype = {
  69363. constructor: SVGPainter,
  69364. getType: function () {
  69365. return 'svg';
  69366. },
  69367. getViewportRoot: function () {
  69368. return this._viewport;
  69369. },
  69370. getViewportRootOffset: function () {
  69371. var viewportRoot = this.getViewportRoot();
  69372. if (viewportRoot) {
  69373. return {
  69374. offsetLeft: viewportRoot.offsetLeft || 0,
  69375. offsetTop: viewportRoot.offsetTop || 0
  69376. };
  69377. }
  69378. },
  69379. refresh: function () {
  69380. var list = this.storage.getDisplayList(true);
  69381. this._paintList(list);
  69382. },
  69383. setBackgroundColor: function (backgroundColor) {
  69384. // TODO gradient
  69385. this._viewport.style.background = backgroundColor;
  69386. },
  69387. _paintList: function (list) {
  69388. this.gradientManager.markAllUnused();
  69389. this.clipPathManager.markAllUnused();
  69390. this.shadowManager.markAllUnused();
  69391. var svgRoot = this._svgRoot;
  69392. var visibleList = this._visibleList;
  69393. var listLen = list.length;
  69394. var newVisibleList = [];
  69395. var i;
  69396. for (i = 0; i < listLen; i++) {
  69397. var displayable = list[i];
  69398. var svgProxy = getSvgProxy(displayable);
  69399. var svgElement = getSvgElement(displayable)
  69400. || getTextSvgElement(displayable);
  69401. if (!displayable.invisible) {
  69402. if (displayable.__dirty) {
  69403. svgProxy && svgProxy.brush(displayable);
  69404. // Update clipPath
  69405. this.clipPathManager.update(displayable);
  69406. // Update gradient and shadow
  69407. if (displayable.style) {
  69408. this.gradientManager
  69409. .update(displayable.style.fill);
  69410. this.gradientManager
  69411. .update(displayable.style.stroke);
  69412. this.shadowManager
  69413. .update(svgElement, displayable);
  69414. }
  69415. displayable.__dirty = false;
  69416. }
  69417. newVisibleList.push(displayable);
  69418. }
  69419. }
  69420. var diff = arrayDiff$1(visibleList, newVisibleList);
  69421. var prevSvgElement;
  69422. // First do remove, in case element moved to the head and do remove
  69423. // after add
  69424. for (i = 0; i < diff.length; i++) {
  69425. var item = diff[i];
  69426. if (item.removed) {
  69427. for (var k = 0; k < item.count; k++) {
  69428. var displayable = visibleList[item.indices[k]];
  69429. var svgElement = getSvgElement(displayable);
  69430. var textSvgElement = getTextSvgElement(displayable);
  69431. remove$1(svgRoot, svgElement);
  69432. remove$1(svgRoot, textSvgElement);
  69433. }
  69434. }
  69435. }
  69436. for (i = 0; i < diff.length; i++) {
  69437. var item = diff[i];
  69438. if (item.added) {
  69439. for (var k = 0; k < item.count; k++) {
  69440. var displayable = newVisibleList[item.indices[k]];
  69441. var svgElement = getSvgElement(displayable);
  69442. var textSvgElement = getTextSvgElement(displayable);
  69443. prevSvgElement
  69444. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  69445. : prepend(svgRoot, svgElement);
  69446. if (svgElement) {
  69447. insertAfter(svgRoot, textSvgElement, svgElement);
  69448. }
  69449. else if (prevSvgElement) {
  69450. insertAfter(
  69451. svgRoot, textSvgElement, prevSvgElement
  69452. );
  69453. }
  69454. else {
  69455. prepend(svgRoot, textSvgElement);
  69456. }
  69457. // Insert text
  69458. insertAfter(svgRoot, textSvgElement, svgElement);
  69459. prevSvgElement = textSvgElement || svgElement
  69460. || prevSvgElement;
  69461. this.gradientManager
  69462. .addWithoutUpdate(svgElement, displayable);
  69463. this.shadowManager
  69464. .addWithoutUpdate(prevSvgElement, displayable);
  69465. this.clipPathManager.markUsed(displayable);
  69466. }
  69467. }
  69468. else if (!item.removed) {
  69469. for (var k = 0; k < item.count; k++) {
  69470. var displayable = newVisibleList[item.indices[k]];
  69471. prevSvgElement
  69472. = svgElement
  69473. = getTextSvgElement(displayable)
  69474. || getSvgElement(displayable)
  69475. || prevSvgElement;
  69476. this.gradientManager.markUsed(displayable);
  69477. this.gradientManager
  69478. .addWithoutUpdate(svgElement, displayable);
  69479. this.shadowManager.markUsed(displayable);
  69480. this.shadowManager
  69481. .addWithoutUpdate(svgElement, displayable);
  69482. this.clipPathManager.markUsed(displayable);
  69483. }
  69484. }
  69485. }
  69486. this.gradientManager.removeUnused();
  69487. this.clipPathManager.removeUnused();
  69488. this.shadowManager.removeUnused();
  69489. this._visibleList = newVisibleList;
  69490. },
  69491. _getDefs: function (isForceCreating) {
  69492. var svgRoot = this._svgRoot;
  69493. var defs = this._svgRoot.getElementsByTagName('defs');
  69494. if (defs.length === 0) {
  69495. // Not exist
  69496. if (isForceCreating) {
  69497. var defs = svgRoot.insertBefore(
  69498. createElement('defs'), // Create new tag
  69499. svgRoot.firstChild // Insert in the front of svg
  69500. );
  69501. if (!defs.contains) {
  69502. // IE doesn't support contains method
  69503. defs.contains = function (el) {
  69504. var children = defs.children;
  69505. if (!children) {
  69506. return false;
  69507. }
  69508. for (var i = children.length - 1; i >= 0; --i) {
  69509. if (children[i] === el) {
  69510. return true;
  69511. }
  69512. }
  69513. return false;
  69514. };
  69515. }
  69516. return defs;
  69517. }
  69518. else {
  69519. return null;
  69520. }
  69521. }
  69522. else {
  69523. return defs[0];
  69524. }
  69525. },
  69526. resize: function (width, height) {
  69527. var viewport = this._viewport;
  69528. // FIXME Why ?
  69529. viewport.style.display = 'none';
  69530. // Save input w/h
  69531. var opts = this._opts;
  69532. width != null && (opts.width = width);
  69533. height != null && (opts.height = height);
  69534. width = this._getSize(0);
  69535. height = this._getSize(1);
  69536. viewport.style.display = '';
  69537. if (this._width !== width || this._height !== height) {
  69538. this._width = width;
  69539. this._height = height;
  69540. var viewportStyle = viewport.style;
  69541. viewportStyle.width = width + 'px';
  69542. viewportStyle.height = height + 'px';
  69543. var svgRoot = this._svgRoot;
  69544. // Set width by 'svgRoot.width = width' is invalid
  69545. svgRoot.setAttribute('width', width);
  69546. svgRoot.setAttribute('height', height);
  69547. }
  69548. },
  69549. /**
  69550. * 获取绘图区域宽度
  69551. */
  69552. getWidth: function () {
  69553. return this._width;
  69554. },
  69555. /**
  69556. * 获取绘图区域高度
  69557. */
  69558. getHeight: function () {
  69559. return this._height;
  69560. },
  69561. _getSize: function (whIdx) {
  69562. var opts = this._opts;
  69563. var wh = ['width', 'height'][whIdx];
  69564. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  69565. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  69566. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  69567. if (opts[wh] != null && opts[wh] !== 'auto') {
  69568. return parseFloat(opts[wh]);
  69569. }
  69570. var root = this.root;
  69571. // IE8 does not support getComputedStyle, but it use VML.
  69572. var stl = document.defaultView.getComputedStyle(root);
  69573. return (
  69574. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  69575. - (parseInt10$2(stl[plt]) || 0)
  69576. - (parseInt10$2(stl[prb]) || 0)
  69577. ) | 0;
  69578. },
  69579. dispose: function () {
  69580. this.root.innerHTML = '';
  69581. this._svgRoot
  69582. = this._viewport
  69583. = this.storage
  69584. = null;
  69585. },
  69586. clear: function () {
  69587. if (this._viewport) {
  69588. this.root.removeChild(this._viewport);
  69589. }
  69590. },
  69591. pathToDataUrl: function () {
  69592. this.refresh();
  69593. var html = this._svgRoot.outerHTML;
  69594. return 'data:image/svg+xml;charset=UTF-8,' + html;
  69595. }
  69596. };
  69597. // Not supported methods
  69598. function createMethodNotSupport$1(method) {
  69599. return function () {
  69600. zrLog('In SVG mode painter not support method "' + method + '"');
  69601. };
  69602. }
  69603. // Unsuppoted methods
  69604. each$1([
  69605. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  69606. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  69607. 'toDataURL', 'pathToImage'
  69608. ], function (name) {
  69609. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  69610. });
  69611. registerPainter('svg', SVGPainter);
  69612. // Import all charts and components
  69613. exports.version = version;
  69614. exports.dependencies = dependencies;
  69615. exports.PRIORITY = PRIORITY;
  69616. exports.init = init;
  69617. exports.connect = connect;
  69618. exports.disConnect = disConnect;
  69619. exports.disconnect = disconnect;
  69620. exports.dispose = dispose;
  69621. exports.getInstanceByDom = getInstanceByDom;
  69622. exports.getInstanceById = getInstanceById;
  69623. exports.registerTheme = registerTheme;
  69624. exports.registerPreprocessor = registerPreprocessor;
  69625. exports.registerProcessor = registerProcessor;
  69626. exports.registerPostUpdate = registerPostUpdate;
  69627. exports.registerAction = registerAction;
  69628. exports.registerCoordinateSystem = registerCoordinateSystem;
  69629. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  69630. exports.registerLayout = registerLayout;
  69631. exports.registerVisual = registerVisual;
  69632. exports.registerLoading = registerLoading;
  69633. exports.extendComponentModel = extendComponentModel;
  69634. exports.extendComponentView = extendComponentView;
  69635. exports.extendSeriesModel = extendSeriesModel;
  69636. exports.extendChartView = extendChartView;
  69637. exports.setCanvasCreator = setCanvasCreator;
  69638. exports.registerMap = registerMap;
  69639. exports.getMap = getMap;
  69640. exports.dataTool = dataTool;
  69641. exports.zrender = zrender;
  69642. exports.graphic = graphic;
  69643. exports.number = number;
  69644. exports.format = format;
  69645. exports.throttle = throttle;
  69646. exports.helper = helper;
  69647. exports.matrix = matrix;
  69648. exports.vector = vector;
  69649. exports.color = color;
  69650. exports.parseGeoJSON = parseGeoJson$1;
  69651. exports.parseGeoJson = parseGeoJson;
  69652. exports.util = ecUtil;
  69653. exports.List = List;
  69654. exports.Model = Model;
  69655. exports.Axis = Axis;
  69656. exports.env = env$1;
  69657. })));
  69658. //# sourceMappingURL=echarts.js.map